问:
React Swiper 6.8.4 only Shows Slides when resizing window or applying Filter
I am pretty new to coding and react and I am having an issue with Swiper 6.8.4 in my React app since i added a FilterMethod.
My idea was to have a Slider with some Projects/Images as Slides in it, and be able to filter these Slide by a multiple checkbox filter. So far everything is working fine. I am able to check multiple checkboxes and projects are filtered correctly, But i think there is a problem when initialising swiper: Every time i reload the page Swiper doesnt show any slides until i resize the page or check some filter checkboxes.

Here is my Code:
Please can somebody help me!

```<code>import React, { useState, Fragment, useEffect } from "react";
import allData from '../allData';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Autoplay,Navigation, Pagination, Controller, Thumbs } from 'swiper';
import 'swiper/swiper-bundle.css';
import './styles.css';

SwiperCore.use([Autoplay,Navigation, Pagination, Controller, Thumbs]);

const project = [
  { type: "Web" },
  { type: "3D" },
  { type: "Photography" },
  { type: "Print" },
  { type: "Practice" }

];

export default function App() {
  const [type, setType] = useState([]);
  const [filteredType, setFilteredType] = useState([]);

  const handleChange = e => {
    if (e.target.checked) {
      setType([...type, e.target.value]);
    } else {
      setType(type.filter(id => id !== e.target.value));
    }
  };

  useEffect(() => {
    if (type.length === 0) {
      setFilteredType(allData);
    } else {
      setFilteredType(
        allData.filter(project =>
          type.some(category => [project.type].flat().includes(category))
        )
      );
    }
  }, [type]);
  const [show, toggleShow] = React.useState(false);

  return (
    <div>

<Swiper

        slidesPerView={'auto'}
        onSlideChange={() => toggleShow(!true)}
        loop={false}
        centeredSlides={true}
        direction={'horizontal'}
        spaceBetween={100}
        slideToClickedSlide={true}
        pagination={{
          "type": "fraction"
        }}
        className="mySwiper">

      {filteredType.map((project, index) => (
        <SwiperSlide className="swiper-slide">
        <img className="img-slide" src={project.image} alt=""/>
        <div className="project-info">
        {show && <div className="info" key={project.id}>{project.info}</div>}

        <div className="text">{project.id} / {project.title}</div>
        </div>

        </SwiperSlide>
      ))}
      </Swiper>

      <div className="filterbox">
          {project.map(project => (
            <label className={`tag${project.type}`}>
              <input
                name="type"
                type="checkbox"
                key={project.id}
                value={project.type}
                onChange={handleChange}>
              </input>
              <span
                className="tags">{project.type}
              </span>
            </label>

          ))}
        </div>
        <button  className="info-button" onClick={() => toggleShow(!show)}>Info</button>

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

答:
This might help

onInit={() => if (typeof window !== 'undefined') window.dispatchEvent(new Event('resize'))}

Body:
I am pretty new to coding and react and I am having an issue with Swiper 6.8.4 in my React app since i added a FilterMethod.
My idea was to have a Slider with some Projects/Images as Slides in it, and be able to filter these Slide by a multiple checkbox filter. So far everything is working fine. I am able to check multiple checkboxes and projects are filtered correctly, But i think there is a problem when initialising swiper: Every time i reload the page Swiper doesnt show any slides until i resize the page or check some filter checkboxes.

Here is my Code:
Please can somebody help me!

import React, { useState, Fragment, useEffect } from "react";
import allData from '../allData';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Autoplay,Navigation, Pagination, Controller, Thumbs } from 'swiper';
import 'swiper/swiper-bundle.css';
import './styles.css';

SwiperCore.use([Autoplay,Navigation, Pagination, Controller, Thumbs]);

const project = [
  { type: "Web" },
  { type: "3D" },
  { type: "Photography" },
  { type: "Print" },
  { type: "Practice" }

];

export default function App() {
  const [type, setType] = useState([]);
  const [filteredType, setFilteredType] = useState([]);

  const handleChange = e => {
    if (e.target.checked) {
      setType([...type, e.target.value]);
    } else {
      setType(type.filter(id => id !== e.target.value));
    }
  };

  useEffect(() => {
    if (type.length === 0) {
      setFilteredType(allData);
    } else {
      setFilteredType(
        allData.filter(project =>
          type.some(category => [project.type].flat().includes(category))
        )
      );
    }
  }, [type]);
  const [show, toggleShow] = React.useState(false);

  return (

<Swiper

        slidesPerView={'auto'}
        onSlideChange={() => toggleShow(!true)}
        loop={false}
        centeredSlides={true}
        direction={'horizontal'}
        spaceBetween={100}
        slideToClickedSlide={true}
        pagination={{
          "type": "fraction"
        }}
        className="mySwiper">

      {filteredType.map((project, index) => (
        <SwiperSlide className="swiper-slide">

        {show &&
{project.info}
}

{project.id} / {project.title}

        </SwiperSlide>
      ))}
      </Swiper>

          {project.map(project => (
            <label className={`tag${project.type}`}>
              <input
                name="type"
                type="checkbox"
                key={project.id}
                value={project.type}
                onChange={handleChange}>
              </input>
              {project.type}

          ))}

        <button  className="info-button" onClick={() => toggleShow(!show)}>Info</button>

  );
};


来源: stackexchange

问:
control a daemon thread with routes in flask
How do you make two routes control a daemon thread in python

flask backend file

```<code>from flask import Flask
from time import time,sleep
from threading import Thread

app = Flask(__name__)

def intro():
    while True:
        sleep(3)
        print (f" Current time : {time()}")

@app.route('/startbot')
def start_bot():
    global bot_thread
    bot_thread = Thread(target=intro, daemon=True)
    bot_thread.start()
    return "bot started "

@app.route('/stopbot')
def stop_bot():
    bot_thread.join()
    return

if __name__ == "__main__":
    app.run()

</code>```

When trying to kill the thread the curl request in the terminal does not return back to the console and the thread keeps on printing data to the terminal

the idea I had was that I would declare the variable that holds the reference to the bot_thread and use the routes to control it

to test this I used curl http://localhost:port/startbot and curl http://localhost:port/stopbot

I can start the bot just fine but when I try to kill it, I get the following

```<code>NameError: name 'bot_thread' is not defined

</code>```

Any help and does and don'ts will be very appreciated

take into consideration that after killing the thread a user can create a new one and also be able to kill it

答:
Here is a Minimal Reproducible Example :

from threading import Thread

def intro():
    print("hello")

global bot_thread

def start_bot():
    bot_thread = Thread(target=intro, daemon=True)
    return

def stop_bot():
    if bot_thread:
        bot_thread.join()

if __name__ == "__main__":
    import time
    start_bot()  # simulating a request on it
    time.sleep(1)  # some time passes ...
    stop_bot()  # simulating a request on it
```
```Traceback (most recent call last):
  File "/home/stack_overflow/so71056246.py", line 25, in <module>
    stop_bot()  # simulating a request on it
  File "/home/stack_overflow/so71056246.py", line 17, in stop_bot
    if bot_thread:
NameError: name 'bot_thread' is not defined
```
<p>My IDE makes the error visually clear for me : the <code>bot_thread</code> is not used, because it is a local variable, not the <code>global</code> one, although they have the same name. This is a pitfall for Python programmers, see this question or this one for example.</p>
<p>So :</p>
<pre class="lang-py prettyprint-override"><code>def start_bot():
    global bot_thread
    bot_thread = Thread(target=intro, daemon=True)
    return
</code>```

but

```<code>Traceback (most recent call last):
  File "/home/stack_overflow/so71056246.py", line 26, in <module>
    stop_bot()  # simulating a request on it
  File "/home/stack_overflow/so71056246.py", line 19, in stop_bot
    bot_thread.join()
  File "/usr/lib/python3.9/threading.py", line 1048, in join
    raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
</code>```

Hence :

def start_bot():
    global bot_thread
    bot_thread = Thread(target=intro, daemon=True)
    bot_thread.start()
    return
```
<p>which finally gives :</p>
```hello
```
<hr />
<p><strong>EDIT</strong></p>
<blockquote>
<p>When trying to kill the thread the curl request in the terminal does not return back to the console and the thread keeps on printing data to the terminal</p>
</blockquote>
<p>@prometheus the <code>bot_thread</code> runs the <code>intro</code> function. Because it contains an infinite loop (<code>while True</code>) it will never reach the end of the function (implicit <code>return</code>) so the thread is never considered as finished. Because of that, when the main thread tries to <code>join</code> (wait until the thread finishes, then get the result), it waits endlessly because the bot thread is stuck in the loop.<br />
So you have to make it possible to exit the <code>while</code> loop. For example (like in the example I linked in a comment), by using another <code>global</code> variable, a flag, that gets set in the main thread (route <code>stop_bot</code>) and that is checked in the <code>intro</code> loop. Like so :</p>
<pre class="lang-py prettyprint-override"><code>from time import time, sleep
from threading import Thread

def intro():
    global the_bot_should_continue_running
    while the_bot_should_continue_running:
        print(time())
        sleep(1)

global bot_thread
global the_bot_should_continue_running

def start_bot():
    global bot_thread, the_bot_should_continue_running
    bot_thread = Thread(target=intro, daemon=True)
    the_bot_should_continue_running = True  # before the `start` !
    bot_thread.start()
    return

def stop_bot():
    if bot_thread:
        global the_bot_should_continue_running
        the_bot_should_continue_running = False
        bot_thread.join()

if __name__ == "__main__":
    start_bot()  # simulating a request on it
    sleep(5.5)  # some time passes ...
    stop_bot()  # simulating a request on it
</code>```

prints 6 times then exits.

ContentLicense: CC BY-SA 4.0

Body:
How do you make two routes control a daemon thread in python

flask backend file

from flask import Flask
from time import time,sleep
from threading import Thread

app = Flask(__name__)

def intro():
    while True:
        sleep(3)
        print (f" Current time : {time()}")

@app.route('/startbot')
def start_bot():
    global bot_thread
    bot_thread = Thread(target=intro, daemon=True)
    bot_thread.start()
    return "bot started "

@app.route('/stopbot')
def stop_bot():
    bot_thread.join()
    return

if __name__ == "__main__":
    app.run()

When trying to kill the thread the curl request in the terminal does not return back to the console and the thread keeps on printing data to the terminal

the idea I had was that I would declare the variable that holds the reference to the bot_thread and use the routes to control it

to test this I used curl http://localhost:port/startbot and curl http://localhost:port/stopbot

I can start the bot just fine but when I try to kill it, I get the following

NameError: name 'bot_thread' is not defined

Any help and does and don'ts will be very appreciated

take into consideration that after killing the thread a user can create a new one and also be able to kill it

Body:
Here is a Minimal Reproducible Example :

from threading import Thread

def intro():
    print("hello")

global bot_thread

def start_bot():
    bot_thread = Thread(target=intro, daemon=True)
    return

def stop_bot():
    if bot_thread:
        bot_thread.join()

if __name__ == "__main__":
    import time
    start_bot()  # simulating a request on it
    time.sleep(1)  # some time passes ...
    stop_bot()  # simulating a request on it

Traceback (most recent call last):
  File "/home/stack_overflow/so71056246.py", line 25, in <module>
    stop_bot()  # simulating a request on it
  File "/home/stack_overflow/so71056246.py", line 17, in stop_bot
    if bot_thread:
NameError: name 'bot_thread' is not defined

My IDE makes the error visually clear for me : the bot_thread is not used, because it is a local variable, not the global one, although they have the same name. This is a pitfall for Python programmers, see this question or this one for example.

So :

def start_bot():
    global bot_thread
    bot_thread = Thread(target=intro, daemon=True)
    return

but

Traceback (most recent call last):
  File "/home/stack_overflow/so71056246.py", line 26, in <module>
    stop_bot()  # simulating a request on it
  File "/home/stack_overflow/so71056246.py", line 19, in stop_bot
    bot_thread.join()
  File "/usr/lib/python3.9/threading.py", line 1048, in join
    raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started

Hence :

def start_bot():
    global bot_thread
    bot_thread = Thread(target=intro, daemon=True)
    bot_thread.start()
    return

which finally gives :

hello

EDIT

When trying to kill the thread the curl request in the terminal does not return back to the console and the thread keeps on printing data to the terminal

@prometheus the bot_thread runs the intro function. Because it contains an infinite loop (while True) it will never reach the end of the function (implicit return) so the thread is never considered as finished. Because of that, when the main thread tries to join (wait until the thread finishes, then get the result), it waits endlessly because the bot thread is stuck in the loop.

So you have to make it possible to exit the while loop. For example (like in the example I linked in a comment), by using another global variable, a flag, that gets set in the main thread (route stop_bot) and that is checked in the intro loop. Like so :

from time import time, sleep
from threading import Thread

def intro():
    global the_bot_should_continue_running
    while the_bot_should_continue_running:
        print(time())
        sleep(1)

global bot_thread
global the_bot_should_continue_running

def start_bot():
    global bot_thread, the_bot_should_continue_running
    bot_thread = Thread(target=intro, daemon=True)
    the_bot_should_continue_running = True  # before the `start` !
    bot_thread.start()
    return

def stop_bot():
    if bot_thread:
        global the_bot_should_continue_running
        the_bot_should_continue_running = False
        bot_thread.join()

if __name__ == "__main__":
    start_bot()  # simulating a request on it
    sleep(5.5)  # some time passes ...
    stop_bot()  # simulating a request on it

prints 6 times then exits.


问:
Godoc documentation not outputting lists
I have, throughout the project I'm responsible for testing and documenting, created documentation for the functions and methods, in the following format:

```<code>// CheckPermissionArray checks that values is an array that contains the `expectedValue`
//
// Parameters:
//
// - `values` : the array to check
// - `expectedValue` : the value to search for
//
// Returns:
//
// - an error iff `expectedValue` is not in `values`
</code>```

The boss and other programmers approve of this format, but the problem is that godoc doesn't recognize the list:

Is there a way to get the list to be recognized?

Visual Studio Code was, to a point, recognizing this documentation just fine, albeit a bit buggy.

答:
This might change in the future with "https://github.com/golang/go/issues/51082" (Feb. 2022)

March 2022: the proposal is accepted, and part of it is in Go 1.19 beta1 (June 2022).

This proposal improves support for headings, lists, and links in Go doc comments, while remaining backwards compatible with existing comments.

It includes a new package, go/doc/comment, exposing a parsed syntax tree for
doc comments, and it includes changes to go/printer and therefore gofmt
to format doc comments in a standard way.

For example, existing lists reformat from the display on the left to the one on the right:

June 2022: CL 415174 adds:

The proposed (#51082) new go doc comment additions supports lists, links, and doc links, but does not support links and doc links inside lists, so implements this.

This implements #53610

Example:

//  - Do this, or...
//  - See [RFC], or...
//
//    [RFC]: https://datatracker.ietf.org/doc/html/rfc2616
//  - Something else
```

Body:
I have, throughout the project I'm responsible for testing and documenting, created documentation for the functions and methods, in the following format:

// CheckPermissionArray checks that values is an array that contains the `expectedValue`
//
// Parameters:
//
// - `values` : the array to check
// - `expectedValue` : the value to search for
//
// Returns:
//
// - an error iff `expectedValue` is not in `values`

The boss and other programmers approve of this format, but the problem is that godoc doesn't recognize the list:

Is there a way to get the list to be recognized?

Visual Studio Code was, to a point, recognizing this documentation just fine, albeit a bit buggy.


问:
Different date formats in pandas dataframe
Below is my data frame -

```<code>date                                name
18-Sep-18                            bb
6-Aug-18                             vv
Kingdom on 2 January 2019            cc
Kingdom on 9 June 2021               aa
States on 10 September 2021          bb
States on 14 April 2021              mm
</code>```

I want my data frame -

```<code>date                                name
2018-09-18                            bb
2018-08-06                            vv
2019-01-02                            cc
2021-06-09                            aa
2021-09-10                            bb
2021-04-14                            mm

</code>```

I have done the following code -

```<code>df['date'] = pd.to_datetime(df['date']).dt.strftime('%m/%d/%Y')
</code>```

But it's not working

答:
You can clean up the data with a regex first (here removing all the non digits before the first digit):

```<code>df['date'] = pd.to_datetime(df['date'].str.replace('^\D+(?=\d)', ''))
</code>```

output (with an new column):

```<code>                          date name      date2
0                    18-Sep-18   bb 2018-09-18
1                     6-Aug-18   vv 2018-08-06
2    Kingdom on 2 January 2019   cc 2019-01-02
3       Kingdom on 9 June 2021   aa 2021-06-09
4  States on 10 September 2021   bb 2021-09-10
5      States on 14 April 2021   mm 2021-04-14
</code>```

Body:
Below is my data frame -

date                                name
18-Sep-18                            bb
6-Aug-18                             vv
Kingdom on 2 January 2019            cc
Kingdom on 9 June 2021               aa
States on 10 September 2021          bb
States on 14 April 2021              mm

I want my data frame -

date                                name
2018-09-18                            bb
2018-08-06                            vv
2019-01-02                            cc
2021-06-09                            aa
2021-09-10                            bb
2021-04-14                            mm

I have done the following code -

df['date'] = pd.to_datetime(df['date']).dt.strftime('%m/%d/%Y')

But it's not working

Body:
You can clean up the data with a regex first (here removing all the non digits before the first digit):

df['date'] = pd.to_datetime(df['date'].str.replace('^\D+(?=\d)', ''))

output (with an new column):

                          date name      date2
0                    18-Sep-18   bb 2018-09-18
1                     6-Aug-18   vv 2018-08-06
2    Kingdom on 2 January 2019   cc 2019-01-02
3       Kingdom on 9 June 2021   aa 2021-06-09
4  States on 10 September 2021   bb 2021-09-10
5      States on 14 April 2021   mm 2021-04-14


问:
What is the alternative for getMonthValue(),getDayOfMonth() in java 7?
```<code>SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS");
Date date = new Date();
</code>```

How Do I make this Java 7 compatible? What changes should I do?

```<code>String part = date.getYear() + "" + String.format("%02d", date.getMonthValue()) + ""
        + String.format("%02d", date.getDayOfMonth()) + "" + String.format("%02d", date.getHour()) + ""
        + String.format("%02d", date.getMinute()) + "" + String.format("%02d", date.getSecond());
</code>```

答:
Use a SimpleDateFormat if upgrading Java (from version 7) is not possible and to avoid any external library:

```<code>DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String part = dateFormat.format(date);
</code>```

Pattern can be changes as needed: see documentation of the SimpleDateFormat class.

As already advised in this answer, upgrade to a newer Java and then use the classes from java.time package and sub-packages (like DateTimeFormatter).

Body:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS");
Date date = new Date();

How Do I make this Java 7 compatible? What changes should I do?

String part = date.getYear() + "" + String.format("%02d", date.getMonthValue()) + ""
        + String.format("%02d", date.getDayOfMonth()) + "" + String.format("%02d", date.getHour()) + ""
        + String.format("%02d", date.getMinute()) + "" + String.format("%02d", date.getSecond());

Body:
Use a SimpleDateFormat if upgrading Java (from version 7) is not possible and to avoid any external library:

DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String part = dateFormat.format(date);

Pattern can be changes as needed: see documentation of the SimpleDateFormat class.

As already advised in this answer, upgrade to a newer Java and then use the classes from java.time package and sub-packages (like DateTimeFormatter).


问:
Dynamicly apply css changes on html code with js
here's the situation

I have a select element in my html code, with many option. One of these options is "Other". What I want is, when I select "Other", without refreshing the page, display an input element right under the select one with JS. The problem is that I have to refresh the page to see the change. Can you help me? :)

There's my code :

```<code><label for="select-tribunal" class="form-label">Cadre Légal</label>
            <select id="select-tribunal" required class="form-select" aria-label="Default select example">
                <?php
                foreach ($tribunaux as $tribunal){
                    echo '<option value="'.$tribunal['id'].'">'.$tribunal['nom'].'</option>';
                }
                ?>
                <option value="0">Autre Tribunal</option>
            </select>
                <input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">
            <script>
                var tribunal = document.getElementById("select-tribunal");
                    if (tribunal.options[tribunal.selectedIndex].value === '0') {
                        document.getElementById('tribunal').style.visibility = 'visible';
                    } else  {
                        document.getElementById('tribunal').style.visibility = 'hidden';
                    }
            </script>
</code>```

Thanks in advance :)

答:
You have to add an eventlistener.

let tribunal = document.getElementById("select-tribunal");
tribunal.addEventListener('change', showInput);
showInput({
  target: tribunal
});

function showInput(event) {
  if (event.target.value === '0') {
    document.getElementById('tribunal').style.visibility = 'visible';
  } else {
    document.getElementById('tribunal').style.visibility = 'hidden';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="select-tribunal" class="form-label">Cadre Légal</label>
<select id="select-tribunal" required class="form-select" aria-label="Default select example">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="0" selected>Autre Tribunal</option>
</select>
<input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal"></code>```

Body:
here's the situation

I have a select element in my html code, with many option. One of these options is "Other". What I want is, when I select "Other", without refreshing the page, display an input element right under the select one with JS. The problem is that I have to refresh the page to see the change. Can you help me? :)

There's my code :

Cadre Légal
            <select id="select-tribunal" required class="form-select" aria-label="Default select example">
                <?php
                foreach ($tribunaux as $tribunal){
                    echo '<option value="'.$tribunal['id'].'">'.$tribunal['nom'].'</option>';
                }
                ?>
                <option value="0">Autre Tribunal</option>
            </select>
                <input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">

Thanks in advance :)

Body:
You have to add an eventlistener.

let tribunal = document.getElementById("select-tribunal");
tribunal.addEventListener('change', showInput);
showInput({
  target: tribunal
});

function showInput(event) {
  if (event.target.value === '0') {
    document.getElementById('tribunal').style.visibility = 'visible';
  } else {
    document.getElementById('tribunal').style.visibility = 'hidden';
  }
}

<label for="select-tribunal" class="form-label">Cadre Légal</label>
<select id="select-tribunal" required class="form-select" aria-label="Default select example">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="0" selected>Autre Tribunal</option>
</select>
<input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">


问:
How to use Server.ScriptTimeout in ASP.NET Core 5 (migration from .NET framework to .NET 5)
Thanks for reading my post.

Originally, I was using ASP.NET MVC on the .NET framework, but I want to migrate to .NET 5.

However, this line of code:

```<code>filterContext.Controller.ControllerContext.HttpContext.Server.ScriptTimeout = TimeoutSeconds;
</code>```

is not working in .NET 5 - how to solve that?

答:
Seems you are trying to set corresponding functionality on asp.net 5 same as previously Server.ScriptTimeout on asp.net MVC. If that is the scenario you could achieve that using ServertimeOut  in IIS and in Program.cs you can set as following way,

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .UseKestrel(option =>
                    {
                        option.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10);
                        option.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(10);
                    })
                    .Build();
                });
```

Note :

You could refer to official document here for futher reference,
additionaly, please share your code in minimal reproducible way so that we can reproduce the issue instead of screenshoot.
it.

You can do that on IIS as well :

For IIS follow these steps to do same thing:

Open your IIS

Go to "Sites" option.

right click on Mouse.

Then open property "Manage Web Site".

Then click on "Advance Settings".

Expand section "Limits", here you can set your "connection time out"

here is the screenshots for your better clarity:

Hope above guideline will help you accordingly.

Body:
Thanks for reading my post.

Originally, I was using ASP.NET MVC on the .NET framework, but I want to migrate to .NET 5.

However, this line of code:

filterContext.Controller.ControllerContext.HttpContext.Server.ScriptTimeout = TimeoutSeconds;

is not working in .NET 5 - how to solve that?

Body:
Seems you are trying to set corresponding functionality on asp.net 5 same as previously Server.ScriptTimeout on asp.net MVC. If that is the scenario you could achieve that using ServertimeOut  in IIS and in Program.cs you can set as following way,

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .UseKestrel(option =>
                    {
                        option.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10);
                        option.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(10);
                    })
                    .Build();
                });

Note :

You could refer to official document here for futher reference,
additionaly, please share your code in minimal reproducible way so that we can reproduce the issue instead of screenshoot.
it.

You can do that on IIS as well :

For IIS follow these steps to do same thing:

Open your IIS

Go to "Sites" option.

right click on Mouse.

Then open property "Manage Web Site".

Then click on "Advance Settings".

Expand section "Limits", here you can set your "connection time out"

here is the screenshots for your better clarity:

Hope above guideline will help you accordingly.


问:
Relative time in weeks is not supported in day.js
I just migrated from moment.js to day.js.
The migration was very smooth but day.js is not providing relative time in weeks.
What I was doing in moment.js

```<code>       // Round relative time evaluation down
       moment.relativeTimeRounding(Math.floor);
       moment.relativeTimeThreshold('s', 60);
       moment.relativeTimeThreshold('m', 60);
       moment.relativeTimeThreshold('h', 24);
       moment.relativeTimeThreshold('d', 7);
       moment.relativeTimeThreshold('w', 4);
       moment.relativeTimeThreshold('M', 12);
</code>```

Using the above relative time config, I got the desired output like 2 weeks ago.

After migration to day.js, now my config is

```<code>    const thresholds = [
      { l: 's', r: 1 },
      { l: 'ss', r: 59, d: 'second' },
      { l: 'm', r: 1 },
      { l: 'mm', r: 59, d: 'minute' },
      { l: 'h', r: 1 },
      { l: 'hh', r: 23, d: 'hour' },
      { l: 'd', r: 1 },
      { l: 'dd', r: 6, d: 'day' },
      { l: 'w', r: 1},
      { l: 'ww', r: 4, d: 'week'},
      { l: 'M', r: 1 },
      { l: 'MM', r: 11, d: 'month' },
      { l: 'y', r: 1 },
      { l: 'yy', d: 'year' },
    ];

</code>```

With above config in day.js I got the following error.

```<code>core.js?7d7a:4073 ERROR TypeError: v is not a function
    at Object.n.fromToBase (VM15721 relativeTime.js:82)
    at i (VM15721 relativeTime.js:32)
    at M.n.from (VM15721 relativeTime.js:93)
    at M.n.fromNow (VM15721 relativeTime.js:103)

</code>```

When I remove

```<code>      { l: 'w', r: 1},
      { l: 'ww', r: 4, d: 'week'},
</code>```

and change the day's threshold to 30,

from day.js config, then it works fine and I got output like 13 days ago.

So, my question is, is there any workaround to get output in weeks instead of days?

答:
updateLocale must be added</p>
```<code>dayjs.extend(updateLocale);
dayjs.updateLocale('en', {
    relativeTime: {
      future: 'in %s',
      past: '%s ago',
      s: 'a few seconds',
      m: 'a minute',
      mm: '%d minutes',
      h: 'an hour',
      hh: '%d hours',
      d: 'a day',
      dd: '%d days',
      w: '%d week',
      ww: '%d weeks',
      M: 'a month',
      MM: '%d months',
      y: 'a year',
      yy: '%d years',
    },
  });
</code>```

Body:
I just migrated from moment.js to day.js.
The migration was very smooth but day.js is not providing relative time in weeks.
What I was doing in moment.js

       // Round relative time evaluation down
       moment.relativeTimeRounding(Math.floor);
       moment.relativeTimeThreshold('s', 60);
       moment.relativeTimeThreshold('m', 60);
       moment.relativeTimeThreshold('h', 24);
       moment.relativeTimeThreshold('d', 7);
       moment.relativeTimeThreshold('w', 4);
       moment.relativeTimeThreshold('M', 12);

Using the above relative time config, I got the desired output like 2 weeks ago.

After migration to day.js, now my config is

    const thresholds = [
      { l: 's', r: 1 },
      { l: 'ss', r: 59, d: 'second' },
      { l: 'm', r: 1 },
      { l: 'mm', r: 59, d: 'minute' },
      { l: 'h', r: 1 },
      { l: 'hh', r: 23, d: 'hour' },
      { l: 'd', r: 1 },
      { l: 'dd', r: 6, d: 'day' },
      { l: 'w', r: 1},
      { l: 'ww', r: 4, d: 'week'},
      { l: 'M', r: 1 },
      { l: 'MM', r: 11, d: 'month' },
      { l: 'y', r: 1 },
      { l: 'yy', d: 'year' },
    ];

With above config in day.js I got the following error.

core.js?7d7a:4073 ERROR TypeError: v is not a function
    at Object.n.fromToBase (VM15721 relativeTime.js:82)
    at i (VM15721 relativeTime.js:32)
    at M.n.from (VM15721 relativeTime.js:93)
    at M.n.fromNow (VM15721 relativeTime.js:103)

When I remove

      { l: 'w', r: 1},
      { l: 'ww', r: 4, d: 'week'},

and change the day's threshold to 30,

from day.js config, then it works fine and I got output like 13 days ago.

So, my question is, is there any workaround to get output in weeks instead of days?

Body:
updateLocale must be added

dayjs.extend(updateLocale);
dayjs.updateLocale('en', {
    relativeTime: {
      future: 'in %s',
      past: '%s ago',
      s: 'a few seconds',
      m: 'a minute',
      mm: '%d minutes',
      h: 'an hour',
      hh: '%d hours',
      d: 'a day',
      dd: '%d days',
      w: '%d week',
      ww: '%d weeks',
      M: 'a month',
      MM: '%d months',
      y: 'a year',
      yy: '%d years',
    },
  });


问:
How to force redraw ApexCharts?
I'm updating ApexCharts using updateSeries while the chart is hidden using display: none. When the series is being updated I think it is checking the width of the element that it is wrapped in. When hidden, the width is considered 0 and therefore the width of the chart is set to 0. I want to force redraw the chart when it is visible but I found nothing in the docs.

PS: The chart restores to its original size when I resize the window.

答:
I don't know weather it will be help you or not I have same issue using with apex chart some lables and title was missing but  when you resize the window it will automatically redraw the chart because apexchart have this property by default
chart: {
redrawOnWindowResize: true
}

I have try this this  put  chart render method inside timeout function and it works for me

```<code>setTimeout(() => {
            chart.render();
},2000)
</code>```

In my case, it seems like chart rending before getting style of parent component

Title: How to force redraw ApexCharts?

Body:
I don't know weather it will be help you or not I have same issue using with apex chart some lables and title was missing but  when you resize the window it will automatically redraw the chart because apexchart have this property by default
chart: {
redrawOnWindowResize: true
}

I have try this this  put  chart render method inside timeout function and it works for me

setTimeout(() => {
            chart.render();
},2000)

In my case, it seems like chart rending before getting style of parent component


问:
Updating a PriorityQueue when iterating it
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}
</code>```

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}
</code>```

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

```<code>PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());
</code>```

with:

```<code>public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}
</code>```

答:
This code is in the Java 6 implementation of PriorityQueue:

```<code>private class Itr implements Iterator<E> {
  /**
   * The modCount value that the iterator believes that the backing
   * Queue should have.  If this expectation is violated, the iterator
   * has detected concurrent modification.
   */
  private int expectedModCount = modCount;

  public E next() {
    if(expectedModCount != modCount) {
      throw new ConcurrentModificationException();
    }

  }

}
</code>```

Now, why is this code here? If you look at the Javadoc for ConcurrentModificationException you will find that the behaviour of an iterator is undefined if modification occurs to the underlying collection before iteration completes. As such, many of the collections implement this modCount mechanism.

To fix your code

You need to ensure that you don't modify the code mid-loop. If your code is single threaded (as it appears to be) then you can simply do as your coworker suggested and copy it into a list for later inclusion. Also, the use of the Iterator.remove() method is documented to prevent ConcurrentModificationExceptions. An example:

```<code>List<Entry> toAdd = new ArrayList<Entry>();
Iterator it = mEntries.iterator();
while(it.hasNext()) {
  Entry e = it.next();

  if(e.getId().equals(someId)) {
    Entry newEntry = e.setData(newData);
    it.remove();
    toAdd.add(newEntry);
  }
}
mEntries.addAll(toAdd);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());

with:

public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}

Body:
This code is in the Java 6 implementation of PriorityQueue:

private class Itr implements Iterator<E> {
  /**
   * The modCount value that the iterator believes that the backing
   * Queue should have.  If this expectation is violated, the iterator
   * has detected concurrent modification.
   */
  private int expectedModCount = modCount;

  public E next() {
    if(expectedModCount != modCount) {
      throw new ConcurrentModificationException();
    }

  }

}

Now, why is this code here? If you look at the Javadoc for ConcurrentModificationException you will find that the behaviour of an iterator is undefined if modification occurs to the underlying collection before iteration completes. As such, many of the collections implement this modCount mechanism.

To fix your code

You need to ensure that you don't modify the code mid-loop. If your code is single threaded (as it appears to be) then you can simply do as your coworker suggested and copy it into a list for later inclusion. Also, the use of the Iterator.remove() method is documented to prevent ConcurrentModificationExceptions. An example:

List<Entry> toAdd = new ArrayList<Entry>();
Iterator it = mEntries.iterator();
while(it.hasNext()) {
  Entry e = it.next();

  if(e.getId().equals(someId)) {
    Entry newEntry = e.setData(newData);
    it.remove();
    toAdd.add(newEntry);
  }
}
mEntries.addAll(toAdd);


问:
How to get Page<RegisteredClient> in Spring Authorization Server?
I want to add or update RegisteredClient use my custom controller,so first need to show the RegisteredClient's list.

so I want to get Page use RegisteredClientRepository.findAll(Pageable pageable),but RegisteredClientRepositor have no findAll method ,just have findById,findByClientId

How can I get The RegisteredClient's list?

答:
finally I use jdbcTemplate to query

@Component
public class CustomRegisteredClientRepo {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public Page<CustomClient> findAll(Pageable page) {
    Order order = !page.getSort().isEmpty() ? page.getSort().toList().get(0) : Order.by("id");

    SqlRowSet rs = jdbcTemplate.queryForRowSet("SELECT * FROM oauth2_registered_client ORDER BY "
        + order.getProperty() + " " + order.getDirection().name() + " LIMIT " + page.getPageSize()
        + " OFFSET " + page.getOffset());

    long count =
        jdbcTemplate.queryForObject("select count(*) from oauth2_registered_client", long.class);

    List<CustomClient> list = new ArrayList<CustomClient>();

    while (rs.next()) {
      CustomClient client = new CustomClient();
      client.setId(rs.getString("id"));
      client.setClientId(rs.getString("client_id"));
      list.add(client);
    }
    return new PageImpl<CustomClient>(list, page, count);
  }
}
```


问:
How to manage Scopes according to the User and not the Client?
I've been following this tutorial in order to create an Authentication Server, but I'm facing some problems regarding the concepts, I guess.

Look, when I register a Client in Repository, I have to define some parameters, like its id, secret, authentication method, grant types, redirection uris and scopes:

```<code>@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("articles-client")
            .clientSecret("{noop}secret")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
            .redirectUri("http://127.0.0.1:8080/login/oauth2/code/articles-client-oidc")
            .redirectUri("http://127.0.0.1:8080/authorized")
            .scope(OidcScopes.OPENID)
            .scope("articles.read")
            .build();
    return new InMemoryRegisteredClientRepository(registeredClient);
}
</code>```

When I'm back to my Resource Server, I find that my client was successfully logged in and it returns with an "articles.read" scope. Everything is fine here, supposing that I want to protect my endpoints with the Client's scope, but this is not my case.

In my situation, I want to protect my endpoints according to my User's role in database.

I'll give you an example, so you don't have to read the whole Baeldung's website:

I try to access: http://localhost:8080/articles.

It redirects to: http://auth-server:9000, where a Spring Security Login Form appears.

When you submit the proper credentials (which are compared from a database using the default Spring Security schema), it basically gets you back to: http://localhost:8080/articles.

Well, in that point, I have an Authorization Token with the Client scope, but not the logged User role.

Is there an standard way to configure my project to achieve this or, do I have to think of a creative way to do so?

Thank you in advance.

答:
For role based authentication you should map authorities in Oauth token.
OAuth2AuthenticationToken.getAuthorities() is used for authorizing requests, such as in hasRole('USER') or hasRole('ADMIN').

For this you need to implement the userAuthoritiesMapper, something like this:

```<code>@Configuration
public class AppConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.oauth2Login().userInfoEndpoint().userAuthoritiesMapper(this.userAuthoritiesMapper());
        //.oidcUserService(this.oidcUserService());
        super.configure(http);
    }

    private GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                if (OidcUserAuthority.class.isInstance(authority)) {
                    OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;

                    OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
                    if (userInfo.containsClaim("role")){
                        String roleName = "ROLE_" + userInfo.getClaimAsString("role");
                        mappedAuthorities.add(new SimpleGrantedAuthority(roleName));
                    }
                } else if (OAuth2UserAuthority.class.isInstance(authority)) {
                    OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
                    Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();

                    if (userAttributes.containsKey("role")){
                        String roleName = "ROLE_" + (String)userAttributes.get("role");
                        mappedAuthorities.add(new SimpleGrantedAuthority(roleName));
                    }
                }
            });

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

Body:
I've been following this tutorial in order to create an Authentication Server, but I'm facing some problems regarding the concepts, I guess.

Look, when I register a Client in Repository, I have to define some parameters, like its id, secret, authentication method, grant types, redirection uris and scopes:

@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("articles-client")
            .clientSecret("{noop}secret")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
            .redirectUri("http://127.0.0.1:8080/login/oauth2/code/articles-client-oidc")
            .redirectUri("http://127.0.0.1:8080/authorized")
            .scope(OidcScopes.OPENID)
            .scope("articles.read")
            .build();
    return new InMemoryRegisteredClientRepository(registeredClient);
}

When I'm back to my Resource Server, I find that my client was successfully logged in and it returns with an "articles.read" scope. Everything is fine here, supposing that I want to protect my endpoints with the Client's scope, but this is not my case.

In my situation, I want to protect my endpoints according to my User's role in database.

I'll give you an example, so you don't have to read the whole Baeldung's website:

I try to access: http://localhost:8080/articles.

It redirects to: http://auth-server:9000, where a Spring Security Login Form appears.

When you submit the proper credentials (which are compared from a database using the default Spring Security schema), it basically gets you back to: http://localhost:8080/articles.

Well, in that point, I have an Authorization Token with the Client scope, but not the logged User role.

Is there an standard way to configure my project to achieve this or, do I have to think of a creative way to do so?

Thank you in advance.

Body:
For role based authentication you should map authorities in Oauth token.
OAuth2AuthenticationToken.getAuthorities() is used for authorizing requests, such as in hasRole('USER') or hasRole('ADMIN').

For this you need to implement the userAuthoritiesMapper, something like this:

@Configuration
public class AppConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.oauth2Login().userInfoEndpoint().userAuthoritiesMapper(this.userAuthoritiesMapper());
        //.oidcUserService(this.oidcUserService());
        super.configure(http);
    }

    private GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                if (OidcUserAuthority.class.isInstance(authority)) {
                    OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;

                    OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
                    if (userInfo.containsClaim("role")){
                        String roleName = "ROLE_" + userInfo.getClaimAsString("role");
                        mappedAuthorities.add(new SimpleGrantedAuthority(roleName));
                    }
                } else if (OAuth2UserAuthority.class.isInstance(authority)) {
                    OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
                    Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();

                    if (userAttributes.containsKey("role")){
                        String roleName = "ROLE_" + (String)userAttributes.get("role");
                        mappedAuthorities.add(new SimpleGrantedAuthority(roleName));
                    }
                }
            });

            return mappedAuthorities;
        };
    }
}


问:
Type mismatch: cannot convert from element type Object to int
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

```<code>for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}
</code>```

答:
You need to use Java generics.

Declare ht as a LinkedHashMap<Integer, Foo> where Foo is whatever data type you expect to be returned by ht.get(). Using the Map interface would be even better:

```<code>LinkedHashMap<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();
// or preferably
Map<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();
</code>```

Body:
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}

Body:
You need to use Java generics.

Declare ht as a LinkedHashMap<Integer, Foo> where Foo is whatever data type you expect to be returned by ht.get(). Using the Map interface would be even better:

LinkedHashMap<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();
// or preferably
Map<Integer, Foo> ht = new LinkedHashMap<Integer, Foo>();


问:
Get variable name from object array
Can't find out how to get element variable name from array.

Need something like that:

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};
foreach (var v in array)
{
 Debug.Log($"{v.ToString()} {v}")
}

// test 1
// test2 2
```

I need that in one method, lets call it "void CombineWithName(params object[] msg){}

答: This is impossible.  The names test1 and test2 are not stored in the variable array but pointers to the location of the data.  Using .net6 on .NETFiddle and the nameof method, the compiler tells you that the expression does not have a name.

Title: Get variable name from object array

Body:
Can't find out how to get element variable name from array.

Need something like that:

var test = 1;
var test2 = "2";

var array = new object[]{test, test2};
foreach (var v in array)
{
 Debug.Log($"{v.ToString()} {v}")
}

// test 1
// test2 2

I need that in one method, lets call it "void CombineWithName(params object[] msg){}


问:
valuelistenablebuilder for ValueNotifier<Map<dynamic, dynamic>>
I came to know that we cannot refresh the state of the class using valuestatebuilder. This is very unfortunate for me. Because after weeks of hardwork  i am finally on the verge to complete my first flutter app/

The problem: I want to update the state of the mainclass. Map is stored in another. I have tried both: setstate and valuenotifier but all in vain. Can someone please tell me how to overcome this problem and how to use listenablebuilder to update the main class? thanks.

Example Code:

```<code>// class where the map<> is located.
// totalBill is the variable i want to use the value of in the next class
    var totalBill = ValueNotifier({});
    Map billl = {};
    int temp = 0;

    class ReusableCard extends StatefulWidget {
      ReusableCard({
        required this.itemName .....
...
...
// down in the class:
return GestureDetector(
      onTap: () {

        setState(() {
          totalBill.value[widget.itemName] = temp;
        });
      },
</code>```

then in the next class:

```<code>ValueListenableBuilder<Map>(
// totalBill is being borrowed from the above example / class
                    valueListenable: totalBill,
                    builder: (context, val, _) {
                      //print(val);
                      //print(itemsInList);

                      return Column(
                        children: [
                          Text(val.toString()),
....
...
</code>```

I will appreciate any help.

答:
ValueNotifier notifies only when its value is changed. In your example you do not change the value (i.e. Map) but you must.

The correct code is:

setState(() {
  totalBill.value = {widget.itemName: temp};
});
```

Body:
I came to know that we cannot refresh the state of the class using valuestatebuilder. This is very unfortunate for me. Because after weeks of hardwork  i am finally on the verge to complete my first flutter app/

The problem: I want to update the state of the mainclass. Map is stored in another. I have tried both: setstate and valuenotifier but all in vain. Can someone please tell me how to overcome this problem and how to use listenablebuilder to update the main class? thanks.

Example Code:

// class where the map<> is located.
// totalBill is the variable i want to use the value of in the next class
    var totalBill = ValueNotifier({});
    Map billl = {};
    int temp = 0;

    class ReusableCard extends StatefulWidget {
      ReusableCard({
        required this.itemName .....
...
...
// down in the class:
return GestureDetector(
      onTap: () {

        setState(() {
          totalBill.value[widget.itemName] = temp;
        });
      },

then in the next class:

ValueListenableBuilder<Map>(
// totalBill is being borrowed from the above example / class
                    valueListenable: totalBill,
                    builder: (context, val, _) {
                      //print(val);
                      //print(itemsInList);

                      return Column(
                        children: [
                          Text(val.toString()),
....
...

I will appreciate any help.


问:
sizeof operator in c
please can anybody help me to implement sizeof() operator in c..

i know the usage .. but i was not able to implement it.

答:
Below is the implementation of sizeof operator

```<code>#define SZOF(x) (size_t)(((x*)(0))+1)
</code>```

Title: sizeof operator in c

Body:
Below is the implementation of sizeof operator

#define SZOF(x) (size_t)(((x*)(0))+1)


问:
Java - How to check if a list is in list of lists
I have a list and list of lists.

How do I check if data is in sheet list and remove it from data list? I tried using containsAll() but it's not removing the same list. I might be doing something wrong.

```<code>import java.util.*;

public class RemoveSameListData {
    public static void main(String[] args) {
        List<List<Object>> sheet = new ArrayList<>();
        List<Object> data = new ArrayList<>();
        data.add("a");
        data.add("a");
        data.add("b");

        List<Object> data2 = new ArrayList<>();
        data2.add("c");
        data2.add("b");
        data2.add("bv");

        List<Object> data3 = new ArrayList<>();
        data3.add("s");
        data3.add("as");
        data3.add("e");

        sheet.add(data);
        sheet.add(data2);
        sheet.add(data3); //here sheet is [[a, a, b], [c, b, bv], [s, as, e]]

        for (List<Object> sameData : sheet) {
           if(data.containsAll(sameData)) {
              data.remove(sameData);
           }
        }
        System.out.println(data);
    }
}
</code>```

Basically, i want to be able to remove list from data that's available in sheet.

Any input is always appreciated. Thank you

答:
like @Lei Yang pointed out in his comment (credits to him!), the equality of list's is checked by equality of the objects.

Thus this succeeds:

```<code>List<List<Object>> sheet = new ArrayList<>(List.of(List.of("a", "a", "b"), List.of("c", "b", "bv"), List.of("s", "as", "e")));
List<Object> data = List.of("a", "a", "b");
assertTrue(sheet.remove(data));
</code>```

Body:
I have a list and list of lists.

How do I check if data is in sheet list and remove it from data list? I tried using containsAll() but it's not removing the same list. I might be doing something wrong.

import java.util.*;

public class RemoveSameListData {
    public static void main(String[] args) {
        List<List<Object>> sheet = new ArrayList<>();
        List<Object> data = new ArrayList<>();
        data.add("a");
        data.add("a");
        data.add("b");

        List<Object> data2 = new ArrayList<>();
        data2.add("c");
        data2.add("b");
        data2.add("bv");

        List<Object> data3 = new ArrayList<>();
        data3.add("s");
        data3.add("as");
        data3.add("e");

        sheet.add(data);
        sheet.add(data2);
        sheet.add(data3); //here sheet is [[a, a, b], [c, b, bv], [s, as, e]]

        for (List<Object> sameData : sheet) {
           if(data.containsAll(sameData)) {
              data.remove(sameData);
           }
        }
        System.out.println(data);
    }
}

Basically, i want to be able to remove list from data that's available in sheet.

Any input is always appreciated. Thank you

Body:
like @Lei Yang pointed out in his comment (credits to him!), the equality of list's is checked by equality of the objects.

Thus this succeeds:

List<List<Object>> sheet = new ArrayList<>(List.of(List.of("a", "a", "b"), List.of("c", "b", "bv"), List.of("s", "as", "e")));
List<Object> data = List.of("a", "a", "b");
assertTrue(sheet.remove(data));


问:
Kable column width in html rmarkdown
I want to display a wide kable table in html rmarkdown to display the first column has long text without any line breaks. When I set the first column's width using column_spec, it doesn't seem to have any effect on the resulting html table. Here's my code. Is there a way to not have any line breaks for the first column? Thanks!

```<code>df <- data.frame(v1 = c('Long text without line breaks', 'Long text without line breaks', 'Long text without line breaks'),
                 v2 = c('text', 'text', 'text'),
                 v3 = c('text', 'text', 'text'),
                 v4 = c('text', 'text', 'text'),
                 v5 = c('text', 'text', 'text'),
                 v6 = c('text', 'text', 'text'),
                 v7 = c('text', 'text', 'text'),
                 v8 = c('text', 'text', 'text'),
                 v9 = c('text', 'text', 'text'),
                 v10 = c('text', 'text', 'text'),
                 v11 = c('text', 'text', 'text'),
                 v12 = c('text', 'text', 'text'),
                 v13 = c('text', 'text', 'text'),
                 v14 = c('text', 'text', 'text'),
                 v15 = c('text', 'text', 'text'),
                 v16 = c('text', 'text', 'text'),
                 v17 = c('text', 'text', 'text'),
                 v18 = c('text', 'text', 'text'),
                 v19 = c('text', 'text', 'text')
                 )

gctbl <- kable(df, col.names = colnames(df), escape = F) %>%
  kable_styling(full_width = T) %>%
  column_spec(1, width = '10in')

gctbl
</code>```

答:
You'll need to set width_min in column_spec. I think 3in is already enough for your column 1 in the example.

If you really need 10in for some reason, you can add scroll_box() to enable x-axis scrolling in the table (not included in my answer).

```<code>kable(df, col.names = colnames(df), escape = F) %>%
  kable_styling(full_width = T) %>%
  column_spec(1, width_min = '3in')
</code>```

Title: Kable column width in html rmarkdown

Body:
I want to display a wide kable table in html rmarkdown to display the first column has long text without any line breaks. When I set the first column's width using column_spec, it doesn't seem to have any effect on the resulting html table. Here's my code. Is there a way to not have any line breaks for the first column? Thanks!

df <- data.frame(v1 = c('Long text without line breaks', 'Long text without line breaks', 'Long text without line breaks'),
                 v2 = c('text', 'text', 'text'),
                 v3 = c('text', 'text', 'text'),
                 v4 = c('text', 'text', 'text'),
                 v5 = c('text', 'text', 'text'),
                 v6 = c('text', 'text', 'text'),
                 v7 = c('text', 'text', 'text'),
                 v8 = c('text', 'text', 'text'),
                 v9 = c('text', 'text', 'text'),
                 v10 = c('text', 'text', 'text'),
                 v11 = c('text', 'text', 'text'),
                 v12 = c('text', 'text', 'text'),
                 v13 = c('text', 'text', 'text'),
                 v14 = c('text', 'text', 'text'),
                 v15 = c('text', 'text', 'text'),
                 v16 = c('text', 'text', 'text'),
                 v17 = c('text', 'text', 'text'),
                 v18 = c('text', 'text', 'text'),
                 v19 = c('text', 'text', 'text')
                 )

gctbl <- kable(df, col.names = colnames(df), escape = F) %>%
  kable_styling(full_width = T) %>%
  column_spec(1, width = '10in')

gctbl

Body:
You'll need to set width_min in column_spec. I think 3in is already enough for your column 1 in the example.

If you really need 10in for some reason, you can add scroll_box() to enable x-axis scrolling in the table (not included in my answer).

kable(df, col.names = colnames(df), escape = F) %>%
  kable_styling(full_width = T) %>%
  column_spec(1, width_min = '3in')


问:
Returning Only Latest Result For Location in SQL
I'm wanting to find the very last pallet placed in a given batch of locations within a warehouse.

I currently have:

```<code>SELECT

max(datreg) AS "_Reg Date",
logguser,
mha,
rack,
horcoor,
vercoor

FROM

L16T3

WHERE

l16lcode = '3'

AND

rack = @('Rack?',rack)

AND

horcoor >= @('Loc From?',horcoor)

AND

horcoor <= @('Loc To?',horcoor)

ORDER BY 1

LIMIT 1
</code>```

I thought this would return just the last pallet placed in that specific location, but I'm still getting like 4 entries for one location.

I would only want the highlighted result, as that is the most recent pallet placed in 110-001-04:

I'm sure this is super simple but im just starting out :)

答:
You can use a combination of ORDER BY and LIMIT to achieve what you want.

Limit

In a lot of other databases, this is called LIMIT, but I missed that you are using an Oracle database, which has a different dialect of SQL. In Oracle, the most direct equivilent of a limit is:

```<code>FETCH FIRST n ROWS ONLY
</code>```

This means that your query can return at most n rows. So, for example, FETCH FIRST 1 ROWS ONLY means that it can return at most 1 row. The issue is that it takes rows from the start of the table, not the end (and despite the wording implying FETCH LAST n ROWS ONLY would be a thing, it doesn't seem to be) --- you can essentially think of it as cutting off the rows below given limit.

For example, if I have rows in order "A", "B", and "C", FETCH FIRST 1 ROWS ONLY only returns "A". If "C" was really the one I wanted (e.g. the row at the bottom), then I would need to add an ORDER BY clause to first order the results so that the one I want is at the top.

Order By

ORDER BY column dir orders your results by a specific column in a specific direction, e.g. in ascending (ASC) or descending (DESC) order. The syntax actually allows for more complex ordering (e.g. ordering by multiple columns or by a function), but for this simple case this should do what we need.

Putting it together

You want to order so that your desired row is at the top of your table, then you want to limit your results set to contain at most one row.

Adding something like this to the end of your query should work:

ORDER BY "_Reg Date" DESC
FETCH FIRST 1 ROWS ONLY
```

Body:
I'm wanting to find the very last pallet placed in a given batch of locations within a warehouse.

I currently have:

SELECT

max(datreg) AS "_Reg Date",
logguser,
mha,
rack,
horcoor,
vercoor

FROM

L16T3

WHERE

l16lcode = '3'

AND

rack = @('Rack?',rack)

AND

horcoor >= @('Loc From?',horcoor)

AND

horcoor <= @('Loc To?',horcoor)

ORDER BY 1

LIMIT 1

I thought this would return just the last pallet placed in that specific location, but I'm still getting like 4 entries for one location.

I would only want the highlighted result, as that is the most recent pallet placed in 110-001-04:

I'm sure this is super simple but im just starting out :)

Body:
You can use a combination of ORDER BY and LIMIT to achieve what you want.

Limit

In a lot of other databases, this is called LIMIT, but I missed that you are using an Oracle database, which has a different dialect of SQL. In Oracle, the most direct equivilent of a limit is:

FETCH FIRST n ROWS ONLY

This means that your query can return at most n rows. So, for example, FETCH FIRST 1 ROWS ONLY means that it can return at most 1 row. The issue is that it takes rows from the start of the table, not the end (and despite the wording implying FETCH LAST n ROWS ONLY would be a thing, it doesn't seem to be) --- you can essentially think of it as cutting off the rows below given limit.

For example, if I have rows in order "A", "B", and "C", FETCH FIRST 1 ROWS ONLY only returns "A". If "C" was really the one I wanted (e.g. the row at the bottom), then I would need to add an ORDER BY clause to first order the results so that the one I want is at the top.

Order By

ORDER BY column dir orders your results by a specific column in a specific direction, e.g. in ascending (ASC) or descending (DESC) order. The syntax actually allows for more complex ordering (e.g. ordering by multiple columns or by a function), but for this simple case this should do what we need.

Putting it together

You want to order so that your desired row is at the top of your table, then you want to limit your results set to contain at most one row.

Adding something like this to the end of your query should work:

ORDER BY "_Reg Date" DESC
FETCH FIRST 1 ROWS ONLY


问:
How to solve Unable to find item ID for item in application in Oracle Apex?
I have a public website made using Apex 21.1.3

When a user shares a page of my website, let's say on facebook, Facebook adds "?fbclickId=something" to the URL.

My app then crashes saying : Unable to find item ID for item fbclickId in application.

Apex thinks the user is trying to set an element that does not exist on the application.

I have url processing layer using htaccess that formats the urls before sending them to Apex in a reverse proxy. I could say let's ignore all what comes after a question mark "?" but in this case I wont be able to set any application item value neither. So that's not possible.

Does anyone have an idea how to make Apex ignore setting a parameter if it doesn't exist ?

Using google for example :

This URL https://www.google.com/?anyparameter=anyvalue will always resolve to https://www.google.com

Thanks

Cheers

答:
I'm not aware of any way to ignore invalid parameters, but you can make the error a bit nicer for the end user.

Create a custom apex error handling function. The only difference with standard error handling is that the error with code WWV_FLOW.FIND_ITEM_ID_ERR has a custom message and no additional info. Change the string "Invalid url arguments" to something more relevant for your business case.

```<code>create or replace function apex_error_custom
    (
      p_error IN apex_error.t_error
    )
    RETURN apex_error.t_error_result
IS
    l_result          apex_error.t_error_result := apex_error.t_error_result();
BEGIN

    l_result := apex_error.init_error_result ( p_error => APEX_ERROR_CUSTOM.p_error );

    IF p_error.apex_error_code = 'WWV_FLOW.FIND_ITEM_ID_ERR' THEN
      l_result.message := 'Invalid url arguments';
      l_result.additional_info := NULL;
    END IF;

    RETURN l_result;
END apex_error_custom;

</code>```

Change the application definition to use the new error function:
Application Definitions > Error Handling > Custom Error Function. Note this affects all errors in the application.

An additional way to make the error nicer is to change the default error page to use a defined template (Shared Components > Themes > your theme > Component Defaults > Error page). Note this affects all errors in the application.

Body:
I'm not aware of any way to ignore invalid parameters, but you can make the error a bit nicer for the end user.

Create a custom apex error handling function. The only difference with standard error handling is that the error with code WWV_FLOW.FIND_ITEM_ID_ERR has a custom message and no additional info. Change the string "Invalid url arguments" to something more relevant for your business case.

create or replace function apex_error_custom
    (
      p_error IN apex_error.t_error
    )
    RETURN apex_error.t_error_result
IS
    l_result          apex_error.t_error_result := apex_error.t_error_result();
BEGIN

    l_result := apex_error.init_error_result ( p_error => APEX_ERROR_CUSTOM.p_error );

    IF p_error.apex_error_code = 'WWV_FLOW.FIND_ITEM_ID_ERR' THEN
      l_result.message := 'Invalid url arguments';
      l_result.additional_info := NULL;
    END IF;

    RETURN l_result;
END apex_error_custom;

Change the application definition to use the new error function:
Application Definitions > Error Handling > Custom Error Function. Note this affects all errors in the application.

An additional way to make the error nicer is to change the default error page to use a defined template (Shared Components > Themes > your theme > Component Defaults > Error page). Note this affects all errors in the application.


问:
Could not find module for target 'x86_64-apple-ios-simulator'
I have my custom framework and it works properly in XCode 10. I rebuild it in XCode 11 beta 3, then integrated into the app, and get the following error:

Could not find module 'MyCustomFramework' for target 'x86_64-apple-ios-simulator'; found: arm64, arm64-apple-ios

Are there some changes I have to make in "valid architectures" in the framework project?

Updated: I can't pick any answer as a correct one as the framework in my case was really tiny (one class, a few methods) and almost not in use, so I decided to get rid of it and move these a few methods into main project.

答:
Delete your pods and
install pods with this command
"arch -x86_64" pod install</p>


问:
Alternatives for pandas apply with slice
I have a df with columns open, high, low, close representing stock prices. I check for liquidity if high != low, and I do it for each row considering all previous rows. apply function works correct, but a little bit slow. Is there an option to make it faster?

```<code>df['liquid'] = df.apply(lambda x: (df.loc[:x.name, 'high'] != df.loc[:x.name, 'low']).all(), axis=1)
</code>```

答:
I did it with np.where which made it 42 times faster finally

```<code>cum_len = np.arange(1, len(df)+1)
cond = (df['high'] != df['low']).cumsum() == cum_len
df['liquid'] = np.where(cond, True, False)
</code>```

Body:
I have a df with columns open, high, low, close representing stock prices. I check for liquidity if high != low, and I do it for each row considering all previous rows. apply function works correct, but a little bit slow. Is there an option to make it faster?

df['liquid'] = df.apply(lambda x: (df.loc[:x.name, 'high'] != df.loc[:x.name, 'low']).all(), axis=1)

Body:
I did it with np.where which made it 42 times faster finally

cum_len = np.arange(1, len(df)+1)
cond = (df['high'] != df['low']).cumsum() == cum_len
df['liquid'] = np.where(cond, True, False)


问:
How many Blur Filter or Deblur models/modules are available in OpenCV or other python libraries?
I am doing a project where I have to remove noise, filter blur, and so many image preprocessing things to be applied in a real-time video to enhance the video quality. So at first, I broke down the video into frames then I wanted to use all the mechanisms.

So, my question is, which deblur approach should I apply to get my desired result, or is there any python library that will be better for my work?

答:
Maybe you could start with scikit-image's Image Deconvolution to "filter blur" and median filtering to remove pepper and salt noise.
Seeing some images could be useful to help you more.</p>


问:
Checking a remote host (Linux) hard disk space
I need to check the available hard disk space for a remote linux host in Python.

Currently i am using shutil to check the same on my host.

import shutil
total, used, free = shutil.disk_usage("D:/")

答:
You may use ssh to execute commands on the remote machine. paramiko is one library that provides ssh functions. Sample code:

from paramiko import SSHClient

ssh = SSHClient()
ssh.load_system_host_keys()
# more options found at https://docs.paramiko.org/en/stable/api/client.html
# ssh.connect(ip,port,username,password)
ssh.connect('serverip', username='youruser')  # using ssh keys
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('df -h /')
outlines = ssh_stdout.readlines()
resp = ''.join(outlines)
print(resp)

```

Alternatively you can setup some monitor service in the remote server, and use some convenient webpages or api to get the information. but that requires more resources.

Body:
You may use ssh to execute commands on the remote machine. paramiko is one library that provides ssh functions. Sample code:

from paramiko import SSHClient

ssh = SSHClient()
ssh.load_system_host_keys()
# more options found at https://docs.paramiko.org/en/stable/api/client.html
# ssh.connect(ip,port,username,password)
ssh.connect('serverip', username='youruser')  # using ssh keys
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('df -h /')
outlines = ssh_stdout.readlines()
resp = ''.join(outlines)
print(resp)

Alternatively you can setup some monitor service in the remote server, and use some convenient webpages or api to get the information. but that requires more resources.


问:
Assign date values for null in a column in a pyspark dataframe
I have a pyspark dataframe:

Location        Month       New_Date    Sales
USA             1/1/2020    1/1/2020    34.56%
COL             1/1/2020    1/1/2020    66.4%
AUS             1/1/2020    1/1/2020    32.98%
NZ              null        null        44.59%
CHN             null        null        21.13%
```
<p>Im creating <code>New_Date</code> column from <code>Month</code> column (MM/dd/yyyy format).
I need to populate <code>New_date</code> values for the rows having <code>Month</code> as null.</p>
<p>And this is what I tried:</p>
```df1=df.filter(col('Month').isNull()) \
.withColumn("current_date",current_date()) \
.withColumn("New_date", trunc(col("current_date"), "month"))
```
<p>But Im getting first date of current month.
I need the first date of <code>Month</code> column
Pls suggest any other approach.</p>
<pre class="lang-none prettyprint-override"><code>Location        Month       New_Date    Sales
USA             1/1/2020    1/1/2020    34.56%
COL             1/1/2020    1/1/2020    66.4%
AUS             1/1/2020    1/1/2020    32.98%
NZ              null        1/1/2020    44.59%
CHN             null        1/1/2020    21.13%
</code>```

Body:
I have a pyspark dataframe:

Location        Month       New_Date    Sales
USA             1/1/2020    1/1/2020    34.56%
COL             1/1/2020    1/1/2020    66.4%
AUS             1/1/2020    1/1/2020    32.98%
NZ              null        null        44.59%
CHN             null        null        21.13%

Im creating New_Date column from Month column (MM/dd/yyyy format).
I need to populate New_date values for the rows having Month as null.

And this is what I tried:

df1=df.filter(col('Month').isNull()) \
.withColumn("current_date",current_date()) \
.withColumn("New_date", trunc(col("current_date"), "month"))

But Im getting first date of current month.
I need the first date of Month column
Pls suggest any other approach.

Location        Month       New_Date    Sales
USA             1/1/2020    1/1/2020    34.56%
COL             1/1/2020    1/1/2020    66.4%
AUS             1/1/2020    1/1/2020    32.98%
NZ              null        1/1/2020    44.59%
CHN             null        1/1/2020    21.13%

Body:
You can use first function over window:

from pyspark.sql import functions as F, Window

w = (Window.orderBy("Month")
     .rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
     )

df1 = df.withColumn(
    "New_date",
    F.coalesce(F.col("Month"), F.first("Month", ignorenulls=True).over(w))
)

df1.show()
#+--------+--------+--------+------+
#|Location|   Month|New_date| Sales|
#+--------+--------+--------+------+
#|      NZ|    null|1/1/2020|44.59%|
#|     CHN|    null|1/1/2020|21.13%|
#|     USA|1/1/2020|1/1/2020|34.56%|
#|     COL|1/1/2020|1/1/2020| 66.4%|
#|     AUS|1/1/2020|1/1/2020|32.98%|
#+--------+--------+--------+------+


问:
I am actually working on an ML problem and I have some date columns that contains just dates in plain integer format and I want to convert it
I am actually working on an ML problem and I have some date columns that contain just dates in plain integer format and I want to convert it.
Like: 20200225 into a date_time format...2020-02-25
I am using python
Any suggestions on how to work my way out.</p>

答:
Please try this

```<code>from datetime import datetime

date_string = "20200625"

print("date_string =", date_string)
print("type of date_string =", type(date_string))

date_object = datetime.strptime(date_string, "%Y%m%d")

print("date_object =", date_object)

print("type of date_object =", type(date_object))
</code>```

sample output:

2022-02-10 08:50:24.100195

date_string = 20200625

type of date_string = <class 'str'>

date_object = 2020-06-25 00:00:00

type of date_object = <class 'datetime.datetime'>

Body:
Please try this

from datetime import datetime

date_string = "20200625"

print("date_string =", date_string)
print("type of date_string =", type(date_string))

date_object = datetime.strptime(date_string, "%Y%m%d")

print("date_object =", date_object)

print("type of date_object =", type(date_object))

sample output:

2022-02-10 08:50:24.100195

date_string = 20200625

type of date_string = <class 'str'>

date_object = 2020-06-25 00:00:00

type of date_object = <class 'datetime.datetime'>


问:
Framework for send http request in iPHone application
What is the best framework for send Http Post and Get request with JSON?</p>

答:
i would suggest ASIHTTPRequest http://allseeing-i.com/ASIHTTPRequest/
there is documentation and examples

hope this will help


问:
ResponseEntity in Optional as ok or noContent, depending if present
Im currently returning my content in this way:

```<code>Optional<String> data = Optional.of("bla");
Optional<ResponseEntity<?>> response = data.map(ResponseEntity::ok);
return response.orElse(ResponseEntity::noContent);
</code>```

is there a way to combine the map with the orElse without saving them into a variable first?

(something like this, but without the cast problems)

```<code>Optional<String> data = Optional.of("bla");
return data.map(ResponseEntity::ok) // Type: ResponseEntity<String>
  .orElse(ResponseEntity::noContent); // Type: ResponseEntity<?> => Cast Error
</code>```

This is a similar problem to

```<code>Optional.of<Object>("bla").orElse(2);
</code>```

but I don't know how how to do this with a map

```<code>Optional.of("bla")
        .<ResponseEntity<?>>map(ResponseEntity::ok)
        .orElse(ResponseEntity::noContent);
</code>```

does not work

答:
Can you describe what your problem is exactly.

Can't you just do something like this:

```<code>return Optional.of("bla")
    .map(ResponseEntity::ok)
    .orElse(ResponseEntity::noContent);
</code>```

Body:
Im currently returning my content in this way:

Optional<String> data = Optional.of("bla");
Optional<ResponseEntity<?>> response = data.map(ResponseEntity::ok);
return response.orElse(ResponseEntity::noContent);

is there a way to combine the map with the orElse without saving them into a variable first?

(something like this, but without the cast problems)

Optional<String> data = Optional.of("bla");
return data.map(ResponseEntity::ok) // Type: ResponseEntity<String>
  .orElse(ResponseEntity::noContent); // Type: ResponseEntity<?> => Cast Error

This is a similar problem to

Optional.of<Object>("bla").orElse(2);

but I don't know how how to do this with a map

Optional.of("bla")
        .<ResponseEntity<?>>map(ResponseEntity::ok)
        .orElse(ResponseEntity::noContent);

does not work

Body:
Can you describe what your problem is exactly.

Can't you just do something like this:

return Optional.of("bla")
    .map(ResponseEntity::ok)
    .orElse(ResponseEntity::noContent);


问:
npm ERR! code EINTEGRITY for typescript@4.5.5 when using win-64 msi
Edit: I’ve discovered that this happens only with the 64-bit windows msi installer and not the 32-bit msi installer

I've tried everything listed in other answers.

delete package-lock.json  (can't doesn't exist)

delete node_modules (didn't help)

npm cache verify (didn't help, says "corrupted content removed" every time)

npm cache clean --force (didn't help)

delete AppData/Local/npm-cache (didn't help)

delete AppData/Roaming/npm (didn't help)

npm i -g npm (didn't help)

npm config set package-lock false (didn't help)

I reset my machine to a fresh install of Win 10 and Win 11 (didn't help)

I disabled auto-proxy (didn't help)

It always fails for typescript@4.5.5.  I have no idea what else to do, and I can't install angular/cli with this failure.

what is the sha512 for typescript@4.5.5 supposed to be?

can I disable EINTEGRITY checks?

are there any other solutions I missed?

$ npm i
npm WARN tarball tarball data for esbuild-wasm@0.14.14 (sha512-qTjK4MWnYtQHCMGg2qDUqeFYXfVvYq5qJkQTIsOV4VZCknoYePVaDTG9ygEB9Ct0kc0DWs7IrS6Ja+GjY62Kzw==) seems to be corrupted. Trying again.

... several more "seems to be corrupted"

npm WARN tarball tarball data for typescript@4.5.5 (sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA==) seems to be corrupted. Trying again.

npm ERR! code EINTEGRITY
npm ERR! sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== integrity checksum failed when using sha512: wanted sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== but got sha512-U0dCcrUYPNLvBHhB3AuhIqz7zrcg2z2u5LCqmZVNN/aUqimo+p2cVyQ1kFsbc9XMmh8tNFcOkuY0itp0Yz31fQ==. (11280693 bytes)

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\chuck\AppData\Local\npm-cache_logs\2022-02-10T02_23_03_444Z-debug-0.log

Possibly related, every time I verify my cache, it thinks new contents are corrupted and removes them

c:\Users\chuck\git\test>npm cache verify
Cache verified and compressed (~\AppData\Local\npm-cache_cacache)
Content verified: 45 (10072506 bytes)
Index entries: 70
Finished in 0.151s

c:\Users\chuck\git\test>npm cache verify
Cache verified and compressed (~\AppData\Local\npm-cache_cacache)
Content verified: 44 (10066799 bytes)
Corrupted content removed: 1
Content garbage-collected: 1 (5707 bytes)
Missing content: 2
Index entries: 68
Finished in 0.188s

c:\Users\chuck\git\test>npm cache verify
Cache verified and compressed (~\AppData\Local\npm-cache_cacache)
Content verified: 40 (9155292 bytes)
Corrupted content removed: 4
Content garbage-collected: 4 (911507 bytes)
Missing content: 6
Index entries: 62
Finished in 0.178s

c:\Users\chuck\git\test>npm cache verify
Cache verified and compressed (~\AppData\Local\npm-cache_cacache)
Content verified: 37 (8712984 bytes)
Corrupted content removed: 3
Content garbage-collected: 3 (442308 bytes)
Missing content: 4
Index entries: 58
Finished in 0.155s

It's like sha512 is a random number generator

答: I found the answer.  I uninstalled the 64bit node and reinstalled with the 32bit version for windows, and all my corruption and EINTEGRITY errors are now gone!</p>


问:
VBA Loop through Sheets where sheetnames are made up of two variables
Caveat: my VBA knowledge is self-taught via Googling so please be patient with me!
I have a set of worksheets and am trying to perform the same set of actions through each sheet. Having problem with my codes:
E.g. worksheets are "Staging AA 101", "Staging AA 102", "Staging AA 201", "Staging BB 101", "Staging BB 102", "Staging BB 201", "Staging CC 101", "Staging CC 102", "Staging CC 201"

My codes are:

```<code>Dim ExpSub(1 To 3) As String
Dim Post(1 To 3) As String
Dim i As Integer 'ExpSub
Dim j As Integer 'Post

ExpSub(1) = "101"
ExpSub(2) = "102"
ExpSub(3) = "201"
Post(1) = "AA"
Post(2) = "BB"
Post(3) = "CC"

For j = 1 To 3 'j for Post
For i = 1 To 3 'i for ExpSub
    Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select
    Range("AK4").Select
    Range(Selection, Selection.Offset(100, 1)).Select
    Selection.ClearContents
Next i
Next j
</code>```

Errored out at this line
Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select

How do i loop through all the sheets with such variables please? Thanks in advance!

答:
Clear Ranges

Option Explicit

Sub ClearRanges()

    Const wsNameLeft As String = "Staging "
    Const rgAddress As String = "AK4:AL104"
    Dim ExpSub As Variant: ExpSub = VBA.Array("101", "102", "201")
    Dim Post As Variant: Post = VBA.Array("AA", "BB", "CC")

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    Dim ws As Workbook
    Dim wsName As String
    Dim e As Long
    Dim p As Long

    For p = 0 To UBound(Post)
        For e = 0 To UBound(ExpSub)
            wsName = wsNameLeft & Post(p) & " " & ExpSub(e)
            On Error Resume Next
                Set ws = wb.Worksheets(wsName)
            On Error GoTo 0
            If Not ws Is Nothing Then ' worksheet found
                ws.Range(rgAddress).ClearContents
                Set ws = Nothing
            Else ' worksheet not found
                ' Look in the immediate window VBE CTRL+G
                Debug.Print "Worksheet '" & wsName & "' not found."
            End If
        Next e
    Next p

    'Range("AK4").Select

    MsgBox "Ranges cleared.", vbInformation

End Sub
```

Body:
Caveat: my VBA knowledge is self-taught via Googling so please be patient with me!
I have a set of worksheets and am trying to perform the same set of actions through each sheet. Having problem with my codes:
E.g. worksheets are "Staging AA 101", "Staging AA 102", "Staging AA 201", "Staging BB 101", "Staging BB 102", "Staging BB 201", "Staging CC 101", "Staging CC 102", "Staging CC 201"

My codes are:

Dim ExpSub(1 To 3) As String
Dim Post(1 To 3) As String
Dim i As Integer 'ExpSub
Dim j As Integer 'Post

ExpSub(1) = "101"
ExpSub(2) = "102"
ExpSub(3) = "201"
Post(1) = "AA"
Post(2) = "BB"
Post(3) = "CC"

For j = 1 To 3 'j for Post
For i = 1 To 3 'i for ExpSub
    Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select
    Range("AK4").Select
    Range(Selection, Selection.Offset(100, 1)).Select
    Selection.ClearContents
Next i
Next j

Errored out at this line
Sheets("Staging " & Post(j) & " " & ExpSub(i)).Select

How do i loop through all the sheets with such variables please? Thanks in advance!


问:
You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without the 'an
Issue: You uploaded an APK or Android App Bundle which has an activity, activity alias, service, or broadcast receiver with intent filter, but without the 'android: exported' property set. This file can't be installed on Android 12 or higher. See developer.android.com/about/versions/12/behavior-changes-12#exported

My AndroidManifest.xml file

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.c4life.guardianangel">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

<application
   tools:replace="android:label"
   android:label="GA"
   android:exported="true"
   android:icon="@mipmap/ic_launcher">
   <meta-data android:name="com.google.android.geo.API_KEY"
       android:value="[insert API key here]"/>
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme"
          />
        <meta-data
          android:name="io.flutter.embedding.android.SplashScreenDrawable"
          android:resource="@drawable/launch_background"
          />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
   <service android:name="changjoopark.com.flutter_foreground_plugin.FlutterForegroundService" android:exported="false"/>
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />

</application>

<uses-sdk
    android:targetSdkVersion="30"
    tools:overrideLibrary="changjoopark.com.flutter_foreground_plugin" />
</code>```

答: If you are not using any other project then update all library latest versions because some old library AndroidManifest.xml not added android: exported in activities, services, or broadcast receivers

Body:
Issue: You uploaded an APK or Android App Bundle which has an activity, activity alias, service, or broadcast receiver with intent filter, but without the 'android: exported' property set. This file can't be installed on Android 12 or higher. See developer.android.com/about/versions/12/behavior-changes-12#exported

My AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.c4life.guardianangel">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

<application
   tools:replace="android:label"
   android:label="GA"
   android:exported="true"
   android:icon="@mipmap/ic_launcher">
   <meta-data android:name="com.google.android.geo.API_KEY"
       android:value="[insert API key here]"/>
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme"
          />
        <meta-data
          android:name="io.flutter.embedding.android.SplashScreenDrawable"
          android:resource="@drawable/launch_background"
          />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
   <service android:name="changjoopark.com.flutter_foreground_plugin.FlutterForegroundService" android:exported="false"/>
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />

</application>

<uses-sdk
    android:targetSdkVersion="30"
    tools:overrideLibrary="changjoopark.com.flutter_foreground_plugin" />


问:
Can a custom allocator improve cache locality for lists?
This is a rather hypothetical question.

I only have limited knowledge about how the cpu cache works.

I know a cpu loads subsequent bytes into the cache.

Since a list uses pointers/indirection into random locations in memory, it has relatively bad locality compared to lets say vector or an array.

My question is: If I write an allocator where the data of all nodes is next to each other (via linear allocator), will this improve the cache loading? The indirection is still there but the data for the different nodes are in similar locations.

答:
Yes and no, but leaning mostly toward no, at least if you use the list in a way that lets you get anything out of it.

The advantage of a linked list is the ability to insert and delete elements in the middle of the list in constant time (provided you already know the point where you're going to insert/delete).

If you allocate objects linearly and insert them into the list linearly and access them linearly, yes, you'll get an improvement in locality. The problem is that if you're going to use the data that way, you might as well just put it in a vector and be done with it.

If you do insertions and deletions at arbitrary positions in the list, even though you originally allocated the nodes in linear order, you quickly end up with the order of the list no longer matching the order of allocation.

So yes, you can get good locality under some circumstances--but those circumstances are basically that you never take advantage of the characteristic(s) of a list that make it useful in the first place.