问:
time complexities of algorithms
What are the time complexities of these two algorithms? I got 3n/2 + 6 for the first one, and 3logn + 6 for the second and I'm not sure if I'm doing them right.

```<code>int i  = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i += 2;
}
StdOut.println(evenSum);
</code>```

and the second is similar it just multiples by  2

```<code>int i = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i *= 2;
}
StdOut.println(evenSum);
</code>```

and I got 3n/2 + 6 and 3log n + 6

答:
Note that for the second code, your loop will never close as i is initialized to 0, which means i=i*2 will be 0 each time.

Time complexity is different from the number of steps taken to execute.

If you are asking about time complexity then for the first it will be O(N) as it has linear iteration i.e.
i=i+2

For the second code, assuming that you plan to correct the initialization of i it will be O(log(N)) as it has exponential iteration i.e
i=i*2

Title: time complexities of algorithms

Body:
What are the time complexities of these two algorithms? I got 3n/2 + 6 for the first one, and 3logn + 6 for the second and I'm not sure if I'm doing them right.

int i  = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i += 2;
}
StdOut.println(evenSum);

and the second is similar it just multiples by  2

int i = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i *= 2;
}
StdOut.println(evenSum);

and I got 3n/2 + 6 and 3log n + 6


来源: stackexchange

问:
Azure DevOps. Missing file when creating a Nuget package
Maybe someone can help me.

I get the following message when creating a NuGet package: File not found. This is displayed to me in the task "NuGet pack".

The NuGet package is built via Azure DevOps and in the build pipline there is a task "Copy Files to:$(build.artifactstagingdirectory)" in which I see that the folders are not copied from the source (vsts-agent\3\s) to the target (vsts-agent\3\a). All the other folders are copied, just this one is not and so the files it contains are not copied. In vsts-agent\3\s everything is present.
My solution in Visual Studio contains the following projects: several UnitTest, several class libraries and a service. The missing folder is the service.

The Agent job in the Build Pipline contains the following Task: Use Nuget, Nuget restore, Assembly manifest Data, Build Solutions ..., Publish symbols Path, Copy Files to..., Publish Artifact:drop, Nuget pack, Nuget push.

What do I need to do so that the service folder is also copied.

Thanks.

答: I'm not sure if you are using "Copy Files" task, try

ContentLicense: CC BY-SA 4.0


问:
What is the right approach to encapsulate platform specific code in Go?
I want to develop a small Go application, which shows the used key stroke shortcuts to the audience of a presentation.

To hook into the keyboard events I will have to use some platform specific code. What is the Go way to encapsulate platform specific code? I've been searching for keywords like compiler switch or platform modules, but I couldn't really find something about.

答:
To make code platform-specific, you can go for build constraints. For more info

Windows

```<code>//go:build windows
// +build windows

</code>```

Not Windows

```<code>//go:build !windows
// +build !windows

</code>```

Not Windows & Darwin

```<code>//go:build !windows && !darwin
// +build !windows,!darwin

</code>```

Mac

```<code>//go:build darwin
// +build darwin

</code>```

Linux

```<code>//go:build linux
// +build linux

</code>```

Example

//go:build windows
// +build windows

package main

func main() {
   // windows specific code
}

```

Or you can place the code in separate file for different OS with file naming convention.

Eg:-

path

path.go

path_windows.go

path_darwin.go

path_linux.go

Building go applications for different OS & Architecture

ContentLicense: CC BY-SA 3.0

Body:
To make code platform-specific, you can go for build constraints. For more info

Windows

//go:build windows
// +build windows

Not Windows

//go:build !windows
// +build !windows

Not Windows & Darwin

//go:build !windows && !darwin
// +build !windows,!darwin

Mac

//go:build darwin
// +build darwin

Linux

//go:build linux
// +build linux

Example

//go:build windows
// +build windows

package main

func main() {
   // windows specific code
}

Or you can place the code in separate file for different OS with file naming convention.

Eg:-

path

path.go

path_windows.go

path_darwin.go

path_linux.go

Building go applications for different OS & Architecture


问:
How to wait for request and user input?
Let's say when a component loads I make an async request. That component also has a submit button that the user can press which triggers a function that relies on the result of that original request. How do I delay executing the triggered function until the async request is finished?

If that doesn't make sense let me give an example. MyComponent makes an async request getRandomColor() on mounted. MyComponent's template has <button @click="handleClick">. handleClick calls some function saveColor(). How do I make sure that saveColor() is not called until my async getRandomColor() is finished?

I'm currently using Vue.js but I think this question applies to all of javascript.

答:
You can achieve this by adding :disabled attribute in your button element. The value of :disabled will be based on the response. i.e. If response will be there then enabled it otherwise disabled.

Working Demo :

const app = Vue.createApp({
  el: '#app',
  data() {
    return {
        buttonText: 'Call Me!',
      apiResponse: [],
      isDisabled: false
    }
  },
  methods: {
    saveColor() {
        console.log('saveColor method call');
    }
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
      this.apiResponse = response.data; // Here we are getting proper response. hence, button is getting enabled.
    }).catch((error) => {
        console.warn('API error');
        });
  }
})
app.mount('#app')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <button v-on:click="saveColor()" :disabled="!apiResponse.length">{{ buttonText }}</button>
</div></code>```

Adding below snippet as per the comment added by the author of the post.

What if I didn't want to use the disabled button? Is there a way to make the button handler wait for the request to finish before it continues execution?

const app = Vue.createApp({
  el: '#app',
  data() {
    return {
        buttonText: 'Call Me!',
      apiResponse: [],
      isDisabled: false
    }
  },
  methods: {
    saveColor() {
        console.log('saveColor method call');
    }
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
      this.apiResponse = response.data; // Here we are getting proper response. hence, button is getting enabled.
    }).catch((error) => {
        console.warn('API error');
        });
  }
})
app.mount('#app')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <button v-on:click.prevent="apiResponse.length ? saveColor() : {}">{{ buttonText }}</button>
</div></code>```

Title: How to wait for request and user input?

Body:
You can achieve this by adding :disabled attribute in your button element. The value of :disabled will be based on the response. i.e. If response will be there then enabled it otherwise disabled.

Working Demo :

const app = Vue.createApp({
  el: '#app',
  data() {
    return {
        buttonText: 'Call Me!',
      apiResponse: [],
      isDisabled: false
    }
  },
  methods: {
    saveColor() {
        console.log('saveColor method call');
    }
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
      this.apiResponse = response.data; // Here we are getting proper response. hence, button is getting enabled.
    }).catch((error) => {
        console.warn('API error');
        });
  }
})
app.mount('#app')

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <button v-on:click="saveColor()" :disabled="!apiResponse.length">{{ buttonText }}</button>
</div>

Adding below snippet as per the comment added by the author of the post.

What if I didn't want to use the disabled button? Is there a way to make the button handler wait for the request to finish before it continues execution?

const app = Vue.createApp({
  el: '#app',
  data() {
    return {
        buttonText: 'Call Me!',
      apiResponse: [],
      isDisabled: false
    }
  },
  methods: {
    saveColor() {
        console.log('saveColor method call');
    }
  },
  mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
      this.apiResponse = response.data; // Here we are getting proper response. hence, button is getting enabled.
    }).catch((error) => {
        console.warn('API error');
        });
  }
})
app.mount('#app')

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <button v-on:click.prevent="apiResponse.length ? saveColor() : {}">{{ buttonText }}</button>
</div>


问:
How to update multiple columns in window frame based on other column value on same window frame
My Dataframe is something like below, trying to update all column values based on the highest version within that group. I am able to update at the complete table level but failed to update the in-group/window frame level.

source:

expected output:

答:
```<code>SELECT *, max_by(status, version) OVER (PARTITION BY number) AS updated_status FROM your_table
</code>```

This should work for your case.

Body:
SELECT *, max_by(status, version) OVER (PARTITION BY number) AS updated_status FROM your_table

This should work for your case.


问:
Remove the extra " " in "lng " in array object javascript
The below code is for csv to array. I am getting an extra "space" in the output.

Example:
output : {lat: 42.546245, "lng ": 1.601554}

expected : {lat: 42.546245, "lng": 1.601554}
Help needed in removing the extra space in the "lng "header.

```<code>function initMap() {
mapLoad();
readFiles();

 }
function readFiles() {
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");

  function csvToArray(str, delimiter = ",") {

    // slice from start of text to the first \n index
    // use split to create an array from string by delimiter
    console.log(str);
    const headers = str.slice(0, str.indexOf("\n")).split(delimiter);

    // slice from \n index + 1 to the end of the text
    // use split to create an array of each csv value row
    // const rows = str.slice(str.indexOf("\n") + 1).split("\n");
    const rows = str.slice(str.indexOf("\n") + 1).split("\n");

    // Map the rows
    // split values from each row into an array
    // use headers.reduce to create an object
    // object properties derived from headers:values
    // the object passed as an element of the array
    const arr = rows.map(function (row) {
      const values = row.split(delimiter).map(Number);
      const el = headers.reduce(function (object, header, index) {
        object[header] = values[index];
        return object;
      }, {});
      return el;
    });

    // return the array
    return arr;
  }

  myForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const input = csvFile.files[0];
    const reader = new FileReader();

    reader.onload = function (e) {
      const text = e.target.result;
      const data = csvToArray(text);
      console.log(data);
      mapLoad_1(data);
    };

    reader.readAsText(input);
  });
  }
</code>```

答:
you can use trim function on header</p>
```<code>object[header.trim()] = values[index];
</code>```

Body:
The below code is for csv to array. I am getting an extra "space" in the output.

Example:
output : {lat: 42.546245, "lng ": 1.601554}

expected : {lat: 42.546245, "lng": 1.601554}
Help needed in removing the extra space in the "lng "header.

function initMap() {
mapLoad();
readFiles();

 }
function readFiles() {
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");

  function csvToArray(str, delimiter = ",") {

    // slice from start of text to the first \n index
    // use split to create an array from string by delimiter
    console.log(str);
    const headers = str.slice(0, str.indexOf("\n")).split(delimiter);

    // slice from \n index + 1 to the end of the text
    // use split to create an array of each csv value row
    // const rows = str.slice(str.indexOf("\n") + 1).split("\n");
    const rows = str.slice(str.indexOf("\n") + 1).split("\n");

    // Map the rows
    // split values from each row into an array
    // use headers.reduce to create an object
    // object properties derived from headers:values
    // the object passed as an element of the array
    const arr = rows.map(function (row) {
      const values = row.split(delimiter).map(Number);
      const el = headers.reduce(function (object, header, index) {
        object[header] = values[index];
        return object;
      }, {});
      return el;
    });

    // return the array
    return arr;
  }

  myForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const input = csvFile.files[0];
    const reader = new FileReader();

    reader.onload = function (e) {
      const text = e.target.result;
      const data = csvToArray(text);
      console.log(data);
      mapLoad_1(data);
    };

    reader.readAsText(input);
  });
  }

Body:
you can use trim function on header

object[header.trim()] = values[index];


问:
How to check if data returned from ajax as json is empty object or not
I have set this script for checking if the email address exists in the DB or not:

```<code>function checkemail(){
            var e = document.getElementById("email").value;
            if(e != ""){
                document.getElementById("emailstatus").innerHTML = 'checking ...';
                $.ajax({
                    type:'get',
                    url:'{!! URL::to('checkEmailExists') !!}',
                    data:{'email':e},
                    success:function(data){
                        // console.log(data);

                        if(Object.keys(data).length === 0)
                        {
                            document.getElementById("emailstatus").style.color = "red";
                            document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
                        }else{
                            document.getElementById("emailstatus").style.color = "green";
                            document.getElementById("emailstatus").innerHTML = e + " is OK";
                        }
                    },
                    error:function(){

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

So the code works fine but the only problem is comes from this condition checking which always returns TRUE:

```<code>if(Object.keys(data).length === 0)
</code>```

Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data)):

```<code>{}
</code>```

Otherwise, it will return this obj:

```<code>{
    "id": 1,
    "name": "Myname",
    "email": "myemail@yahoo.com",
    "email_verified_at": null,
    "created_at": "2022-02-09T05:49:27.000000Z",
    "updated_at": "2022-02-09T05:49:27.000000Z"
}
</code>```

So I need to properly check if the returned object is empty or not.

But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.

So how to properly check if the returned object is empty or not?

答:
Object.keys should work:

I suggest you double-check the params sent to the success function.

Body:
I have set this script for checking if the email address exists in the DB or not:

function checkemail(){
            var e = document.getElementById("email").value;
            if(e != ""){
                document.getElementById("emailstatus").innerHTML = 'checking ...';
                $.ajax({
                    type:'get',
                    url:'{!! URL::to('checkEmailExists') !!}',
                    data:{'email':e},
                    success:function(data){
                        // console.log(data);

                        if(Object.keys(data).length === 0)
                        {
                            document.getElementById("emailstatus").style.color = "red";
                            document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
                        }else{
                            document.getElementById("emailstatus").style.color = "green";
                            document.getElementById("emailstatus").innerHTML = e + " is OK";
                        }
                    },
                    error:function(){

                    }
                });
            }
        }

So the code works fine but the only problem is comes from this condition checking which always returns TRUE:

if(Object.keys(data).length === 0)

Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data)):

{}

Otherwise, it will return this obj:

{
    "id": 1,
    "name": "Myname",
    "email": "myemail@yahoo.com",
    "email_verified_at": null,
    "created_at": "2022-02-09T05:49:27.000000Z",
    "updated_at": "2022-02-09T05:49:27.000000Z"
}

So I need to properly check if the returned object is empty or not.

But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.

So how to properly check if the returned object is empty or not?


问:
Why does optional chaining allows rendering when fetching data through useEffect in an app that uses context?
I'm new to the webdev world and want to learn ReactJS. I followed a tutorial I found on YouTube made by Traversy where he makes a task tracker and now I want to make some changes to it to learn and practice some more.

I want to use context for the appointments (originally named tasks in the tutorial), add a calendar with react-calendar and use react-router-dom.
I got stuck for a while trying to make the list render, because it only rendered "empty". Later on found this post with a similar issue to mine: Only run a useEffect fetch after first useEffect fetch has fired and setUser in context

I changed bits of my code based on that post and now it does render the appointment list, but I don't know why it didn't work before and I'm unsure on why it does work now. I don't even know if I'm using context correctly or just prop-drilling. Help would be greatly appreciated. Thank you.

Also, sorry if my code is a mess, I'm new at this.

App.js

```<code>import { createContext, useState, useEffect } from "react";
import Dashboard from "./views/Dashboard";
import './App.css';
import { BrowserRouter as Router, Route, Routes} from "react-router-dom";
import AddAppointmentForm from "./views/AddAppointmentForm";

export const AppContext = createContext();
export const AppUpdateContext = createContext();

function App() {
  const [appointments, setAppointments] = useState([])
  const updateAppointments = (apptList) => {
    setAppointments(apptList)
  }

  return (
    <AppContext.Provider value={ appointments }>
      <AppUpdateContext.Provider value={ updateAppointments }>
        <Router>
          <Routes>

              <Route path="/" element={<Dashboard appointments={appointments} />} />
              {/* <Route path="/add" element={<AddAppointmentForm />} />  TBA */}

          </Routes>
        </Router>
      </AppUpdateContext.Provider>
    </AppContext.Provider>
  );
}

export default App;
</code>```

Dashboard.js

```<code>import { useEffect, useContext} from "react";
import { AppContext } from "../App";
import { AppUpdateContext } from "../App";
import AppointmentList from "../components/AppointmentList";
import Header from "../components/Header";

// function Dashboard() {  // this is how it used to be
  function Dashboard(props) {
  const appointments = useContext(AppContext)
  const setAppointments = useContext(AppUpdateContext)

  const fetchAppointmentList = async () => {
    const res = await fetch("http://localhost:5000/appointments");
    const data = await res.json();

    return data;
  }

  useEffect(() => {
    const getAppointments = async () => {
      const appointmentsFromServer = await fetchAppointmentList();
      setAppointments(appointmentsFromServer);
    }

    getAppointments();
    console.log("ñññññ",appointments)
  }, []);

  console.log("aagh",appointments)

  return (
    <div style={dashboardStyle}>
      <Header />
      {/* {appointments.lenght>0 ? (<AppointmentList />) : <p>empty</p>} this is how it used to be */}
      <AppointmentList appointments={props?.appointments}/>
    </div>
  );
}

const dashboardStyle = {
  maxWidth: "31.25rem",
  overflow: "auto",
  minHeight: "18.75rem",
  border: "1px solid steelblue",
  margin: "1.875rem auto",
  padding: ".5rem",
  boxSizing: "border-box",
}

export default Dashboard;
</code>```

AppointmentList.js

```<code>import Appointment from "./Appointment";
import { AppContext } from "../App";
import { useContext } from "react";

function AppointmentList({ appointments }) {
// function AppointmentList() {  // this is how it used to be
  // const { appointments, setAppointments } = useContext(AppContext)
  console.log("appList",appointments)  // this is how it used to be

  return (
    <>
      {
        appointments.map(appt => (
          <Appointment key={appt.id} appointment={appt} />
        ))
      }
    </>
  );
}

export default AppointmentList;
</code>```

答:
Why does optional chaining allows rendering when fetching data through
useEffect in an app that uses context?

```<code><AppointmentList appointments={props?.appointments}/>
</code>```

It allows rendering by preventing accidental accesses into potentially null or undefined objects. The only way props could be undefined though is if you just simply don't declare it, i.e. const Dashboard = () => {.... vs const Dashboard = (props) => {.....

You are drilling the appointments state through props. AppointmentList  can use the AppContext context to access the appointments state, while Dashboard can use the AppUpdateContext context to update the appointments state.

App

```<code>function App() {
  const [appointments, setAppointments] = useState([]);
  const updateAppointments = (apptList) => {
    setAppointments(apptList);
  };

  return (
    <AppContext.Provider value={{ appointments }}> // <-- need object here
      <AppUpdateContext.Provider value={{ updateAppointments }}> // <-- and here
        <Router>
          <Routes>
              <Route path="/" element={<Dashboard />} /> // <-- don't pass props
          </Routes>
        </Router>
      </AppUpdateContext.Provider>
    </AppContext.Provider>
  );
}
</code>```

Dashboard

```<code>function Dashboard() { // <-- no props
  const { updateAppointments } = useContext(AppUpdateContext); // <-- access from context

  const fetchAppointmentList = async () => {
    const res = await fetch("http://localhost:5000/appointments");
    const data = await res.json();

    return data;
  };

  useEffect(() => {
    const getAppointments = async () => {
      const appointmentsFromServer = await fetchAppointmentList();
      updateAppointments(appointmentsFromServer);
    }

    getAppointments();
  }, []);

  return (
    <div style={dashboardStyle}>
      <Header />
      <AppointmentList /> // <-- don't pass props
    </div>
  );
}
</code>```

AppointmentList

```<code>function AppointmentList() { // <-- no props
  const { appointments } = useContext(AppContext); // <-- access from context

  return appointments.map(appt => (
    <Appointment key={appt.id} appointment={appt} />
  ));
}
</code>```

Body:
I'm new to the webdev world and want to learn ReactJS. I followed a tutorial I found on YouTube made by Traversy where he makes a task tracker and now I want to make some changes to it to learn and practice some more.

I want to use context for the appointments (originally named tasks in the tutorial), add a calendar with react-calendar and use react-router-dom.
I got stuck for a while trying to make the list render, because it only rendered "empty". Later on found this post with a similar issue to mine: Only run a useEffect fetch after first useEffect fetch has fired and setUser in context

I changed bits of my code based on that post and now it does render the appointment list, but I don't know why it didn't work before and I'm unsure on why it does work now. I don't even know if I'm using context correctly or just prop-drilling. Help would be greatly appreciated. Thank you.

Also, sorry if my code is a mess, I'm new at this.

App.js

import { createContext, useState, useEffect } from "react";
import Dashboard from "./views/Dashboard";
import './App.css';
import { BrowserRouter as Router, Route, Routes} from "react-router-dom";
import AddAppointmentForm from "./views/AddAppointmentForm";

export const AppContext = createContext();
export const AppUpdateContext = createContext();

function App() {
  const [appointments, setAppointments] = useState([])
  const updateAppointments = (apptList) => {
    setAppointments(apptList)
  }

  return (
    <AppContext.Provider value={ appointments }>
      <AppUpdateContext.Provider value={ updateAppointments }>
        <Router>
          <Routes>

              <Route path="/" element={<Dashboard appointments={appointments} />} />
              {/* <Route path="/add" element={<AddAppointmentForm />} />  TBA */}

          </Routes>
        </Router>
      </AppUpdateContext.Provider>
    </AppContext.Provider>
  );
}

export default App;

Dashboard.js

import { useEffect, useContext} from "react";
import { AppContext } from "../App";
import { AppUpdateContext } from "../App";
import AppointmentList from "../components/AppointmentList";
import Header from "../components/Header";

// function Dashboard() {  // this is how it used to be
  function Dashboard(props) {
  const appointments = useContext(AppContext)
  const setAppointments = useContext(AppUpdateContext)

  const fetchAppointmentList = async () => {
    const res = await fetch("http://localhost:5000/appointments");
    const data = await res.json();

    return data;
  }

  useEffect(() => {
    const getAppointments = async () => {
      const appointmentsFromServer = await fetchAppointmentList();
      setAppointments(appointmentsFromServer);
    }

    getAppointments();
    console.log("ñññññ",appointments)
  }, []);

  console.log("aagh",appointments)

  return (

      {/* {appointments.lenght>0 ? (<AppointmentList />) :
empty
} this is how it used to be */}
      <AppointmentList appointments={props?.appointments}/>

  );
}

const dashboardStyle = {
  maxWidth: "31.25rem",
  overflow: "auto",
  minHeight: "18.75rem",
  border: "1px solid steelblue",
  margin: "1.875rem auto",
  padding: ".5rem",
  boxSizing: "border-box",
}

export default Dashboard;

AppointmentList.js

import Appointment from "./Appointment";
import { AppContext } from "../App";
import { useContext } from "react";

function AppointmentList({ appointments }) {
// function AppointmentList() {  // this is how it used to be
  // const { appointments, setAppointments } = useContext(AppContext)
  console.log("appList",appointments)  // this is how it used to be

  return (
    <>
      {
        appointments.map(appt => (
          <Appointment key={appt.id} appointment={appt} />
        ))
      }
    </>
  );
}

export default AppointmentList;

Body:
Why does optional chaining allows rendering when fetching data through
useEffect in an app that uses context?

<AppointmentList appointments={props?.appointments}/>

It allows rendering by preventing accidental accesses into potentially null or undefined objects. The only way props could be undefined though is if you just simply don't declare it, i.e. const Dashboard = () => {.... vs const Dashboard = (props) => {.....

You are drilling the appointments state through props. AppointmentList  can use the AppContext context to access the appointments state, while Dashboard can use the AppUpdateContext context to update the appointments state.

App

function App() {
  const [appointments, setAppointments] = useState([]);
  const updateAppointments = (apptList) => {
    setAppointments(apptList);
  };

  return (
    <AppContext.Provider value={{ appointments }}> // <-- need object here
      <AppUpdateContext.Provider value={{ updateAppointments }}> // <-- and here
        <Router>
          <Routes>
              <Route path="/" element={<Dashboard />} /> // <-- don't pass props
          </Routes>
        </Router>
      </AppUpdateContext.Provider>
    </AppContext.Provider>
  );
}

Dashboard

function Dashboard() { // <-- no props
  const { updateAppointments } = useContext(AppUpdateContext); // <-- access from context

  const fetchAppointmentList = async () => {
    const res = await fetch("http://localhost:5000/appointments");
    const data = await res.json();

    return data;
  };

  useEffect(() => {
    const getAppointments = async () => {
      const appointmentsFromServer = await fetchAppointmentList();
      updateAppointments(appointmentsFromServer);
    }

    getAppointments();
  }, []);

  return (
    <div style={dashboardStyle}>
      <Header />
      <AppointmentList /> // <-- don't pass props
    </div>
  );
}

AppointmentList

function AppointmentList() { // <-- no props
  const { appointments } = useContext(AppContext); // <-- access from context

  return appointments.map(appt => (
    <Appointment key={appt.id} appointment={appt} />
  ));
}


问:
sorting some data
I am trying to sort some data in bash. Data looks like below.

```<code>    20110724.gz   1347
    20110724.gz   2128
    20110725.gz   1315
    20110725.gz   2334
    20110726.gz   808
    20110726.gz   1088
    -bash-3.2$
</code>```

After sorting, it should look like

```<code>    20110724.gz 3475
    20110725.gz 3649
    20110726.gz 1896
</code>```

Basically, for a given date, the data are summed up. Can somebody help? Thanks.

hmm, hopefully I figure it out in a few days.

答:
Here's a quick and dirty perl oneliner:</p>

```<code>$ perl -e 'my %h = (); while (<>) { chomp; my ($fname, $count) = split; $h{$fname} += $count;} foreach my $k (sort keys %h) {print $k, " ", $h{$k}, "\n"}' < datafile
</code>```

Title: sorting some data

Body:
I am trying to sort some data in bash. Data looks like below.

    20110724.gz   1347
    20110724.gz   2128
    20110725.gz   1315
    20110725.gz   2334
    20110726.gz   808
    20110726.gz   1088
    -bash-3.2$

After sorting, it should look like

    20110724.gz 3475
    20110725.gz 3649
    20110726.gz 1896

Basically, for a given date, the data are summed up. Can somebody help? Thanks.

hmm, hopefully I figure it out in a few days.

Body:
Here's a quick and dirty perl oneliner:

$ perl -e 'my %h = (); while (<>) { chomp; my ($fname, $count) = split; $h{$fname} += $count;} foreach my $k (sort keys %h) {print $k, " ", $h{$k}, "\n"}' < datafile


问:
show date in correct format angular
I am making an application in which I want user to submit date date is getting stored in database in this format 2003-06-01T00:00:00.000+00:00 I want to display it as 01/06/2003 or 1st June 2003 can any body help me how can I do this?

答:
You could use date pipe to format your standard ISO date in html template. Find the date object from your template, wrap the value in {{}} and then add | date pipe to format it. https://angular.io/api/common/DatePipe

    {{date}}
    yyyy-MM-dd
    {{date | localDate:'yyyy-MM-dd' }}
    {{date | date:'yyyy-MM-dd'}}
```

Here is a working example: https://stackblitz.com/edit/angular-local-date-pipe-bu2nxp?file=src%2Fapp%2Fapp.component.html

Title: show date in correct format angular

Body:
You could use date pipe to format your standard ISO date in html template. Find the date object from your template, wrap the value in {{}} and then add | date pipe to format it. https://angular.io/api/common/DatePipe

    <td>{{date}} </td>
    <td>yyyy-MM-dd</td>
    <td>{{date | localDate:'yyyy-MM-dd' }}</td>
    <td>{{date | date:'yyyy-MM-dd'}}</td>

Here is a working example: https://stackblitz.com/edit/angular-local-date-pipe-bu2nxp?file=src%2Fapp%2Fapp.component.html


问:
Using header of different dataframe as title in for loop in pandas
I managed to plot a few charts out with using this for loop:

```<code>for i in df.columns[2:7]:
   df.plot.scatter(x='out_date', y=i, figsize = (10,7))
   plt.axvline(x=cutoff_date, color='r')
   plt.xlabel('out date')
   plt.ylabel('sucesses')
</code>```

I wanted to add titles to the plots using the header of a different dataframe with the following code but the title will only be added to the last plot instead of every plot:

```<code>for x in df2.columns[67:72]:
   plt.title(x)
</code>```

Is there a way to fix this?

答:
Try to zip your 2 dataframes:

```<code>for i, title in zip(df.columns[2:7], df2.columns[67:72]):
   ax = df.plot.scatter(x='out_date', y=i, figsize = (10,7), title=title)
   ax.axvline(x=cutoff_date, color='r')
   ax.set_xlabel('out date')
   ax.set_ylabel('sucesses')
</code>```

You can also use AxesSubplot instance returned by df.plot methods instead of functions of plt module.

Body:
I managed to plot a few charts out with using this for loop:

for i in df.columns[2:7]:
   df.plot.scatter(x='out_date', y=i, figsize = (10,7))
   plt.axvline(x=cutoff_date, color='r')
   plt.xlabel('out date')
   plt.ylabel('sucesses')

I wanted to add titles to the plots using the header of a different dataframe with the following code but the title will only be added to the last plot instead of every plot:

for x in df2.columns[67:72]:
   plt.title(x)

Is there a way to fix this?

Body:
Try to zip your 2 dataframes:

for i, title in zip(df.columns[2:7], df2.columns[67:72]):
   ax = df.plot.scatter(x='out_date', y=i, figsize = (10,7), title=title)
   ax.axvline(x=cutoff_date, color='r')
   ax.set_xlabel('out date')
   ax.set_ylabel('sucesses')

You can also use AxesSubplot instance returned by df.plot methods instead of functions of plt module.


问:
SQL Graph Database VS Cosmos Gremlin graph DB
I have been thinking about what are the pros and cons of SQL Graph Database and Cosmos Graph Database, as far as I understand, SQL graph database is using nodes and vertex, but it still stores all of the information in tables.

So my question would be if the graph data can be handled by graph Db, what are the advantages of using SQL graph database? What is the added value of it compared with the original graph Database ?

答:
SQL Graph Database and Cosmos Graph Database both are almost same kind of services, just the structure of handling the data is different. As such there are no advantages and disadvantages, but choosing the right service based on your use-case is the key factor.

Azure Cosmos DB's Gremlin API combines the power of graph database
algorithms with highly scalable, managed infrastructure to provide a
unique, flexible solution to most common data problems associated with
lack of flexibility and relational approaches.

So, by using Azure Cosmos DB Gremlin API, you will get more leverage on the datasets with additional features. On the top of that, all the prerequisites will be taken care by CosmosDB while creating the database using Gremlin API.

In SQL Graph DB, nodes and edges are in tabular form, whereas in Cosmos DB it is in JSON like format.

I would highly encourage you to analyze how these databases support graph database models and the mechanism to exploit the maximum potential of these database systems for the right use-cases.

Please refer below articles to get the better understanding of both the services.

SQL Graph Architecture

Introduction to Gremlin API in Azure Cosmos DB


问:
Check for child key/value pairs in JSON
I need to identify if my JSON feed has child key/value pairs and handle them differently. what i mean is:

```<code>{
    "dashboard" :[
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":"" },

    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    "related" : [
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        }]
  ]
</code>```

How do i identify that this JSON has those child ("related") key/value pairs?

答:
After parsing the JSON string into a JavaScript object (see greengit's answer), you have three options:

typeof obj.related !== 'undefined'

obj.related !== undefined. Be careful when using the undefined variable, it can be changed by other scripts. If you are using it, make sure to wrap your code in anonymous function that sets it to a correct value - see Javascript Garden about that, under "Handling Changes to the Value of undefined"

'related' in obj

IIRC, using in should be the fastest

update I remember it the other way around - in is the slowest way of doing that, by a large margin (98%!). Also, using typeof obj.key !== 'undefined' is much faster  than obj.key !== undefined (the latter is 80% slower). See http://jsperf.com/in-vs-not-undefined.

Title: Check for child key/value pairs in JSON

Body:
I need to identify if my JSON feed has child key/value pairs and handle them differently. what i mean is:

{
    "dashboard" :[
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":"" },

    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    "related" : [
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        },
    {
        "name": "",
        "image": "",
        "description":"",
        "linkurl":""
        }]
  ]

How do i identify that this JSON has those child ("related") key/value pairs?


问:
How to make function like confirm
I want to make custom confirm function.

so, I make a code like :

```<code>function confirm(msg){
  var obj = document.createElement("div");
  var body = document.createElement("div");
  body.innerHTML = msg;

  var foot = document.createElement("div");

  var ok = document.createElement("div");
  ok.innerHTML = "OK";

  var cancel = document.createElement("div");
  cancel.innerHTML = "Cancel";

  foot.appendChild(ok);
  foot.appendChild(cancel);
  obj.appendChild(body);
  obj.appendChild(foot);

  document.getElementsByTagName("body")[0].appendChild(obj);

  ok.onclick = function(){
    return true;
  }

  cancel.onclick = function(){
    return false;
  }
}
</code>```

or

```<code>returnValue = -1;
ok.onclick = function(){
  returnValue = true;
}

canacel.onclick = function(){
  returnValue = false;
}

while(true){
  if(returnValue !== -1) break;
}

return returnValue;
</code>```

If this custom confirm function must get 1 parameter like original confirm function.

How can make the custom confirm function?

答:
like my case i used promise to solve the delete confirmation problem, here is the code

```<code>function deleteBook(id, elm) {
const container_alert = document.querySelector('.container-alert')

alertMsg('Anda yakin ingin menghapus?').then(() => {
        // console.log('i love you');
        let index = books.findIndex(book => book.id == id);
        books.splice(index, 1)
        updateDataToStorage();
        elm.parentNode.parentNode.remove()

        container_alert.classList.add('hidden')
}).catch(() => {
    container_alert.classList.add('hidden')
})
</code>```

}

and my alert function code is as follows

```<code>function alertMsg(msg) {
const container_alert = document.querySelector('.container-alert')
const btn_yes = document.querySelector('.action-alert .yes')
const btn_cancel = document.querySelector('.action-alert .cancel')

container_alert.classList.remove('hidden')

return new Promise((resolve, reject) => {

    btn_yes.addEventListener('click', function(){
        resolve()
    })

    btn_cancel.addEventListener('click', function(){
        reject()
    })
})
</code>```

}

Title: How to make function like confirm

Body:
I want to make custom confirm function.

so, I make a code like :

function confirm(msg){
  var obj = document.createElement("div");
  var body = document.createElement("div");
  body.innerHTML = msg;

  var foot = document.createElement("div");

  var ok = document.createElement("div");
  ok.innerHTML = "OK";

  var cancel = document.createElement("div");
  cancel.innerHTML = "Cancel";

  foot.appendChild(ok);
  foot.appendChild(cancel);
  obj.appendChild(body);
  obj.appendChild(foot);

  document.getElementsByTagName("body")[0].appendChild(obj);

  ok.onclick = function(){
    return true;
  }

  cancel.onclick = function(){
    return false;
  }
}

or

returnValue = -1;
ok.onclick = function(){
  returnValue = true;
}

canacel.onclick = function(){
  returnValue = false;
}

while(true){
  if(returnValue !== -1) break;
}

return returnValue;

If this custom confirm function must get 1 parameter like original confirm function.

How can make the custom confirm function?

Body:
like my case i used promise to solve the delete confirmation problem, here is the code

function deleteBook(id, elm) {
const container_alert = document.querySelector('.container-alert')

alertMsg('Anda yakin ingin menghapus?').then(() => {
        // console.log('i love you');
        let index = books.findIndex(book => book.id == id);
        books.splice(index, 1)
        updateDataToStorage();
        elm.parentNode.parentNode.remove()

        container_alert.classList.add('hidden')
}).catch(() => {
    container_alert.classList.add('hidden')
})

}

and my alert function code is as follows

function alertMsg(msg) {
const container_alert = document.querySelector('.container-alert')
const btn_yes = document.querySelector('.action-alert .yes')
const btn_cancel = document.querySelector('.action-alert .cancel')

container_alert.classList.remove('hidden')

return new Promise((resolve, reject) => {

    btn_yes.addEventListener('click', function(){
        resolve()
    })

    btn_cancel.addEventListener('click', function(){
        reject()
    })
})

}


答:
I have created a small stackblitz for this. You can see date being formatted 4 different ways here:

Plain old javascript date

Formatted Javascript Date

Using Angular Pipe in HTML file

Using formateDate() function in component.ts file.

Please refer to this link: https://stackblitz.com/edit/angular-cue9h6?file=src%2Fapp%2Fapp.component.html

Title: show date in correct format angular

Body: I am making an application in which I want user to submit date date is getting stored in database in this format 2003-06-01T00:00:00.000+00:00 I want to display it as 01/06/2003 or 1st June 2003 can any body help me how can I do this?


问:
Python Selenium - open more Chrome apps
I'm using Selenium to automate certain stuff in Chrome and I know how to open multiple tabs, but is it possible to open Chrome itself multiple times?

Right now, when I want to open a new Chrome app the old one closes. I want it to stay open.

答:
every time you want to open a new Chrome Browser you have to create a new instance of the webdriver.

from time import sleep
from selenium import webdriver

fist_driver = webdriver.Chrome(executable_path="/path/to/chromedriver")
fist_driver.get("https://google.com")
second_driver = webdriver.Chrome(executable_path="/path/to/chromedriver")
second_driver.get("https://ifconfig.me")
sleep(5)
# using for loop
for _ in range(2): # How much browser you want to open
    driver = webdriver.Chrome(executable_path="/path/to/driver")
    driver.get("https://google.com")
sleep(5)
```

Title: Python Selenium - open more Chrome apps


问:
Pipeline design
I have got the following question about the pipeline design..

Can you please help me understand what we should be doing inside the request pipeline and response pipeline?

Let's say.. I am designing a proxy service that calls 2 separate business services and sends the response to the caller..
The proxy service will have assign, service callout, routing and reply action.  I can do everything inside the request pipeline and I don't understand the purpose of the response pipeline.

Can anyone help me understand what we should be doing inside the response pipeline?
Thank you

答:
A typical scenario in an OSB pipeline would be to validate, transform and enrich the request in the Request Pipeline, Route to a business service (which appears after the pipeline pair), then validate, transform and enrich the response in the Response Pipeline.  In this case in your pipeline, after the Pipeline Pair node, you will have a Route node.

Often people will use a service callout instead of a Route node.  In that case, you may not have anything (like a Route node) appearing after your pipeline pair and you can do everything in the Request pipeline.

You should understand the difference between a Route node and a Service Callout.  Routing to a business service uses non blocking IO compared to a Service Callout which will block a thread, so using a Route is the much more scalable option.

Title: Pipeline design


问:
Merge specifications of different types in Criteria Query Specifications
I'm having an Activity entity which is in @ManyToOne relationship with Event entity and their corresponding metamodels - Activity_ and Event_ were generated by JPA model generator.

I've created specialized classes ActivitySpecifications and EventSpecifications. Those classes contain only static methods whose return Specification. For example:

```<code>public interface EventSpecifications {

   static Specification<Event> newerThan(LocalDateTime date) {
       return (root, cq, cb) -> cb.gt(Event_.date, date);
   }

  ...
}
</code>```

so when I want to build query matching multiple specifications, I can execute following statement using findAll on JpaSpecificationExecutor<Event> repository.

```<code>EventSpecifications.newerThan(date).and(EventSpecifications.somethingElse())
</code>```

and ActivitySpecifications example:

```<code>static Specification<Activity> forActivityStatus(int status) { ... }
</code>```

How do I use EventSpecifications from ActivitySpecifications ? I mean like merge specifications of different type. I'm sorry, but I don't even know how to ask it properly, but theres simple example:

I want to select all activities with status = :status and where activity.event.date is greater than :date

```<code>static Specification<Activity> forStatusAndNewerThan(int status, LocalDateTime date) {
    return forActivityStatus(status)
         .and((root, cq, cb) -> root.get(Activity_.event) ....
         // use EventSpecifications.newerThan(date) somehow up there
}
</code>```

Is something like this possible?

The closest thing that comes to my mind is using the following:

```<code>return forActivityStatus(status)
             .and((root, cq, cb) -> cb.isTrue(EventSpecifications.newerThan(date).toPredicate(???, cq, cb));
</code>```

where ??? requires Root<Event>, but I can only get Path<Event> using root.get(Activity_.event).

答:
Consider the following :

```<code>ClassA {
 id;
}

ClassB {
 foreignId; //id of A
}
</code>```

For combining Specification<ClassA> specA, Specification<ClassB> specB

```<code>specB = specB.and(combineSpecs(specA);

private static Specification<ClassB> combineSpecs(Specification<ClassA> specA) {
   return (root_b,query,builder) {
     Subquery<ClassA> sub = query.subquery(ClassA.class);
     Root<ClassA> root_a = sub.from(ClassA.class);
     Predicate p1 = specA.toPredicate(root_a,query,builder);
     Predicate p2 = builder.equal(root_a.get("id"),root_b.get("foreignId"));
     Predicate predicate = builder.and(p1,p2);
     sub.select(root_a).where(predicate);
     return builder.exists(sub);
   };
}
</code>```

Body:
I'm having an Activity entity which is in @ManyToOne relationship with Event entity and their corresponding metamodels - Activity_ and Event_ were generated by JPA model generator.

I've created specialized classes ActivitySpecifications and EventSpecifications. Those classes contain only static methods whose return Specification. For example:

public interface EventSpecifications {

   static Specification<Event> newerThan(LocalDateTime date) {
       return (root, cq, cb) -> cb.gt(Event_.date, date);
   }

  ...
}

so when I want to build query matching multiple specifications, I can execute following statement using findAll on JpaSpecificationExecutor<Event> repository.

EventSpecifications.newerThan(date).and(EventSpecifications.somethingElse())

and ActivitySpecifications example:

static Specification<Activity> forActivityStatus(int status) { ... }

How do I use EventSpecifications from ActivitySpecifications ? I mean like merge specifications of different type. I'm sorry, but I don't even know how to ask it properly, but theres simple example:

I want to select all activities with status = :status and where activity.event.date is greater than :date

static Specification<Activity> forStatusAndNewerThan(int status, LocalDateTime date) {
    return forActivityStatus(status)
         .and((root, cq, cb) -> root.get(Activity_.event) ....
         // use EventSpecifications.newerThan(date) somehow up there
}

Is something like this possible?

The closest thing that comes to my mind is using the following:

return forActivityStatus(status)
             .and((root, cq, cb) -> cb.isTrue(EventSpecifications.newerThan(date).toPredicate(???, cq, cb));

where ??? requires Root<Event>, but I can only get Path<Event> using root.get(Activity_.event).

Body:
Consider the following :

ClassA {
 id;
}

ClassB {
 foreignId; //id of A
}

For combining Specification<ClassA> specA, Specification<ClassB> specB

specB = specB.and(combineSpecs(specA);

private static Specification<ClassB> combineSpecs(Specification<ClassA> specA) {
   return (root_b,query,builder) {
     Subquery<ClassA> sub = query.subquery(ClassA.class);
     Root<ClassA> root_a = sub.from(ClassA.class);
     Predicate p1 = specA.toPredicate(root_a,query,builder);
     Predicate p2 = builder.equal(root_a.get("id"),root_b.get("foreignId"));
     Predicate predicate = builder.and(p1,p2);
     sub.select(root_a).where(predicate);
     return builder.exists(sub);
   };
}


问:
Left Join two tables & group by a column into an array
Let's assume we have two tables:
websites

id
label

1
my.website.com

2
new.app.gov.uk

And domains:

id
websiteId
domain

1
1
domain1.info

2
1
domain2.io

Can I left join them so I can get something like:

id
label
domains

1
my.website.com
[domain1.info, domain2.io]

2
new.app.gov.uk
[]

答:
The STRING_AGG() is an aggregate function that concatenates rows of strings into a single string, separated by a specified separator. It does not add the separator at the end of the result string.

Use this snippet for MySql:

```<code>SELECT t1.id,t1.label,IFNULL(CONCAT('[',GROUP_CONCAT(domain),']'),'[]')  as domains
 FROM websites t1
 left join domains t2
 on t1.id=t2.websiteId
 group by t1.id,t1.label
</code>```

Output:

```<code>id  label           domains
1   my.website.com  [domain1.info,domain2.io]
2   new.app.gov.uk  []
</code>```

Use this snippet for SQL-Server :

```<code>SELECT t1.id,t1.label,isnull('['+STRING_AGG(domain,',')+']','[]')
  FROM websites t1
  left join
  domains t2
  on t1.id=t2.websiteId
  group by t1.id,t1.label
</code>```

Output:

```<code>id  label           domains
1   my.website.com  [domain1.info,domain2.io]
2   new.app.gov.uk  []
</code>```

Body:
The STRING_AGG() is an aggregate function that concatenates rows of strings into a single string, separated by a specified separator. It does not add the separator at the end of the result string.

Use this snippet for MySql:

SELECT t1.id,t1.label,IFNULL(CONCAT('[',GROUP_CONCAT(domain),']'),'[]')  as domains
 FROM websites t1
 left join domains t2
 on t1.id=t2.websiteId
 group by t1.id,t1.label

Output:

id  label           domains
1   my.website.com  [domain1.info,domain2.io]
2   new.app.gov.uk  []

Use this snippet for SQL-Server :

SELECT t1.id,t1.label,isnull('['+STRING_AGG(domain,',')+']','[]')
  FROM websites t1
  left join
  domains t2
  on t1.id=t2.websiteId
  group by t1.id,t1.label

Output:

id  label           domains
1   my.website.com  [domain1.info,domain2.io]
2   new.app.gov.uk  []


问:
ASP.NET GridView sorting on a calculated field
I have a DataBound GridView.  However I have one column where the value comes from a calculation in the code behind - it is displayed within a TemplateField.

How can a sort my grid based on this calculated value ?

答: Another solution is to consider is adding calculated column to the database table itself.  This has the benefit of returning the calculated column in the same SQL expression that loads the rest of the row, but unfortunately does require changing the database schema.</p>

OwnerDisplayName: Tom Carter

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Frank Schwieterman

LastEditorDisplayName: Frank Schwieterman


问:
Using text/event-stream in Intellij HTTP Client
I have Spring based Java application with a REST controller which returns Project-Reactor's Flux type.
The MediaType this GET endpoint returns is TEXT_EVENT_STREAM_VALUE.

To be clearer on the matter, the endpoint looks a little as follows, omitting the actual operation to return as it's not important:

@GetMapping(value = "/sample", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Sample> getSampleFlux() {
    return /* A Flux containing Sample */
}
```

<p>This bit of code works, as when I call it from my code or through for example Chrome using the endpoint, the results are streamed through as desired.</p>

<p>However, I wanted to test this behavior with Intellij's HTTP Client.
To this end, I created the following operation in a <code>*.http</code> file in my project:</p>

```GET localhost:8080/sample
Accept: text/event-stream
###
```

Running it works from within Intellij, but nothing is returned, ever.

Can anybody tell me what I am missing here?
I am likely wrongfully using the HTTP Client, but I can't find any clear samples from other people trying to do something similar.

答:
Apparently, it was fixed in 2021.3:
https://youtrack.jetbrains.com/issue/IDEA-239328</p>

Body:
I have Spring based Java application with a REST controller which returns Project-Reactor's Flux type.
The MediaType this GET endpoint returns is TEXT_EVENT_STREAM_VALUE.

To be clearer on the matter, the endpoint looks a little as follows, omitting the actual operation to return as it's not important:

@GetMapping(value = "/sample", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Sample> getSampleFlux() {
    return /* A Flux containing Sample */
}

This bit of code works, as when I call it from my code or through for example Chrome using the endpoint, the results are streamed through as desired.

However, I wanted to test this behavior with Intellij's HTTP Client.
To this end, I created the following operation in a *.http file in my project:

GET localhost:8080/sample
Accept: text/event-stream
###

Running it works from within Intellij, but nothing is returned, ever.

Can anybody tell me what I am missing here?
I am likely wrongfully using the HTTP Client, but I can't find any clear samples from other people trying to do something similar.


问:
How can i dynamically (in a loop) show images in google colab?
I have been trying to use pyplot/matplotlib to show images as they change in a loop, but i haven't been able to get anything working. I am basically unable to update the image being shown. here is the code to replicate the problem:</p>

```<code>f = plt.figure(1)
ax = plt.gca()
show_obj= ax.imshow(np.random.randn(28,28))
for i in range(10):
  print(i)
  # None of these 3 options work
  if True:
    # the image does not update
    show_obj.set_data(np.random.randn(28,28))
    f.canvas.draw()
  if False:
    # image does not update
    ax.clear()
    ax.imshow(np.random.rand(28,28))
    pass
  if False:
    # starts drawing new axes
    f = plt.figure(1)
    ax = plt.gca()
    ax.imshow(np.random.rand(28,28))
  plt.show()
</code>```

答:
my contribution:

```<code>import time #optional, just for demo
from matplotlib import pyplot as plt
from IPython.display import clear_output
from cv2 import imread #Hack
from google.colab.patches import cv2_imshow #Hack

#Initializations
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
fig = ax1.get_figure()
path = 'file.png' #your drive temporal file path
line1, = ax1.plot([],[])
line2, = ax2.plot([],[])

#update as many times you wish
line1.set_data([1,2,3,4],[0,8,2,4])
line2.set_data([1,2,3,4],[0,-8,-2,-4])

#Animation purposes
clear_output()
fig.savefig(path, format='png') #Hack
img = imread(path)
cv2_imshow(img)
time.sleep(20)     #demo: it show the img even when halted
</code>```

Explanation:

The reason that you can't update your images is because google.colab writes a fixed temporal file.

Sol. write your own image and upload it by your own.

Body:
I have been trying to use pyplot/matplotlib to show images as they change in a loop, but i haven't been able to get anything working. I am basically unable to update the image being shown. here is the code to replicate the problem:

f = plt.figure(1)
ax = plt.gca()
show_obj= ax.imshow(np.random.randn(28,28))
for i in range(10):
  print(i)
  # None of these 3 options work
  if True:
    # the image does not update
    show_obj.set_data(np.random.randn(28,28))
    f.canvas.draw()
  if False:
    # image does not update
    ax.clear()
    ax.imshow(np.random.rand(28,28))
    pass
  if False:
    # starts drawing new axes
    f = plt.figure(1)
    ax = plt.gca()
    ax.imshow(np.random.rand(28,28))
  plt.show()

Body:
my contribution:

import time #optional, just for demo
from matplotlib import pyplot as plt
from IPython.display import clear_output
from cv2 import imread #Hack
from google.colab.patches import cv2_imshow #Hack

#Initializations
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
fig = ax1.get_figure()
path = 'file.png' #your drive temporal file path
line1, = ax1.plot([],[])
line2, = ax2.plot([],[])

#update as many times you wish
line1.set_data([1,2,3,4],[0,8,2,4])
line2.set_data([1,2,3,4],[0,-8,-2,-4])

#Animation purposes
clear_output()
fig.savefig(path, format='png') #Hack
img = imread(path)
cv2_imshow(img)
time.sleep(20)     #demo: it show the img even when halted

Explanation:

The reason that you can't update your images is because google.colab writes a fixed temporal file.

Sol. write your own image and upload it by your own.


问:
i want to change my API response to become array of array object in laravel
i have a problem for the response, i want to change the response API because i need for my mobile APP, the feature have filter object based on date. So i hope you all can help me to solve the problem

i wanna change the response for my API

before:

```<code>{
    "tasks": [
        {
            "id": 7,
            "user_id": 1,
            "title": "gh",
            "date": "2022-02-10 13:05:00",
            "deskripsi": "gfh",
            "created_at": "2022-02-09T06:05:56.000000Z",
            "updated_at": "2022-02-09T06:05:56.000000Z"
        },
        {
            "id": 5,
            "user_id": 1,
            "title": "ghf",
            "date": "2022-02-17 16:05:00",
            "deskripsi": "fghf",
            "created_at": "2022-02-09T06:05:12.000000Z",
            "updated_at": "2022-02-09T06:05:12.000000Z"
        },
        {
            "id": 6,
            "user_id": 1,
            "title": "fgh",
            "date": "2022-02-17 18:05:00",
            "deskripsi": "gh",
            "created_at": "2022-02-09T06:05:40.000000Z",
            "updated_at": "2022-02-09T06:05:40.000000Z"
        }
    ]
}
</code>```

here is the code for the response API above

```<code>return response([
            'tasks' => Task::where('user_id', auth()->user()->id)->where('date','>',NOW())->orderBy('date','asc')->get(),
        ],200);
</code>```

and i want to change it my response API into this response

```<code>{
    "tasks": [
        {
            "date": "2022-02-10",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               },
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 15:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
        {
            "date": "2022-02-12",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-12 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
    ]
}
</code>```

答:
Do groupBy on the resulting Collection from the query (see docs: https://laravel.com/docs/9.x/collections#method-groupby)

For example, you could do:

```<code>$tasksGroupedByDate = Task::where(.......)
    ->get()
    ->groupBy(fn (Task $task) => $task->date->format('Y-m-d'));
</code>```

(Note: above uses PHP 7.4 arrow functions. Also, add a date cast on the date column in your Task model to be able to use ->format( directly on the date field)

The above code results to:

```<code>{
  '2022-01-01' => [
    { Task object },
    { Task object },
    { Task object },
  ],
  '2022-01-02' => [
    { Task object },
    { Task object },
    { Task object },
  ],
}
</code>```

(used Task object for brevity, but that will be ['id' => 1, 'title' => 'Task name', .....])

To morph that to the structure you want, you can use map and then values to remove the keys and turn it back to an ordered array:

```<code>$tasksGroupedByDate->map(fn ($tasksInGroup, $date) => [
    'date' => $date,
    'task' => $tasksInGroup
])->values();
</code>```

If you want to combine everything into one method chain:

```<code>return [
    'tasks' => Task::where(......)
        ->get()
        ->groupBy(fn (Task $task) => $task->date->format('Y-m-d'))
        ->map(fn ($tasksInGroup, $date) => [
            'date' => $date,
            'task' => $tasksInGroup
        ])
        ->values(),
];
</code>```

Body:
i have a problem for the response, i want to change the response API because i need for my mobile APP, the feature have filter object based on date. So i hope you all can help me to solve the problem

i wanna change the response for my API

before:

{
    "tasks": [
        {
            "id": 7,
            "user_id": 1,
            "title": "gh",
            "date": "2022-02-10 13:05:00",
            "deskripsi": "gfh",
            "created_at": "2022-02-09T06:05:56.000000Z",
            "updated_at": "2022-02-09T06:05:56.000000Z"
        },
        {
            "id": 5,
            "user_id": 1,
            "title": "ghf",
            "date": "2022-02-17 16:05:00",
            "deskripsi": "fghf",
            "created_at": "2022-02-09T06:05:12.000000Z",
            "updated_at": "2022-02-09T06:05:12.000000Z"
        },
        {
            "id": 6,
            "user_id": 1,
            "title": "fgh",
            "date": "2022-02-17 18:05:00",
            "deskripsi": "gh",
            "created_at": "2022-02-09T06:05:40.000000Z",
            "updated_at": "2022-02-09T06:05:40.000000Z"
        }
    ]
}

here is the code for the response API above

return response([
            'tasks' => Task::where('user_id', auth()->user()->id)->where('date','>',NOW())->orderBy('date','asc')->get(),
        ],200);

and i want to change it my response API into this response

{
    "tasks": [
        {
            "date": "2022-02-10",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               },
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 15:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
        {
            "date": "2022-02-12",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-12 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
    ]
}

Body:
Do groupBy on the resulting Collection from the query (see docs: https://laravel.com/docs/9.x/collections#method-groupby)

For example, you could do:

$tasksGroupedByDate = Task::where(.......)
    ->get()
    ->groupBy(fn (Task $task) => $task->date->format('Y-m-d'));

(Note: above uses PHP 7.4 arrow functions. Also, add a date cast on the date column in your Task model to be able to use ->format( directly on the date field)

The above code results to:

{
  '2022-01-01' => [
    { Task object },
    { Task object },
    { Task object },
  ],
  '2022-01-02' => [
    { Task object },
    { Task object },
    { Task object },
  ],
}

(used Task object for brevity, but that will be ['id' => 1, 'title' => 'Task name', .....])

To morph that to the structure you want, you can use map and then values to remove the keys and turn it back to an ordered array:

$tasksGroupedByDate->map(fn ($tasksInGroup, $date) => [
    'date' => $date,
    'task' => $tasksInGroup
])->values();

If you want to combine everything into one method chain:

return [
    'tasks' => Task::where(......)
        ->get()
        ->groupBy(fn (Task $task) => $task->date->format('Y-m-d'))
        ->map(fn ($tasksInGroup, $date) => [
            'date' => $date,
            'task' => $tasksInGroup
        ])
        ->values(),
];


问:
Do we have to manually configure api endpoint in openapi 2.0?
I am new to Java. I am working on a legacy app that uses openapi 2.0 for swagger. I added a new controller with 2 api endpoints. Those 2 api endpoints are not showing up in swagger-ui. I see the entries for existing endpoints in openapi.json. I am trying my best not to manually edit openapi.json. Do we have to manually configure api endpoints in openapi.json version2.0 for it to show up in swagger ui? We use gradle to build our project. I re-built the project, but no luck.

Most of the tutorial seems to be for openapi 3.0, not 2.0. openapi 3.0 seems to auto generate all the endpoints in swagger-ui, but not sure if 2.0 does that.

答:
Most of the tutorial seems to be for openapi 3.0, not 2.0

Yes, 3.x is the latest version. The versions from 3.0 onwards are called OpenAPI. The ones prior to 3.0 are called Swagger for historical reasons.

openapi 3.0 seems to auto generate all the endpoints in swagger-ui, but not sure if 2.0 does that.

Your problem is not related to the version of your specification.
You always want your API specification to be in sync with your implementation. Therefore you need to decide what's your source of thruth, your API spec or your code.
So choose an approach:

Either you generate code from your specification, for example by following this tutorial. From the generated code, you can have the Swagger UI documentation auto-generated as well. There are several code generators for OpenAPI, you have to choose one.

Or you manually write your code, based on your spec of course. Based on annotations, you can have the documentation created. That approach is explained here, for example.

Based on your statements

I added a new controller with 2 api endpoints. [...] I am trying my best not to manually edit openapi.json

I assume that you go with the second approach. So you best look into how your documentation gets auto-generated at the moment, to ensure your new endpoints are also shown. Further judgement of what is wrong is not possible based on what you have asked.


问:
Nuget Failed to install package "RazorGenerator.Mvc" with specific version 2.3.12
I had this error while trying to install Nuget package "RazorGenerator.Mvc" with the specific version 2.3.12 using this command:

```<code>Install-Package RazorGenerator.Mvc -Version 2.3.12
</code>```

However, when running the command, Visual Studio returned this error:

```<code>Failed to add reference. The package 'RazorGenerator.Mvc' tried to add a framework reference to 'System.Web.Mvc' which was not found in the GAC. This is possibly a bug in the package. Please contact the package owners for assistance. Cannot find assembly 'System.Web.Mvc'.
</code>```

My project already has the package "Microsoft.AspNet.Mvc" installed with the latest version, I have also tried installing this package with version 3.0.50813.1 but both attempts didn't resolve the error.
Do you guys have any idea how to fix this issue? The specific version of the package "RazorGenerator.Mvc" has to be 2.3.12.

答:
For anyone wondering, I have resolved this error. Somehow I couldn't use Nuget package manager to install "RazorGenerator.Mvc" to the correct version  "2.3.12" - the installed RazorGenerator package was of a different version, I couldn't uninstall it nor update to 2.3.12 because of dependencies from other packages. However, I have resolved the issue by updating this line in
"packages.config" and rebuild the solution.

```<code><package id="RazorGenerator.Mvc" version="2.3.12" targetFramework="net48" />
</code>```

After this, the version of "RazorGenerator.Mvc.dll" in my bin folder, and the version in Nuget was "2.3.12".

Body:
I had this error while trying to install Nuget package "RazorGenerator.Mvc" with the specific version 2.3.12 using this command:

Install-Package RazorGenerator.Mvc -Version 2.3.12

However, when running the command, Visual Studio returned this error:

Failed to add reference. The package 'RazorGenerator.Mvc' tried to add a framework reference to 'System.Web.Mvc' which was not found in the GAC. This is possibly a bug in the package. Please contact the package owners for assistance. Cannot find assembly 'System.Web.Mvc'.

My project already has the package "Microsoft.AspNet.Mvc" installed with the latest version, I have also tried installing this package with version 3.0.50813.1 but both attempts didn't resolve the error.
Do you guys have any idea how to fix this issue? The specific version of the package "RazorGenerator.Mvc" has to be 2.3.12.

Body:
For anyone wondering, I have resolved this error. Somehow I couldn't use Nuget package manager to install "RazorGenerator.Mvc" to the correct version  "2.3.12" - the installed RazorGenerator package was of a different version, I couldn't uninstall it nor update to 2.3.12 because of dependencies from other packages. However, I have resolved the issue by updating this line in
"packages.config" and rebuild the solution.

<package id="RazorGenerator.Mvc" version="2.3.12" targetFramework="net48" />

After this, the version of "RazorGenerator.Mvc.dll" in my bin folder, and the version in Nuget was "2.3.12".


问:
How to catch an empty query exception with Django
I'm after an elegant and efficient approach.

I am doing a query to a model that has a chance to return an empty queryset and if that happens I must do a query with other parameters that will work for sure.

It would be really nice if I could put the query inside a simple try except but it doesn't catch like so.

What's holding me back from using .exists() is that it feels like I'm doing the query to the database two times. One to check the existence and the other to really get the object.

答:
To avoid double-query you can do:

```<code>objects = models.MyModel.objects.filter(key=value)

if not objects:
    objects = models.MyModel.objects.filter(another_key=another_value)
</code>```

In this case bool(objects) does not evaluate query for existance unlike using exists or len()

Per documentation:

Additionally, if a some_queryset has not yet been evaluated, but you know that it will be at some point, then using some_queryset.exists() will do more overall work (one query for the existence check plus an extra one to later retrieve the results) than using bool(some_queryset), which retrieves the results and then checks if any were returned.

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.exists

Body:
To avoid double-query you can do:

objects = models.MyModel.objects.filter(key=value)

if not objects:
    objects = models.MyModel.objects.filter(another_key=another_value)

In this case bool(objects) does not evaluate query for existance unlike using exists or len()

Per documentation:

Additionally, if a some_queryset has not yet been evaluated, but you know that it will be at some point, then using some_queryset.exists() will do more overall work (one query for the existence check plus an extra one to later retrieve the results) than using bool(some_queryset), which retrieves the results and then checks if any were returned.

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.exists


问:
Custom "Basic" Authentication for my WCF services. REST and RIA. Possible?
My server side contains WCF4 REST services and I'm going to add RIA services for my future SL4 application.  Currently I'm doing Basic authentication like this:

```<code>var auth = HttpContext.Current.Request.Headers.GetValues("Authorization");
</code>```

And so on.. You get the idea.. I call this on every request. If header not present or I can't validate UN/Password - I do this:

```<code>outgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Secure Area\"");
</code>```

That got me by so far but I'm refactoring my server side. Implementing IoC for linked services. Created custom ServiceHost, ServiceHostFactory, InstanceProvider and all is well.

Now I need to figure how to properly handle authentication and authorization with WCF so I don't have to manually inspect headers. I do have my custom MembershipProvider so there have to be some method that get's UN/PW to process.

Any pointers? I looked at http://www.codeproject.com/KB/WCF/BasicAuthWCFRest.aspx but it uses RequestInterceptor and it is not available in WCF4. I found ServiceAuthenticationManager and ServiceAuthorizationManager but there is no samples available on how to code and wire those..

Can anybody suggest which way I should go?

答: Try to use this custom HTTP module. It will add new authentication mode to IIS and it will allow you using custom credentials validation.</p>

Body:
My server side contains WCF4 REST services and I'm going to add RIA services for my future SL4 application.  Currently I'm doing Basic authentication like this:

var auth = HttpContext.Current.Request.Headers.GetValues("Authorization");

And so on.. You get the idea.. I call this on every request. If header not present or I can't validate UN/Password - I do this:

outgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Secure Area\"");

That got me by so far but I'm refactoring my server side. Implementing IoC for linked services. Created custom ServiceHost, ServiceHostFactory, InstanceProvider and all is well.

Now I need to figure how to properly handle authentication and authorization with WCF so I don't have to manually inspect headers. I do have my custom MembershipProvider so there have to be some method that get's UN/PW to process.

Any pointers? I looked at http://www.codeproject.com/KB/WCF/BasicAuthWCFRest.aspx but it uses RequestInterceptor and it is not available in WCF4. I found ServiceAuthenticationManager and ServiceAuthorizationManager but there is no samples available on how to code and wire those..

Can anybody suggest which way I should go?


问:
Created an image gallery with Bootstrap Grid & Flexbox but the some images are not occupying 100% of the flex container
I'm new to web development and I'm trying to create a responsive image gallery with Bootstrap Grid and flexbox but for some reason some of the images are not taking the full height of flex container.

What it looks like right now

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />

          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html></code>```

What should I do so that all images are of the same height, alternatively occupy full height of the flex container?

答:
Add height:100%on a tag

```<code>.tile a{
 height:100%;
}
</code>```

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}
.tile a{
 height:100%;
}
.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />

          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">

              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />

          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html></code>```

Body:
I'm new to web development and I'm trying to create a responsive image gallery with Bootstrap Grid and flexbox but for some reason some of the images are not taking the full height of flex container.

What it looks like right now

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>

What should I do so that all images are of the same height, alternatively occupy full height of the flex container?

Body:
Add height:100%on a tag

.tile a{
 height:100%;
}

* {
  margin: 0px;
  padding: 0px;
}
html,
body {
  position: relative;
}

body {
  overflow-y: auto;
  min-height: 100vh;
}

.container {
  margin-top: 20px;
}

.tile {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}
.tile a{
 height:100%;
}
.tile img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s;
}
.tile img:hover {
  filter: brightness(50%);
  transform: scale(1.1);
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                class="img-one"
                src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg"
                alt=""
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2013/07/02/22/20/bouquet-142876_960_720.jpg"
                alt=""
                class="img-two"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2013/10/02/23/03/mountains-190055_960_720.jpg"
                alt=""
                class="img-three"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/06/19/20/13/sunset-815270_960_720.jpg"
                alt=""
                class="img-four"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2014/01/22/19/44/flower-field-250016_960_720.jpg"
                alt=""
                class="img-five"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/rose-729509_960_720.jpg"
                alt=""
                class="img-six"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg"
                alt=""
                class="img-seven"
              />
            </a>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-lg-3 mb-4">
          <div class="tile">
            <a class="picture" href="#">
              <img
                src="https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"
                alt=""
                class="img-eight"
              />
            </a>
          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>


问:
PhpStorm/WebStorm ESLint autofix TypeScript
I´m working on a Vue3 TypeScript application.

I have activated the checkbox in PhpStorm's ESLint settings to "Run 'eslint --fix' on save" but it does not work.

After a long search for that I only found a https://github.com/microsoft/vscode-eslint/issues/609#issuecomment-460554105 for Visual Studio Code

.eslintrc.js

module.exports = {
    root: true,
    parser: "vue-eslint-parser",
    parserOptions: {
        ecmaVersion: 2021,
        parser: "@typescript-eslint/parser",
        sourceType: "module"
    },
    plugins: [
        '@typescript-eslint',
    ],
    env: {
        node: true,
        es6: true,
    },
    extends: [
        "eslint:recommended",
        "plugin:vue/vue3-recommended",
        'plugin:@typescript-eslint/recommended',
        "prettier"
    ],
    rules: {
        // override/add rules settings here, such as:
        // 'vue/no-unused-vars': 'error'
    },
};
```

Hope someone can help me to get it working in PhpStorm.

答:
Ok, I found a Solution for this, the Problem was that the official by prettier provided eslint extension didn´t work, after isntalling eslint-plugin-prettier and changing my .eslintrc.js file to

module.exports = {
    root: true,
    parser: "vue-eslint-parser",
    parserOptions: {
        ecmaVersion: 2021,
        parser: "@typescript-eslint/parser",
        sourceType: "module",
    },
    plugins: ["@typescript-eslint", "prettier"],
    env: {
        node: true,
        es6: true,
    },
    extends: [
        "eslint:recommended",
        "plugin:vue/vue3-recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:prettier/recommended",
    ],
    rules: {
        // override/add rules settings here, such as:
        // 'vue/no-unused-vars': 'error'
    },
};

```

atleast it works now.

Body:
I´m working on a Vue3 TypeScript application.

I have activated the checkbox in PhpStorm's ESLint settings to "Run 'eslint --fix' on save" but it does not work.

After a long search for that I only found a https://github.com/microsoft/vscode-eslint/issues/609#issuecomment-460554105 for Visual Studio Code

.eslintrc.js

module.exports = {
    root: true,
    parser: "vue-eslint-parser",
    parserOptions: {
        ecmaVersion: 2021,
        parser: "@typescript-eslint/parser",
        sourceType: "module"
    },
    plugins: [
        '@typescript-eslint',
    ],
    env: {
        node: true,
        es6: true,
    },
    extends: [
        "eslint:recommended",
        "plugin:vue/vue3-recommended",
        'plugin:@typescript-eslint/recommended',
        "prettier"
    ],
    rules: {
        // override/add rules settings here, such as:
        // 'vue/no-unused-vars': 'error'
    },
};

Hope someone can help me to get it working in PhpStorm.

Body:
Ok, I found a Solution for this, the Problem was that the official by prettier provided eslint extension didn´t work, after isntalling eslint-plugin-prettier and changing my .eslintrc.js file to

module.exports = {
    root: true,
    parser: "vue-eslint-parser",
    parserOptions: {
        ecmaVersion: 2021,
        parser: "@typescript-eslint/parser",
        sourceType: "module",
    },
    plugins: ["@typescript-eslint", "prettier"],
    env: {
        node: true,
        es6: true,
    },
    extends: [
        "eslint:recommended",
        "plugin:vue/vue3-recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:prettier/recommended",
    ],
    rules: {
        // override/add rules settings here, such as:
        // 'vue/no-unused-vars': 'error'
    },
};

atleast it works now.


问:
Recyclerview onViewScrolled called multiple times
Currently working on recyclerview that refreshes every time I choose something.

Everytime I would set again the adapter after I selected a choice.

For example, if I choose Fruit, the recyclerview will change to fruits.

I would attach a new adapter to the recyclerview everytime.

The problem with this is whenever I check on onViewScrolled, it is getting called the same amount as I changed the recyclerview data.

My question is, why does this occurs ? Is it because the old adapter didn't detach ?

If yes, how do I detach it properly ?

答:
I think you have a problem with the recycler adapter class. For example, you change some data and scroll down. When your scroll is up and that shows your old data.

Add this code in the adapter class.

```<code> @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }
</code>```

Body:
I think you have a problem with the recycler adapter class. For example, you change some data and scroll down. When your scroll is up and that shows your old data.

Add this code in the adapter class.

 @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }