问:
Non direct son to take the entire width of a grid layout
i've been trying to make the text div to take the entire width of the grid layout but have it's content in line with the rest of the layout itself
I've used width: 100vw, tried padding the corners yet it doesn't work properly and is a bit clunky.

I've uploaded it to the codepen for better understanding
https://codepen.io/Aegtar/pen/PoObBdG

what is needed is that the green part will take the entire width yet the text inside will stay within the lightsalmon div.

the HTML :

```<code>      <div class='main-layout'>
        <div class='weather-page'>
          <div class='top-side'>
            <div>WeatherPage</div>
            <div class='text-container'>
              <div class='ha'>
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat expedita molestiae nisi dolorum est,
                tempore dolore! Itaque quidem nobis deleniti! Lorem ipsum dolor sit amet.
              </div>
            </div>
            <button>
              2
            </button>
            <button>
             2
            </button>
          </div>

        </div>
      </div>
      <section class='footer'>Footer</section>
    </div>
</code>```

the scss :

```<code>
.main-layout {
  display: grid;
  grid-template-columns: minmax(10px, 1fr) minmax(auto, 1300px) minmax(10px, 1fr);

  > * {
    grid-column: 2;
  }

  > *.full {
    grid-column: 1 / -1;
  }
}

.home-page {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  width: 50%;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.weather-page {
  gap: 10px;
  grid-auto-flow: column;
  background-color: lightsalmon;
  .top-side {
    gap: 20px;
    align-items: center;
    flex-direction: column;
    display: flex;
    margin-bottom: 30px;

    .text-container {
      background-color: lightgreen;
      .ha {
        text-align: center;
      }
    }
}

.footer {
  background-color: rgb(25, 118, 210);
}
</code>```

any help is appreciated!

答:
It seems like you're not really using your grid. You're creating 2 empty columns on the sides for styling and putting all the content in the center column. Why not use the default layout with a simple container and recreate what you want just by using the basic stylings with  width, margin and padding.

* { margin: 0 auto; }
.width-90 { width: 90%; }
.width-100 { width: 100%; }

article {
  text-align: center;
  max-width: 1300px;
  border: solid 1px black;
}

  article > * { padding: 10px 0 30px 0; }
  article header, article section { background-color: lightsalmon; }
  article main { background-color: lightgreen; }
  article footer { background-color: lightblue; }
  /*SCSS was not supported in this snippet but you could remove the word article in the lines above and then just place them in article if you want it to be specific with SCSS*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div class='main-layout'>
        <article class='weather-page'>

          <header class="header width-90">
            <h2>WeatherPage</h2>
          </header>

          <main class='main width-100'>
              <p class="width-90"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat expedita molestiae nisi dolorum est, tempore dolore! Itaque quidem nobis deleniti! Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, at. Atque alias modi nam provident quam, consectetur unde sunt exercitationem corrupti veritatis ea, itaque sint vero voluptatibus in fugit delectus recusandae eos enim deleniti doloribus magni. Repudiandae obcaecati blanditiis temporibus, vitae numquam illum ducimus voluptates sed in repellat quis esse! Cupiditate facilis magni velit molestias iure enim optio ratione. Ad? </p>
          </main>

          <section class="section-buttons width-90">
            <p><button>2</button></p>
            <p><button>2</button></p>
          </section>

          <footer class='footer width-100'>
            <p class="width-90">Footer</p>
          </footer>

        </article>
    </div></code>```

If you really want to keep your html structure the way it is then you could probably use a variable since you're working with SCSS. You could try this for example:

```<code>
$grid-sides: 10px;

.main-layout {
  display: grid;
  grid-template-columns: minmax($grid-sides, 1fr) minmax(auto, 1300px) minmax($grid-sides, 1fr);

  /* ... everything else ...*/
}

/* at the right place in your SCSS*/
.text-container {
      margin-left: -$grid-sides;
      margin-right: -$grid-sides;
      padding-left: $grid-sides;
      padding-right: $grid-sides;
      background-color: lightgreen;
      /* ... everything else ...*/
}

</code>```

Body:
i've been trying to make the text div to take the entire width of the grid layout but have it's content in line with the rest of the layout itself
I've used width: 100vw, tried padding the corners yet it doesn't work properly and is a bit clunky.

I've uploaded it to the codepen for better understanding
https://codepen.io/Aegtar/pen/PoObBdG

what is needed is that the green part will take the entire width yet the text inside will stay within the lightsalmon div.

the HTML :

WeatherPage

                Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat expedita molestiae nisi dolorum est,
                tempore dolore! Itaque quidem nobis deleniti! Lorem ipsum dolor sit amet.

            <button>
              2
            </button>
            <button>
             2
            </button>

Footer

the scss :

.main-layout {
  display: grid;
  grid-template-columns: minmax(10px, 1fr) minmax(auto, 1300px) minmax(10px, 1fr);

  > * {
    grid-column: 2;
  }

  > *.full {
    grid-column: 1 / -1;
  }
}

.home-page {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  width: 50%;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.weather-page {
  gap: 10px;
  grid-auto-flow: column;
  background-color: lightsalmon;
  .top-side {
    gap: 20px;
    align-items: center;
    flex-direction: column;
    display: flex;
    margin-bottom: 30px;

    .text-container {
      background-color: lightgreen;
      .ha {
        text-align: center;
      }
    }
}

.footer {
  background-color: rgb(25, 118, 210);
}

any help is appreciated!

Body:
It seems like you're not really using your grid. You're creating 2 empty columns on the sides for styling and putting all the content in the center column. Why not use the default layout with a simple container and recreate what you want just by using the basic stylings with  width, margin and padding.

* { margin: 0 auto; }
.width-90 { width: 90%; }
.width-100 { width: 100%; }

article {
  text-align: center;
  max-width: 1300px;
  border: solid 1px black;
}

  article > * { padding: 10px 0 30px 0; }
  article header, article section { background-color: lightsalmon; }
  article main { background-color: lightgreen; }
  article footer { background-color: lightblue; }
  /*SCSS was not supported in this snippet but you could remove the word article in the lines above and then just place them in article if you want it to be specific with SCSS*/

      <div class='main-layout'>
        <article class='weather-page'>

          <header class="header width-90">
            <h2>WeatherPage</h2>
          </header>

          <main class='main width-100'>
              <p class="width-90"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat expedita molestiae nisi dolorum est, tempore dolore! Itaque quidem nobis deleniti! Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, at. Atque alias modi nam provident quam, consectetur unde sunt exercitationem corrupti veritatis ea, itaque sint vero voluptatibus in fugit delectus recusandae eos enim deleniti doloribus magni. Repudiandae obcaecati blanditiis temporibus, vitae numquam illum ducimus voluptates sed in repellat quis esse! Cupiditate facilis magni velit molestias iure enim optio ratione. Ad? </p>
          </main>

          <section class="section-buttons width-90">
            <p><button>2</button></p>
            <p><button>2</button></p>
          </section>

          <footer class='footer width-100'>
            <p class="width-90">Footer</p>
          </footer>

        </article>
    </div>

If you really want to keep your html structure the way it is then you could probably use a variable since you're working with SCSS. You could try this for example:

$grid-sides: 10px;

.main-layout {
  display: grid;
  grid-template-columns: minmax($grid-sides, 1fr) minmax(auto, 1300px) minmax($grid-sides, 1fr);

  /* ... everything else ...*/
}

/* at the right place in your SCSS*/
.text-container {
      margin-left: -$grid-sides;
      margin-right: -$grid-sides;
      padding-left: $grid-sides;
      padding-right: $grid-sides;
      background-color: lightgreen;
      /* ... everything else ...*/
}


来源: stackexchange

问:
How to generate a random normal distribution of integers
How to generate a random integer as with np.random.randint(), but with a normal distribution around 0.

np.random.randint(-10, 10) returns integers with a discrete uniform distribution
np.random.normal(0, 0.1, 1) returns floats with a normal distribution

What I want is a kind of combination between the two functions.

答:
Old question, new answer:

For a bell-shaped distribution on the integers {-10, -9, ..., 9, 10}, you can use the binomial distribution with n=20 and p=0.5, and subtract 10 from the samples.

For example,

```<code>In [167]: import numpy as np

In [168]: import matplotlib.pyplot as plt

In [169]: rng = np.random.default_rng()

In [170]: N = 5000000   # Number of samples to generate

In [171]: samples = rng.binomial(n=20, p=0.5, size=N) - 10

In [172]: samples.min(), samples.max()
Out[172]: (-10, 10)
</code>```

Note that the probability of -10 or 10 is pretty low, so you won't necessarily see them in any given sample, especially if you use a smaller N.

np.bincount() is an efficient way to generate a histogram for a collection of small nonnegative integers:

```<code>In [173]: counts = np.bincount(samples + 10, minlength=20)

In [174]: counts
Out[174]:
array([     4,    104,    889,   5517,  22861,  73805, 184473, 369441,
       599945, 800265, 881140, 801904, 600813, 370368, 185082,  73635,
        23325,   5399,    931,     95,      4])

In [175]: plt.bar(np.arange(-10, 11), counts)
Out[175]: <BarContainer object of 21 artists>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Old question, new answer:

For a bell-shaped distribution on the integers {-10, -9, ..., 9, 10}, you can use the binomial distribution with n=20 and p=0.5, and subtract 10 from the samples.

For example,

In [167]: import numpy as np

In [168]: import matplotlib.pyplot as plt

In [169]: rng = np.random.default_rng()

In [170]: N = 5000000   # Number of samples to generate

In [171]: samples = rng.binomial(n=20, p=0.5, size=N) - 10

In [172]: samples.min(), samples.max()
Out[172]: (-10, 10)

Note that the probability of -10 or 10 is pretty low, so you won't necessarily see them in any given sample, especially if you use a smaller N.

np.bincount() is an efficient way to generate a histogram for a collection of small nonnegative integers:

In [173]: counts = np.bincount(samples + 10, minlength=20)

In [174]: counts
Out[174]:
array([     4,    104,    889,   5517,  22861,  73805, 184473, 369441,
       599945, 800265, 881140, 801904, 600813, 370368, 185082,  73635,
        23325,   5399,    931,     95,      4])

In [175]: plt.bar(np.arange(-10, 11), counts)
Out[175]: <BarContainer object of 21 artists>

ContentLicense: CC BY-SA 4.0


问:
ReactJS- Use slug instead of Id in the URL with React router
In short: I want to show the slug instead of the Id in the URL, whats the best way to do that?

In my app.js component I am using React-router this way so far:

```<code> <Router history={browserHistory}>
    <Route path="/" component={Main}>
      <IndexRoute component={Home}></IndexRoute>
        <Route path="/profile/:slug" component={Split}></Route>
    </Route>

  </Router>
</code>```

Then in my profile component I am using Link to go to that specific profile via the slug:

```<code><Link to={'/profile/' + username.slug}>{username}</Link>
</code>```

I was thinking of keying them together in my profile reducer or something?

Any tips would be very helpful!

答:
```<code>**//Server Side Communicate with frontend. Product data....**
const products = [
  {
    img:"https://cdn-images-fishry.azureedge.net/product/Krunch-500x360-a6056d0-kfc.png/xs",
    title:"Kuranch burger",
    discription:"Enjoy the crispy chicken fillet in a soft bun with spicy mayo and our signature sauce with fresh lettuce.",
    price:210,
    slug:"EVERYDAY-VALUE",
  },
  {
    img:"https://cdn-images-fishry.azureedge.net/product/Krunch-500x360-a6056d0-kfc.png/xs",
    title:"Kurnach burger",
    discription:"Enjoy the crispy chicken fillet in a soft bun with spicy mayo and our signature sauce with fresh lettuce.",
    price:200,
    slug:"EVERYDAY-VALUE",
  },

  ]
</code>```
<p>//then</p>
```<code>app.get("/products/:slug", function (req, resp) {
  const slugs = req.params.slug;
  const pro = products.filter(p=>p.slug==slugs)
  resp.send(pro);
});
</code>```

Body:
In short: I want to show the slug instead of the Id in the URL, whats the best way to do that?

In my app.js component I am using React-router this way so far:

 <Router history={browserHistory}>
    <Route path="/" component={Main}>
      <IndexRoute component={Home}></IndexRoute>
        <Route path="/profile/:slug" component={Split}></Route>
    </Route>

  </Router>

Then in my profile component I am using Link to go to that specific profile via the slug:

<Link to={'/profile/' + username.slug}>{username}</Link>

I was thinking of keying them together in my profile reducer or something?

Any tips would be very helpful!

Body:
**//Server Side Communicate with frontend. Product data....**
const products = [
  {
    img:"https://cdn-images-fishry.azureedge.net/product/Krunch-500x360-a6056d0-kfc.png/xs",
    title:"Kuranch burger",
    discription:"Enjoy the crispy chicken fillet in a soft bun with spicy mayo and our signature sauce with fresh lettuce.",
    price:210,
    slug:"EVERYDAY-VALUE",
  },
  {
    img:"https://cdn-images-fishry.azureedge.net/product/Krunch-500x360-a6056d0-kfc.png/xs",
    title:"Kurnach burger",
    discription:"Enjoy the crispy chicken fillet in a soft bun with spicy mayo and our signature sauce with fresh lettuce.",
    price:200,
    slug:"EVERYDAY-VALUE",
  },

  ]

//then

app.get("/products/:slug", function (req, resp) {
  const slugs = req.params.slug;
  const pro = products.filter(p=>p.slug==slugs)
  resp.send(pro);
});


问:
Back button of the browser is not working + content is not loading if don't click on refresh button
I am really new to JS/jQuery/Ajax I have this code. I want that the content in article tag change but to keep all the rest (header, menu and footer) stays the same while the user click on a link of on the website. I absolutely don't want to have the full page reloading entirely because it causes a poor user experience.
This works perfectly and the code is loading the new page, title is changing when you click on a link BUT the back button of the browser does no longer works, title is still the same as the page I was on, really annoying. What should I do to fix this really annoying issue?

```<code>$(function() {
  var $article = $("article"),

      init = function() {
        // Do this when a page loads.
      },
      ajaxLoad = function(html) {
        document.title = html
          .match(/<title>(.*?)<\/title>/)[1]
          .trim();
        init();
      };
  init();

  $(document).on("click", "a, area", function() {
    var href = $(this).attr("href");
    history.pushState({}, '', href);
    $article.load(href + " article>*", ajaxLoad);
    return false;
  });
});
</code>```

Thanks so much for your help!

答:
I added that after the last init()

and it works perfectly!

```<code>$(window).on("popstate", function(e) {
    if (e.originalEvent.state !== null) {
      loadPage(location.href);
    }
  });

  loadPage = function(href) {
    $article.load(href + " article>*", ajaxLoad);
  };
</code>```

Body:
I am really new to JS/jQuery/Ajax I have this code. I want that the content in article tag change but to keep all the rest (header, menu and footer) stays the same while the user click on a link of on the website. I absolutely don't want to have the full page reloading entirely because it causes a poor user experience.
This works perfectly and the code is loading the new page, title is changing when you click on a link BUT the back button of the browser does no longer works, title is still the same as the page I was on, really annoying. What should I do to fix this really annoying issue?

$(function() {
  var $article = $("article"),

      init = function() {
        // Do this when a page loads.
      },
      ajaxLoad = function(html) {
        document.title = html
          .match(/<title>(.*?)<\/title>/)[1]
          .trim();
        init();
      };
  init();

  $(document).on("click", "a, area", function() {
    var href = $(this).attr("href");
    history.pushState({}, '', href);
    $article.load(href + " article>*", ajaxLoad);
    return false;
  });
});

Thanks so much for your help!

Body:
I added that after the last init()

and it works perfectly!

$(window).on("popstate", function(e) {
    if (e.originalEvent.state !== null) {
      loadPage(location.href);
    }
  });

  loadPage = function(href) {
    $article.load(href + " article>*", ajaxLoad);
  };


问:
Encountering a problem while using ngrok link for simulations
I recently started encountering an error with the ngrok link used for simulation. I usually use the function: meshcat = StartMeshcat() for simulation the models in deepnote. But recently I started getting a security error sometimes and other times it asks me to sign up and install some authtoken. I signed up for the ngrok account and also installed the authtoken but it still doesn't work.

Can you let me know how I should set this up so it works? Also, you could recommend some alternative ways (other than ngrok) to do the simulations that would also be really helpful.

Thank you very much.

答:
We've actually been working with the ngrok folks to see if we can make it easier. https://github.com/RobotLocomotion/drake/issues/16300.

But for now I'm afraid you'll need to make a ngrok account and set your token as an environment variable.


问:
Recyclerview sort by current date
In the recyclerview, I have data in the format dd/MM/yyyy with a period titled date.I want this data to list only the dates that are less than the current date.I am using sqlite as database.</p>

答: you should use ORDER BY  in your sql request. And should format date in milliseconds before pass it into database. Then, when you called data in recycler view use SimpleDateFormat for formatting date into dd/mm/yyyy. For current date use Calendar.getInstance.getDateInMillis

Title: Recyclerview sort by current date


问:
replace blank with 0 based on value in another column
I have a df like this:

```<code>                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,NA,NA,4,3),
                                   SCOOTER = c(2,3,6,9,0))
</code>```

I will like to replace NA's in column BOAT with '0'if the column CAR is 'NO', so I can have something like this:

```<code>                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,0,0,4,3),
                                   SCOOTER = c(2,3,6,9,0))
</code>```

I thought something like this, but it didnt work:

```<code>NEW_df %>%
  mutate(across(BOAT, ~ if_else(CAR == NO & is.na(.), 0, .)))
</code>```

Is it even possible to place the replaced values in a new column too.

答:
You can also use data.table</p>
```<code>library(data.table)
NEW_df <- as.data.table(NEW_df)
NEW_df[is.na(BOAT) & CAR == "NO", BOAT := 0]
</code>```

Body:
I have a df like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,NA,NA,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I will like to replace NA's in column BOAT with '0'if the column CAR is 'NO', so I can have something like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,0,0,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I thought something like this, but it didnt work:

NEW_df %>%
  mutate(across(BOAT, ~ if_else(CAR == NO & is.na(.), 0, .)))

Is it even possible to place the replaced values in a new column too.

Body:
You can also use data.table

library(data.table)
NEW_df <- as.data.table(NEW_df)
NEW_df[is.na(BOAT) & CAR == "NO", BOAT := 0]


问:
Finding Max element of the list of lists in c++ (conversion of python function)
I wanted to convert the following function python to c++:

```<code>def find_max_value(list):
max_value_list = []
for i in list:
    max_value_list.append(i[0])
return max(max_value_list)
</code>```

The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [237.026305, 263.076182, 237.629826, 247.023679, 4.523158]]

The Output is 520.293431.

I have tried but getting some errors. Could you please mention where I'm doing wrong?

```<code>std::list<int> find_max_value(std::list<int> a(std::list<double> b)){
std::list<int> max_value_list;
for (std::list<int>::iterator i = *a.begin(); i!=*a.end(); ++i){
    max_value_list.push_back(i.front());
    return std::max_element(i);
}
}
</code>```

Those are the errors:

Thanks in advance!!!

答:
I'm going to guess you are looking for something like this:

```<code>double find_max_value(const std::list<std::list<double>>& a){
  return std::max_element(a.begin(), a.end(),
    [](const std::list<double>& lhs, const std::list<double>& rhs) {
      return lhs.front() < rhs.front();
    }
  )->front();
}
</code>```

This assumes none of the lists involved are empty.

Body:
I wanted to convert the following function python to c++:

def find_max_value(list):
max_value_list = []
for i in list:
    max_value_list.append(i[0])
return max(max_value_list)

The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [237.026305, 263.076182, 237.629826, 247.023679, 4.523158]]

The Output is 520.293431.

I have tried but getting some errors. Could you please mention where I'm doing wrong?

std::list<int> find_max_value(std::list<int> a(std::list<double> b)){
std::list<int> max_value_list;
for (std::list<int>::iterator i = *a.begin(); i!=*a.end(); ++i){
    max_value_list.push_back(i.front());
    return std::max_element(i);
}
}

Those are the errors:

Thanks in advance!!!

Body:
I'm going to guess you are looking for something like this:

double find_max_value(const std::list<std::list<double>>& a){
  return std::max_element(a.begin(), a.end(),
    [](const std::list<double>& lhs, const std::list<double>& rhs) {
      return lhs.front() < rhs.front();
    }
  )->front();
}

This assumes none of the lists involved are empty.


问:
weird jquery and IE issue
I found a weird problem with jQuery and IE and I was wondering if there is a fix or a work around. Basically, when the page initially loads, or if it is accessed directly from the url (eg. you copy paste the url and go to it), The page gives jQuery errors in IE (all other browsers are fine).

However, on the same page, if you refresh the page, everything runs and loads just fine. Has anybody encounter such problem?

答:
I figured it out: apparently this is caused if you have the content-type meta tag:

```<code><meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</code>```

after loading the jQuery. To fix, you just have to make sure to put that line before loading your jQuery. Very weird though, I would expect something like this to error on all browsers, not only IE.

Title: weird jquery and IE issue

Body:
I figured it out: apparently this is caused if you have the content-type meta tag:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

after loading the jQuery. To fix, you just have to make sure to put that line before loading your jQuery. Very weird though, I would expect something like this to error on all browsers, not only IE.


问:
Trouble reading user accessible files
I am using nativescript-mediafilepicker as means of choosing a file, and this can read external storage successfully (I have downloaded a PDF to the 'downloads' folder on iOS and I am able to pick it.) I then try to load the file using the file system module from nativescript library, and this fails because it is listed as NativeScript encountered a fatal error: Uncaught Error: You can‚Äôt save the file ‚Äúcom.xxxxxx‚Äù because the volume is read only. This doesn't make sense as I am trying to read anyway - I don't understand where the saving part is from. The error comes from fileSystemModule.File.fromPath() line.

Something to note that file['file'] is file:///Users/adair/Library/Developer/CoreSimulator/Devices/82F397CE-B0B3-4ADD-AD52-805265C7AC49/data/Containers/Data/Application/7B47A8BD-6DBA-42CF-8792-38A8C5E61174/tmp/com.xxxxxx/test.pdf

Is the file automatically being pulled to an application specific directory after this media picker?

getFiles() {
      let extensions = [];
      if (app.ios) {
        extensions = [kUTTypePDF]; // you can get more types from here: https://developer.apple.com/documentation/mobilecoreservices/uttype
      } else {
        extensions = ["pdf"];
      }
      const mediaFilePicker = new Mediafilepicker();
      const filePickerOptions = {
        android: {
          extensions,
          maxNumberFiles: 1,
        },
        ios: {
          extensions,
          maxNumberFiles: 1,
        },
      };
      masterPermissions
        .requestPermissions([masterPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,masterPermissions.PERMISSIONS.WRITE_EXTERNAL_STORAGE])
        .then((fulfilled) => {
          console.log(fulfilled);
          mediaFilePicker.openFilePicker(filePickerOptions);
          mediaFilePicker.on("getFiles", function (res) {
            let results = res.object.get("results");
            let file = results[0];
            console.dir(file);
            let fileObject = fileSystemModule.File.fromPath(file["file"]);
            console.log(fileObject);
          });

          mediaFilePicker.on("error", function (res) {
            let msg = res.object.get("msg");
            console.log(msg);
          });

          mediaFilePicker.on("cancel", function (res) {
            let msg = res.object.get("msg");
            console.log(msg);
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
```

答:
The issue I have experienced is resultant of the expectation of File.fromPath and what is returned by the file picker. File picker is returning a "file://path" URI, and File.fromPath is expecting a string of just "path".

Simply using the following instead is enough.

let fileObject = fileSystemModule.File.fromPath(file["file"].replace("file://","");
```

Title: Trouble reading user accessible files


问:
Clear IntelliJ console from java
Is there a way to clear IntelliJ console from code? I've tried all the solutions I've found, like:

```<code>Runtime.getRuntime().exec("clear")
System.out.print("\033[H\033[2J");
System.out.flush();
</code>```

even printing a lot of "\b"s just prints a odd char instead of erasing the output.
Printing a lot of "\n" doesn't work for me, for two reasons:

you are still able to scroll up;

pointer is not placed at the beginning of the console.

I just need to trigger the console "Clear All" button (the little trashcan icon), but from within the code. Every hack is well accepted.

答:
IntelliJ IDEA console is not a real terminal, so there is no command to clear it from your Java code.

Try run your application in other console and you can make a function like this:

```<code>public static void ClearConsole(){
    try{
        String operatingSystem = System.getProperty("os.name") //Check the current operating system

        if(operatingSystem.contains("Windows")){
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cls");
            Process startProcess = pb.inheritIO.start();
            startProcess.waitFor();
        } else {
            ProcessBuilder pb = new ProcessBuilder("clear");
            Process startProcess = pb.inheritIO.start();

            startProcess.waitFor();
        }
    }catch(Exception e){
        System.out.println(e);
    }
}
</code>```

Title: Clear IntelliJ console from java

Body:
Is there a way to clear IntelliJ console from code? I've tried all the solutions I've found, like:

Runtime.getRuntime().exec("clear")
System.out.print("\033[H\033[2J");
System.out.flush();

even printing a lot of "\b"s just prints a odd char instead of erasing the output.
Printing a lot of "\n" doesn't work for me, for two reasons:

you are still able to scroll up;

pointer is not placed at the beginning of the console.

I just need to trigger the console "Clear All" button (the little trashcan icon), but from within the code. Every hack is well accepted.

Body:
IntelliJ IDEA console is not a real terminal, so there is no command to clear it from your Java code.

Try run your application in other console and you can make a function like this:

public static void ClearConsole(){
    try{
        String operatingSystem = System.getProperty("os.name") //Check the current operating system

        if(operatingSystem.contains("Windows")){
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cls");
            Process startProcess = pb.inheritIO.start();
            startProcess.waitFor();
        } else {
            ProcessBuilder pb = new ProcessBuilder("clear");
            Process startProcess = pb.inheritIO.start();

            startProcess.waitFor();
        }
    }catch(Exception e){
        System.out.println(e);
    }
}


问:
How to export a variable from a scheduled function
I have a function that gets input constantly but then only processes it every minute with a cron job.

The most recent output should be stored in a variable and retrieved from the outside at random times.

Here in a very simplified form:

```<code>let input = 'something';

let data = '';
data += input;

require('node-schedule').scheduleJob('* * * * *', somethingMore);

function somethingMore() {
let output = data += 'More';
// return output;
}

console.log(output);
</code>```

Initializing the variable outside the function like above doesn't seem to work in this case.

Calling the function directly or assigning it to a variable doesn't help, as it would run it before it's due.

I also tried with buffers, but they don't seem to work either, unless I missed something.

The only thing that does work is writing a file to disk with fs and then reading from there, but I guess it's not the best of solutions.

答:
It seems like you just let your chron function run as scheduled and you save the latest result in a module-scoped variable.  Then, create another exported function that anyone else can call to get the latest result.

You're only showing pseudo-code (not your real code) so it is not clear exactly what you want to save for future inquiries to return.  You will have to implement that part yourself.

So, if you just wanted to save the most recent value:

```<code>// module-scoped variable to save recent data
// you may want to call your function to initialize it when
// the module loads, otherwise it may be undefined for a little bit
// of time
let lastData;

require('node-schedule').scheduleJob('* * * * * *', () => {
     // do something that gets someData
     lastData = someData;
});

// let outside caller get the most recent data
module.exports.getLastData = function() {
    return lastData;
}
</code>```

Body:
I have a function that gets input constantly but then only processes it every minute with a cron job.

The most recent output should be stored in a variable and retrieved from the outside at random times.

Here in a very simplified form:

let input = 'something';

let data = '';
data += input;

require('node-schedule').scheduleJob('* * * * *', somethingMore);

function somethingMore() {
let output = data += 'More';
// return output;
}

console.log(output);

Initializing the variable outside the function like above doesn't seem to work in this case.

Calling the function directly or assigning it to a variable doesn't help, as it would run it before it's due.

I also tried with buffers, but they don't seem to work either, unless I missed something.

The only thing that does work is writing a file to disk with fs and then reading from there, but I guess it's not the best of solutions.

Body:
It seems like you just let your chron function run as scheduled and you save the latest result in a module-scoped variable.  Then, create another exported function that anyone else can call to get the latest result.

You're only showing pseudo-code (not your real code) so it is not clear exactly what you want to save for future inquiries to return.  You will have to implement that part yourself.

So, if you just wanted to save the most recent value:

// module-scoped variable to save recent data
// you may want to call your function to initialize it when
// the module loads, otherwise it may be undefined for a little bit
// of time
let lastData;

require('node-schedule').scheduleJob('* * * * * *', () => {
     // do something that gets someData
     lastData = someData;
});

// let outside caller get the most recent data
module.exports.getLastData = function() {
    return lastData;
}


问:
Optimize a query with IN() clauses oracle
Here I have a query like below:

```<code>SELECT /*+ USE_NL_WITH_INDEX(D) */ N.MARCHE,N.NLBIX,D.NUORD,D.NUCON, 0 NUBI2, N.COINF, D.COINL, D.COINA, D.COINV, N.COINN, D.COINC, D.NUCPT, D.COINI, N.COINK, N.CNACT, N.NUCAR
FROM VBANET N, VBADET D
WHERE N.MARCHE IN ('DDL')
AND D.MARCHE(+)= N.MARCHE
AND D.NUBIX(+)= N.NUBIX AND N.CTFNE NOT IN ('T','R')
AND
D.CTFRE(+) != 'R' AND (N.NLBIX IN (SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */ DISTINCT FN.NLBIX
FROM DICCRN FN, RICCRD FD
WHERE
FN.MARCHE IN ('OCC') AND
FD.NLBIX(+)= FN.NLBIX AND
FD.MARCHE(+)= FN.MARCHE AND
( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )) )
</code>```

How can I optimize this subquery :

```<code>(N.NLBIX IN (SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */ DISTINCT FN.NLBIX
    FROM DICCRN FN, RICCRD FD
    WHERE
    FN.MARCHE IN ('OCC') AND
    FD.NLBIX(+)= FN.NLBIX AND
    FD.MARCHE(+)= FN.MARCHE AND
    ( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )) )
</code>```

because it generate :
|   7 |   VIEW PUSHED PREDICATE                        | VW_NSO_1 |   181K|

|   9 |     HASH JOIN RIGHT OUTER                      |          |   181K|    15M|  7690   (1)|

THIS IS THE EXECUTION PLAN

答:
This is a comment that doesn't fit in the comments secion. I rewrote the query using modern join syntax, so it's easier for me (and others) to understand it. It takes the form:

```<code>select
  n.marche,n.nlbix,d.nuord,d.nucon, 0 nubi2, n.coinf, d.coinl, d.coina,
  d.coinv, n.coinn, d.coinc, d.nucpt, d.coini, n.coink, n.cnact, n.nucar
from vbanet n
left join vbadet d on d.marche = n.marche
                  and d.nubix = n.nubix
                  and d.ctfre != 'r'
where n.marche in ('ddl') -- IN #1
  and n.ctfne not in ('t','r') -- IN #2
  and n.nlbix in ( -- IN #3
    select distinct fn.nlbix
    from diccrn fn
    left join riccrd fd on fd.nlbix = fn.nlbix
                       and fd.marche = fn.marche
    where fn.marche in ('occ') -- IN #4
      and (fn.nuseq is not null or fd.nuseq is not null)
  )
</code>```

IN #1, #2, and #4 are trivial, so we can assume you want to optimize #3.

First, you don't need DISTINCT in the subquery. But more importantly, you can use EXISTS instead of IN that offers more opportunities for optimization, provided there are good indexes that can be used (there should be).

EDIT: Rephrasing using EXISTS

Now that I see the query better, I think it can be rephrased to use EXISTS as:

```<code>select
  n.marche, n.nlbix, d.nuord, d.nucon, 0 as nubi2, n.coinf, d.coinl, d.coina,
  d.coinv, n.coinn, d.coinc, d.nucpt, d.coini, n.coink, n.cnact, n.nucar
from vbanet n
left join vbadet d on d.marche = n.marche
                  and d.nubix = n.nubix
                  and d.ctfre <> 'r'
where n.marche = 'ddl'
  and n.ctfne not in ('t','r')
  and exists (
    select 1
    from diccrn fn
    left join riccrd fd on fd.nlbix = fn.nlbix
                       and fd.marche = fn.marche
    where fn.nlbix = n.nlbix
      and fn.marche = 'occ'
      and (fn.nuseq is not null or fd.nuseq is not null)
  );
</code>```

The EXISTS subquery can benefit from the indexes:

```<code>create index ix1 on diccrn (marche, nlbix, nuseq);

create index ix2 on riccrd (nlbix, marche, nuseq);
</code>```

Body:
Here I have a query like below:

SELECT /*+ USE_NL_WITH_INDEX(D) */ N.MARCHE,N.NLBIX,D.NUORD,D.NUCON, 0 NUBI2, N.COINF, D.COINL, D.COINA, D.COINV, N.COINN, D.COINC, D.NUCPT, D.COINI, N.COINK, N.CNACT, N.NUCAR
FROM VBANET N, VBADET D
WHERE N.MARCHE IN ('DDL')
AND D.MARCHE(+)= N.MARCHE
AND D.NUBIX(+)= N.NUBIX AND N.CTFNE NOT IN ('T','R')
AND
D.CTFRE(+) != 'R' AND (N.NLBIX IN (SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */ DISTINCT FN.NLBIX
FROM DICCRN FN, RICCRD FD
WHERE
FN.MARCHE IN ('OCC') AND
FD.NLBIX(+)= FN.NLBIX AND
FD.MARCHE(+)= FN.MARCHE AND
( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )) )

How can I optimize this subquery :

(N.NLBIX IN (SELECT /*+ UNNEST NO_USE_HASH_AGGREGATION */ DISTINCT FN.NLBIX
    FROM DICCRN FN, RICCRD FD
    WHERE
    FN.MARCHE IN ('OCC') AND
    FD.NLBIX(+)= FN.NLBIX AND
    FD.MARCHE(+)= FN.MARCHE AND
    ( FN.NUSEQ IS NOT NULL OR FD.NUSEQ IS NOT NULL )) )

because it generate :
|   7 |   VIEW PUSHED PREDICATE                        | VW_NSO_1 |   181K|

|   9 |     HASH JOIN RIGHT OUTER                      |          |   181K|    15M|  7690   (1)|

THIS IS THE EXECUTION PLAN

Body:
This is a comment that doesn't fit in the comments secion. I rewrote the query using modern join syntax, so it's easier for me (and others) to understand it. It takes the form:

select
  n.marche,n.nlbix,d.nuord,d.nucon, 0 nubi2, n.coinf, d.coinl, d.coina,
  d.coinv, n.coinn, d.coinc, d.nucpt, d.coini, n.coink, n.cnact, n.nucar
from vbanet n
left join vbadet d on d.marche = n.marche
                  and d.nubix = n.nubix
                  and d.ctfre != 'r'
where n.marche in ('ddl') -- IN #1
  and n.ctfne not in ('t','r') -- IN #2
  and n.nlbix in ( -- IN #3
    select distinct fn.nlbix
    from diccrn fn
    left join riccrd fd on fd.nlbix = fn.nlbix
                       and fd.marche = fn.marche
    where fn.marche in ('occ') -- IN #4
      and (fn.nuseq is not null or fd.nuseq is not null)
  )

IN #1, #2, and #4 are trivial, so we can assume you want to optimize #3.

First, you don't need DISTINCT in the subquery. But more importantly, you can use EXISTS instead of IN that offers more opportunities for optimization, provided there are good indexes that can be used (there should be).

EDIT: Rephrasing using EXISTS

Now that I see the query better, I think it can be rephrased to use EXISTS as:

select
  n.marche, n.nlbix, d.nuord, d.nucon, 0 as nubi2, n.coinf, d.coinl, d.coina,
  d.coinv, n.coinn, d.coinc, d.nucpt, d.coini, n.coink, n.cnact, n.nucar
from vbanet n
left join vbadet d on d.marche = n.marche
                  and d.nubix = n.nubix
                  and d.ctfre <> 'r'
where n.marche = 'ddl'
  and n.ctfne not in ('t','r')
  and exists (
    select 1
    from diccrn fn
    left join riccrd fd on fd.nlbix = fn.nlbix
                       and fd.marche = fn.marche
    where fn.nlbix = n.nlbix
      and fn.marche = 'occ'
      and (fn.nuseq is not null or fd.nuseq is not null)
  );

The EXISTS subquery can benefit from the indexes:

create index ix1 on diccrn (marche, nlbix, nuseq);

create index ix2 on riccrd (nlbix, marche, nuseq);


问:
pyenv does not affect the python being used and activate does not exist
I am using a pyenv guide from here Managing Multiple Python Versions With pyenv

I have already created a 3.6.7 version:

```<code>13:24:51/hercl $pyenv versions
  system
* 3.6.7 (set by /Users/steve/.pyenv/version)
</code>```

I made 3.6.7 global:

```<code>pyenv global 3.6.7

</code>```

But the python being used is the system version

```<code> $python -V
Python 3.9.9
</code>```

Also there are many references to pyenv activate but that command does not exist??

```<code> $pyenv commands
--version
commands
completions
exec
global
help
hooks
init
install
local
prefix
rehash
root
shell
shims
uninstall
version
version-file
version-file-read
version-file-write
version-name
version-origin
versions
whence
which

</code>```

So how is the 3.6.7 version to be activated?

Update. here is how I installed and enabled pyenv:

```<code>git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bashrc
</code>```

Also do I really need to uninstall the python versions already installed via brew?  installing-pyenv-on-macos

答:
While I had installed pyenv I had missed installing pyenv-virtualenv.

```<code>brew install pyenv-virtualenv
</code>```

The following had already been added to ~/.bashrc but the second line had not been working. it does now

```<code>eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

</code>```

And pyenv activate now runs fine

```<code>$pyenv activate 3.6.7
pyenv-virtualenv: virtualenv `/Users/steve/git/hercl/.venv' is already activated
</code>```

Wow that was a confusing problem.

Update An additional step is needed: to manually add the $HOME/.pyenv/shims directory to the PATH.  So now the last three lines of my ~/.bash_profile are:

```<code>export PATH=.:$HOME/.pyenv/bin:$HOME/.pyenv/shims:/opt/brew/bin:/opt/homebrew/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/bin:/usr/local/bin:/bin
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
</code>```

Body:
I am using a pyenv guide from here Managing Multiple Python Versions With pyenv

I have already created a 3.6.7 version:

13:24:51/hercl $pyenv versions
  system
* 3.6.7 (set by /Users/steve/.pyenv/version)

I made 3.6.7 global:

pyenv global 3.6.7

But the python being used is the system version

 $python -V
Python 3.9.9

Also there are many references to pyenv activate but that command does not exist??

 $pyenv commands
--version
commands
completions
exec
global
help
hooks
init
install
local
prefix
rehash
root
shell
shims
uninstall
version
version-file
version-file-read
version-file-write
version-name
version-origin
versions
whence
which

So how is the 3.6.7 version to be activated?

Update. here is how I installed and enabled pyenv:

git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bashrc

Also do I really need to uninstall the python versions already installed via brew?  installing-pyenv-on-macos

Body:
While I had installed pyenv I had missed installing pyenv-virtualenv.

brew install pyenv-virtualenv

The following had already been added to ~/.bashrc but the second line had not been working. it does now

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

And pyenv activate now runs fine

$pyenv activate 3.6.7
pyenv-virtualenv: virtualenv `/Users/steve/git/hercl/.venv' is already activated

Wow that was a confusing problem.

Update An additional step is needed: to manually add the $HOME/.pyenv/shims directory to the PATH.  So now the last three lines of my ~/.bash_profile are:

export PATH=.:$HOME/.pyenv/bin:$HOME/.pyenv/shims:/opt/brew/bin:/opt/homebrew/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/bin:/usr/local/bin:/bin
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"


问:
NSImage size not real size with some pictures?
I see that sometimes NSImage size is not real size (with some pictures) and CIImage size is always real. I was testing with this image.

This is source code which I wrote for testing:

```<code>NSImage *_imageNSImage = [[NSImage alloc]initWithContentsOfFile:@"<path to image>"];

NSSize _dimensions = [_imageNSImage size];

[_imageNSImage release];

NSLog(@"Width from CIImage: %f",_dimensions.width);
NSLog(@"Height from CIImage: %f",_dimensions.height);

NSURL *_myURL = [NSURL fileURLWithPath:@"<path to image>"];
CIImage *_imageCIImage = [CIImage imageWithContentsOfURL:_myURL];

NSRect _rectFromCIImage = [_imageCIImage extent];

NSLog(@"Width from CIImage: %f",_rectFromCIImage.size.width);
NSLog(@"Height from CIImage: %f",_rectFromCIImage.size.height);
</code>```

And output is:

So how that can be?? Maybe I'm doing something wrong?

答:
NSImage's size param returns size information dependent to screen resolution and scaling configuration.

Real size of image you can get with the following extension:

```<code>extension NSImage {
    var sizeReal: NSSize {
        guard representations.count > 0 else { return NSSize(width: 0, height: 0) }

        let rep = self.representations[0]
        return NSSize(width: rep.pixelsWide, height: rep.pixelsHigh)
    }
}
</code>```

Body:
I see that sometimes NSImage size is not real size (with some pictures) and CIImage size is always real. I was testing with this image.

This is source code which I wrote for testing:

NSImage *_imageNSImage = [[NSImage alloc]initWithContentsOfFile:@"<path to image>"];

NSSize _dimensions = [_imageNSImage size];

[_imageNSImage release];

NSLog(@"Width from CIImage: %f",_dimensions.width);
NSLog(@"Height from CIImage: %f",_dimensions.height);

NSURL *_myURL = [NSURL fileURLWithPath:@"<path to image>"];
CIImage *_imageCIImage = [CIImage imageWithContentsOfURL:_myURL];

NSRect _rectFromCIImage = [_imageCIImage extent];

NSLog(@"Width from CIImage: %f",_rectFromCIImage.size.width);
NSLog(@"Height from CIImage: %f",_rectFromCIImage.size.height);

And output is:

So how that can be?? Maybe I'm doing something wrong?

Body:
NSImage's size param returns size information dependent to screen resolution and scaling configuration.

Real size of image you can get with the following extension:

extension NSImage {
    var sizeReal: NSSize {
        guard representations.count > 0 else { return NSSize(width: 0, height: 0) }

        let rep = self.representations[0]
        return NSSize(width: rep.pixelsWide, height: rep.pixelsHigh)
    }
}


问:
How to implement a Fibonacci sequence in JavaScript?
I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I'm not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci(n) {
  let number1 = 0;
  let number2 = 1;

  for (i = 0; i < n; i++) {
    let current = number1 + number2;
    number1 = number2;
    number2 = current;
    console.log(current);
  }
}

helperFibonacci(2);```

Please help me implement this function without passing an argument. thanks!

答:
Try with this one , works great , have a good coding :)

```<code> function fib(n) {
 let fibList = [];
 if (n < 2) {
    fibList.push(0);
 } else {
    let prev = 0;
    let curr = 1;
    fibList.push(prev, curr);
    for (let i = 2; i < n; i++) {
        const next = prev + curr;
        prev = curr;
        curr = next;
        fibList.push(curr);
    }
 }
 console.log(fibList);
 }
</code>```

Body:
I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I'm not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci(n) {
  let number1 = 0;
  let number2 = 1;

  for (i = 0; i < n; i++) {
    let current = number1 + number2;
    number1 = number2;
    number2 = current;
    console.log(current);
  }
}

helperFibonacci(2);

Please help me implement this function without passing an argument. thanks!

Body:
Try with this one , works great , have a good coding :)

 function fib(n) {
 let fibList = [];
 if (n < 2) {
    fibList.push(0);
 } else {
    let prev = 0;
    let curr = 1;
    fibList.push(prev, curr);
    for (let i = 2; i < n; i++) {
        const next = prev + curr;
        prev = curr;
        curr = next;
        fibList.push(curr);
    }
 }
 console.log(fibList);
 }


问:
cant seem to Deserialize to strongly typed list object from array
I'm trying to deserialize use the following Json and classes:

```<code>List<Root> OBJTEST = (List<Root>)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(List<Root>));
</code>```

Classes:

```<code>[DataContract]
public class Root
{
    [DataMember]
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }

    [DataMember]
    [JsonProperty("Time Series (Daily)")]
    public TimeSeriesDaily TimeSeriesDaily { get; set; }
}

[DataContract]
public class MetaData
{
    [DataMember]
    [JsonProperty("1. Information")]
    public string _1Information { get; set; }

    [DataMember]
    [JsonProperty("2. Symbol")]
    public string _2Symbol { get; set; }

    [DataMember]
    [JsonProperty("3. Last Refreshed")]
    public string _3LastRefreshed { get; set; }

    [DataMember]
    [JsonProperty("4. Output Size")]
    public string _4OutputSize { get; set; }

    [DataMember]
    [JsonProperty("5. Time Zone")]
    public string _5TimeZone { get; set; }
}

[DataContract]
public class _20220203
{
    [DataMember]
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [DataMember]
    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [DataMember]
    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [DataMember]
    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [DataMember]
    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

public class _20220202
{
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}
</code>```

JSON:

```<code>{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-02-04",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "1. open": "137.8600",
        "2. high": "138.8200",
        "3. low": "136.2150",
        "4. close": "137.1500",
        "5. volume": "4142045"
    },
    "2022-02-03": {
        "1. open": "137.0000",
        "2. high": "138.7600",
        "3. low": "135.8310",
        "4. close": "137.7800",
        "5. volume": "6100777"
    }
  }
}
</code>```

I could not get above to work
sourcing : "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo"

The objective is to return a List<Root> of strongly typed objects.

答:
try this

```<code>    string json = string.Empty;
    using (var client = new HttpClient())
    {
        var baseAddress = "https://www.alphavantage.co";
        var api = "/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo";

        client.BaseAddress = new Uri(baseAddress);
        var contentType = new MediaTypeWithQualityHeaderValue("application/json");
        client.DefaultRequestHeaders.Accept.Add(contentType);
        var response = client.GetAsync(api).Result;
        if (response.IsSuccessStatusCode)
            json = response.Content.ReadAsStringAsync().Result;
    }
    Data data =JsonConvert.DeserializeObject<Data>(json);
</code>```

and you can get TimeSeriesDaily list

```<code>List<TimeSeriesDaily> timeSeriesDaily = data.TimeSeriesDaily.Select(tsd => AddDate(tsd) ).ToList();

private TimeSeriesDaily AddDate(KeyValuePair<string, TimeSeriesDaily> tsdd)
{
    var tsd=tsdd.Value;
    tsd.Date=tsdd.Key;
    return tsd;
}
</code>```

classes

```<code>public partial class Data
    {
        [JsonProperty("Meta Data")]
        public MetaData MetaData { get; set; }

        [JsonProperty("Time Series (Daily)")]
        public Dictionary<string, TimeSeriesDaily> TimeSeriesDaily { get; set; }
    }

    public partial class MetaData
    {
        [JsonProperty("1. Information")]
        public string The1Information { get; set; }

        [JsonProperty("2. Symbol")]
        public string The2Symbol { get; set; }

        [JsonProperty("3. Last Refreshed")]
        public DateTimeOffset The3LastRefreshed { get; set; }

        [JsonProperty("4. Output Size")]
        public string The4OutputSize { get; set; }

        [JsonProperty("5. Time Zone")]
        public string The5TimeZone { get; set; }
    }

public partial class TimeSeriesDaily
{
    [JsonIgnore]
    public string Date { get; set; }

    [JsonProperty("1. open")]
    public string The1Open { get; set; }

    [JsonProperty("2. high")]
    public string The2High { get; set; }

    [JsonProperty("3. low")]
    public string The3Low { get; set; }

    [JsonProperty("4. close")]
    public string The4Close { get; set; }

    [JsonProperty("5. volume")]
    public long The5Volume { get; set; }
}
</code>```

Body:
I'm trying to deserialize use the following Json and classes:

List<Root> OBJTEST = (List<Root>)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(List<Root>));

Classes:

[DataContract]
public class Root
{
    [DataMember]
    [JsonProperty("Meta Data")]
    public MetaData MetaData { get; set; }

    [DataMember]
    [JsonProperty("Time Series (Daily)")]
    public TimeSeriesDaily TimeSeriesDaily { get; set; }
}

[DataContract]
public class MetaData
{
    [DataMember]
    [JsonProperty("1. Information")]
    public string _1Information { get; set; }

    [DataMember]
    [JsonProperty("2. Symbol")]
    public string _2Symbol { get; set; }

    [DataMember]
    [JsonProperty("3. Last Refreshed")]
    public string _3LastRefreshed { get; set; }

    [DataMember]
    [JsonProperty("4. Output Size")]
    public string _4OutputSize { get; set; }

    [DataMember]
    [JsonProperty("5. Time Zone")]
    public string _5TimeZone { get; set; }
}

[DataContract]
public class _20220203
{
    [DataMember]
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [DataMember]
    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [DataMember]
    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [DataMember]
    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [DataMember]
    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

public class _20220202
{
    [JsonProperty("1. open")]
    public string _1Open { get; set; }

    [JsonProperty("2. high")]
    public string _2High { get; set; }

    [JsonProperty("3. low")]
    public string _3Low { get; set; }

    [JsonProperty("4. close")]
    public string _4Close { get; set; }

    [JsonProperty("5. volume")]
    public string _5Volume { get; set; }
}

JSON:

{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2022-02-04",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2022-02-04": {
        "1. open": "137.8600",
        "2. high": "138.8200",
        "3. low": "136.2150",
        "4. close": "137.1500",
        "5. volume": "4142045"
    },
    "2022-02-03": {
        "1. open": "137.0000",
        "2. high": "138.7600",
        "3. low": "135.8310",
        "4. close": "137.7800",
        "5. volume": "6100777"
    }
  }
}

I could not get above to work
sourcing : "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo"

The objective is to return a List<Root> of strongly typed objects.

Body:
try this

    string json = string.Empty;
    using (var client = new HttpClient())
    {
        var baseAddress = "https://www.alphavantage.co";
        var api = "/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo";

        client.BaseAddress = new Uri(baseAddress);
        var contentType = new MediaTypeWithQualityHeaderValue("application/json");
        client.DefaultRequestHeaders.Accept.Add(contentType);
        var response = client.GetAsync(api).Result;
        if (response.IsSuccessStatusCode)
            json = response.Content.ReadAsStringAsync().Result;
    }
    Data data =JsonConvert.DeserializeObject<Data>(json);

and you can get TimeSeriesDaily list

List<TimeSeriesDaily> timeSeriesDaily = data.TimeSeriesDaily.Select(tsd => AddDate(tsd) ).ToList();

private TimeSeriesDaily AddDate(KeyValuePair<string, TimeSeriesDaily> tsdd)
{
    var tsd=tsdd.Value;
    tsd.Date=tsdd.Key;
    return tsd;
}

classes

public partial class Data
    {
        [JsonProperty("Meta Data")]
        public MetaData MetaData { get; set; }

        [JsonProperty("Time Series (Daily)")]
        public Dictionary<string, TimeSeriesDaily> TimeSeriesDaily { get; set; }
    }

    public partial class MetaData
    {
        [JsonProperty("1. Information")]
        public string The1Information { get; set; }

        [JsonProperty("2. Symbol")]
        public string The2Symbol { get; set; }

        [JsonProperty("3. Last Refreshed")]
        public DateTimeOffset The3LastRefreshed { get; set; }

        [JsonProperty("4. Output Size")]
        public string The4OutputSize { get; set; }

        [JsonProperty("5. Time Zone")]
        public string The5TimeZone { get; set; }
    }

public partial class TimeSeriesDaily
{
    [JsonIgnore]
    public string Date { get; set; }

    [JsonProperty("1. open")]
    public string The1Open { get; set; }

    [JsonProperty("2. high")]
    public string The2High { get; set; }

    [JsonProperty("3. low")]
    public string The3Low { get; set; }

    [JsonProperty("4. close")]
    public string The4Close { get; set; }

    [JsonProperty("5. volume")]
    public long The5Volume { get; set; }
}


问:
Add dynamic value beside label in Material UI React Tabs Component
I am creating tabs using material ui and i want to add value beside label (ex: 05 written beside Recommendation label) which will be dynamic in the tabs component just like shown in below image:

Here is my code snippet of Tabs component:

```<code>    <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
      <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
         <Tab label="Recommendation" />
         <Tab label="Ongoing" />
         <Tab label="Completed" />
      </Tabs>
   </Box>
</code>```

答:
One option is to create your own component, pass that in as a the Tab label, and then style it as needed.  For example:

```<code>const TabWithCount = ({ children, count }) => {
  return (
    <Box sx={{ display: "inline-flex", alignItems: "center" }}>
      <Typography component="div">{children}</Typography>
      {count ? (
        <Typography
          component="div"
          variant="body2"
          sx={{ marginLeft: "0.5rem" }}
        >
          {count}
        </Typography>
      ) : null}
    </Box>
  );
};

...

<Tab
  label={<TabWithCount count="05">Recommendation</TabWithCount>}
/>
</code>```

I've created a quick (unstyled) example to illustrate the solution: https://codesandbox.io/s/basictabs-material-demo-forked-i9543?file=/demo.js

Body:
I am creating tabs using material ui and i want to add value beside label (ex: 05 written beside Recommendation label) which will be dynamic in the tabs component just like shown in below image:

Here is my code snippet of Tabs component:

    <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
      <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
         <Tab label="Recommendation" />
         <Tab label="Ongoing" />
         <Tab label="Completed" />
      </Tabs>
   </Box>

Body:
One option is to create your own component, pass that in as a the Tab label, and then style it as needed.  For example:

const TabWithCount = ({ children, count }) => {
  return (
    <Box sx={{ display: "inline-flex", alignItems: "center" }}>
      <Typography component="div">{children}</Typography>
      {count ? (
        <Typography
          component="div"
          variant="body2"
          sx={{ marginLeft: "0.5rem" }}
        >
          {count}
        </Typography>
      ) : null}
    </Box>
  );
};

...

<Tab
  label={<TabWithCount count="05">Recommendation</TabWithCount>}
/>

I've created a quick (unstyled) example to illustrate the solution: https://codesandbox.io/s/basictabs-material-demo-forked-i9543?file=/demo.js


问:
R: dplyr and row_number() does not enumerate as expected
I want to enumerate each record of a dataframe/tibble resulted from a grouping. The index is according a defined order. If I use row_number() it does enumerate but within group. But I want that it enumerates without considering the former grouping.

Here is an example. To make it simple I used the most minimal dataframe:

```<code>library(dplyr)

df0 <- data.frame( x1 = rep(LETTERS[1:2],each=2)
                 , x2 = rep(letters[1:2], 2)
                 , y = floor(abs(rnorm(4)*10))
)
df0
#   x1 x2  y
# 1  A  a 12
# 2  A  b 24
# 3  B  a  0
# 4  B  b 12
</code>```

Now, I group this table:

```<code> df1 <- df0 %>% group_by(x1,x2) %>% summarize(y=sum(y))
</code>```

This gives me a object of class tibble:

```<code> # A tibble: 4 x 3
 # Groups:   x1 [?]
 #   x1    x2        y
 #   <fct> <fct> <dbl>
 # 1 A     a        12
 # 2 A     b        24
 # 3 B     a         0
 # 4 B     b        12
</code>```

I want to add a row number to this table using row_numer():

```<code> df2 <- df1 %>% arrange(desc(y)) %>% mutate(index = row_number())
 df2
 # A tibble: 4 x 4
 # Groups:   x1 [2]
 #   x1    x2        y index
 #   <fct> <fct> <dbl> <int>
 # 1 A     b        24     1
 # 2 A     a        12     2
 # 3 B     b        12     1
 # 4 B     a         0     2
</code>```

row_number() does enumerate within the former grouping. This was not my intention. This can be avoid converting tibble to a dataframe first:

```<code> df2 <- df2 %>% as.data.frame() %>% arrange(desc(y)) %>% mutate(index = row_number())
 df2
 #   x1 x2  y index
 # 1  A  b 24     1
 # 2  A  a 12     2
 # 3  B  b 12     3
 # 4  B  a  0     4
</code>```

My question is: is this behaviour intended?
If yes: is it not very dangerous to incorporate former data processing into tibble? Which type of processing is incorporated?
At the moment I will convert tibble into dataframe to avoid this kind of unexpected results.

答:
As camille nicely showed, there are good reasons for wanting to have the result of summarize() retain additional layers of grouping and it's a documented behaviour so not really dangerous or unexpected per se.

However one additional tip is that if you are just going to call ungroup() after summarize() you might as well use summarize(.groups = "drop") which will return an ungrouped tibble and save you a line of code.

library(tidyverse)

df0 <- data.frame(
  x1 = rep(LETTERS[1:2], each = 2),
  x2 = rep(letters[1:2], 2),
  y = floor(abs(rnorm(4) * 10))
)

df0 %>%
  group_by(x1,x2) %>%
  summarize(y=sum(y), .groups = "drop") %>%
  arrange(desc(y)) %>%
  mutate(index = row_number())
#> # A tibble: 4 x 4
#>   x1    x2        y index
#>   <chr> <chr> <dbl> <int>
#> 1 A     b         8     1
#> 2 A     a         2     2
#> 3 B     a         2     3
#> 4 B     b         1     4
```

Created on 2022-02-06 by the reprex package (v2.0.1)

Body:
I want to enumerate each record of a dataframe/tibble resulted from a grouping. The index is according a defined order. If I use row_number() it does enumerate but within group. But I want that it enumerates without considering the former grouping.

Here is an example. To make it simple I used the most minimal dataframe:

library(dplyr)

df0 <- data.frame( x1 = rep(LETTERS[1:2],each=2)
                 , x2 = rep(letters[1:2], 2)
                 , y = floor(abs(rnorm(4)*10))
)
df0
#   x1 x2  y
# 1  A  a 12
# 2  A  b 24
# 3  B  a  0
# 4  B  b 12

Now, I group this table:

 df1 <- df0 %>% group_by(x1,x2) %>% summarize(y=sum(y))

This gives me a object of class tibble:

 # A tibble: 4 x 3
 # Groups:   x1 [?]
 #   x1    x2        y
 #   <fct> <fct> <dbl>
 # 1 A     a        12
 # 2 A     b        24
 # 3 B     a         0
 # 4 B     b        12

I want to add a row number to this table using row_numer():

 df2 <- df1 %>% arrange(desc(y)) %>% mutate(index = row_number())
 df2
 # A tibble: 4 x 4
 # Groups:   x1 [2]
 #   x1    x2        y index
 #   <fct> <fct> <dbl> <int>
 # 1 A     b        24     1
 # 2 A     a        12     2
 # 3 B     b        12     1
 # 4 B     a         0     2

row_number() does enumerate within the former grouping. This was not my intention. This can be avoid converting tibble to a dataframe first:

 df2 <- df2 %>% as.data.frame() %>% arrange(desc(y)) %>% mutate(index = row_number())
 df2
 #   x1 x2  y index
 # 1  A  b 24     1
 # 2  A  a 12     2
 # 3  B  b 12     3
 # 4  B  a  0     4

My question is: is this behaviour intended?
If yes: is it not very dangerous to incorporate former data processing into tibble? Which type of processing is incorporated?
At the moment I will convert tibble into dataframe to avoid this kind of unexpected results.

Body:
As camille nicely showed, there are good reasons for wanting to have the result of summarize() retain additional layers of grouping and it's a documented behaviour so not really dangerous or unexpected per se.

However one additional tip is that if you are just going to call ungroup() after summarize() you might as well use summarize(.groups = "drop") which will return an ungrouped tibble and save you a line of code.

library(tidyverse)

df0 <- data.frame(
  x1 = rep(LETTERS[1:2], each = 2),
  x2 = rep(letters[1:2], 2),
  y = floor(abs(rnorm(4) * 10))
)

df0 %>%
  group_by(x1,x2) %>%
  summarize(y=sum(y), .groups = "drop") %>%
  arrange(desc(y)) %>%
  mutate(index = row_number())
#> # A tibble: 4 x 4
#>   x1    x2        y index
#>   <chr> <chr> <dbl> <int>
#> 1 A     b         8     1
#> 2 A     a         2     2
#> 3 B     a         2     3
#> 4 B     b         1     4

Created on 2022-02-06 by the reprex package (v2.0.1)


问:
Iterable O(1) insert and random delete collection
I am looking to implement my own collection class.  The characteristics I want are:

Iterable - order is not important

Insertion - either at end or at iterator location, it does not matter

Random Deletion - this is the tricky one.  I want to be able to have a reference to a piece of data which is guaranteed to be within the list, and remove it from the list in O(1) time.

I plan on the container only holding custom classes, so I was thinking a doubly linked list that required the components to implement a simple interface (or abstract class).

Here is where I am getting stuck.  I am wondering whether it would be better practice to simply have the items in the list hold a reference to their node, or to build the node right into them.  I feel like both would be fairly simple, but I am worried about coupling these nodes into a bunch of classes.

I am wondering if anyone has an idea as to how to minimize the coupling, or possibly know of another data structure that has the characteristics I want.

答:
In C++, this sounds like the perfect fit for std::unordered_set (that's std::tr1::unordered_set or boost::unordered_set to you if you have an older compiler). It's implemented as a hash set, which has the characteristics you describe.

Here's the interface documentation. Note that the hash containers actually offer two sets of iterators, the usual ones and local ones which only go through one bucket.

Many other languages have "hash sets" as well, certainly Java and C#.


问:
Spark Add New Column with List Count
Let's say I have the following data - order_id and product_names.

```<code>data = [["1", ["Organic A", "Apple"],
        ["2", ["Organic B", "Chocolate", "Organic C]]
</code>```

If I want to create a dataframe and add a new column product_count so the output looks like the following, how can I do that?

```<code>Output:
+----------------------------------------------------------------+
|order_id | product_count|                          product_names|
+----------------------------------------------------------------+
|       1 |             2|                 ["Organic A", "Apple"]|
|       2 |             3| ["Organic B", "Chocolate", "Organic C]|
+----------------------------------------------------------------+

</code>```

答:
You can use the size function to get the length of the product_names field.

```<code>df = df.select('order_id', F.size('product_names').alias('product_count'), 'product_names')
df.show(truncate=False)
</code>```

Title: Spark Add New Column with List Count

Body:
Let's say I have the following data - order_id and product_names.

data = [["1", ["Organic A", "Apple"],
        ["2", ["Organic B", "Chocolate", "Organic C]]

If I want to create a dataframe and add a new column product_count so the output looks like the following, how can I do that?

Output:
+----------------------------------------------------------------+
|order_id | product_count|                          product_names|
+----------------------------------------------------------------+
|       1 |             2|                 ["Organic A", "Apple"]|
|       2 |             3| ["Organic B", "Chocolate", "Organic C]|
+----------------------------------------------------------------+

Body:
You can use the size function to get the length of the product_names field.

df = df.select('order_id', F.size('product_names').alias('product_count'), 'product_names')
df.show(truncate=False)


问:
Clearing console in Intellij-idea
Could anyone tell me if it's possible to clear console in intellij-idea and how?

So far I have tried:

```<code>System.out.print("\033[H\033[2J");
System.out.flush();
</code>```

and:

```<code>Runtime.getRuntime().exec("clear");
</code>```

but any of those did work.

I'm using Intellij-idea ultimate 2017 2.4 and Linux Mint.

答:
IntelliJ IDEA console is not a real terminal, so there is no command to clear it from your Java code.

See the issue here.

Try run your application in other terminal, then you can make a function like this:

```<code>public static void ClearConsole(){
    try{
        String operatingSystem = System.getProperty("os.name") //Check the current operating system

        if(operatingSystem.contains("Windows")){
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cls");
            Process startProcess = pb.inheritIO.start();
            startProcess.waitFor();
        } else {
            ProcessBuilder pb = new ProcessBuilder("clear");
            Process startProcess = pb.inheritIO.start();

            startProcess.waitFor();
        }
    }catch(Exception e){
        System.out.println(e);
    }
}
</code>```

Title: Clearing console in Intellij-idea

Body:
Could anyone tell me if it's possible to clear console in intellij-idea and how?

So far I have tried:

System.out.print("\033[H\033[2J");
System.out.flush();

and:

Runtime.getRuntime().exec("clear");

but any of those did work.

I'm using Intellij-idea ultimate 2017 2.4 and Linux Mint.

Body:
IntelliJ IDEA console is not a real terminal, so there is no command to clear it from your Java code.

See the issue here.

Try run your application in other terminal, then you can make a function like this:

public static void ClearConsole(){
    try{
        String operatingSystem = System.getProperty("os.name") //Check the current operating system

        if(operatingSystem.contains("Windows")){
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "cls");
            Process startProcess = pb.inheritIO.start();
            startProcess.waitFor();
        } else {
            ProcessBuilder pb = new ProcessBuilder("clear");
            Process startProcess = pb.inheritIO.start();

            startProcess.waitFor();
        }
    }catch(Exception e){
        System.out.println(e);
    }
}


问:
jQuery Setting Element Styles Based On Modal Visibility Behaves Differently in Firefox and Chrome
I'm new to jquery and javascript. I have a website with multiple unique modal/popups that are triggered via a CSS :target selector, which sets them to display: block. I'm trying to use jquery to hide a separate element among other things.

The logic is:

If a modal is visible, then hide element. Else show element. I'm currently using popstate in my jquery. This is because the modals can close if the user presses their browser back button. So I don't want to use any click functions. Everything seems to be working fine, except the if/else statements that detect the visibility of the modals seem to behave differently between Firefox and Chrome? When it hides the element in Firefox, it shows it Chrome. When it hides it in Chrome, it shows it in Firefox. Why the opposite behavior? What am I doing wrong?

$(window).on('popstate', function(event) {
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}</code>```

This element should hide when modal is open

  Click Me To Open Modal

I'm a Modal. Press browser back button to close

```
</div>
</div>
</p>
<p>Alternate jQuery:</p>
<p>Setting the length to 1 works in Firefox and works oppositely in Chrome.<br/>
Setting the length to 0 works in Chrome and works oppositely in Firefox.</p>
```$(window).on('popstate', function(event) {
    if ( $('.modal-overlay:visible').length === 1 ) {
        console.log("Modal ON");
        $('#wrapper').css('overflow-y', 'hidden');
        $('#extra_element').css('display', 'none');
    }
    else {
        console.log("Modal OFF");
        $('#wrapper').css('overflow-y', 'scroll');
        $('#extra_element').css('display', 'block');
    }
});
```

Is there another way to do this correctly?

答:
This would be a Chrome bug, according to the specs, at the step 10 of the History traversal algorithm the UA should call the "scroll to fragment" algorithm which is responsible for updating the document's target element (:target) and only at the step 18.1 it should fire the popstate event.

Chrome does fire the event before it updates the document's target element, and thus your CSS :target selector doesn't match yet.

I did open an issue so they get this in-line with the standards, but for the time being you can workaround that by waiting just a task after the event fired:

$(window).on('popstate', async function(event) {
  await new Promise(res => setTimeout(() => res()));
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}</code>```

This element should hide when modal is open

  Click Me To Open Modal

Press browser back button to close

```

Body:
I'm new to jquery and javascript. I have a website with multiple unique modal/popups that are triggered via a CSS :target selector, which sets them to display: block. I'm trying to use jquery to hide a separate element among other things.

The logic is:

If a modal is visible, then hide element. Else show element. I'm currently using popstate in my jquery. This is because the modals can close if the user presses their browser back button. So I don't want to use any click functions. Everything seems to be working fine, except the if/else statements that detect the visibility of the modals seem to behave differently between Firefox and Chrome? When it hides the element in Firefox, it shows it Chrome. When it hides it in Chrome, it shows it in Firefox. Why the opposite behavior? What am I doing wrong?

$(window).on('popstate', function(event) {
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});

.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}

This element should hide when modal is open

  Click Me To Open Modal

I'm a Modal. Press browser back button to close

Alternate jQuery:

Setting the length to 1 works in Firefox and works oppositely in Chrome.

Setting the length to 0 works in Chrome and works oppositely in Firefox.

$(window).on('popstate', function(event) {
    if ( $('.modal-overlay:visible').length === 1 ) {
        console.log("Modal ON");
        $('#wrapper').css('overflow-y', 'hidden');
        $('#extra_element').css('display', 'none');
    }
    else {
        console.log("Modal OFF");
        $('#wrapper').css('overflow-y', 'scroll');
        $('#extra_element').css('display', 'block');
    }
});

Is there another way to do this correctly?

Body:
This would be a Chrome bug, according to the specs, at the step 10 of the History traversal algorithm the UA should call the "scroll to fragment" algorithm which is responsible for updating the document's target element (:target) and only at the step 18.1 it should fire the popstate event.

Chrome does fire the event before it updates the document's target element, and thus your CSS :target selector doesn't match yet.

I did open an issue so they get this in-line with the standards, but for the time being you can workaround that by waiting just a task after the event fired:

$(window).on('popstate', async function(event) {
  await new Promise(res => setTimeout(() => res()));
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});

.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="extra_element">This element should hide when modal is open</div>

<div>
  <a href="#content">Click Me To Open Modal</a>
  <div id="content" class="modal">Press browser back button to close
  </div>
</div>


问:
How do I make an html link look like a button?
I'm using ASP.NET, some of my buttons just do redirects.  I'd rather they were ordinary links, but I don't want my users to notice much difference in the appearance.  I considered images wrapped by anchors, i.e.  tags, but I don't want to have to fire up an image editor every time I change the text on a button.</p>

答:
You could create a standard button, then use it as the background image for a link.  Then you can set the text in the link without changing the image.

The best solutions if you don't a special rendered button are the two already given by TStamper and Ólafur Waage.

OwnerDisplayName: MatthewMartin

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: ck


答:
Take a look at tries.

Apparently they can beat hashtables:

Unlike most other algorithms, tries have the peculiar feature that the time to insert, or to delete or to find is almost identical because the code paths followed for each are almost identical. As a result, for situations where code is inserting, deleting and finding in equal measure tries can handily beat binary search trees or even hash tables, as well as being better for the CPU's instruction and branch caches.

It may or may not fit your usage, but if it does, it's likely one of the best options possible.

Title: Iterable O(1) insert and random delete collection

Body:
I am looking to implement my own collection class.  The characteristics I want are:

Iterable - order is not important

Insertion - either at end or at iterator location, it does not matter

Random Deletion - this is the tricky one.  I want to be able to have a reference to a piece of data which is guaranteed to be within the list, and remove it from the list in O(1) time.

I plan on the container only holding custom classes, so I was thinking a doubly linked list that required the components to implement a simple interface (or abstract class).

Here is where I am getting stuck.  I am wondering whether it would be better practice to simply have the items in the list hold a reference to their node, or to build the node right into them.  I feel like both would be fairly simple, but I am worried about coupling these nodes into a bunch of classes.

I am wondering if anyone has an idea as to how to minimize the coupling, or possibly know of another data structure that has the characteristics I want.


问:
Why iterators are called fail safe or fail fast?
Why are iterators called "fail-safe" and "fail-fast" even though Iterator.remove() doesn't throw any ConcurrentModificationException while iterating through a Collection (for example, HashMap) using Iterator ?

答:
My answer includes two points.

To the answer marked correct, it is important to add that fail-fast behaviour of iterators is not 100% reliable (and API docs state that). The docs say it behaves on the best-effort basis and it is advised to use it only for bugs detection:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs

Thus, you probably should take this behaviour into account when writing code, but you definitely must not fully rely on it.

There is a very good article on that. I know it was written later than asked. However, I find it useful to understand what's called concurrent modification policy.

So, there are four policies, and among them there is no fail-safe one:

Fail-fast

Weakly consistent

Snapshot

undefined

The conclusion from the article says:

After all this, where does “fail-safe” come into the picture? Answer: it doesn’t. The words “fail-safe” are never used in the Java SE specifications that describe the concurrent modification policy of a collection. As such, there is no reliable, consistent definition of “fail-safe” for an Iterator. One can attempt to apply the general concept of “fail-safety” to an Iterator, but this is open to varying, misleading, and even contradictory interpretations.

Don’t use “fail-safe” to describe a Java Iterator. Instead, use one of the documented policies listed above.


问:
How to shift each letter of the string by a given number of letters?
How can i shift each letter of a string by a given number of letters down or up in bash, without using a hardcoded dictionary?</p>

答:
Without using tr, shift 1 to 25 characters
and can be decrypted using 26 - original key</p>
```<code>#!/bin/bash

#set -x

i=0
for letters in {A..Z}
do
abc_cap[$i]="$letters"
((i++))
done

i=0
for letters in {a..z}
do
abc_small[$i]="$letters"
((i++))
done

read -r -p "Enter message to be encrypted/decrypted: " -a message
read -r -p "Enter shift amount (26 - orig key for decrypt): " shift_amount

echo -n "Encrypted message: "

if [ "$shift_amount" -gt 25 ] || [ "$shift_amount" -lt 1 ]
then
echo "Shift amount out of range"
exit
fi

for word in "${message[@]}"
do

while read -r -n 1 letter
do
if [[ "$letter" = [a-z] ]]
then
        for a in "${!abc_small[@]}"
        do
        if [ "${abc_small[$a]}" = "$letter" ]
        then
        a=$(echo "($a + $shift_amount) % 26" | bc)
        echo -n "${abc_small[$a]}"
        fi
        done

elif [[ "$letter" = [A-Z] ]]
then
        for a in "${!abc_cap[@]}"
        do
       if [ "${abc_cap[$a]}" = "$letter" ]
        then
        a=$(echo "($a + $shift_amount) % 26" | bc)
        echo -n "${abc_cap[$a]}"
        fi
        done

elif [[ "$letter" = "" ]]
then echo -n " "

else echo -n "$letter"
fi

done < <(echo "$word")
done
echo
exit

</code>```

Body:
Without using tr, shift 1 to 25 characters
and can be decrypted using 26 - original key

#!/bin/bash

#set -x

i=0
for letters in {A..Z}
do
abc_cap[$i]="$letters"
((i++))
done

i=0
for letters in {a..z}
do
abc_small[$i]="$letters"
((i++))
done

read -r -p "Enter message to be encrypted/decrypted: " -a message
read -r -p "Enter shift amount (26 - orig key for decrypt): " shift_amount

echo -n "Encrypted message: "

if [ "$shift_amount" -gt 25 ] || [ "$shift_amount" -lt 1 ]
then
echo "Shift amount out of range"
exit
fi

for word in "${message[@]}"
do

while read -r -n 1 letter
do
if [[ "$letter" = [a-z] ]]
then
        for a in "${!abc_small[@]}"
        do
        if [ "${abc_small[$a]}" = "$letter" ]
        then
        a=$(echo "($a + $shift_amount) % 26" | bc)
        echo -n "${abc_small[$a]}"
        fi
        done

elif [[ "$letter" = [A-Z] ]]
then
        for a in "${!abc_cap[@]}"
        do
       if [ "${abc_cap[$a]}" = "$letter" ]
        then
        a=$(echo "($a + $shift_amount) % 26" | bc)
        echo -n "${abc_cap[$a]}"
        fi
        done

elif [[ "$letter" = "" ]]
then echo -n " "

else echo -n "$letter"
fi

done < <(echo "$word")
done
echo
exit


问:
Finding Max element of the list of lists in c++ (conversion of python function)
I wanted to convert the following function python to c++:

```<code>def find_max_value(list):
max_value_list = []
for i in list:
    max_value_list.append(i[0])
return max(max_value_list)
</code>```

The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [237.026305, 263.076182, 237.629826, 247.023679, 4.523158]]

The Output is 520.293431.

I have tried but getting some errors. Could you please mention where I'm doing wrong?

```<code>std::list<int> find_max_value(std::list<int> a(std::list<double> b)){
std::list<int> max_value_list;
for (std::list<int>::iterator i = *a.begin(); i!=*a.end(); ++i){
    max_value_list.push_back(i.front());
    return std::max_element(i);
}
}
</code>```

Those are the errors:

Thanks in advance!!!

答:
Note: This finds the max element in a list of lists as the title asked for. The python code however finds the max element of the first elements in the inner lists - which is what Igor's answer does.

You need a 2D std::list in order for your data to be stored in a similar way as in the python code. You can then use std::max_element on all the inner lists.

Example:

```<code>#include <algorithm>
#include <iostream>
#include <limits>
#include <list>

double find_max_value(const std::list<std::list<double>>& list) {
    // start with the lowest possible double
    double result = std::numeric_limits<double>::lowest();

    for (auto& inner : list) {
        if (!inner.empty())
            result = std::max(result, *std::max_element(inner.begin(), inner.end()));
    }

    return result;
}

int main() {
    std::list<std::list<double>> list{
        {90.272948, 210.999601, 90.31622, 349.000214, 4.042645},
        {520.293431, 349.000041, 520.285479, 211.000041, 2.007837},
        {237.026305, 263.076182, 237.629826, 247.023679, 4.523158}};

    std::cout << find_max_value(list) << '\n';
}
</code>```

Output

```<code>520.293
</code>```

Body:
I wanted to convert the following function python to c++:

def find_max_value(list):
max_value_list = []
for i in list:
    max_value_list.append(i[0])
return max(max_value_list)

The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [237.026305, 263.076182, 237.629826, 247.023679, 4.523158]]

The Output is 520.293431.

I have tried but getting some errors. Could you please mention where I'm doing wrong?

std::list<int> find_max_value(std::list<int> a(std::list<double> b)){
std::list<int> max_value_list;
for (std::list<int>::iterator i = *a.begin(); i!=*a.end(); ++i){
    max_value_list.push_back(i.front());
    return std::max_element(i);
}
}

Those are the errors:

Thanks in advance!!!

Body:
Note: This finds the max element in a list of lists as the title asked for. The python code however finds the max element of the first elements in the inner lists - which is what Igor's answer does.

You need a 2D std::list in order for your data to be stored in a similar way as in the python code. You can then use std::max_element on all the inner lists.

Example:

#include <algorithm>
#include <iostream>
#include <limits>
#include <list>

double find_max_value(const std::list<std::list<double>>& list) {
    // start with the lowest possible double
    double result = std::numeric_limits<double>::lowest();

    for (auto& inner : list) {
        if (!inner.empty())
            result = std::max(result, *std::max_element(inner.begin(), inner.end()));
    }

    return result;
}

int main() {
    std::list<std::list<double>> list{
        {90.272948, 210.999601, 90.31622, 349.000214, 4.042645},
        {520.293431, 349.000041, 520.285479, 211.000041, 2.007837},
        {237.026305, 263.076182, 237.629826, 247.023679, 4.523158}};

    std::cout << find_max_value(list) << '\n';
}

Output

520.293


问:
Turtle goto method

from turtle import Turtle, Screen
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake')
screen.tracer(0)
starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    turtle = Turtle('square')
    turtle.color('white')
    turtle.penup()
    turtle.goto(position)
    segments.append(turtle)

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)

    for seg_num in range(len(segments) - 1, 0, -1):
        new_x = segments[seg_num - 1].xcor()
        new_y = segments[seg_num - 1].xcor()
        segments[seg_num].goto(new_x, new_y)

screen.exitonclick()
```

My problem is in the for loop on line 25.
Could anyone explain why there is just one square showing on the screen rather than two because if the third item goes to the second positions coordinates, and the second item goes to the coordinates of the first position, surely there should be two squares?

Sorry if this is unclear, this is the best I can try to explain it.
https://i.stack.imgur.com/ed9Ld.png

答:
The problem is your first (zero index) segment never moves.  So fairly quickly all your segments share its position.  If we move the first segment as part of the loop, then all the segments slither after it:</p>
```<code>from turtle import Turtle, Screen

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

def run():
    if game_is_on:
        for index in range(len(segments) - 1, 0, -1):
            segments[index].setposition(segments[index - 1].position())

        segments[0].forward(20)

    screen.update()
    screen.ontimer(run, 100)

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake')
screen.tracer(0)

segments = []

for position in starting_positions:
    turtle = Turtle('square')
    turtle.color('white')
    turtle.penup()
    turtle.goto(position)
    segments.append(turtle)

game_is_on = True

screen.update()

run()

screen.exitonclick()
</code>```

Title: Turtle goto method

Body:
from turtle import Turtle, Screen
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake')
screen.tracer(0)
starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    turtle = Turtle('square')
    turtle.color('white')
    turtle.penup()
    turtle.goto(position)
    segments.append(turtle)

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)

    for seg_num in range(len(segments) - 1, 0, -1):
        new_x = segments[seg_num - 1].xcor()
        new_y = segments[seg_num - 1].xcor()
        segments[seg_num].goto(new_x, new_y)

screen.exitonclick()

My problem is in the for loop on line 25.
Could anyone explain why there is just one square showing on the screen rather than two because if the third item goes to the second positions coordinates, and the second item goes to the coordinates of the first position, surely there should be two squares?

Sorry if this is unclear, this is the best I can try to explain it.
https://i.stack.imgur.com/ed9Ld.png

Body:
The problem is your first (zero index) segment never moves.  So fairly quickly all your segments share its position.  If we move the first segment as part of the loop, then all the segments slither after it:

from turtle import Turtle, Screen

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

def run():
    if game_is_on:
        for index in range(len(segments) - 1, 0, -1):
            segments[index].setposition(segments[index - 1].position())

        segments[0].forward(20)

    screen.update()
    screen.ontimer(run, 100)

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake')
screen.tracer(0)

segments = []

for position in starting_positions:
    turtle = Turtle('square')
    turtle.color('white')
    turtle.penup()
    turtle.goto(position)
    segments.append(turtle)

game_is_on = True

screen.update()

run()

screen.exitonclick()


问:
Undefined index error
i am trying to Post something but keep getting Undefined index error. I have encountered this problem before and using  if(isset($_POST['in_come']) solved my previous problem. But, now it does not. What can cause this problem? Everything seems correct.Html posts an input and php should have gotten it
Thanks</p>

答:
The problem is caused by you trying to access an array index that doesn't exist. E.g:

```<code>$foo = array('bar');
echo $foo[99999];
</code>```

That means you have a logic error somewhere in your code.

Title: Undefined index error

Body:
The problem is caused by you trying to access an array index that doesn't exist. E.g:

$foo = array('bar');
echo $foo[99999];

That means you have a logic error somewhere in your code.