问:
How to fix error Failed assertion: line 1869 pos 16: 'constraints.hasBoundedWidth': is not true. when i'm using GridView.count in flutter?
I'm using GridView.count in the showModalBottomSheet when click button.
But i got this error 'package:flutter/src/rendering/viewport.dart': Failed assertion: line 1869 pos 16: 'constraints.hasBoundedWidth': is not true.
package:flutter/…/rendering/viewport.dart:1869
Can anyone help? Please.

Here it's my code

```<code>loatingActionButton: FloatingActionButton(
    child: const Icon(Icons.add),
    onPressed: () {
      showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SizedBox.expand(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text("Add"),
                ),
                GridView.count(
                  crossAxisCount: 1,
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  children: <Widget>[
                    Container(
                      child: Text("item 1"),
                    ),
                    Container(
                      child: Text("item 2"),
                    ),
                  ],
                )
              ],
            ),
          );
        },
      );
    },
  ),
</code>```

答:
You try it set width, height of SizedBox

Use

 SizedBox(width: xx, height: xx)

Instead of

 SizedBox.expand

Body:
I'm using GridView.count in the showModalBottomSheet when click button.
But i got this error 'package:flutter/src/rendering/viewport.dart': Failed assertion: line 1869 pos 16: 'constraints.hasBoundedWidth': is not true.
package:flutter/…/rendering/viewport.dart:1869
Can anyone help? Please.

Here it's my code

loatingActionButton: FloatingActionButton(
    child: const Icon(Icons.add),
    onPressed: () {
      showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SizedBox.expand(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text("Add"),
                ),
                GridView.count(
                  crossAxisCount: 1,
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  children: <Widget>[
                    Container(
                      child: Text("item 1"),
                    ),
                    Container(
                      child: Text("item 2"),
                    ),
                  ],
                )
              ],
            ),
          );
        },
      );
    },
  ),


来源: stackexchange

问:
Set CMake Ninja build output same format as Unix Makefiles
In my C++ app I use CLion as IDE and I have set it up like this.

I noticed that the Generator (under Settings->Build->CMake) has been changed to Ninja.

And the build output is no longer nice and descriptive (and warnings are no longer shown):

With the Unix Makefiles generator, it used to output like this:

Which is much nicer, showing more information and warnings.

Is there a way I can set the Ninja build output format the same as the one of Unix Makefiles?

答:
... (and warnings are no longer shown) ... showing more information and warnings ...

Ninja absolutely does still show warnings when they appear.

Is there a way I can set the Ninja build output format the same as the one of Unix Makefiles?

No. However, the best you can do (short of patching Ninja) is this:

Add --verbose to the "Build options:" line entry item in that same settings dialog from your first picture to get line-by-line outputs in Ninja.

ContentLicense: CC BY-SA 4.0


问:
react-native-datetimepicker/datetimepicker is 1 day off
I'm so confused what's going on. I just implemented react-native-datetimepicker/datetimepicker for a user to select their birthday.

If I select June 8, 2000 -> the date returned is 2000-06-09T00:00:00.000Z, which means the users birthday is set for June 9, 2000.

here is the element:

```<code>       <DateTimePicker
          value={this.props.date}
          mode={this.props.mode}
          display="calendar"
          onChange={(event, date) => {
            this.handleDatePicked(event, date)
          }}
        />

        async handleDatePicked(event, date) {
          console.log(new Date(date))
          await this.props.onSelect(this.props.propName, date)
          await this.changeState()
        }
</code>```

console.log(date) logs 2000-06-09T00:00:00.000Z

console.log(new Date(date)) logs 2000-06-09T00:00:00.000Z

BUT! console.log(new Date(date).getDate()) logs 8

And when I reopen the calendar, it is set on June 8, 2000.

My mind is exploding -- what is going on here? June 8, 2000 is only for the example - it's constantly off by 1 day no matter what day, month or year is selected. My hypothesis is something to do with timezone maybe? Any help is greatly appreciated!

答:
This is because Date.getDate() returns the day and month according to local time. The date object you’ve provided is set to UTC time, which means when the date is converted to your local time zone it is actually the day before.

To fix this problem, set the timeZoneOffsetInMinutes prop of your date picker.

Unfortunately, this prop has known implementation problems on Android. A good alternative may be to avoid the prop entirely, and instead use a date library like date-fns to manipulate the time zone of the outputted date object.

Body:
I'm so confused what's going on. I just implemented react-native-datetimepicker/datetimepicker for a user to select their birthday.

If I select June 8, 2000 -> the date returned is 2000-06-09T00:00:00.000Z, which means the users birthday is set for June 9, 2000.

here is the element:

       <DateTimePicker
          value={this.props.date}
          mode={this.props.mode}
          display="calendar"
          onChange={(event, date) => {
            this.handleDatePicked(event, date)
          }}
        />

        async handleDatePicked(event, date) {
          console.log(new Date(date))
          await this.props.onSelect(this.props.propName, date)
          await this.changeState()
        }

console.log(date) logs 2000-06-09T00:00:00.000Z

console.log(new Date(date)) logs 2000-06-09T00:00:00.000Z

BUT! console.log(new Date(date).getDate()) logs 8

And when I reopen the calendar, it is set on June 8, 2000.

My mind is exploding -- what is going on here? June 8, 2000 is only for the example - it's constantly off by 1 day no matter what day, month or year is selected. My hypothesis is something to do with timezone maybe? Any help is greatly appreciated!


问:
I think it's a basic question but I don't get why I get 0 in this function
```<code>a = 0

def add(number):
    number += 1
    return number

for i in range(20):
    add(a)

print(a)
</code>```

I'm wondering why I get 0 for the print(a) call in the last line.
I put 0 for the first loop of the add()function and it should return 1 and so on in the for loop.
What am I missing?

答:
it seems you aren't actually changing the value of a, try changing your for loop to look something like this:

```<code>for i in range(20):
    a = add(a)
</code>```

To make use of the return keyword, make sure you understand that it sends back a value to the main program, treat it like another variable.

Body:
a = 0

def add(number):
    number += 1
    return number

for i in range(20):
    add(a)

print(a)

I'm wondering why I get 0 for the print(a) call in the last line.
I put 0 for the first loop of the add()function and it should return 1 and so on in the for loop.
What am I missing?

Body:
it seems you aren't actually changing the value of a, try changing your for loop to look something like this:

for i in range(20):
    a = add(a)

To make use of the return keyword, make sure you understand that it sends back a value to the main program, treat it like another variable.


答:
I think you're just missing assigning the return value of add() back to a. Without the assignment, a never changes because function arguments are passed by value, not reference.

```<code>a = 0

def add(number):
    number += 1
    return number

for i in range(20):
    a = add(a)

print(a)
</code>```

Title: I think it's a basic question but I don't get why I get 0 in this function

Body:
I think you're just missing assigning the return value of add() back to a. Without the assignment, a never changes because function arguments are passed by value, not reference.

a = 0

def add(number):
    number += 1
    return number

for i in range(20):
    a = add(a)

print(a)


答:
When you pass an int to a function, you're basically passing a copy of it. So your function adds 1 to a copy of a and returns it, but there's nothing there to catch the returned value.

When you pass a list or dict to a function, you're passing a reference to the original object, though. If you change it inside your function it changes thoughout your code:

a = 0
b = [0]
c = {"engelbert": 0}

def add(number, lst, dct):
    number += 1
    lst[0] += 1
    dct["engelbert"] += 1
    # No return statement:
    # Function returns `None` by default

for i in range(20):
    add(a, b, c)

print(a, b, c)
# 0 [20] {'engelbert': 20}
```


问:
Solving an equation in Python
i'm trying to solve an equation but I don't know the way to do this. I've got a vector x wich is actually a matrix type and I would like to solve the equation x.transpose()*v=0 where v is another vector

Can someone help me?

I thank you in advance

答:
Take any vector at all and project it into the orthogonal complement of x.

```<code>Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> x = numpy.matrix([1, 3.14, 2.73]).T
>>> P = x * x.T / (x.T * x) # projector onto the space spanned by x
>>> Pperp = numpy.identity(3) - P # projector onto x's orthogonal complement
>>> Pperp * x
matrix([[  0.00000000e+00],
        [  0.00000000e+00],
        [ -2.22044605e-16]])
>>> y = numpy.matrix(numpy.ones((3,1)))
>>> yperp = Pperp * y
>>> yperp
matrix([[ 0.62484642],
        [-0.17798225],
        [-0.02416928]])
>>> x.T * yperp
matrix([[ -4.16333634e-16]])
</code>```

As written, this is quite unrestrained and gives a fairly arbitrary solution, but the same idea can be built up to find a set of basis vectors for all solutions.

ContentLicense: CC BY-SA 3.0

Title: Solving an equation in Python

Body:
Take any vector at all and project it into the orthogonal complement of x.

Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> x = numpy.matrix([1, 3.14, 2.73]).T
>>> P = x * x.T / (x.T * x) # projector onto the space spanned by x
>>> Pperp = numpy.identity(3) - P # projector onto x's orthogonal complement
>>> Pperp * x
matrix([[  0.00000000e+00],
        [  0.00000000e+00],
        [ -2.22044605e-16]])
>>> y = numpy.matrix(numpy.ones((3,1)))
>>> yperp = Pperp * y
>>> yperp
matrix([[ 0.62484642],
        [-0.17798225],
        [-0.02416928]])
>>> x.T * yperp
matrix([[ -4.16333634e-16]])

As written, this is quite unrestrained and gives a fairly arbitrary solution, but the same idea can be built up to find a set of basis vectors for all solutions.


问:
How to make each current element in loop centered in container

As the container slides to the left, I want each tab to be centered for a brief moment in the container.

Before the animation begins, I want the very first tab to be centered in the container on page load before the animation begins. I know I need to divide each element's offsetWidth by 2 so that it is calculated to be centered but I'm not sure where/how to do that.

Link to JS Fiddle: https://jsfiddle.net/nb5a92x3/

window.onload = function() {

    const tabsContainer = document.querySelector('.tabsContainer');
    const tabs = tabsContainer.querySelectorAll('.tab');

    function animate(target) {
        let siblings = [];
        let elm = target;
        let keyframes = [];
        let offset;

        // Push the widths of each previous element to an array
        while (elm = elm.previousElementSibling) {
            siblings.push(elm.offsetWidth);
        }

        // Add the sum of all previous elements
        offset = siblings.reduce((prev, current) => prev + current, 0);

        // Animate the container to the left
        setTimeout(function() {
            tabsContainer.style.left = `calc(50% - ${offset}px)`;
        }, i * 800);
    }

    // Run the code
    for (i = 0; i < tabs.length; i++) {
        animate(tabs[i]);
    }
  }
```
<pre class="lang-css prettyprint-override"><code>body {
    background: #ccc;
}

section {
    text-align: center;
    width: 375px;
    background: white;
    margin: 0 auto;
    padding: 16px;
    position: relative;
    display: flex;
    overflow: hidden;
}

.tabsContainer {
    display: flex;
    position: relative;
    margin: 0;
    padding: 0;
    list-style: none;
    gap: 0 16px;
    transition: left 0.2s ease;

    .tab {
        border-radius: 25px;
        background: gray;
        text-align: center;
        height: 34px;
        display: inline-flex;
        align-items: center;
        padding: 0 16px;
    }
}
</code>```

TAB ONE

ANOTHER TAB HERE

A REALLY LONG TAB HERE

LAST TAB

```

答:
If you set in CSS your container to margin-left: 50%

than all you need is x = EL_curr.offsetLeft + EL_curr.offsetWidth / 2

and apply that x value to the slider-container CSS translateX (which is far more performant than animating the CSS left property, since transform can be hardware accelerated).

// Utility functions:

const EL  = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);

// Tabs animator:

const tabsAnimator = (EL_slider) => {
  const ELS_items = ELS(".tab", EL_slider);
  const tot = ELS_items.length;
  let curr = 0;
  let tOut;

  const anim = () => {
    const EL_curr = ELS_items[curr];
    const x = EL_curr.offsetLeft + EL_curr.offsetWidth / 2;
    EL_slider.style.transform = `translateX(-${x}px)`;
    curr += 1; // Increment counter
    if (curr > tot - 1) curr = 0; // Reset counter
    tOut = setTimeout(anim, 1500);
  };

  anim(); // Init!
};

ELS(".tabsContainer").forEach(tabsAnimator);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  box-sizing: border-box;
}

.tabsWrapper {
  width: 375px;
  margin: 20px auto;
  padding: 16px 0;
  position: relative;
  overflow: hidden;
  background: #ccc;
  border-radius: 3em;
}

.tabsContainer {
  position: relative;
  padding: 0;
  display: inline-flex;
  list-style: none;
  gap: 0 15px;
  transition: transform 0.3s;
  margin-left: 50%;
}

.tabsContainer .tab {
  border-radius: 25px;
  background: gold;
  white-space: nowrap;
  padding: 5px 15px;
}</code>```

5 OFF FRIDAY

10 OFFSUMMER

SAVE MORE

HALF OFF EVERYTHING

JavaScript

HTML

CSS

```

don't use horizontal paddings on the wrapper or container slider.

don't just use section as a selector. It's too common. Use rather a specific class like .tabsWrapper on the wrapper parent.

Additionally, if you'd like to pause the animation on "mouseenter", use clearTimeout(tOut); — and just anim() in the "mouseleave" Event.

Body:
As the container slides to the left, I want each tab to be centered for a brief moment in the container.

Before the animation begins, I want the very first tab to be centered in the container on page load before the animation begins. I know I need to divide each element's offsetWidth by 2 so that it is calculated to be centered but I'm not sure where/how to do that.

Link to JS Fiddle: https://jsfiddle.net/nb5a92x3/

window.onload = function() {

    const tabsContainer = document.querySelector('.tabsContainer');
    const tabs = tabsContainer.querySelectorAll('.tab');

    function animate(target) {
        let siblings = [];
        let elm = target;
        let keyframes = [];
        let offset;

        // Push the widths of each previous element to an array
        while (elm = elm.previousElementSibling) {
            siblings.push(elm.offsetWidth);
        }

        // Add the sum of all previous elements
        offset = siblings.reduce((prev, current) => prev + current, 0);

        // Animate the container to the left
        setTimeout(function() {
            tabsContainer.style.left = `calc(50% - ${offset}px)`;
        }, i * 800);
    }

    // Run the code
    for (i = 0; i < tabs.length; i++) {
        animate(tabs[i]);
    }
  }

body {
    background: #ccc;
}

section {
    text-align: center;
    width: 375px;
    background: white;
    margin: 0 auto;
    padding: 16px;
    position: relative;
    display: flex;
    overflow: hidden;
}

.tabsContainer {
    display: flex;
    position: relative;
    margin: 0;
    padding: 0;
    list-style: none;
    gap: 0 16px;
    transition: left 0.2s ease;

    .tab {
        border-radius: 25px;
        background: gray;
        text-align: center;
        height: 34px;
        display: inline-flex;
        align-items: center;
        padding: 0 16px;
    }
}

TAB ONE

ANOTHER TAB HERE

A REALLY LONG TAB HERE

LAST TAB

Body:
If you set in CSS your container to margin-left: 50%

than all you need is x = EL_curr.offsetLeft + EL_curr.offsetWidth / 2

and apply that x value to the slider-container CSS translateX (which is far more performant than animating the CSS left property, since transform can be hardware accelerated).

// Utility functions:

const EL  = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);

// Tabs animator:

const tabsAnimator = (EL_slider) => {
  const ELS_items = ELS(".tab", EL_slider);
  const tot = ELS_items.length;
  let curr = 0;
  let tOut;

  const anim = () => {
    const EL_curr = ELS_items[curr];
    const x = EL_curr.offsetLeft + EL_curr.offsetWidth / 2;
    EL_slider.style.transform = `translateX(-${x}px)`;
    curr += 1; // Increment counter
    if (curr > tot - 1) curr = 0; // Reset counter
    tOut = setTimeout(anim, 1500);
  };

  anim(); // Init!
};

ELS(".tabsContainer").forEach(tabsAnimator);

* {
  margin: 0;
  box-sizing: border-box;
}

.tabsWrapper {
  width: 375px;
  margin: 20px auto;
  padding: 16px 0;
  position: relative;
  overflow: hidden;
  background: #ccc;
  border-radius: 3em;
}

.tabsContainer {
  position: relative;
  padding: 0;
  display: inline-flex;
  list-style: none;
  gap: 0 15px;
  transition: transform 0.3s;
  margin-left: 50%;
}

.tabsContainer .tab {
  border-radius: 25px;
  background: gold;
  white-space: nowrap;
  padding: 5px 15px;
}

<section class="tabsWrapper">
  <ul class="tabsContainer">
    <li class="tab">5 OFF FRIDAY</li>
    <li class="tab">10 OFFSUMMER</li>
    <li class="tab">SAVE MORE</li>
    <li class="tab">HALF OFF EVERYTHING</li>
  </ul>
</section>

<section class="tabsWrapper">
  <ul class="tabsContainer">
    <li class="tab">JavaScript</li>
    <li class="tab">HTML</li>
    <li class="tab">CSS</li>
  </ul>
</section>

don't use horizontal paddings on the wrapper or container slider.

don't just use section as a selector. It's too common. Use rather a specific class like .tabsWrapper on the wrapper parent.

Additionally, if you'd like to pause the animation on "mouseenter", use clearTimeout(tOut); — and just anim() in the "mouseleave" Event.


问:
SQL How to convert a date into hours per minute? Then subtract two of the colums (end-start) and set it as a new column?
I am wondering, how can I convert datetime into hours per minute? I want the following. To minus the end_trip with the start_trip that is in hours and minutes. Moreover, I want to create a new column for the result. However, I am getting nowhere. I want to use basic arithmetic for this not some built in functions like DATEDIFF. Please help.

Below is my code

```<code>INSERT INTO TRIP VALUES(
TO_DATE('26-01-2022 14:00:00', 'DD/MM/YYYY HH24:MI:SS'), - start_time
TO_DATE('26-01-2022 14:50:00', 'DD/MM/YYYY HH24:MI:SS')  - end_time
;

SELECT
trip_start_actual as start_time, trip_end_actual as end_time, (trip_end_actual - trip_start_actual)
from trip;
commit;
</code>```

答:
Subtracting two dates in Oracle will yield a difference in fractional days.  To get minutes from that, simply multiply that difference by 1440:

SELECT trip_start_actual AS start_time,
       trip_end_actual AS end_time,
       1440 * (trip_end_actual - trip_start_actual) AS num_minutes
FROM trip;
```

Body:
I am wondering, how can I convert datetime into hours per minute? I want the following. To minus the end_trip with the start_trip that is in hours and minutes. Moreover, I want to create a new column for the result. However, I am getting nowhere. I want to use basic arithmetic for this not some built in functions like DATEDIFF. Please help.

Below is my code

INSERT INTO TRIP VALUES(
TO_DATE('26-01-2022 14:00:00', 'DD/MM/YYYY HH24:MI:SS'), - start_time
TO_DATE('26-01-2022 14:50:00', 'DD/MM/YYYY HH24:MI:SS')  - end_time
;

SELECT
trip_start_actual as start_time, trip_end_actual as end_time, (trip_end_actual - trip_start_actual)
from trip;
commit;


问:
How do filter with multiple contains in pyspark
I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:

```<code>     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
I'm going to travel.           ...
</code>```

I have an array:

```<code>array=["mother","father"]
</code>```

And the output must be this:

```<code>     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
</code>```

A simple filter for word in array.

答:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First, we setup,

import pandas as pd

array=["mother","father"]
df = pd.DataFrame({"sentence": ["My father is big.", "My mother is beautiful.", "I'm going to travel. "]})
```
<p>and then we can create a native Python function to express the logic:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List, Dict, Any, Iterable

def myfilter(df: List[Dict[str,Any]]) -> Iterable[Dict[str, Any]]:
    for row in df:
        for value in array:
            if value in row["sentence"]:
                yield row
</code>```

and then test it on Pandas:

from fugue import transform
transform(df, myfilter, schema="*")
```
<p>Because of works on Pandas, we can execute it on Spark by specifying the engine:</p>
<pre class="lang-py prettyprint-override"><code>import fugue_spark
transform(df, myfilter, schema="*", engine="spark").show()
</code>```
```<code>+---+--------------------+
| id|            sentence|
+---+--------------------+
|  0|   My father is big.|
|  1|My mother is beau...|
+---+--------------------+
</code>```

Note we need .show() because Spark evaluates lazily. Schema is also a Spark requirement so Fugue interprets the "*" as all columns in = all columns out.

The fugue transform function can take both Pandas DataFrame inputs and Spark DataFrame inputs.

Edit:
You can replace the myfilter function above with a Pandas implementation like this:

def myfilter(df: pd.DataFrame) -> pd.DataFrame:
    res = df.loc[df["sentence"].str.contains("|".join(array))]
    return res
```

and Fugue will be able to port it to Spark the same way. Fugue knows how to adjust to the type hints and this will be faster than the native Python implementation because it takes advantage of Pandas being vectorized.

Body:
I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:

     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
I'm going to travel.           ...

I have an array:

array=["mother","father"]

And the output must be this:

     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...

A simple filter for word in array.

Body:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First, we setup,

import pandas as pd

array=["mother","father"]
df = pd.DataFrame({"sentence": ["My father is big.", "My mother is beautiful.", "I'm going to travel. "]})

and then we can create a native Python function to express the logic:

from typing import List, Dict, Any, Iterable

def myfilter(df: List[Dict[str,Any]]) -> Iterable[Dict[str, Any]]:
    for row in df:
        for value in array:
            if value in row["sentence"]:
                yield row

and then test it on Pandas:

from fugue import transform
transform(df, myfilter, schema="*")

Because of works on Pandas, we can execute it on Spark by specifying the engine:

import fugue_spark
transform(df, myfilter, schema="*", engine="spark").show()

+---+--------------------+
| id|            sentence|
+---+--------------------+
|  0|   My father is big.|
|  1|My mother is beau...|
+---+--------------------+

Note we need .show() because Spark evaluates lazily. Schema is also a Spark requirement so Fugue interprets the "*" as all columns in = all columns out.

The fugue transform function can take both Pandas DataFrame inputs and Spark DataFrame inputs.

Edit:
You can replace the myfilter function above with a Pandas implementation like this:

def myfilter(df: pd.DataFrame) -> pd.DataFrame:
    res = df.loc[df["sentence"].str.contains("|".join(array))]
    return res

and Fugue will be able to port it to Spark the same way. Fugue knows how to adjust to the type hints and this will be faster than the native Python implementation because it takes advantage of Pandas being vectorized.


问:
How can i solve route.params is undefined?
i have this part in my code, i want to test, but when i run the test route.params sound like the wrong:

```<code> onMounted(async () => {
        try {
          const { tokenId } = route.params
</code>```

it i used to get the id from url, but at the moment to test it

i am getting this error
Error TypeError: Cannot read property 'params' of undefined

this is my test:

```<code>beforeEach(() => {
  wrapper = shallowMount(App, {
    mocks: {
      route: {
          params: {
            id: 'id'
          }
        }
    },
    global: {
      plugins: [store],
    },
    computed: { notFound: () => {} },
  })
})
</code>```

答:
Your mocks.route does not mock

```<code>import { useRoute } from 'vue-router'
//...

setup() {
  const route = useRoute();
  //...
}
</code>```

You might want to have a look at examples presented here for a detailed approach on how to test various router related scenarios with a vue3 composition api setup.

To simply make your component not fail when useRoute() returns undefined, you could use this:

```<code>const { tokenId } = route?.params || {};
if (tokenId) {
  // do your thing...
}
</code>```

There's no need for try.

To test that your component does what it's supposed to based on tokenId route param value, then you should mock vue-router in your test, to return a function returning a params object:

This should work:

```<code>jest.mock('vue-router', () => ({
  useRoute: () => ({ params: { id: 'id' } })
}));
</code>```

Body:
i have this part in my code, i want to test, but when i run the test route.params sound like the wrong:

 onMounted(async () => {
        try {
          const { tokenId } = route.params

it i used to get the id from url, but at the moment to test it

i am getting this error
Error TypeError: Cannot read property 'params' of undefined

this is my test:

beforeEach(() => {
  wrapper = shallowMount(App, {
    mocks: {
      route: {
          params: {
            id: 'id'
          }
        }
    },
    global: {
      plugins: [store],
    },
    computed: { notFound: () => {} },
  })
})

Body:
Your mocks.route does not mock

import { useRoute } from 'vue-router'
//...

setup() {
  const route = useRoute();
  //...
}

You might want to have a look at examples presented here for a detailed approach on how to test various router related scenarios with a vue3 composition api setup.

To simply make your component not fail when useRoute() returns undefined, you could use this:

const { tokenId } = route?.params || {};
if (tokenId) {
  // do your thing...
}

There's no need for try.

To test that your component does what it's supposed to based on tokenId route param value, then you should mock vue-router in your test, to return a function returning a params object:

This should work:

jest.mock('vue-router', () => ({
  useRoute: () => ({ params: { id: 'id' } })
}));


问:
Adding a Nested Statement
The problem,

Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle.

I currently have

```<code>import java.util.Scanner;
public class FourDecimalThirtySix {
    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if ( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                return;
            }
        }
    }
}
</code>```

I am trying to add an else statement to this for it to say "these values cannot make a triangle" if the original conditions are not meet.  Currently the program does not do anything if the 3 conditions are not met

答:
If any condition is not met the code should print "these values cannot make a triangle". So you just need to add else blocks for each if statement.

Code:-

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

public class FourDecimalThirtySix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                else{
                    System.out.println("these values cannot make a triangle");
                    return;
                }
            }
            else{
                System.out.println("these values cannot make a triangle");
                return;
            }
        }
        else{
            System.out.println("these values cannot make a triangle");
            return;
        }
    }

}

</code>```

The above approach is not recommended, as it uses return statements that end the function process abruptly.

A wiser approach is to use a single if with logical and operators and a single corresponding else block.

Code:-

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

public class FourDecimalThirtySix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if((a+b) > c && (a+c) > b && (b+c) > a) {
            System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.%n", a, b, c);
        }
        else{
            System.out.println("these values cannot make a triangle");
        }

    }

}
</code>```

This is a cleaner approach.

Happy coding!

Title: Adding a Nested Statement

Body:
The problem,

Write an application that reads three nonzero values entered by the user and determines and prints whether they could represent the sides of a triangle.

I currently have

import java.util.Scanner;
public class FourDecimalThirtySix {
    public static void main (String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if ( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                return;
            }
        }
    }
}

I am trying to add an else statement to this for it to say "these values cannot make a triangle" if the original conditions are not meet.  Currently the program does not do anything if the 3 conditions are not met

Body:
If any condition is not met the code should print "these values cannot make a triangle". So you just need to add else blocks for each if statement.

Code:-

import java.util.Scanner;

public class FourDecimalThirtySix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if ( (a + b) > c) {
            if ( (a + c) > b) {
                if( (b + c) > a)
                    System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.", a,
                        b, c);
                else{
                    System.out.println("these values cannot make a triangle");
                    return;
                }
            }
            else{
                System.out.println("these values cannot make a triangle");
                return;
            }
        }
        else{
            System.out.println("these values cannot make a triangle");
            return;
        }
    }

}

The above approach is not recommended, as it uses return statements that end the function process abruptly.

A wiser approach is to use a single if with logical and operators and a single corresponding else block.

Code:-

import java.util.Scanner;

public class FourDecimalThirtySix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter three sizes, speparated by spaces");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();
        input.close();

        if((a+b) > c && (a+c) > b && (b+c) > a) {
            System.out.printf("A triangle can be made of %.2f, %.2f, by %.2f.%n", a, b, c);
        }
        else{
            System.out.println("these values cannot make a triangle");
        }

    }

}

This is a cleaner approach.

Happy coding!


问:
How to use variables in dot notation like square bracket notation
I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

```<code>var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'
</code>```

答:
The short answer is: you can't access a property using dot notation unless you know the property's name.

Dot notation also puts a restriction on the property names you can access because the property name must be a valid JavaScript identifier. For example, if you had a property called my prop (or better yet, my%prop) then it would not be possible to access it without using bracket notation because it would lead to a syntax error is most cases.

The Member Operators page on MDN explains this a bit further.

As an aside:

Wouldn't it be a little confusing to be able to dynamically look up properties using dot notation?

```<code>item.x // is this the property "x" or do I have to look up variable "x"?
</code>```

Body:
I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'

Body:
The short answer is: you can't access a property using dot notation unless you know the property's name.

Dot notation also puts a restriction on the property names you can access because the property name must be a valid JavaScript identifier. For example, if you had a property called my prop (or better yet, my%prop) then it would not be possible to access it without using bracket notation because it would lead to a syntax error is most cases.

The Member Operators page on MDN explains this a bit further.

As an aside:

Wouldn't it be a little confusing to be able to dynamically look up properties using dot notation?

item.x // is this the property "x" or do I have to look up variable "x"?


问:
Tweepy AttributeError: 'API' object has no attribute 'search'
I'm trying to get tweets using tweepy but I am running into this error:

AttributeError: 'API' object has no attribute 'search'

Code:

```<code>import tweepy

# Authentication
consumerKey = "Type your consumer key here"
consumerSecret = "Type your consumer secret here"
accessToken = "Type your accedd token here"
accessTokenSecret = "Type your access token secret here"

auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)
#Sentiment Analysis

def percentage(part,whole):
    return 100 * float(part)/float(whole)

keyword = input("Please enter keyword or hashtag to search: ")
noOfTweet = int(input ("Please enter how many tweets to analyze: "))

tweets = tweepy.Cursor(api.search, q=keyword).items(noOfTweet)
</code>```

How can I fix this?

答:
use api.search_tweets instead of api.search

tweepy v.4.0.0 has changed it..

Body:
I'm trying to get tweets using tweepy but I am running into this error:

AttributeError: 'API' object has no attribute 'search'

Code:

import tweepy

# Authentication
consumerKey = "Type your consumer key here"
consumerSecret = "Type your consumer secret here"
accessToken = "Type your accedd token here"
accessTokenSecret = "Type your access token secret here"

auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)
#Sentiment Analysis

def percentage(part,whole):
    return 100 * float(part)/float(whole)

keyword = input("Please enter keyword or hashtag to search: ")
noOfTweet = int(input ("Please enter how many tweets to analyze: "))

tweets = tweepy.Cursor(api.search, q=keyword).items(noOfTweet)

How can I fix this?


问:
Python variable won't update outside of module
I have a variable called store_number that I pass in from my main.py into a module called store_selector which increments the store number until it finds a valid store. The whole thing is in a while loop and after the first loop the store variable does not keep it's updated value from the store_selector module but instead reverts to it's original value. I know this has something to do with declaring a global variable but the problem is if I declare a global variable inside the module I assume it will keep assigning the initial value when that module is called (since it's in a while loop in the main.py)

Any ideas?

Inside main.py

```<code>store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)
</code>```

Inside functions.py

```<code>def store_selector(driver, store_number):
    textbox = driver.find_element(By.ID, "myStore-formInput")
    #time.sleep(1)
    store_number += 1
    textbox.send_keys(store_number, Keys.RETURN)
    time.sleep(1)
    while driver.find_element(By.ID, "myStore-errorMessage").is_displayed() and store_number < 10000:
        store_number += 1
        textbox.clear()
        textbox.send_keys(store_number, Keys.RETURN)
        time.sleep(1)
    else:
        store_button = driver.find_element(By.CSS_SELECTOR, f'button[data-storeid="{str(store_number).zfill(4)}"]')
        store_button.click()
</code>```

答:
You can just move store_number+=1 into your main script

```<code>store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)
    store_number+=1
</code>```

Or if you insist on doing so in store_selector, return the incremented value to the main function

```<code>store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_number = store_selector(driver, store_number)
    item_inspector(driver)
</code>```

and

```<code>def store_selector(driver, store_number):
    store_number += 1

    ########
    # Your function
    ########

    return store_number
</code>```

You should really be using the first solution unless you have a really good reason to be incrementing your counter in the function (i.e. conditional incrementation)

Body:
I have a variable called store_number that I pass in from my main.py into a module called store_selector which increments the store number until it finds a valid store. The whole thing is in a while loop and after the first loop the store variable does not keep it's updated value from the store_selector module but instead reverts to it's original value. I know this has something to do with declaring a global variable but the problem is if I declare a global variable inside the module I assume it will keep assigning the initial value when that module is called (since it's in a while loop in the main.py)

Any ideas?

Inside main.py

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)

Inside functions.py

def store_selector(driver, store_number):
    textbox = driver.find_element(By.ID, "myStore-formInput")
    #time.sleep(1)
    store_number += 1
    textbox.send_keys(store_number, Keys.RETURN)
    time.sleep(1)
    while driver.find_element(By.ID, "myStore-errorMessage").is_displayed() and store_number < 10000:
        store_number += 1
        textbox.clear()
        textbox.send_keys(store_number, Keys.RETURN)
        time.sleep(1)
    else:
        store_button = driver.find_element(By.CSS_SELECTOR, f'button[data-storeid="{str(store_number).zfill(4)}"]')
        store_button.click()

Body:
You can just move store_number+=1 into your main script

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)
    store_number+=1

Or if you insist on doing so in store_selector, return the incremented value to the main function

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_number = store_selector(driver, store_number)
    item_inspector(driver)

and

def store_selector(driver, store_number):
    store_number += 1

    ########
    # Your function
    ########

    return store_number

You should really be using the first solution unless you have a really good reason to be incrementing your counter in the function (i.e. conditional incrementation)


问:
Ruby regular expression help using match to extract pieces of html doc
I have an HTML document of this format:

```<code><tr><td colspan="4"><span class="fullName">Bill Gussio</span></td></tr>
    <tr>
        <td class="sectionHeader">Contact</td>
        <td class="sectionHeader">Phone</td>
        <td class="sectionHeader">Home</td>
        <td class="sectionHeader">Work</td>
    </tr>
    <tr valign="top">
        <td class="sectionContent"><span>Screen Name:</span> <span>bhjiggy</span><br><span>Email 1:</span> <span>wmgussio@erols.com</span></td>
        <td class="sectionContent"><span>Mobile: </span><span>2404173223</span></td>
        <td class="sectionContent"><span>NY</span><br><span>New York</span><br><span>78642</span></td>
        <td class="sectionContent"><span>MD</span><br><span>Owings Mills</span><br><span>21093</span></td>
    </tr>

    <tr><td colspan="4"><hr class="contactSeparator"></td></tr>

    <tr><td colspan="4"><span class="fullName">Eddie Osefo</span></td></tr>
    <tr>
        <td class="sectionHeader">Contact</td>
        <td class="sectionHeader">Phone</td>
        <td class="sectionHeader">Home</td>
        <td class="sectionHeader">Work</td>
    </tr>
    <tr valign="top">
        <td class="sectionContent"><span>Screen Name:</span> <span>eddieOS</span><br><span>Email 1:</span> <span>osefo@wam.umd.edu</span></td>
        <td class="sectionContent"></td>
        <td class="sectionContent"><span></span></td>
        <td class="sectionContent"><span></span></td>
    </tr>

    <tr><td colspan="4"><hr class="contactSeparator"></td></tr>
</code>```

So it alternates - chunk of contact info and then a "contact separator".  I want to grab the contact info so my first obstacle is to grab the chunks in between the contact separator.  I have already figured out the regular expression using rubular.  It is:

```<code>/<tr><td colspan="4"><span class="fullName">((.|\s)*?)<hr class="contactSeparator">/
</code>```

You can check on rubular to verify that this isolates chunks.

However my big issue is that I am having trouble with the ruby code.  I use the built in match function and make prints, but do not get the results I expect.  Here is the code:

```<code>page = agent.get uri.to_s
chunks = page.body.match(/<tr><td colspan="4"><span class="fullName">((.|\s)*?)<hr class="contactSeparator">/).captures

chunks.each do |chunk|
   puts "new chunk: " + chunk.inspect
end
</code>```

Note that page.body is just the body of the html document grabbed by Mechanize.  The html document is much larger but has this format.  So, the unexpected output is below:

```<code>new chunk: "Bill Gussio</span></td></tr>\r\n\t<tr>\r\n\t\t<td class=\"sectionHeader\">Contact</td>\r\n\t\t<td class=\"sectionHeader\">Phone</td>\r\n\t\t<td class=\"sectionHeader\">Home</td>\r\n\t\t<td class=\"sectionHeader\">Work</td>\r\n\t</tr>\r\n\t<tr valign=\"top\">\r\n\t\t<td class=\"sectionContent\"><span>Screen Name:</span> <span>bhjiggy</span><br><span>Email 1:</span> <span>wmgussio@erols.com</span></td>\r\n\t\t<td class=\"sectionContent\"><span>Mobile: </span><span>2404173223</span></td>\r\n\t\t<td class=\"sectionContent\"><span>NY</span><br><span>New York</span><br><span>78642</span></td>\r\n\t\t<td class=\"sectionContent\"><span>MD</span><br><span>Owings Mills</span><br><span>21093</span></td>\r\n\t</tr>\r\n\t\r\n\t<tr><td colspan=\"4\">"
new chunk: ">"
</code>```

There are 2 surprises here for me:

1) There are not 2 matches that contain the chunks of contact info, even though on rubular I have verified that these chunks should be extracted.

2) All of the \r\n\t (line feeds, tabs, etc.) are showing up in the matches.

Can anyone see the issue here?

Alternatively, if anyone knows of a good free AOL contacts importer, that would be great.  I have been using blackbook but it keeps failing for me on AOL and I am attempting to fix it.  Unfortunately, AOL has no contacts API yet.

Thank you!

答:
This is the code that parses that HTML.  Feel free to suggest something better:</p>

```<code>contacts = []
    email, mobile = "",""

    names = page.search("//span[@class='fullName']")

    # Every contact has a fullName node, so for each fullName node, we grab the chunk of contact info
    names.each do |n|

      # next_sibling.next_sibling skips:
      # <tr>
      #   <td class=\"sectionHeader\">Contact</td>
      #   <td class=\"sectionHeader\">Phone</td>
      #   <td class=\"sectionHeader\">Home</td>
      #   <td class=\"sectionHeader\">Work</td>
      # </tr>
      # to give us the actual chunk of contact information
      # then taking the children of that chunk gives us rows of contact info
      contact_info_rows = n.parent.parent.next_sibling.next_sibling.children

      # Iterate through the rows of contact info
      contact_info_rows.each do |row|

        # Iterate through the contact info in each row
        row.children.each do |info|
          # Get Email. There are two ".next_siblings" because space after "Email 1" element is processed as a sibling
          if info.content.strip == "Email 1:" then email = info.next_sibling.next_sibling.content.strip end

          # If the contact info has a screen name but no email, use screenname@aol.com
          if (info.content.strip == "Screen Name:" && email == "") then email = info.next_sibling.next_sibling.content.strip + "@aol.com" end

          # Get Mobile #'s
          if info.content.strip == "Mobile:" then mobile = info.next_sibling.content.strip end

          # Maybe we can try and get zips later.  Right now the zip field can look like the street address field
          # so we can not tell the difference.  There is no label node
          #zip_match = /\A\D*(\d{5})-?\d{4}\D*\z/i.match(info.content.strip)
          #zip_match = /\A\D*(\d{5})[^\d-]*\z/i.match(info.content.strip)
        end

      end

      contacts << { :name => n.content, :email => email, :mobile => mobile }

      # clear variables
      email, mobile = "", ""
    end
</code>```

OwnerDisplayName: Tony

ContentLicense: CC BY-SA 2.5

Body:
I have an HTML document of this format:

Bill Gussio

        Contact
        Phone
        Home
        Work

        Screen Name: bhjiggy
Email 1: wmgussio@erols.com
        Mobile: 2404173223
        NY
New York
78642
        MD
Owings Mills
21093

Eddie Osefo

        Contact
        Phone
        Home
        Work

        Screen Name: eddieOS
Email 1: osefo@wam.umd.edu

So it alternates - chunk of contact info and then a "contact separator".  I want to grab the contact info so my first obstacle is to grab the chunks in between the contact separator.  I have already figured out the regular expression using rubular.  It is:

/
((.|\s)*?)
/

You can check on rubular to verify that this isolates chunks.

However my big issue is that I am having trouble with the ruby code.  I use the built in match function and make prints, but do not get the results I expect.  Here is the code:

page = agent.get uri.to_s
chunks = page.body.match(/
((.|\s)*?)
/).captures

chunks.each do |chunk|
   puts "new chunk: " + chunk.inspect
end

Note that page.body is just the body of the html document grabbed by Mechanize.  The html document is much larger but has this format.  So, the unexpected output is below:

new chunk: "Bill Gussio
\r\n\t
\r\n\t\tContact	\r\n\t\tPhone	\r\n\t\tHome	\r\n\t\tWork	\r\n\t
\r\n\t
\r\n\t\tScreen Name: bhjiggy
Email 1: wmgussio@erols.com	\r\n\t\tMobile: 2404173223	\r\n\t\tNY
New York
78642	\r\n\t\tMD
Owings Mills
21093	\r\n\t
\r\n\t\r\n\t
"
new chunk: ">"

There are 2 surprises here for me:

1) There are not 2 matches that contain the chunks of contact info, even though on rubular I have verified that these chunks should be extracted.

2) All of the \r\n\t (line feeds, tabs, etc.) are showing up in the matches.

Can anyone see the issue here?

Alternatively, if anyone knows of a good free AOL contacts importer, that would be great.  I have been using blackbook but it keeps failing for me on AOL and I am attempting to fix it.  Unfortunately, AOL has no contacts API yet.

Thank you!

LastEditorDisplayName: Chad Birch

Body:
This is the code that parses that HTML.  Feel free to suggest something better:

contacts = []
    email, mobile = "",""

    names = page.search("//span[@class='fullName']")

    # Every contact has a fullName node, so for each fullName node, we grab the chunk of contact info
    names.each do |n|

      # next_sibling.next_sibling skips:
      # <tr>
      #   <td class=\"sectionHeader\">Contact</td>
      #   <td class=\"sectionHeader\">Phone</td>
      #   <td class=\"sectionHeader\">Home</td>
      #   <td class=\"sectionHeader\">Work</td>
      # </tr>
      # to give us the actual chunk of contact information
      # then taking the children of that chunk gives us rows of contact info
      contact_info_rows = n.parent.parent.next_sibling.next_sibling.children

      # Iterate through the rows of contact info
      contact_info_rows.each do |row|

        # Iterate through the contact info in each row
        row.children.each do |info|
          # Get Email. There are two ".next_siblings" because space after "Email 1" element is processed as a sibling
          if info.content.strip == "Email 1:" then email = info.next_sibling.next_sibling.content.strip end

          # If the contact info has a screen name but no email, use screenname@aol.com
          if (info.content.strip == "Screen Name:" && email == "") then email = info.next_sibling.next_sibling.content.strip + "@aol.com" end

          # Get Mobile #'s
          if info.content.strip == "Mobile:" then mobile = info.next_sibling.content.strip end

          # Maybe we can try and get zips later.  Right now the zip field can look like the street address field
          # so we can not tell the difference.  There is no label node
          #zip_match = /\A\D*(\d{5})-?\d{4}\D*\z/i.match(info.content.strip)
          #zip_match = /\A\D*(\d{5})[^\d-]*\z/i.match(info.content.strip)
        end

      end

      contacts << { :name => n.content, :email => email, :mobile => mobile }

      # clear variables
      email, mobile = "", ""
    end


问:
If jupyter notebook is ready but Dask dashboard is still showing that its running some task, can I execute my next cell?
I am new to Dask. I was using it with an xarray dataset. I persisted the dataset in memory and the jupyter cell showed that it was ready (no more asterisk). But the dask dashboard was busy executing the task. I didn't understand. When this happens, should I wait till dask dashboard has stabilized or am I free to run the next cell?

答:
No, you do not need to wait. Isn't that great?

xarray and dask work together to schedule tasks, and dask's scheduler automatically tracks the dependency graph of all tasks.

If a local xarray operation requires the work to be completed, dask will block execution until all needed operations are complete. For example, plotting will immediately trigger computation and will bring all necessary data to the notebook so it can be rendered. Similarly, calling compute() or executing another operation which requires the data to be local or executed, such as writing to a file, plotting, coercing to a native python or numpy data type (e.g. da.values or bool(da.isnull().any())) will all trigger computation on the workers, and the operation will block until the necessary tasks have completed. Conversely, distributed operations which only return a dask-backed xarray object will only do enough computing locally to schedule the operations on the cluster.

Persist operations are a special case where the task graph is executed on the workers, but the result is not brought to the local notebook, and the notebook may continue executing while the work is done. If you'd like to wait for the work to complete, you can always block progress with dd.wait(). But you don't necessarily need to - if you execute a later step which does need the data, this step will block until the computations are complete.

See the docs on using xarray with dask, Dask's Lazy Execution tutorial, and Dask: Best Practices for more info.


问:
Error: Unable to upload artifact PitchAiIngest referenced by CodeUri parameter of PitchAiIngest resource
Pretty new to AWS Lambda function, and this is my time to get my hands dirty. I got this error in the title when I wanted to docker build my function. And here is how I configured my function:

```<code>  PitchAiIngest:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub pitch-ai-ingest-${Environment}
      Handler: lambda_function.lambda_handler
      Runtime: python3.7
      CodeUri: pitchai_ingest/
      Description: get pitchai information from API and publish to dynamodb
      MemorySize: 128
      Timeout: 900
      Role: !GetAtt LambdaRole.Arn
      Environment:
        Variables:
          LOGGING_LEVEL: INFO
          APP_NAME: pitch-ai-ingest
          APP_ENV: !Ref Environment
          DYNAMO_DB: !Ref PitchAiEventDynamoDBTable
          PLAYER_DB: !Ref PitchAiPlayerDynamoDBTable
          PITCH_SQS: !Ref PitchAiIngestQueue
      Tags:
        env: !Ref Environment
        service: pitch-ai-service
        function_name: !Sub pitch-ai-ingest-${Environment}
</code>```

Roughly speaking, I post the snippet above in file cfn-tempate.yml under the same directory of folder pitchai_ingest (including Lambda handler).

What should I do to fix it?

答: I mistakenly set AWS_ACCESS_KEY_ID as AWS_ACCESS_KEY. That's why the credential wasn't found.

Body:
Pretty new to AWS Lambda function, and this is my time to get my hands dirty. I got this error in the title when I wanted to docker build my function. And here is how I configured my function:

  PitchAiIngest:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub pitch-ai-ingest-${Environment}
      Handler: lambda_function.lambda_handler
      Runtime: python3.7
      CodeUri: pitchai_ingest/
      Description: get pitchai information from API and publish to dynamodb
      MemorySize: 128
      Timeout: 900
      Role: !GetAtt LambdaRole.Arn
      Environment:
        Variables:
          LOGGING_LEVEL: INFO
          APP_NAME: pitch-ai-ingest
          APP_ENV: !Ref Environment
          DYNAMO_DB: !Ref PitchAiEventDynamoDBTable
          PLAYER_DB: !Ref PitchAiPlayerDynamoDBTable
          PITCH_SQS: !Ref PitchAiIngestQueue
      Tags:
        env: !Ref Environment
        service: pitch-ai-service
        function_name: !Sub pitch-ai-ingest-${Environment}

Roughly speaking, I post the snippet above in file cfn-tempate.yml under the same directory of folder pitchai_ingest (including Lambda handler).

What should I do to fix it?


问:
RStudio can't deal with file names with unicode characters
I've suddenly started having a problem in RStudio when I've got file/folder names that contain unicode characters. I've been running the exact same code for months, but it stopped working this morning.

For example, when I run list.files() on a file path containing "Ø", it doesn't work. However, I can change my working directory to that folder and then run list.files():

# RUNNING IN RSTUDIO
list.files("S:/Spildevand/Lille ØU-sag")
#> character(0)

setwd("S:/Spildevand/Lille ØU-sag")
list.files()
#>  [1] "~$P WW analysis.docx"
#>  [2] "Anmeldelse til Compliance"
#>  [3] "Budgetter_2021.03.22.xlsx"
#>  etc
```
<p>But it works fine if I run it from the R GUI:</p>
<pre class="lang-r prettyprint-override"><code># RUNNING IN R GUI
list.files("S:/Spildevand/Lille ØU-sag")
#>  [1] "~$P WW analysis.docx"
#>  [2] "Anmeldelse til Compliance"
#>  [3] "Budgetter_2021.03.22.xlsx"
#>  etc
</code>```

Similarly, saving an RDS file containing a special character works in R GUI, but not RStudio:

x <- 1
saveRDS(x, "æ rstudio.RDS")  # or "æ rgui.RDS"
```
<p><img src="https://i.stack.imgur.com/muwNI.png" alt="enter image description here" /></p>
<p>I don't understand why this has suddenly started happening, nor why it would matter whether or not I run it in RStudio. The session info is slightly different, RStudio has two extra bits: <code>system code page: 65001</code> and <code>tools_4.1.2</code>. Don't know what they mean or whether they're relevant.</p>
```RStudio:
--------
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
system code page: 65001

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.1.2 tools_4.1.2

R GUI:
------
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252
[2] LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.1.2
```

答:
This is a bug in the current release of RStudio (2021.09.2+382). We're currently working on getting a patch release out, but in the interim, you can download the previous release from:

https://s3.amazonaws.com/rstudio-ide-build/desktop/windows/RStudio-2021.09.1-372.exe

Body:
I've suddenly started having a problem in RStudio when I've got file/folder names that contain unicode characters. I've been running the exact same code for months, but it stopped working this morning.

For example, when I run list.files() on a file path containing "Ø", it doesn't work. However, I can change my working directory to that folder and then run list.files():

# RUNNING IN RSTUDIO
list.files("S:/Spildevand/Lille ØU-sag")
#> character(0)

setwd("S:/Spildevand/Lille ØU-sag")
list.files()
#>  [1] "~$P WW analysis.docx"
#>  [2] "Anmeldelse til Compliance"
#>  [3] "Budgetter_2021.03.22.xlsx"
#>  etc

But it works fine if I run it from the R GUI:

# RUNNING IN R GUI
list.files("S:/Spildevand/Lille ØU-sag")
#>  [1] "~$P WW analysis.docx"
#>  [2] "Anmeldelse til Compliance"
#>  [3] "Budgetter_2021.03.22.xlsx"
#>  etc

Similarly, saving an RDS file containing a special character works in R GUI, but not RStudio:

x <- 1
saveRDS(x, "æ rstudio.RDS")  # or "æ rgui.RDS"

I don't understand why this has suddenly started happening, nor why it would matter whether or not I run it in RStudio. The session info is slightly different, RStudio has two extra bits: system code page: 65001 and tools_4.1.2. Don't know what they mean or whether they're relevant.

RStudio:
--------
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
system code page: 65001

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.1.2 tools_4.1.2

R GUI:
------
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252
[2] LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.1.2


问:
Average using loops
```<code>average = total / count
while PEnd !="Q" :
    total = total + value
    average = 0.0
    value = int(input("Enter an input value: "))
    total = total + value
    count = 1
     value = int(input("Enter an input value: "))
     PEnd = input("Enter character Q to quit or any other character to continue:
    ")
    PEnd = " "
    PEnd = input("Enter character Q to quit or any other character to continue: ")
    total = 0
     count = count + 1
    print("The average is: ", average)
</code>```

Anyone know how to rearrange this code so that when the values that are inputted are 3 4 8 4 , the average is 4.75. have tried rewriting it and getting average as 2 with code below and 4 when count = 0

here's my try:

```<code>PEnd = " "
while PEnd !="Q" :
    value = int(input("Enter an input value: "))
    average = 0.0
    total = 0
    count = 1
    total = total + value
    count = count + 1
    average = total / count

    PEnd = input("Enter character Q to quit or any other character to continue: ")

print("The average is: ", average)
</code>```

答:
break your program into its parts

get a bunch of integers from the user

average those numbers

print the result

It helps me to actually break my program into its logical components so i would start with just getting a list of numbers

```<code>import re
def get_ints():
    while True:
       user_input = input("enter a number or numbers(or nothing to quit)")
       if not user_input:
          break
       for a_number in re.findall("\d+",user_input):
           yield int(a_number)

a_bunch_of_numbers = list(get_ints())
# you could enter 1 number at a time or a list of numbers seperated by non-numbers
print(a_bunch_of_numbers) # looks right :)
</code>```

assuming(and verifying) that part works i move on to the next part of creating the average

```<code>average = sum(a_bunch_of_numbers)/len(a_bunch_of_numbers)
# or numpy.mean(a_bunch_of_numbers)
</code>```

finally all i need to do is print the result

Title: Average using loops

Body:
average = total / count
while PEnd !="Q" :
    total = total + value
    average = 0.0
    value = int(input("Enter an input value: "))
    total = total + value
    count = 1
     value = int(input("Enter an input value: "))
     PEnd = input("Enter character Q to quit or any other character to continue:
    ")
    PEnd = " "
    PEnd = input("Enter character Q to quit or any other character to continue: ")
    total = 0
     count = count + 1
    print("The average is: ", average)

Anyone know how to rearrange this code so that when the values that are inputted are 3 4 8 4 , the average is 4.75. have tried rewriting it and getting average as 2 with code below and 4 when count = 0

here's my try:

PEnd = " "
while PEnd !="Q" :
    value = int(input("Enter an input value: "))
    average = 0.0
    total = 0
    count = 1
    total = total + value
    count = count + 1
    average = total / count

    PEnd = input("Enter character Q to quit or any other character to continue: ")

print("The average is: ", average)

Body:
break your program into its parts

get a bunch of integers from the user

average those numbers

print the result

It helps me to actually break my program into its logical components so i would start with just getting a list of numbers

import re
def get_ints():
    while True:
       user_input = input("enter a number or numbers(or nothing to quit)")
       if not user_input:
          break
       for a_number in re.findall("\d+",user_input):
           yield int(a_number)

a_bunch_of_numbers = list(get_ints())
# you could enter 1 number at a time or a list of numbers seperated by non-numbers
print(a_bunch_of_numbers) # looks right :)

assuming(and verifying) that part works i move on to the next part of creating the average

average = sum(a_bunch_of_numbers)/len(a_bunch_of_numbers)
# or numpy.mean(a_bunch_of_numbers)

finally all i need to do is print the result


问:
Is there a way to have a loose interface with SOME strictness?
I was hoping I could have an interface like:

```<code>interface Item {
  [ index: string ] : string | number | Item,
  id: number,
}
</code>```

So that an Item, can have any properties with string/number/object values, BUT-- if an id property is used, it MUST be a number.

Is this possible?

EDIT

I originally asked this, but then tested it out and what I did seems to work fine, UNLESS I am using optional attributes...

If I do this, then I get a typescript error:

```<code>interface Item {
  [ index: string ] : string | number | Item,
  id?: number,
}
</code>```

In order to get this to work, I have to do:

```<code>interface Item {
  [ index: string ] : string | number | Item | undefined,
  id?: number,
}
</code>```

Which I don't think I want all my other properties to be potentially undefined...  Is there another way to have id be optional?

EDIT AGAIN

Turns out even with the | undefined this doesn't work..  If I do the following:

```<code>let i : Item = { id: 123, foo: { bar: { id: 555} } };
console.log(i.foo.bar.id);
</code>```

I get errors about "object is possibly undefined"

答:
Answer already provided by "noob" but extending a Record seems to work fine:

https://www.typescriptlang.org/play?#code/C4TwDgpgBAKhDOwoF4oCUIGMD2AnAJgDyK4CWAdgOYA0UJFlAPuQK4C2ARhLgHxQBkUAN4AoKOKil8AfgBcUVp24BuEQF9VIgDYQkwAAzy4iFMLESAZtmzyAjNXPiOAQ1zyARACZ36kdt1QwLZGCEioohKS+B627g6RVjZQ9o5QLm5QXj5qfjp6niEm4alSdvGW1mWp6R7eviJAA

```<code>type Test = Record<string, string|number> & {
    id?: number;
};

let t0: Test = {
    foo: 1,
    bar: "2"
}

let t1: Test = {
    id: "1",
    foo: 1,
    bar: "2"
}

let t2: Test = {
    id: 1,
    foo: 1,
    bar: "2"
}
</code>```

You will see an error:

Errors in code Type 'string' is not assignable to type 'number |
undefined'.

Body:
I was hoping I could have an interface like:

interface Item {
  [ index: string ] : string | number | Item,
  id: number,
}

So that an Item, can have any properties with string/number/object values, BUT-- if an id property is used, it MUST be a number.

Is this possible?

EDIT

I originally asked this, but then tested it out and what I did seems to work fine, UNLESS I am using optional attributes...

If I do this, then I get a typescript error:

interface Item {
  [ index: string ] : string | number | Item,
  id?: number,
}

In order to get this to work, I have to do:

interface Item {
  [ index: string ] : string | number | Item | undefined,
  id?: number,
}

Which I don't think I want all my other properties to be potentially undefined...  Is there another way to have id be optional?

EDIT AGAIN

Turns out even with the | undefined this doesn't work..  If I do the following:

let i : Item = { id: 123, foo: { bar: { id: 555} } };
console.log(i.foo.bar.id);

I get errors about "object is possibly undefined"

Body:
Answer already provided by "noob" but extending a Record seems to work fine:

https://www.typescriptlang.org/play?#code/C4TwDgpgBAKhDOwoF4oCUIGMD2AnAJgDyK4CWAdgOYA0UJFlAPuQK4C2ARhLgHxQBkUAN4AoKOKil8AfgBcUVp24BuEQF9VIgDYQkwAAzy4iFMLESAZtmzyAjNXPiOAQ1zyARACZ36kdt1QwLZGCEioohKS+B627g6RVjZQ9o5QLm5QXj5qfjp6niEm4alSdvGW1mWp6R7eviJAA

type Test = Record<string, string|number> & {
    id?: number;
};

let t0: Test = {
    foo: 1,
    bar: "2"
}

let t1: Test = {
    id: "1",
    foo: 1,
    bar: "2"
}

let t2: Test = {
    id: 1,
    foo: 1,
    bar: "2"
}

You will see an error:

Errors in code Type 'string' is not assignable to type 'number |
undefined'.


问:
Eject excess space from string in C
I need to write a function which will eject excess space from string in C.

Example:

```<code>char s[]="  abcde    abcde    ";
</code>```

OUTPUT:

```<code>"abcde abcde"
</code>```

Code:

```<code>#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
  int i, x;
  for (i = x = 0; str[i]; ++i)
    if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
      str[x++] = str[i];
  if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
  return str;
}

int main() {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"", eject(s));
  return 0;
}
</code>```

This code doesn't work for string "          "
If this string is found program should print:

```<code>""
</code>```

How to fix this?

答:
Basically, you need to remove the consecutive space characters between the words in the input string and all leading and trailing space characters of the input string. That means, write code to remove the consecutive space characters in the input string and while removing the consecutive space characters, remove the leading and trailing space characters completely.

You can do it in just one iteration. No need to write the different functions for removing the leading and trailing spaces of input string, as shown in the other post.

You can do:

```<code>#include <stdio.h>
#include <ctype.h>

char * eject (char *str) {
    if (str == NULL) {
        printf ("Invalid input..\n");
        return NULL;
    }

    /* Pointer to keep track of position where next character to be write
     */
    char * p = str;
    for (unsigned int i = 0; str[i] ; ++i) {
        if ((isspace (str[i])) && ((p == str) || (str[i + 1] == '\0') || (str[i] == (str[i + 1])))) {
            continue;
        }
        *p++ = str[i];
    }

    /* Add the null terminating character.
     */
    *p = '\0';
    return str;
}

int main (void) {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"\n", eject(s));

  char s1[] = "      ";
  printf("\"%s\"\n", eject(s1));

  char s2[] = "ab  yz   ";
  printf("\"%s\"\n", eject(s2));

  char s3[] = "  ddd xx  jj m";
  printf("\"%s\"\n", eject(s3));

  char s4[] = "";
  printf("\"%s\"\n", eject(s4));

  return 0;
}
</code>```

Output:

```<code># ./a.out
"abcde abcde"
""
"ab yz"
"ddd xx jj m"
""
</code>```

Title: Eject excess space from string in C

Body:
I need to write a function which will eject excess space from string in C.

Example:

char s[]="  abcde    abcde    ";

OUTPUT:

"abcde abcde"

Code:

#include <stdio.h>
#include <ctype.h>
char *eject(char *str) {
  int i, x;
  for (i = x = 0; str[i]; ++i)
    if (!isspace(str[i]) || (i > 0 && !isspace(str[i - 1])))
      str[x++] = str[i];
  if(x > 0 && str[x-1] == ' ') str[x-1] = '\0';
  return str;
}

int main() {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"", eject(s));
  return 0;
}

This code doesn't work for string "          "
If this string is found program should print:

""

How to fix this?

Body:
Basically, you need to remove the consecutive space characters between the words in the input string and all leading and trailing space characters of the input string. That means, write code to remove the consecutive space characters in the input string and while removing the consecutive space characters, remove the leading and trailing space characters completely.

You can do it in just one iteration. No need to write the different functions for removing the leading and trailing spaces of input string, as shown in the other post.

You can do:

#include <stdio.h>
#include <ctype.h>

char * eject (char *str) {
    if (str == NULL) {
        printf ("Invalid input..\n");
        return NULL;
    }

    /* Pointer to keep track of position where next character to be write
     */
    char * p = str;
    for (unsigned int i = 0; str[i] ; ++i) {
        if ((isspace (str[i])) && ((p == str) || (str[i + 1] == '\0') || (str[i] == (str[i + 1])))) {
            continue;
        }
        *p++ = str[i];
    }

    /* Add the null terminating character.
     */
    *p = '\0';
    return str;
}

int main (void) {
  char s[] = "  abcde    abcde    ";
  printf("\"%s\"\n", eject(s));

  char s1[] = "      ";
  printf("\"%s\"\n", eject(s1));

  char s2[] = "ab  yz   ";
  printf("\"%s\"\n", eject(s2));

  char s3[] = "  ddd xx  jj m";
  printf("\"%s\"\n", eject(s3));

  char s4[] = "";
  printf("\"%s\"\n", eject(s4));

  return 0;
}

Output:

# ./a.out
"abcde abcde"
""
"ab yz"
"ddd xx jj m"
""


问:
filter array based on another nested array
In the code below, I apply filter on array based on other arrays. For example : Filter data array based on property names from cols and values from values array.

const
    data = [{ name: "Tiger Nixon", position: "Accountant", salary: 10800, start_date: "2011\\/04\\/25", office: "Edinburgh", rating: 5421 }, { name: "Garrett Winters", position: "Accountant", salary: 170750, start_date: "2011\\/07\\/25", office: "Tokyo", rating: 8422 }, { name: "Garrett Winters", position: "Analyst", salary: 170750, start_date: "2011\\/07\\/25", office: "Tokyo", rating: 8422 }, { name: "Ashton Cox", position: "Junior Technical Author", salary: 86000, start_date: "2009\\/01\\/12", office: "San Francisco", rating: 1562 }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: 433060, start_date: "2012\\/03\\/29", office: "Edinburgh", rating: 6224 }],
    cols = ['name', 'position'],
    values = ['Garrett Winters', 'Accountant'],
    result = data.filter(o => cols.every((k, i) => o[k] === values[i]));

    console.log(result);```
</div>
</div>
</p>
<p>The above code is working fine. But if I have nested array for numeric in <code>values</code> (see below). I want to accommodate this condition <code>salary >= nestedarray[0] && salary <= nestedarray[1]</code></p>
```cols = ['salary', 'position']
values = [[50000,500000], 'Accountant']
```
<p>I tried this but not working -</p>
```result = data.filter(o => cols.every((k, i) => if(Array.isArray(values[i]) {o[k] >= values[i][0] && o[k] <= values[i][1] } else {o[k] === values[i]}))
```

答:
You have to use the ternary operator to perform a conditional in an expression, not if.

```<code>result = data.filter(o => cols.every((k, i) =>
    Array.isArray(values[i]) ?
        o[k] >= values[i][0] && o[k] <= values[i][1] :
        o[k] === values[i]
    ));
</code>```

Body:
In the code below, I apply filter on array based on other arrays. For example : Filter data array based on property names from cols and values from values array.

const
    data = [{ name: "Tiger Nixon", position: "Accountant", salary: 10800, start_date: "2011\\/04\\/25", office: "Edinburgh", rating: 5421 }, { name: "Garrett Winters", position: "Accountant", salary: 170750, start_date: "2011\\/07\\/25", office: "Tokyo", rating: 8422 }, { name: "Garrett Winters", position: "Analyst", salary: 170750, start_date: "2011\\/07\\/25", office: "Tokyo", rating: 8422 }, { name: "Ashton Cox", position: "Junior Technical Author", salary: 86000, start_date: "2009\\/01\\/12", office: "San Francisco", rating: 1562 }, { name: "Cedric Kelly", position: "Senior Javascript Developer", salary: 433060, start_date: "2012\\/03\\/29", office: "Edinburgh", rating: 6224 }],
    cols = ['name', 'position'],
    values = ['Garrett Winters', 'Accountant'],
    result = data.filter(o => cols.every((k, i) => o[k] === values[i]));

    console.log(result);

The above code is working fine. But if I have nested array for numeric in values (see below). I want to accommodate this condition salary >= nestedarray[0] && salary <= nestedarray[1]

cols = ['salary', 'position']
values = [[50000,500000], 'Accountant']

I tried this but not working -

result = data.filter(o => cols.every((k, i) => if(Array.isArray(values[i]) {o[k] >= values[i][0] && o[k] <= values[i][1] } else {o[k] === values[i]}))

Body:
You have to use the ternary operator to perform a conditional in an expression, not if.

result = data.filter(o => cols.every((k, i) =>
    Array.isArray(values[i]) ?
        o[k] >= values[i][0] && o[k] <= values[i][1] :
        o[k] === values[i]
    ));


问:
Can i use Jsoup in Jetpack Compose in kotlin
In traditional xml way , i use GlobalScope.launch{}  with  runOnUiThread {} to work with Jsoup.But in jetpack Compose this not work anymore. It just instant closed when run it.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        GlobalScope.launch{

            val url="somewebsite.com"
            var doc= Jsoup.connect(url).get()

          runOnUiThread {
          }
        }

        setContent {
            WannaJsoupTheme {

                Surface(color = MaterialTheme.colors.background) {
                    Greeting("Android")
                }
            }
        }
    }
}
```

答:
Explanation

Based on the above code, apparently you're using the main thread to perform I/O operations. Main thread are generally used for user interface operations. It's better to use background threads for I/O operations. - They are more efficient.

Here's demo app which I created to demonstrate use of JSoup with MVVM architecture.

Link - https://github.com/TheCodeMonks/NYTimes-App

Solution - https://gist.github.com/Spikeysanju/111e061ad82f3b7be6beb419fb18bca4

Quick Solution

```<code>class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {

        // Initiate Coroutine scope
        val scope = rememberCoroutineScope()
        var text by remember {
            mutableStateOf("")
        }

        JsoupTheme {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {

                // Initiate coroutine scope will will run on IO thread &  write method to get the text from the website
                scope.launch(Dispatchers.IO) {
                    val url = "https://en.wikipedia.org/wiki/Steve_Jobs"
                    Jsoup.connect(url).get().also {
                        text = it.text()
                    }
                }

                // Fetch result from the state variable [Text]
                Text(text = "Result: $text")

            }
        }
    }
}
</code>```

}

Body:
Explanation

Based on the above code, apparently you're using the main thread to perform I/O operations. Main thread are generally used for user interface operations. It's better to use background threads for I/O operations. - They are more efficient.

Here's demo app which I created to demonstrate use of JSoup with MVVM architecture.

Link - https://github.com/TheCodeMonks/NYTimes-App

Solution - https://gist.github.com/Spikeysanju/111e061ad82f3b7be6beb419fb18bca4

Quick Solution

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {

        // Initiate Coroutine scope
        val scope = rememberCoroutineScope()
        var text by remember {
            mutableStateOf("")
        }

        JsoupTheme {
            // A surface container using the 'background' color from the theme
            Surface(
                modifier = Modifier.fillMaxSize(),
                color = MaterialTheme.colors.background
            ) {

                // Initiate coroutine scope will will run on IO thread &  write method to get the text from the website
                scope.launch(Dispatchers.IO) {
                    val url = "https://en.wikipedia.org/wiki/Steve_Jobs"
                    Jsoup.connect(url).get().also {
                        text = it.text()
                    }
                }

                // Fetch result from the state variable [Text]
                Text(text = "Result: $text")

            }
        }
    }
}

}


问:
Make a loop wait for 2 seconds after fetching every 5 pages
I want the script call to wait for 2 seconds after every 5 pages.

My requirements are that the for loop should wait for 2 seconds when pageData.Number reaches page 5. So basically, the loop should wait for 2 seconds after every 5 pages.

Not sure how to check if the page reaches page 5 and wait for 2 seconds.

for (var i = 1; i <= pageData.Number; i++) {
  var pageRequest = $.getJSON(URL, function (data) {
    if (i % 5 == 0) {
      sleep(5000);
    }
    /* .... */
  }).fail(function () {
    errorPage.push(i);
  });
}

// from https://www.sitepoint.com/delay-sleep-pause-wait/
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
```

答:
Here's how you could do it - with async/await and without jQuery.

/**
 * @summary waits a specified number of seconds
 * @param {number} [seconds] seconds to wait
 * @returns {Promise<void>}
 * @link https://github.com/samliew/se-electionbot/blob/master/src/bot/utils.js#L910
 */
const wait = (seconds = 1) => new Promise((r) => setTimeout(r, seconds * 1e3));

/**
 * Your main function, async
 */
(async function () {

  // Variables, from your question
  const errorPage = [];
  const pageData = {
    Number: 10,
  };

  // test json endpoint, you can substitute this with an array
  const url = 'https://reqbin.com/echo/get/json';

  for (let i = 1; i <= pageData.Number; i++) {

    // Fetch url
    const data = await fetch(url).then(response =>
      // Convert data to json, or return null on error
      response.ok ? response.json() : errorPage.push(i) && null
    );

    // Data exists
    if(data) {
        // Do something with data
        console.log(`Request ${i} completed.`);
    }

    // Short wait after every fifth request
    if (i % 5 === 0) {
      console.log('Waiting for 2 seconds...');
      await wait(2);
    }
  }

  console.log('Done!');

})(); // end main function```


问:
How do I parse the following string?

Possible Duplicates:

  How to parseInt a string with leading 0

  Workarounds for JavaScript parseInt octal bug

How can I parse the "09" into number?

       alert(parseInt("09"));

This returns me 0 ..Why is that and how do I fix this?

答:
Specify the base as well:

```<code>alert(parseInt("09", 10));  // outputs 9
</code>```

Title: How do I parse the following string?

Body:
Specify the base as well:

alert(parseInt("09", 10));  // outputs 9


问:
powershell: pipe file content into a command
I'm not fluent into PowerShell, and I struggle on a somewhat simple problem:

I want to encrypt a (small) random file with DPAPI and write the result into another file.

I can encrypt an immediate string:

```<code>'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
--> the result is a bunch of digits: 1000000d08c9d[...]0e35854
</code>```

Same thing, output into a file:

```<code>'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path output.txt
--> the file is created, and contains the right data
</code>```

But I don't understand how to get data from a file:

```<code># content of a file
Get-Content -Path input.txt
# --> 1st line
#     blah
#     last line

# pipe it into a command
Get-Content -Path input.txt | Measure-Object -line -word
# --> Lines Words Characters Property
#     ----- ----- ---------- --------
#         3     5

# but can not pipe it into ConvertTo-SecureString
Get-Content -Path input.txt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is an empty string.
#     + ...  -Path input.txt |  ConvertTo-SecureString -AsPlainText -Force | Conve ...
#     +                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#     + CategoryInfo          : InvalidData : (:PSObject) [ConvertTo-SecureString], ParameterBindingValidationException
#     + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
</code>```

Question: how can I make ConvertTo-SecureString to read a file's content?

答:
Thanks to @Santiago Squarzon for the answer: Get-Content by default return an array of strings.

To get the "real" data, the "-raw" parameter must be used.

```<code>Get-Content -Path input.txt -Raw | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> 1000000d08c9d[...]0e35854
</code>```

Body:
I'm not fluent into PowerShell, and I struggle on a somewhat simple problem:

I want to encrypt a (small) random file with DPAPI and write the result into another file.

I can encrypt an immediate string:

'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
--> the result is a bunch of digits: 1000000d08c9d[...]0e35854

Same thing, output into a file:

'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path output.txt
--> the file is created, and contains the right data

But I don't understand how to get data from a file:

# content of a file
Get-Content -Path input.txt
# --> 1st line
#     blah
#     last line

# pipe it into a command
Get-Content -Path input.txt | Measure-Object -line -word
# --> Lines Words Characters Property
#     ----- ----- ---------- --------
#         3     5

# but can not pipe it into ConvertTo-SecureString
Get-Content -Path input.txt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is an empty string.
#     + ...  -Path input.txt |  ConvertTo-SecureString -AsPlainText -Force | Conve ...
#     +                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#     + CategoryInfo          : InvalidData : (:PSObject) [ConvertTo-SecureString], ParameterBindingValidationException
#     + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

Question: how can I make ConvertTo-SecureString to read a file's content?

Body:
Thanks to @Santiago Squarzon for the answer: Get-Content by default return an array of strings.

To get the "real" data, the "-raw" parameter must be used.

Get-Content -Path input.txt -Raw | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> 1000000d08c9d[...]0e35854


问:
Changing python list size during iteration. Is it okay?
```<code>a = [1,2,3,4,5]

for i in range(len(a)):
    a.pop(0)
    print ('%d/%d' % (i, len(a)))
</code>```

Above is simple code changes list size during iterating itself.

```<code>$ python test.py
0/4
1/3
2/2
3/1
4/0
</code>```

And the result was like above.

From 2/2, i exceed the total iteration size!

Question

Could anyone tell me why the code still executes after exceeding the size?

答:
hmm... for easier explanation, what happened here is

when you run for i in range(len(a)):

it will automatically run for i in range(5):

so it will not call the len function again and again for each loop

This is another example:

```<code>length=5
for i in range(length):
    length=2
    print(length)
</code>```

the result is

```<code>2
2
2
2
2
</code>```

Correct me if I am wrong, but I think most of for iteration (any language) is fixed since beginning, if you want to loop something that is not fixed, better use while

```<code>length=5
i=0
while i < length:
    length=2
    print(length)
    i+=1
</code>```

The result

```<code>2
2
</code>```

Body:
a = [1,2,3,4,5]

for i in range(len(a)):
    a.pop(0)
    print ('%d/%d' % (i, len(a)))

Above is simple code changes list size during iterating itself.

$ python test.py
0/4
1/3
2/2
3/1
4/0

And the result was like above.

From 2/2, i exceed the total iteration size!

Question

Could anyone tell me why the code still executes after exceeding the size?

Body:
hmm... for easier explanation, what happened here is

when you run for i in range(len(a)):

it will automatically run for i in range(5):

so it will not call the len function again and again for each loop

This is another example:

length=5
for i in range(length):
    length=2
    print(length)

the result is

2
2
2
2
2

Correct me if I am wrong, but I think most of for iteration (any language) is fixed since beginning, if you want to loop something that is not fixed, better use while

length=5
i=0
while i < length:
    length=2
    print(length)
    i+=1

The result

2
2


问:
Create Week Date Range column based on the service date
I need to create WeekDateRange column based on the ServiceDate column.
Each WeekDateRange value should START with Monday date and END with Sunday date associated with ServiceDate in (mm/dd/yyyy - mm/dd/yyyy) format.

```<code>SELECT s.ServiceDate
FROM ServiceInfo AS s
</code>```

ServiceDate

2022-01-03

2022-01-07

2022-01-15

2022-01-26

2022-01-29

2022-02-01

2022-02-04

2022-02-06

2022-02-07

I tried to use below query, however 2022-02-06 ServiceDate assigns to 02/07/2022 - 02/13/2022  week.

```<code>SELECT s.ServiceDate,
       CONCAT(CONVERT(VARCHAR, DATEADD(DAY, 2 - DATEPART(WEEKDAY,
            s.ServiceDate), CAST(s.ServiceDate AS DATE)), 101),
            ' - ', CONVERT(VARCHAR, DATEADD(DAY, 8 - DATEPART(WEEKDAY,
            s.ServiceDate), CAST(s.ServiceDate AS DATE)), 101)) AS
            WeekDateRange

FROM ServiceInfo AS s
</code>```

The output:

ServiceDate
WeekDateRange

2022-01-03
01/03/2022 - 01/09/2022

2022-01-07
01/03/2022 - 01/09/2022

2022-01-15
01/10/2022 - 01/16/2022

2022-01-26
01/24/2022 - 01/30/2022

2022-01-29
01/24/2022 - 01/30/2022

2022-02-01
01/31/2022 - 02/06/2022

2022-02-04
01/31/2022 - 02/06/2022

2022-02-06
02/07/2022 - 02/13/2022 (Needs to be 01/31/2022 - 02/06/2022)

2022-02-07
02/07/2022 - 02/13/2022

答:
You can use a reference date that is Monday to calculate the difference in days. Perform integer division by 7 and then multiply by 7 will gives you back no of days that starts on Monday

1st Jan, 1900 is a Monday, StartDate :

```<code>   DATEADD(DAY, DATEDIFF(DAY, '19000101', s.ServiceDate) / 7 * 7, '19000101')
</code>```

For End date, just add 1 week to the difference in days and subtract 1 day from the reference date which is 31 Dec 1899

```<code>   DATEADD(DAY, (DATEDIFF(DAY, '19000101', s.ServiceDate) / 7 + 1) * 7, '18991231')
</code>```

dbfiddle

Body:
I need to create WeekDateRange column based on the ServiceDate column.
Each WeekDateRange value should START with Monday date and END with Sunday date associated with ServiceDate in (mm/dd/yyyy - mm/dd/yyyy) format.

SELECT s.ServiceDate
FROM ServiceInfo AS s

ServiceDate

2022-01-03

2022-01-07

2022-01-15

2022-01-26

2022-01-29

2022-02-01

2022-02-04

2022-02-06

2022-02-07

I tried to use below query, however 2022-02-06 ServiceDate assigns to 02/07/2022 - 02/13/2022  week.

SELECT s.ServiceDate,
       CONCAT(CONVERT(VARCHAR, DATEADD(DAY, 2 - DATEPART(WEEKDAY,
            s.ServiceDate), CAST(s.ServiceDate AS DATE)), 101),
            ' - ', CONVERT(VARCHAR, DATEADD(DAY, 8 - DATEPART(WEEKDAY,
            s.ServiceDate), CAST(s.ServiceDate AS DATE)), 101)) AS
            WeekDateRange

FROM ServiceInfo AS s

The output:

ServiceDate
WeekDateRange

2022-01-03
01/03/2022 - 01/09/2022

2022-01-07
01/03/2022 - 01/09/2022

2022-01-15
01/10/2022 - 01/16/2022

2022-01-26
01/24/2022 - 01/30/2022

2022-01-29
01/24/2022 - 01/30/2022

2022-02-01
01/31/2022 - 02/06/2022

2022-02-04
01/31/2022 - 02/06/2022

2022-02-06
02/07/2022 - 02/13/2022 (Needs to be 01/31/2022 - 02/06/2022)

2022-02-07
02/07/2022 - 02/13/2022

Body:
You can use a reference date that is Monday to calculate the difference in days. Perform integer division by 7 and then multiply by 7 will gives you back no of days that starts on Monday

1st Jan, 1900 is a Monday, StartDate :

   DATEADD(DAY, DATEDIFF(DAY, '19000101', s.ServiceDate) / 7 * 7, '19000101')

For End date, just add 1 week to the difference in days and subtract 1 day from the reference date which is 31 Dec 1899

   DATEADD(DAY, (DATEDIFF(DAY, '19000101', s.ServiceDate) / 7 + 1) * 7, '18991231')

dbfiddle


问:
Adobe Sign API Create Web Form issue : use exist template
How to use the template in Adobe sign API POST /widgets API.

I can't get transientDocumentId of Template.

Please help me with this.

答:
I have found the solution.</p>
```<code>
$.ajax({
...

data: JSON.stringify({
    fileInfos: {
      libraryDocumentId: "{libraryDocumentId}" // instead transientDocumentId
    },
    ...
  })
})

</code>```

Body:
I have found the solution.

$.ajax({
...

data: JSON.stringify({
    fileInfos: {
      libraryDocumentId: "{libraryDocumentId}" // instead transientDocumentId
    },
    ...
  })
})


问:
How select and remove rows based on position for a specific range in R
Suppose I have two data frames like this:

```<code>df1 <- data.frame(a = c(1,2,4,0,0),
             b = c(0,3,5,5,0),
             c = c(0,0,6,7,6))

df2 <- data.frame(a = c(3,6,8,0,0),
             b = c(0,9,10,4,0),
             c = c(0,0,1,4,9))
</code>```

And then I joint it, like

```<code>df3 <- full_join(df1, df2)
print(df3)

   a  b c
1  1  0 0
2  2  3 0
3  4  5 6
4  0  5 7
5  0  0 6
6  3  0 0
7  6  9 0
8  8 10 1
9  0  4 4
10 0  0 9
</code>```

Note that I have always the same pattern, with zeros in rows 1 and 2; and in rows 9 and 10. And I also have zeros between rows 4 and 7.
I want to remove, only, the zeros between rows 4 and 7.
So, I can solve it, like:

```<code>df3[4,1] <- NA
df3[5,1] <- NA
df3[5,2] <- NA
df3[6,2] <- NA
df3[6,3] <- NA
df3[7,3] <- NA

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)

  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9
</code>```

But it is not elegant and very time-consuming.
Any thoughts? I really appreciate it, thanks in advance.
Best!

Body:
Suppose I have two data frames like this:

df1 <- data.frame(a = c(1,2,4,0,0),
             b = c(0,3,5,5,0),
             c = c(0,0,6,7,6))

df2 <- data.frame(a = c(3,6,8,0,0),
             b = c(0,9,10,4,0),
             c = c(0,0,1,4,9))

And then I joint it, like

df3 <- full_join(df1, df2)
print(df3)

   a  b c
1  1  0 0
2  2  3 0
3  4  5 6
4  0  5 7
5  0  0 6
6  3  0 0
7  6  9 0
8  8 10 1
9  0  4 4
10 0  0 9

Note that I have always the same pattern, with zeros in rows 1 and 2; and in rows 9 and 10. And I also have zeros between rows 4 and 7.
I want to remove, only, the zeros between rows 4 and 7.
So, I can solve it, like:

df3[4,1] <- NA
df3[5,1] <- NA
df3[5,2] <- NA
df3[6,2] <- NA
df3[6,3] <- NA
df3[7,3] <- NA

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)

  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9

But it is not elegant and very time-consuming.
Any thoughts? I really appreciate it, thanks in advance.
Best!

Body:
df3 %>%
  mutate(rn = between(row_number(), 4, 7)) %>%
  summarise(across(-rn, ~.x[!(.x == 0 & rn)]))
  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9