问:
React Router Dom V6 pass array to path
I want to render same page by multiple routes in react-router-dom v6 like how it was in v5.
However, I couldn't find a efficient way to do it.

Example in v5 I can do this:

```<code>    <BrowserRouter>
      <Switch>
        <Route path={["/dashboard", "/home"]} render={<Home />} />
        <Route path="/other" render={<OtherPage/>} />
        <Route path={["/", "/404"]} render={<NotFound />} />
      </Switch>
    </BrowserRouter>

</code>```

But in v6, it is said that the path needs to be a string.

The only way I found that can achieve this is to separate them as follow:

```<code>    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<Home />} />
        <Route path="/home" element={<Home />} />
      </Routes>
    </BrowserRouter>

</code>```

Which means I have to write <Home /> multiple times.

I want to keep my code as CLEAN as possible.

I checked the official documentation, but didn't mention about this part. And I did research, but couldn't find a solution.

答:
There is no need for custom solutions. The cleanest solution is to loop internally:

```<code><Routes>
  {["/dashboard", "/home"].map(path => (
    <Route
      key="Home" // optional: avoid full re-renders on route changes
      path={path}
      element={<Home />}
    />
  ))}
</Routes>
</code>```

For your use case with only two routes, I personally think having separate routes is more readable. But for my use case; where I have 6+ routes pointing to the same component, it doesn't make sense any longer.

Key prop

The fixed key is a "hack" that's only needed for specific cases where your users have a way to switch between the URLs internally and/or if the component is heavy. Using the same key for all routes in the Array tells React that the component didn't unmount when React Router switches routes and that only the props changed, this way React doesn't re-render the entire branch. It works because React Router never renders two routes at any point in time.

Playground

https://stackblitz.com/edit/github-otdpok?file=src/App.tsx

Title: React Router Dom V6 pass array to path

Body:
I want to render same page by multiple routes in react-router-dom v6 like how it was in v5.
However, I couldn't find a efficient way to do it.

Example in v5 I can do this:

    <BrowserRouter>
      <Switch>
        <Route path={["/dashboard", "/home"]} render={<Home />} />
        <Route path="/other" render={<OtherPage/>} />
        <Route path={["/", "/404"]} render={<NotFound />} />
      </Switch>
    </BrowserRouter>

But in v6, it is said that the path needs to be a string.

The only way I found that can achieve this is to separate them as follow:

    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<Home />} />
        <Route path="/home" element={<Home />} />
      </Routes>
    </BrowserRouter>

Which means I have to write <Home /> multiple times.

I want to keep my code as CLEAN as possible.

I checked the official documentation, but didn't mention about this part. And I did research, but couldn't find a solution.

Body:
There is no need for custom solutions. The cleanest solution is to loop internally:

<Routes>
  {["/dashboard", "/home"].map(path => (
    <Route
      key="Home" // optional: avoid full re-renders on route changes
      path={path}
      element={<Home />}
    />
  ))}
</Routes>

For your use case with only two routes, I personally think having separate routes is more readable. But for my use case; where I have 6+ routes pointing to the same component, it doesn't make sense any longer.

Key prop

The fixed key is a "hack" that's only needed for specific cases where your users have a way to switch between the URLs internally and/or if the component is heavy. Using the same key for all routes in the Array tells React that the component didn't unmount when React Router switches routes and that only the props changed, this way React doesn't re-render the entire branch. It works because React Router never renders two routes at any point in time.

Playground

https://stackblitz.com/edit/github-otdpok?file=src/App.tsx


来源: stackexchange

问:
What SPN do I need to set for a net.tcp service?
I have a wcf application hosted in a windows service running a local windows account. Do I need to set an SPN for this account? If so, what's the protocol the SPN needs to be set under? I know how to do this for services over HTTP, but have never done it for net.tcp.</p>

答:
Change the service account to an AD account and register the SPN's as shown. Use your own service name e.g. fooservice

setspn -A fooservice/servermachinename domain\serviceAccountName

  setspn -A fooservice/servermachinename.fullyqualifieddomainname
  domain\serviceAccountName

In the client config set:

```<code><identity>
    <serviceprincipalname value="fooservice/servermachinename" />
</identity>
</code>```

OwnerDisplayName: Esteban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: John Nolan

Body:
Change the service account to an AD account and register the SPN's as shown. Use your own service name e.g. fooservice

setspn -A fooservice/servermachinename domain\serviceAccountName

  setspn -A fooservice/servermachinename.fullyqualifieddomainname
  domain\serviceAccountName

In the client config set:

<identity>
    <serviceprincipalname value="fooservice/servermachinename" />
</identity>

ContentLicense: CC BY-SA 3.0


问:
Complex HTML/CSS Layout
I've been a web developer for really quite some time now, but this is something I've never really done, and my progress so far has used some very complex methods.  The following is the layout I want, there are rules to this layout though, as I will explain in a moment.

```<code>    ----------------------------------------------------
    |                      HEADER                      |
    ----------------------------------------------------
     ________   _______________________________________
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |________| |                                       |
               |                                       |
               |                                       |
               |                                       |
               |                                       |
               |                                       |
               |_______________________________________|
</code>```

The sidebar and the header are static and so is the body, however you can scroll the body.  Using the CSS property overflow:scroll on a container for the body section is not an option.  The reason being is that it's an ASP.NET application which utilises the maintainpositiononscrollback, meaning that the browser scrollbar - not a contain scrollbar - is what is used to record the x and y position.  I have achieved this but using some complex layout techniques which just aren't pretty.

So my HTML looks like the following:

```<code><div id="header">
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="#">Telephone</a></li>
    <li><a href="#">My Department</a></li>
    <li><a href="#">My Profile</a></li>
  </ul>
</div>

<div id="sidebar-container">
  <div id="sidebar">
    <!-- sidebar code using ul's and li's -->
  </div>
</div>

<div id="content-top-border"></div>
<div id="content-left-border"></div>

<div id="content-wrap">
  <div id="content">
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  </div>
</div>

<div id="content-right-border"></div>
<div id="content-bottom-border"></div>
<div id="bottom-block"></div>
</code>```

So I use all of these divs for a specific reason, so I can absolutely position borders on the content area.  The rest of the divs actually block off content by changing the background colour of them so you can't see the content when you scroll.

My CSS file is far too large to be posting on here, but here's the general idea:

```<code>div#header {
    height:30px;
    background-color:#d7d7d7;
    position:fixed;
    top:0;
    left:0;
    right:0;
}

div#sidebar {
    position:fixed;
    top:30px;
    left:0;
    overflow:auto;
    bottom:4px;
    width:148px;
    background-color:#d7d7d7;
}

div#sidebar ul {
    border:1px solid #9a9a9a;
    border-bottom:0;
    font-family:Tahoma;
    margin:0 0 0 4px;
    padding:0;
    list-style-type:none;
    font-size:0.75em;
    width:137px;
    clear:both;
    background-color:white;
}
</code>```

So as you can see from the sidebar, I set a fixed width, make it position:fixed and then set a background.  The containing
 has a fixed width thus causing a block.  When you horizontally scroll the page, the content will be hidden when it hits the sidebar.  This creates an effect much like any client-side application.

```<code>#content-wrap {
    position: absolute;
    top: 30px;
    bottom: 15px;
    left: 147px;
    right:0;
    background-color:#d7d7d7;
    z-index:-998;
}

#content {
    z-index:-995;
    position:absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
    padding:10px 10px 20px 10px;
    background-color:#FFF;
    color:#292929;
}
</code>```

So you can see that the #content has absolute positioning keeping it in that content box.  Anything outside of the content box is never displayed even if you scroll horizontally or vertically.

Are there better ways of doing this?  It seems a heck-of-a-lot of HTML/CSS to be doing something really quite simple.

EDIT: This layout isn't a problem whatsoever.  That part isn't even difficult.  What's difficult is maintaining simple HTML/CSS with a complex layout, and by complex, I don't mean something I'm unable to achieve.  I have achieved the desired effect already, I'm just looking for a better way of doing it.

EDIT: This is based on business requirements, I don't have a choice :)

答:
Fixed position elements are typically a bit of a warning sign for me- by taking things out of the document flow you are losing one of the main benefits of CSS, which is it's flexibility. Again, by mixing px and em measurements you are creating a slightly mixed-up stylesheet jam that doesn't allow for the page to be resized easily.

However the central problem seems to be a question of whether you are barking up the right tree in terms of approach and outcomes. Do you have to be using the maintainpositiononscrollback option from ASP.NET? It wouldn't be too hard to implement a bit of light javascript to create an equivalent effect on an overflowed div. If you are stuck with the asp.net code, do you have to have your text in a small box like that or could you just let the page be as long as the content?

If you have to use the maintainpositionscrollback and you have to have the content in a small box you might be better off using some less standards-friendly code for your markup- perhaps putting the content in an iFrame would give you the behaviour you are looking for. If you're losing most of the benefits of semantic html and css in order to implement the design you want then you're not going to sacrifice much more by taking a different approach to the design.

OwnerDisplayName: Kezzer

Title: Complex HTML/CSS Layout

Body:
I've been a web developer for really quite some time now, but this is something I've never really done, and my progress so far has used some very complex methods.  The following is the layout I want, there are rules to this layout though, as I will explain in a moment.

    ----------------------------------------------------
    |                      HEADER                      |
    ----------------------------------------------------
     ________   _______________________________________
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |        | |                                       |
    |________| |                                       |
               |                                       |
               |                                       |
               |                                       |
               |                                       |
               |                                       |
               |_______________________________________|

The sidebar and the header are static and so is the body, however you can scroll the body.  Using the CSS property overflow:scroll on a container for the body section is not an option.  The reason being is that it's an ASP.NET application which utilises the maintainpositiononscrollback, meaning that the browser scrollbar - not a contain scrollbar - is what is used to record the x and y position.  I have achieved this but using some complex layout techniques which just aren't pretty.

So my HTML looks like the following:

Home

Telephone

My Department

My Profile

    <asp:ContentPlaceHolder ID="MainContent" runat="server" />

So I use all of these divs for a specific reason, so I can absolutely position borders on the content area.  The rest of the divs actually block off content by changing the background colour of them so you can't see the content when you scroll.

My CSS file is far too large to be posting on here, but here's the general idea:

div#header {
    height:30px;
    background-color:#d7d7d7;
    position:fixed;
    top:0;
    left:0;
    right:0;
}

div#sidebar {
    position:fixed;
    top:30px;
    left:0;
    overflow:auto;
    bottom:4px;
    width:148px;
    background-color:#d7d7d7;
}

div#sidebar ul {
    border:1px solid #9a9a9a;
    border-bottom:0;
    font-family:Tahoma;
    margin:0 0 0 4px;
    padding:0;
    list-style-type:none;
    font-size:0.75em;
    width:137px;
    clear:both;
    background-color:white;
}

So as you can see from the sidebar, I set a fixed width, make it position:fixed and then set a background.  The containing
 has a fixed width thus causing a block.  When you horizontally scroll the page, the content will be hidden when it hits the sidebar.  This creates an effect much like any client-side application.

#content-wrap {
    position: absolute;
    top: 30px;
    bottom: 15px;
    left: 147px;
    right:0;
    background-color:#d7d7d7;
    z-index:-998;
}

#content {
    z-index:-995;
    position:absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
    padding:10px 10px 20px 10px;
    background-color:#FFF;
    color:#292929;
}

So you can see that the #content has absolute positioning keeping it in that content box.  Anything outside of the content box is never displayed even if you scroll horizontally or vertically.

Are there better ways of doing this?  It seems a heck-of-a-lot of HTML/CSS to be doing something really quite simple.

EDIT: This layout isn't a problem whatsoever.  That part isn't even difficult.  What's difficult is maintaining simple HTML/CSS with a complex layout, and by complex, I don't mean something I'm unable to achieve.  I have achieved the desired effect already, I'm just looking for a better way of doing it.

EDIT: This is based on business requirements, I don't have a choice :)

LastEditorDisplayName: Kezzer

OwnerDisplayName: glenatron


问:
Call a stored procedure which contains parameters and output param from another stored procedure?
This is just an example to demonstrate.

Stored procedure A:

```<code>Create PROCEDURE InsertNode

@ID nvarchar(64),
@Name nvarchar(64),
@Total int OUTPUT
AS
INSERT INTO [TableA] (ID,Name) VALUES (@ID, @Name)
SELECT @Total = Count(*) FROM TableA
</code>```

Stored procedure B:

```<code>Create PROCEDURE CallInsertNode

@InputID nvarchar(64),
@InputName nvarchar(64),
@ResultTotal
AS
EXEC InsertNode ...// how can I define the input params(@InputID, @Input Name) and output param (@ResultTotal) for Stored procedure A (like passing parameters)?
</code>```

Thank you.

答:
```<code>EXEC InsertNode
    @Id = @InputId,
    @Name = @InputName,
    @Total = @ResultTotal OUTPUT
</code>```

Body:
This is just an example to demonstrate.

Stored procedure A:

Create PROCEDURE InsertNode

@ID nvarchar(64),
@Name nvarchar(64),
@Total int OUTPUT
AS
INSERT INTO [TableA] (ID,Name) VALUES (@ID, @Name)
SELECT @Total = Count(*) FROM TableA

Stored procedure B:

Create PROCEDURE CallInsertNode

@InputID nvarchar(64),
@InputName nvarchar(64),
@ResultTotal
AS
EXEC InsertNode ...// how can I define the input params(@InputID, @Input Name) and output param (@ResultTotal) for Stored procedure A (like passing parameters)?

Thank you.


问:
How to modify subscribe result in angular template?
I have an observable this.result$ to which i am subscribing inside template . for e.g result is- [{id : "1", value: "test"}]. How can I add new object to this so that it become like this-
[{id : "1", value: "test"},{id : "2", value: "new"}]

```<code><mat-form-field *ngIf="result$ | async">
  <mat-select [compareWith] = "compareFn">
    <mat-option *ngFor = "let item of result$ | async" [value]="item">
       {{item.value}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

答:
You can add new element in a observable array like this</p>
```<code>this.result$ = this.result$.pipe(map((r) => [...r, { id: "2", value: "new" }]));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an observable this.result$ to which i am subscribing inside template . for e.g result is- [{id : "1", value: "test"}]. How can I add new object to this so that it become like this-
[{id : "1", value: "test"},{id : "2", value: "new"}]

<mat-form-field *ngIf="result$ | async">
  <mat-select [compareWith] = "compareFn">
    <mat-option *ngFor = "let item of result$ | async" [value]="item">
       {{item.value}}
    </mat-option>
  </mat-select>
</mat-form-field>

Body:
You can add new element in a observable array like this

this.result$ = this.result$.pipe(map((r) => [...r, { id: "2", value: "new" }]));


问:
Changing Axios baseUrl accessible from env file after building React App
Currently I am using .env file placed in react app root folder with variable

REACT_APP_BASE_URL = http://localhost:8081

I user axios defaults to set base url for api requests

Axios.defaults.baseUrl = process.env.REACT_APP_BASEURL

After building React App .env file is not considered and in case I have my base URL changed, how can I do that without re-building whole React App.
I want to make base url independent, so I can dynamically change base url. What would be the best solution for that?

答:
BaseUrl:

```<code>  const defaultSettings = {
  DEV_REACT_APP_BASE_URL: 'http://localhost:3001',
  REACT_APP_BASE_URL: 'https://example.com',
};
const settings = {defaultSettings, ...process.env};
export default settings;
</code>```

AXIOS baseUrl:

```<code>import axios from "axios";
import settings from "./settings";

const instance = axios.create({
  baseURL:
    process.env.NODE_ENV == "production"
      ? settings.defaultSettings.REACT_APP_BASE_URL
      : settings.defaultSettings.DEV_REACT_APP_BASE_URL,
  timeout: 1000,
  headers: { "Content-Type": "application/json" },
});

export default instance;
</code>```

Body:
BaseUrl:

  const defaultSettings = {
  DEV_REACT_APP_BASE_URL: 'http://localhost:3001',
  REACT_APP_BASE_URL: 'https://example.com',
};
const settings = {defaultSettings, ...process.env};
export default settings;

AXIOS baseUrl:

import axios from "axios";
import settings from "./settings";

const instance = axios.create({
  baseURL:
    process.env.NODE_ENV == "production"
      ? settings.defaultSettings.REACT_APP_BASE_URL
      : settings.defaultSettings.DEV_REACT_APP_BASE_URL,
  timeout: 1000,
  headers: { "Content-Type": "application/json" },
});

export default instance;


问:
How do I take a set of arrays (strings) and create a multidimensional slice of those arrays in Golang?
I am trying to implement a function, that when passed an array of strings, it creates a slice of arrays, and adds to it every array that is passed. It would return the final slice of all arrays that was passed.

Just as a test, I initialized 4 arrays and tried to create a function that would do just this. However, it fails quite miserably. This is what I have so far. Not sure how to go about this.

```<code>func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    FinalSlice(array1)
    FinalSlice(array2)
    FinalSlice(array3)
    fmt.Println(FinalSlice(array4))

}

func FinalSlice(array []string) [][]string {
    var slice [][]string
    for i, _ := range slice {
        slice[i] = array
    }
    return slice

}
</code>```

Right now this is the output:

```<code>[]
</code>```

答:
Couldn't one just say something like

```<code>func bundleSlices( slices ...[]int) [][]int {
    return slices
}
</code>```

And then:

```<code>package main

import "fmt"

func main() {
    arr1 := []int{1, 2, 3}
    arr2 := []int{4, 5, 6}
    arr3 := []int{7, 8, 9}

    bundled := bundleSlices( arr1, arr2, arr3 )

    fmt.Println(bundled)

}
</code>```

to get

```<code>[[1 2 3] [4 5 6] [7 8 9]]
</code>```

Body:
I am trying to implement a function, that when passed an array of strings, it creates a slice of arrays, and adds to it every array that is passed. It would return the final slice of all arrays that was passed.

Just as a test, I initialized 4 arrays and tried to create a function that would do just this. However, it fails quite miserably. This is what I have so far. Not sure how to go about this.

func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    FinalSlice(array1)
    FinalSlice(array2)
    FinalSlice(array3)
    fmt.Println(FinalSlice(array4))

}

func FinalSlice(array []string) [][]string {
    var slice [][]string
    for i, _ := range slice {
        slice[i] = array
    }
    return slice

}

Right now this is the output:

[]

Body:
Couldn't one just say something like

func bundleSlices( slices ...[]int) [][]int {
    return slices
}

And then:

package main

import "fmt"

func main() {
    arr1 := []int{1, 2, 3}
    arr2 := []int{4, 5, 6}
    arr3 := []int{7, 8, 9}

    bundled := bundleSlices( arr1, arr2, arr3 )

    fmt.Println(bundled)

}

to get

[[1 2 3] [4 5 6] [7 8 9]]


问:
Eclipse with Lombok - search for getter and setter usages
I'm using Eclipse with Lombok. The getters and setters are generated properly but they are not visible in class body (that's the whole point, I know). However, because of that, I am unable to execute a search for usages of a getter or a setter from inside the class. So if I want to check what and where actually sets a particular value of a field, I have to execute a String search for the getter name, which is slow and may give bad results (for a field of the same name in another class, for example).

Is there a way in Eclipse to look for a getter/setter usage for a field for lombok-generated methods?

答: Apart from finding the method in outline and then right click and find references, there is no other option as of now. Same holds good for constructors provided by lombok.</p>


问:
Stick button to right side of div
http://jsfiddle.net/kn5sH/

What do I need to add in order to stick the button to the right side of the div on the same line as the header?

HTML:

```<code><div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
</div>
</code>```

CSS:

```<code>div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
}
</code>```

More specifically:

The right side of the button should be x pixels away from the right
edge of the div.

It should be on the same line as the header.

Should be contained in the div (stuff like float or relative
positioning pops it out of the div visually)

What CSS techniques can be used to do this?  Thanks.

答:
```<code>margin-left:  auto;
</code>```

was sufficient for me

Title: Stick button to right side of div

Body:
http://jsfiddle.net/kn5sH/

What do I need to add in order to stick the button to the right side of the div on the same line as the header?

HTML:

 Ok

    <button type='button'>Button</button>

CSS:

div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
}

More specifically:

The right side of the button should be x pixels away from the right
edge of the div.

It should be on the same line as the header.

Should be contained in the div (stuff like float or relative
positioning pops it out of the div visually)

What CSS techniques can be used to do this?  Thanks.

Body:
margin-left:  auto;

was sufficient for me


问:
Data Manipulation in multiple columns(absolute, percentage, and categorical) in pandas dataframe
I need to make a function, which takes input as dataframe, and dictionary{"Col_1" :% change,"Col_2":absolute change,"Col_3": 0/1(Categorical)} and it should make the changes to the dataframe.

I Have data frame like this

Date
col_1
col_2
col_3

01/01/2022
90
100
0

01/02/2022
80
110
1

01/03/2022
92
120
0

01/04/2022
96
130
0

01/05/2022
99
150
1

01/06/2022
105
155
1

Now I pass the dictionary say,

```<code>{"Date":["01/01/2022","01/02/2022"],"col_1":[-10,-10],"col_2":10,"col_3":[1,0]}
</code>```

for "col_1" I am passing -10,-10 percentage change to its previous values on specified date.

for "col_2" I am passing an absolute number that is 10 (it should replace previous values by 10)
specified date.

for "col_3" I am passing a binary number and it updated in dataframe on specified date.

Then my desired out would look like this

Date
col_1
col_2
col_3

01/01/2022
81
10
1

01/02/2022
72
10
0

01/03/2022
92
120
0

01/04/2022
96
120
0

01/05/2022
99
150
1

01/06/2022
105
155
1

I followed tried this code:

```<code>def per_change(df,cols,d):
    df[cols] = df[cols].add(df[cols].div(100).mul(pd.Series(d)), fill_value=0)
    return df
</code>```

but it didn't worked out. Please help!!

Body:
I need to make a function, which takes input as dataframe, and dictionary{"Col_1" :% change,"Col_2":absolute change,"Col_3": 0/1(Categorical)} and it should make the changes to the dataframe.

I Have data frame like this

Date
col_1
col_2
col_3

01/01/2022
90
100
0

01/02/2022
80
110
1

01/03/2022
92
120
0

01/04/2022
96
130
0

01/05/2022
99
150
1

01/06/2022
105
155
1

Now I pass the dictionary say,

{"Date":["01/01/2022","01/02/2022"],"col_1":[-10,-10],"col_2":10,"col_3":[1,0]}

for "col_1" I am passing -10,-10 percentage change to its previous values on specified date.

for "col_2" I am passing an absolute number that is 10 (it should replace previous values by 10)
specified date.

for "col_3" I am passing a binary number and it updated in dataframe on specified date.

Then my desired out would look like this

Date
col_1
col_2
col_3

01/01/2022
81
10
1

01/02/2022
72
10
0

01/03/2022
92
120
0

01/04/2022
96
120
0

01/05/2022
99
150
1

01/06/2022
105
155
1

I followed tried this code:

def per_change(df,cols,d):
    df[cols] = df[cols].add(df[cols].div(100).mul(pd.Series(d)), fill_value=0)
    return df

but it didn't worked out. Please help!!

Body:
You could use dic["Date"] as a boolean mask and update values in df using the values under the other keys in dic:

msk = df['Date'].isin(dic['Date'])
df.loc[msk, 'col_1'] *= (1 + np.array(dic['col_1']) / 100)
df.loc[msk, 'col_2'] = dic['col_2']
df.loc[msk, 'col_3'] = dic['col_3']

Output:

         Date  col_1  col_2  col_3
0  01/01/2022   81.0     10      1
1  01/02/2022   72.0     10      0
2  01/03/2022   92.0    120      0
3  01/04/2022   96.0    130      0
4  01/05/2022   99.0    150      1
5  01/06/2022  105.0    155      1


问:
I'm not able to start the mongo db server, getting the following error: [nodemon] app crashed - waiting for file changes before starting
This is server.js and .env file
I'm trying to start the server but it is throwing an error.

server.js

```<code> const express = require('express');
 const cors = require('cors');
 const mongoose = require('mongoose');

 require('dotenv').config();

 const app = express();
 const port = process.env.PORT || 5000;

 app.use(cors());
 app.use(express.json());

 const uri = process.env.ATLAS_URI;
 mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });

 const connection = mongoose.connection;
 connection.once('open',() => {
     console.log("MongoDB database connection established successfully");
 })
 app.listen(port, () => {
     console.log(`Server is running on port: ${port}`);
 })

</code>```

.env

```<code>ATLAS_URI = mongodb+srv://rnvsri:vastav123@cluster0.dgnw1.mongodb.net/test?retryWrites=true&w=majority
</code>```

Issue:

In cmd, I'm giving the command nodemon server.js

but the server is not starting and it is throwing the following error.

```<code>nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (node:net:1334:16)
    at listenInCluster (node:net:1382:12)
    at Server.listen (node:net:1469:7)
    at Function.listen (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/server.js:20:6)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1361:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...

</code>```

Can someone help?

答:
port you are using is used by another process you can find it by
command
lsof -i :PORT  and can kill using kill command

kill PID

Body:
This is server.js and .env file
I'm trying to start the server but it is throwing an error.

server.js

 const express = require('express');
 const cors = require('cors');
 const mongoose = require('mongoose');

 require('dotenv').config();

 const app = express();
 const port = process.env.PORT || 5000;

 app.use(cors());
 app.use(express.json());

 const uri = process.env.ATLAS_URI;
 mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });

 const connection = mongoose.connection;
 connection.once('open',() => {
     console.log("MongoDB database connection established successfully");
 })
 app.listen(port, () => {
     console.log(`Server is running on port: ${port}`);
 })

.env

ATLAS_URI = mongodb+srv://rnvsri:vastav123@cluster0.dgnw1.mongodb.net/test?retryWrites=true&w=majority

Issue:

In cmd, I'm giving the command nodemon server.js

but the server is not starting and it is throwing the following error.

nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (node:net:1334:16)
    at listenInCluster (node:net:1382:12)
    at Server.listen (node:net:1469:7)
    at Function.listen (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/server.js:20:6)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1361:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...

Can someone help?


问:
how to set different color every bar ApexChart
I'm using ApexChart for a project, and I want to set different colors for each bar. I pass the data array and the color array to the component, based on the color array index the relevant data bar should be colored.

Current implementation as below, I tired colors: method but it only gets the first color of the color array.

```<code>const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            horizontal: true,
            barHeight: '85%',
        },
    },
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
    },
};

const series = [
    {
        data: exampleChartData.data || [],

    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);
</code>```

答:
You need to add distributed: true option inside bar key of plotOptions as well as adding the colors option as array. You can take a look at this sandbox for a live working example. And your final code will be like this:

```<code>const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            distributed: true, // this line is mandatory
            horizontal: true,
            barHeight: '85%',
        },
    },
    colors: [ // this array contains different color code for each data
        "#33b2df",
        "#546E7A",
        "#d4526e",
        "#13d8aa",
        "#A5978B",
        "#2b908f",
        "#f9a3a4",
        "#90ee7e",
        "#f48024",
        "#69d2e7"
    ],
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
    },
};

const series = [
    {
        data: exampleChartData.data || [],
    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);
</code>```

Body:
I'm using ApexChart for a project, and I want to set different colors for each bar. I pass the data array and the color array to the component, based on the color array index the relevant data bar should be colored.

Current implementation as below, I tired colors: method but it only gets the first color of the color array.

const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            horizontal: true,
            barHeight: '85%',
        },
    },
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
    },
};

const series = [
    {
        data: exampleChartData.data || [],

    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);

Body:
You need to add distributed: true option inside bar key of plotOptions as well as adding the colors option as array. You can take a look at this sandbox for a live working example. And your final code will be like this:

const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            distributed: true, // this line is mandatory
            horizontal: true,
            barHeight: '85%',
        },
    },
    colors: [ // this array contains different color code for each data
        "#33b2df",
        "#546E7A",
        "#d4526e",
        "#13d8aa",
        "#A5978B",
        "#2b908f",
        "#f9a3a4",
        "#90ee7e",
        "#f48024",
        "#69d2e7"
    ],
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },
    },
};

const series = [
    {
        data: exampleChartData.data || [],
    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);


问:
Kubernetes Ingress non-root path 404 Not Found
I have the following that config that works when I try <NodeIP>:30080

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: app-deployment
spec:
  replicas: 3
  template:
    metadata:
      labels:
        name: app-node
    spec:
      containers:
        - name: app
          image: myregistry.net/repo/app:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 8080
          env:
            - name: NODE_ENV
              value: production
---
apiVersion: v1
kind: Service
metadata:
  name: app-service
spec:
  selector:
    name: app-node
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
      nodePort: 30080
  type: NodePort
</code>```

I am trying to use an Ingress:

```<code> apiVersion: extensions/v1beta1
 kind: Ingress
 metadata:
   name: nginx-ingress
 spec:
   rules:
   - host: myhost.com
     http:
       paths:
       - path: /app
         backend:
           serviceName: app-service
           servicePort: 80
</code>```

myhost.com works with the nginx intro screen, but myhost.com/app gives 404 Not Found. Where is the issue in my setup?

UPDATE:

```<code>   - path: /
     backend:
       serviceName: app-service
       servicePort: 80
</code>```

If I do root path it works, but how come /app doesn't?

答:
As specified by brandon-barnett the issue is coming from the path but after reading the link he shared, big ups to you Brandon, I realised that a more specific rewrite rule would have to specified for it to work. In my case

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  ingressClassName: nginx
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - path: /something(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: http-svc
            port:
              number: 80
</code>```

The trick is with /$2 at annotation and (/|$)(.*) at the path. So what this rewrite does is that it picks everything that comes after something/ and replaces $2 with it, so:

rewrite.bar.com/something rewrites to http-svc:80/

rewrite.bar.com/something/ rewrites to http-svc:80/

rewrite.bar.com/something/new rewrites to http-svc:80/new

rewrite.bar.com/something/new/old rewrites to http-svc:80/new/old

Body:
I have the following that config that works when I try <NodeIP>:30080

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: app-deployment
spec:
  replicas: 3
  template:
    metadata:
      labels:
        name: app-node
    spec:
      containers:
        - name: app
          image: myregistry.net/repo/app:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 8080
          env:
            - name: NODE_ENV
              value: production
---
apiVersion: v1
kind: Service
metadata:
  name: app-service
spec:
  selector:
    name: app-node
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
      nodePort: 30080
  type: NodePort

I am trying to use an Ingress:

 apiVersion: extensions/v1beta1
 kind: Ingress
 metadata:
   name: nginx-ingress
 spec:
   rules:
   - host: myhost.com
     http:
       paths:
       - path: /app
         backend:
           serviceName: app-service
           servicePort: 80

myhost.com works with the nginx intro screen, but myhost.com/app gives 404 Not Found. Where is the issue in my setup?

UPDATE:

   - path: /
     backend:
       serviceName: app-service
       servicePort: 80

If I do root path it works, but how come /app doesn't?

Body:
As specified by brandon-barnett the issue is coming from the path but after reading the link he shared, big ups to you Brandon, I realised that a more specific rewrite rule would have to specified for it to work. In my case

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  ingressClassName: nginx
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - path: /something(/|$)(.*)
        pathType: Prefix
        backend:
          service:
            name: http-svc
            port:
              number: 80

The trick is with /$2 at annotation and (/|$)(.*) at the path. So what this rewrite does is that it picks everything that comes after something/ and replaces $2 with it, so:

rewrite.bar.com/something rewrites to http-svc:80/

rewrite.bar.com/something/ rewrites to http-svc:80/

rewrite.bar.com/something/new rewrites to http-svc:80/new

rewrite.bar.com/something/new/old rewrites to http-svc:80/new/old


问:
Plotting piecewise functions using Matplotlib
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The above error is what I got for the below code intended to plot the piecewise function created. Can't figure it out.

```<code>import numpy as np
import matplotlib.pyplot as plt
def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0

xlist = np.linspace(0,1,num = 1000)
ylist = f(xlist)

plt.plot(ylist,xlist)
plt.show()
</code>```

答:
You can use the function you have already defined and vectorize is using np.vectorize.

```<code>import numpy as np
import matplotlib.pyplot as plt
    def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0.    # make this change to ensure float values

xlist = np.linspace(0,1,num = 1000)
ylist = np.vectorize(f)(xlist)

plt.plot(ylist,xlist)
plt.show()
</code>```

The issue you are running into in your code is that you are passing an array to f rather than applying f element-wise, so any comparison gives an array of True or False values; this is what is ambiguous in the error message. Using np.vectorize will change the function defined to apply to each element of the array and give you the desired output.

Body:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The above error is what I got for the below code intended to plot the piecewise function created. Can't figure it out.

import numpy as np
import matplotlib.pyplot as plt
def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0

xlist = np.linspace(0,1,num = 1000)
ylist = f(xlist)

plt.plot(ylist,xlist)
plt.show()

Body:
You can use the function you have already defined and vectorize is using np.vectorize.

import numpy as np
import matplotlib.pyplot as plt
    def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0.    # make this change to ensure float values

xlist = np.linspace(0,1,num = 1000)
ylist = np.vectorize(f)(xlist)

plt.plot(ylist,xlist)
plt.show()

The issue you are running into in your code is that you are passing an array to f rather than applying f element-wise, so any comparison gives an array of True or False values; this is what is ambiguous in the error message. Using np.vectorize will change the function defined to apply to each element of the array and give you the desired output.


问:
Task List Throws "Collection was modified; enumeration operation may not execute."
Creating a list of Tasks to run parallel like this:

```<code>if (call.Item.PictureDetails != null)
{
    List<Task> lstTasks = new List<Task>();
    foreach (var url in call.Item.PictureDetails.PictureURL.Cast<string>().ToList())
    {
        var newTile = AddNewPicTile(url);
        lstTasks.Add(Task.Run(() => {
            UploadPicture(newTile);
        }));
    }
    // Run all pic upload tasks in parallel...
    await Task.WhenAll(lstTasks);
}
</code>```

Execution throws "Collection was modified..." exception but I can't figure out why.    I use similar code to this elsewhere in my app where I perform a while() loop that reads data from a database and it works fine.   Like this...

```<code>        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                RadTileElement newTile = AddNewPicTile(rdr["PictureUrl"].ToString());   //...must create this var here otherwise we won't be able to access rdr from a background thread (it will be closed by then)

                lstTasks.Add(Task.Run(() => {
                    UploadPicture(newTile);
                }));
            }
        }
        rdr.Close();
    }
    conn.Close();
}

// Run all pic upload tasks in parallel...
await Task.WhenAll(lstTasks);
</code>```

What is it about the string list that could cause it to yell at me like that?

答: Actually - problem was not related to List.  Not even in the code posted.    Thanks to Caius Jard who got me looking elsewhere for it.</p>

Body:
Creating a list of Tasks to run parallel like this:

if (call.Item.PictureDetails != null)
{
    List<Task> lstTasks = new List<Task>();
    foreach (var url in call.Item.PictureDetails.PictureURL.Cast<string>().ToList())
    {
        var newTile = AddNewPicTile(url);
        lstTasks.Add(Task.Run(() => {
            UploadPicture(newTile);
        }));
    }
    // Run all pic upload tasks in parallel...
    await Task.WhenAll(lstTasks);
}

Execution throws "Collection was modified..." exception but I can't figure out why.    I use similar code to this elsewhere in my app where I perform a while() loop that reads data from a database and it works fine.   Like this...

        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                RadTileElement newTile = AddNewPicTile(rdr["PictureUrl"].ToString());   //...must create this var here otherwise we won't be able to access rdr from a background thread (it will be closed by then)

                lstTasks.Add(Task.Run(() => {
                    UploadPicture(newTile);
                }));
            }
        }
        rdr.Close();
    }
    conn.Close();
}

// Run all pic upload tasks in parallel...
await Task.WhenAll(lstTasks);

What is it about the string list that could cause it to yell at me like that?


问:
How to retrieve the original data from nls model in R?
non-linear least square (nls() function in core R) generates a list object with a bunch of useful info inside, is there also the original data that were the input of the model? I suspect yes, as functions as predict() or fitted() are actually defined on this object and generate predictions in ranges of the original fitted data. So, how can one access this data through the model object?

Imagine this setting

```<code># generating some data
generated_data <- hist(rnorm(1000, 50, 10))
data <- data.frame(x = generated_data$mids, y = generated_data$counts)

# a dummy model
my_model <- nls(y ~ N * dnorm(x, m, s), data=data, start=c(m=55, s=12, N=sum(data$y)) )
</code>```

How can I access x and y values by the my_model object?

答:
The data indeed is there but it's a bit buried within the environment of the model that is also saved within the object, I figured it out looking at the source code. You can access the input values of through getEnv() function which is available through the m object and that is part of the list returned by nls.

So on the dummy example:

```<code># generating some data
generated_data <- hist(rnorm(1000, 50, 10))
data <- data.frame(x = generated_data$mids, y = generated_data$counts)

# a dummy model
my_model <- nls(y ~ N * dnorm(x, m, s), data=data, start=c(m=55, s=12, N=sum(data$y)) )

original_x_values <- my_model$m$getEnv()$x
original_y_values <- my_model$m$getEnv()$y
</code>```

Body:
non-linear least square (nls() function in core R) generates a list object with a bunch of useful info inside, is there also the original data that were the input of the model? I suspect yes, as functions as predict() or fitted() are actually defined on this object and generate predictions in ranges of the original fitted data. So, how can one access this data through the model object?

Imagine this setting

# generating some data
generated_data <- hist(rnorm(1000, 50, 10))
data <- data.frame(x = generated_data$mids, y = generated_data$counts)

# a dummy model
my_model <- nls(y ~ N * dnorm(x, m, s), data=data, start=c(m=55, s=12, N=sum(data$y)) )

How can I access x and y values by the my_model object?

Body:
The data indeed is there but it's a bit buried within the environment of the model that is also saved within the object, I figured it out looking at the source code. You can access the input values of through getEnv() function which is available through the m object and that is part of the list returned by nls.

So on the dummy example:

# generating some data
generated_data <- hist(rnorm(1000, 50, 10))
data <- data.frame(x = generated_data$mids, y = generated_data$counts)

# a dummy model
my_model <- nls(y ~ N * dnorm(x, m, s), data=data, start=c(m=55, s=12, N=sum(data$y)) )

original_x_values <- my_model$m$getEnv()$x
original_y_values <- my_model$m$getEnv()$y


问:
resource:memory error when trying to run an ECS task using AWS CLI
I'm trying to set up CI with AWS ECS and docker. I use Codeship as a CI tool, but that should not really matter much.

I do the following steps in a shell script:

build an image with my Dockerfile,

push the image to ECS repository,

push a task-definition.json to ECS aws ecs register-task-definition --family postgraphile --cli-input-json file:///deploy/ecs-task-def.json --region us-east-2

run the ECS task aws ecs run-task --task-definition postgraphile --cluster testcluster --region us-east-2

Shell script runs successfully, however I see an error in output after I try to run my ECS task:

```<code>{
    "tasks": [],
    "failures": [
        {
            "arn": "arn:aws:ecs:us-east-2:99999999999:container-instance/050ab165-7669-45d5-8be7-d990cf4fff42",
            "reason": "RESOURCE:MEMORY"
        }
    ]
}
</code>```

my ecs-task-def.json:

```<code>{
  "containerDefinitions": [
    {
      "name": "postgraphile-container",
      "image": "999999999999.dkr.ecr.us-east-2.amazonaws.com/test-repository",
      "memory": 500,
      "essential": true,
      "portMappings": [
        {
          "hostPort": 5000,
          "containerPort": 5000
        }
      ]
    }
  ],
  "volumes": [],
  "memory": "900",
  "cpu": "128",
  "placementConstraints": [],
  "family": "postgraphile",
  "taskRoleArn": ""
}
</code>```

I think I already checked all the memory limits.. am I missing anything?

UPDATE:
After couple of reboots of ec2 instance I can finally run the ecs task with no errors. After running task several times, the error returns

答: I had faced similar error while deploying services to EC2 using docker. I was using putty not CLI. I ran command docker images to get the size of each image. I found total size was more than my EC2 instance storage. I increased the EC2 instance volume to 20GB (EC2-->Volume-->Modify volume). Issue was resolved. Later I faced issue again after multiple trial and error. This time, I found I had lot of unused images which got accumulated after multiple docker compose commands. I removed all the containers, volumes and images and memory error was resolved.

Body:
I'm trying to set up CI with AWS ECS and docker. I use Codeship as a CI tool, but that should not really matter much.

I do the following steps in a shell script:

build an image with my Dockerfile,

push the image to ECS repository,

push a task-definition.json to ECS aws ecs register-task-definition --family postgraphile --cli-input-json file:///deploy/ecs-task-def.json --region us-east-2

run the ECS task aws ecs run-task --task-definition postgraphile --cluster testcluster --region us-east-2

Shell script runs successfully, however I see an error in output after I try to run my ECS task:

{
    "tasks": [],
    "failures": [
        {
            "arn": "arn:aws:ecs:us-east-2:99999999999:container-instance/050ab165-7669-45d5-8be7-d990cf4fff42",
            "reason": "RESOURCE:MEMORY"
        }
    ]
}

my ecs-task-def.json:

{
  "containerDefinitions": [
    {
      "name": "postgraphile-container",
      "image": "999999999999.dkr.ecr.us-east-2.amazonaws.com/test-repository",
      "memory": 500,
      "essential": true,
      "portMappings": [
        {
          "hostPort": 5000,
          "containerPort": 5000
        }
      ]
    }
  ],
  "volumes": [],
  "memory": "900",
  "cpu": "128",
  "placementConstraints": [],
  "family": "postgraphile",
  "taskRoleArn": ""
}

I think I already checked all the memory limits.. am I missing anything?

UPDATE:
After couple of reboots of ec2 instance I can finally run the ecs task with no errors. After running task several times, the error returns


答:
As per my understanding of your question, if all the numbers are separated with spaces, you can use split() method in python and and store them individually.

```<code>s=str(a[0])
x=s.split()
result=map(float, x)
</code>```

you can convert this map object result to your required 1D array type.

Title: Extracting elements from a list of size 1

Body:
I have a np array of this type. It is of size 1 but there are 90 numbers in it. Is there any way I can extract all those numbers and save them as a new 1D numpy array?

    Array of int64    list    (90,)  A = [7.065590000000000000e+05   7.221840000000000000e+05
    7.378090000000000000e+05
    1.503434000000000000e+06
    ...
    2.381593400000000000e+07
    2.383155900000000000e+07
    2.384718400000000000e+07]

Body:
As per my understanding of your question, if all the numbers are separated with spaces, you can use split() method in python and and store them individually.

s=str(a[0])
x=s.split()
result=map(float, x)

you can convert this map object result to your required 1D array type.


问:
React.js/React-Native how to skip Map() iteration if condition is falsy?
I have this simple component in React-Native, My goal is to skip the iteration if the given argument gradeIsMandatory is false, it should only iterate over warranty and price,
How can I achieve this result without affecting performance? I will take any advice thanks

import React, { useCallback } from 'react';
import { View, Text, SafeAreaView, SectionList, StyleSheet, Image, TouchableOpacity, Alert} from 'react-native';

export const ModalHeader: React.FC<{}> = () => {
    const gradeIsMandatory = false

    //code I tried to use
    useEffect(()=>{
        if(!gradeIsMandatory){
            let appendGrade =  { key: 'grade', title: 'Grade' }
            modalTabs.push(appendGrade)
        }
    },[])
    return (
        <View>
            <View>
                <View>
                    {modalTabs.map((tab, i) => (
                        <TouchableOpacity>
                          <Text>{tab.title}</Text>
                        </TouchableOpacity>
                    ))}
                </View>
            </View>
        </View>
    );
}

const modalTabs = [
    { key: 'warranty', title: 'Your Waranty' },
    { key: 'price', title: 'Your price' }
]```

答:
I would delete the useEffect and render this:</p>
```<code>return (
    <View>
        <View>
            <View>
                {modalTabs.map((tab, i) => (
                    <TouchableOpacity>
                      <Text>{tab.title}</Text>
                    </TouchableOpacity>
                ))}
                {
                  gradeIsMandatory && <TouchableOpacity><Text>Grade</Text></TouchableOpacity>
                }
            </View>
        </View>
    </View>
);
</code>```

Body:
I would delete the useEffect and render this:

return (
    <View>
        <View>
            <View>
                {modalTabs.map((tab, i) => (
                    <TouchableOpacity>
                      <Text>{tab.title}</Text>
                    </TouchableOpacity>
                ))}
                {
                  gradeIsMandatory && <TouchableOpacity><Text>Grade</Text></TouchableOpacity>
                }
            </View>
        </View>
    </View>
);


问:
Verify if a Job will fit in a cluster before launching it
I have an application that will start Jobs in different K8S cluster/cloud provider depending of different criteria, including the current availability of the cluster.
In other word, my application will loop over acceptable K8S clusters, and if a cluster is currently full, the job can be launched in a different cluster.

My problem is, how to determine that the Job will fit or not in the cluster.
My first idea was to loop over all nodes, and see how many have enough resources (Mem/CPU) to run my job.

While doable, it seems there is no native API to get used resources for one specific node. I can code that, but this gives me the feeling this is not the right solution, as it seems to be redoing part of the kube scheduler, and I am sure there are lot of edge case to be taken in account.

Maybe I am overthinking this, and this totally the right path, but I wanted to check if there was not cleaner solution.

答:
You can use kube-state-metrics which exposes a metrics api that you could query.

With that you have node metrics like kube_node_status_allocatable or kube_node_status_capacity and pod metrics like kube_pod_container_resource_requests or kube_pod_container_resource_limits.


问:
When should I unsubscribe from firestore listener?
I am writing a social app where users can check if they have new messages when they navigate to ChatList page. My idea is the following. On useEffect I load the newest 10 chats. Then if the user wants to see their oldest chats, I will have "more" button which will load nxt batch of chats. I don't want to load everything at once, since some users may have lost of chats. This is part of my code:

```<code>import { fetchInitialChats, fetchNextChats } from "./actions";

function ChatList(props) {
  const limit = 10;
  const [chats, setChats] = useState([]);
  const [lastFetched, setLastFetched] = useState(null);

  useEffect(() => {
    console.log("fetch initial chats");
    async function initialFetch() {
      let result;
      try {
        result = await fetchInitialChats(setLastFetched, limit);
        console.log("result: ", result);
        setChats(result);
        setError(false);
      } catch (error) {
        setError(true);
        console.log("Error during initial fetch of chats: ", error);
      }
    }
    initialFetch();
  }, []);
</code>```

In my actions.js file I implement fetchInitialChats and  fetchNextChats:

```<code>export const fetchInitialChats = async (setLastFetched, limit) => {
  console.log("fetching initial batch of chats");
  let chats = [];
  let query = await firebase
    .firestore()
    .collection("Chats")
    .where("users", "array-contains", firebase.auth().currentUser.uid)
    .orderBy("lastMessageTimestamp", "desc")
    .limit(limit);
  const unsubRef = query.onSnapshot((snapshot) => {
    chats = snapshot.docs.map((doc) => {
      const data = doc.data();
      const id = doc.id;
      return { id, ...data };
    });
   if (snapshot.docs.length > 0) {
     const last = snapshot.docs[snapshot.docs.length - 1];
     setLastFetched(last);
   }
  });
  unsubRef();
  return chats;
};
</code>```

My questions are two:

Is this the right way to subscribe from a listener? Do I need to unsubscribe from useEffect or from somewhere else?

Is this actually the right way to perform pagination when using lister. If I am fetching chats with simple get(), without listening for new updates, sure, this is the way to go. What if I am listening to live updates and I want to perform pagination?

答:
To answer your questions,

No, This is not the right way to add the listener to firestore or any other SDK, We should have to use the useEffect hook or custom hook to manage the listeners.

If you are about to implement the pagination, you can use the code below for you.

I have created a custom hook to manage the chat listener separately from the main screen code base.

Note: This is sample code not a full feature working code make changes as per the requirements

```<code>import React, { useEffect } from 'react'
import { FlatList } from 'react-native'

const useChats = (limit = 10) => {

    const [chatsData, setChatsData] = useState([])
    const [lastFetched, setLastFetched] = useState(null)

    useEffect(() => {
        let chats = [];
        let query = await firebase
                        .firestore()
                        .collection("Chats")
                        .where("users", "array-contains", firebase.auth().currentUser.uid)
                        .orderBy("lastMessageTimestamp", "desc")
                        .limit(limit);

        const unsubRef = query.onSnapshot((snapshot) => {
            chats = snapshot.docs.map((doc) => {
                const data = doc.data();
                const id = doc.id;
                return { id, ...data };
            });

            setChatsData(chats)

            if (snapshot.docs.length > 0) {
                const last = snapshot.docs[snapshot.docs.length - 1];
                setLastFetched(last);
            }
        });

        return unsubRef();
    }, [])

    const fetchMore = (limit = 10) => {
        let chats = [];
        let query = await firebase
                        .firestore()
                        .collection("Chats")
                        .where("users", "array-contains", firebase.auth().currentUser.uid)
                        .orderBy("lastMessageTimestamp", "desc")
                        .limit(limit)
                        .after(lastFetched)

        const unsubRef = query.onSnapshot((snapshot) => {
            chats = snapshot.docs.map((doc) => {
                const data = doc.data();
                const id = doc.id;
                return { id, ...data };
            });

            setChatsData(chats)

            if (snapshot.docs.length > 0) {
                const last = snapshot.docs[snapshot.docs.length - 1];
                setLastFetched(last);
            }
        });

        return unsubRef();
    }

    return [chatsData, lastFetched, { fetchMore }]
}

function ChatList(props) {
    const [chatsData, lastFetched, { fetchMore }] = useChats()

    return (
        <FlatList
            data={chatsData}
            renderItem={() => {
                return (
                    // Your chat rendering goes to here..
                )
            }}
            onEndReached={fetchMore}
            onEndReachedThreshold={0.01}
        />
    )
}
</code>```

Body:
I am writing a social app where users can check if they have new messages when they navigate to ChatList page. My idea is the following. On useEffect I load the newest 10 chats. Then if the user wants to see their oldest chats, I will have "more" button which will load nxt batch of chats. I don't want to load everything at once, since some users may have lost of chats. This is part of my code:

import { fetchInitialChats, fetchNextChats } from "./actions";

function ChatList(props) {
  const limit = 10;
  const [chats, setChats] = useState([]);
  const [lastFetched, setLastFetched] = useState(null);

  useEffect(() => {
    console.log("fetch initial chats");
    async function initialFetch() {
      let result;
      try {
        result = await fetchInitialChats(setLastFetched, limit);
        console.log("result: ", result);
        setChats(result);
        setError(false);
      } catch (error) {
        setError(true);
        console.log("Error during initial fetch of chats: ", error);
      }
    }
    initialFetch();
  }, []);

In my actions.js file I implement fetchInitialChats and  fetchNextChats:

export const fetchInitialChats = async (setLastFetched, limit) => {
  console.log("fetching initial batch of chats");
  let chats = [];
  let query = await firebase
    .firestore()
    .collection("Chats")
    .where("users", "array-contains", firebase.auth().currentUser.uid)
    .orderBy("lastMessageTimestamp", "desc")
    .limit(limit);
  const unsubRef = query.onSnapshot((snapshot) => {
    chats = snapshot.docs.map((doc) => {
      const data = doc.data();
      const id = doc.id;
      return { id, ...data };
    });
   if (snapshot.docs.length > 0) {
     const last = snapshot.docs[snapshot.docs.length - 1];
     setLastFetched(last);
   }
  });
  unsubRef();
  return chats;
};

My questions are two:

Is this the right way to subscribe from a listener? Do I need to unsubscribe from useEffect or from somewhere else?

Is this actually the right way to perform pagination when using lister. If I am fetching chats with simple get(), without listening for new updates, sure, this is the way to go. What if I am listening to live updates and I want to perform pagination?

Body:
To answer your questions,

No, This is not the right way to add the listener to firestore or any other SDK, We should have to use the useEffect hook or custom hook to manage the listeners.

If you are about to implement the pagination, you can use the code below for you.

I have created a custom hook to manage the chat listener separately from the main screen code base.

Note: This is sample code not a full feature working code make changes as per the requirements

import React, { useEffect } from 'react'
import { FlatList } from 'react-native'

const useChats = (limit = 10) => {

    const [chatsData, setChatsData] = useState([])
    const [lastFetched, setLastFetched] = useState(null)

    useEffect(() => {
        let chats = [];
        let query = await firebase
                        .firestore()
                        .collection("Chats")
                        .where("users", "array-contains", firebase.auth().currentUser.uid)
                        .orderBy("lastMessageTimestamp", "desc")
                        .limit(limit);

        const unsubRef = query.onSnapshot((snapshot) => {
            chats = snapshot.docs.map((doc) => {
                const data = doc.data();
                const id = doc.id;
                return { id, ...data };
            });

            setChatsData(chats)

            if (snapshot.docs.length > 0) {
                const last = snapshot.docs[snapshot.docs.length - 1];
                setLastFetched(last);
            }
        });

        return unsubRef();
    }, [])

    const fetchMore = (limit = 10) => {
        let chats = [];
        let query = await firebase
                        .firestore()
                        .collection("Chats")
                        .where("users", "array-contains", firebase.auth().currentUser.uid)
                        .orderBy("lastMessageTimestamp", "desc")
                        .limit(limit)
                        .after(lastFetched)

        const unsubRef = query.onSnapshot((snapshot) => {
            chats = snapshot.docs.map((doc) => {
                const data = doc.data();
                const id = doc.id;
                return { id, ...data };
            });

            setChatsData(chats)

            if (snapshot.docs.length > 0) {
                const last = snapshot.docs[snapshot.docs.length - 1];
                setLastFetched(last);
            }
        });

        return unsubRef();
    }

    return [chatsData, lastFetched, { fetchMore }]
}

function ChatList(props) {
    const [chatsData, lastFetched, { fetchMore }] = useChats()

    return (
        <FlatList
            data={chatsData}
            renderItem={() => {
                return (
                    // Your chat rendering goes to here..
                )
            }}
            onEndReached={fetchMore}
            onEndReachedThreshold={0.01}
        />
    )
}


答:
Here's an updated response with your more full dataset now that I understand your goal better.

In processing the data I used a renaming function with a regex to clean up the names but this is optional. I also converted the scores to a factor so  it's easy to treat them as ordinal discrete data (which they are) rather than continuous. However I convert back to continuous data in the bottom example to calculate a mean() which is one option for decrowding the plot.

Given the large volume, I opted for a stacked bar plot using geom_bar(position = "stack"), but try "dodge" to see for yourself.

Also I commented out the line to facet by LIKE but you should try it out to see if that is more informative.

I also applied some aesthetics that I subjectively like but mostly to demonstrate that there's a lot of control in {ggplot2} that you can customize.

I applied likert scale labels to the color scale which you can customize if that's helpful or just omit by dropping the labels = likert_scale.

library(tidyverse)

d <- structure(list(AD_BORING_1 = c("3", "2", "4", "1", "6", "3", "7", "6", "2", "3", "5", "4", "6", "5", "5", "6", "5", "2", "2", "6", "2", "3", "5", "4", "5", "5", "1", "2", "4", "2", "3", "6", "5", "5", "3"), AD_IRRITATING_1 = c("3", "2", "2", "1", "7", "5", "6", "4", "5", "5", "1", "5", "4", "3", "5", "6", "5", "2", "2", "4", "5", "3", "2", "4", "3", "4", "1", "2", "4", "5", "4", "4", "7", "4", "2"), AD_DISTURBING_1 = c("3", "1", "3", "3", "4", "1", "3", "2", "2", "4", "1", "3", "4", "2", "1", "4", "2", "2", "2", "4", "1", "5", "1", "2", "2", "2", "1", "2", "4", "2", "4", "2", "4", "6", "2"), AD_CREDIBLE_1 = c("5", "5", "3", "2", "1", "2", "6", "3", "6", "3", "5", "4", "2", "3", "4", "1", "5", "3", "3", "2", "1", "3", "5", "3", "2", "4", "6", "6", "3", "1", "5", "6", "2", "3", "5"), AD_GOOD_1 = c("5", "5", "3", "2", "2", "5", "3", "4", "5", "2", "5", "2", "1", "5", "4", "2", "2", "5", "5", "2", "3", "5", "4", "4", "4", "4", "6", "4", "3", "2", "4", "4", "1", "4", "5"), AD_HONEST_1 = c("5", "3", "3", "2", "2", "1", "4", "3", "5", "2", "6", "1", "2", "2", "3", "2", "4", "3", "2", "2", "2", "3", "2", "4", "1", "3", "4", "3", "2", "2", "3", "5", "1", "4", "3"), AD_TRUTHFUL_1 = c("5", "3", "4", "2", "2", "1", "5", "3", "5", "2", "5", "2", "2", "3", "3", "2", "5", "3", "2", "1", "2", "2", "4", "5", "1", "3", "4", "4", "4", "1", "2", "3", "1", "1", "3"), AD_LIKEABLE_1 = c("5", "4", "3", "2", "2", "6", "2", "4", "5", "4", "4", "3", "3", "4", "3", "4", "5", "6", "7", "1", "2", "2", "2", "4", "1", "3", "6", "6", "2", "4", "1", "4", "1", "3", "5"), AD_ENJOYABLE_1 = c("5", "5", "3", "2", "2", "4", "2", "4", "5", "4", "5", "3", "2", "6", "3", "2", "5", "6", "7", "2", "2", "2", "4", "5", "2", "3", "7", "6", "3", "4", "4", "3", "1", "3", "4"), LIKE_1 = c("6", "5", "3", "2", "1", "4", "2", "3", "5", "3", "4", "3", "1", "4", "3", "3", "5", "5", "7", "1", "4", "5", "4", "4", "2", "4", "6", "6", "4", "3", "4", "4", "1", "2", "5")), row.names = c(NA, -35L), class = c("tbl_df", "tbl", "data.frame"))

# make labels in case that helps
likert_breaks <- c("Strongly Disagree", "Somewhat Disagree", "Slightly Disagree", "Neutral", "Slightly Agree", "Somewhat Agree", "Strongly Agree")

# process and plot as stacked bar plot with optional faceting
d %>%
  rename_with(~str_extract(.x, "(?<=_)(.*)(?=_)"), contains("AD")) %>%
  rename(LIKE = LIKE_1) %>%
  mutate(across(everything(), as.integer)) %>%
  mutate(respondent = row_number()) %>%
  pivot_longer(-c(respondent, LIKE), names_to = "adjective", values_to = "likert") %>%
  mutate(likert = factor(likert)) %>%
  ggplot(aes(adjective, fill = likert)) +
  geom_bar(stat = "count", position = "stack") +
  # facet_wrap(~LIKE) +
  scale_fill_viridis_d(option = "A", begin = 0, end = 0.85, labels = likert_breaks) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90))
```
<p><img src="https://i.imgur.com/vkxlnNz.png" alt="" /></p>
<p>Another option to keep things more compact is just to show the mean score for each adjective. In this case you need to leave it as a <code>numeric</code> so you can apply a summarizing function like <code>mean()</code>.</p>
<pre class="lang-r prettyprint-override"><code># just show mean likert scores for each
d %>%
  rename_with(~str_extract(.x, "(?<=_)(.*)(?=_)"), contains("AD")) %>%
  rename(LIKE = LIKE_1) %>%
  mutate(across(everything(), as.integer)) %>%
  mutate(respondent = row_number()) %>%
  pivot_longer(-c(respondent, LIKE), names_to = "adjective", values_to = "likert") %>%
  group_by(adjective) %>%
  summarise(likert = mean(likert)) %>%
  ggplot(aes(reorder(adjective, -likert), likert)) +
  geom_col() +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90))
</code>```

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

Title: I need to barplot and compare different items of a survey (columns in the dataset)

Body:
I'm analyzing a dataset for my master thesis. The data come from a survey I created. I'm trying to google anything I can but being the dataset not sparse enough I'm having some lengths problems (for example, some item have values ranging from 1-7, some others only from 2-6. the scale used is a 7 point likert scale but if, for example, an item didn't get 7 at least once, it will be of a different length compared to a more sparse one)(Problem 1).

structure(list(AD_BORING_1 = c("3", "2", "4", "1", "6", "3",
"7", "6", "2", "3", "5", "4", "6", "5", "5", "6", "5", "2", "2",
"6", "2", "3", "5", "4", "5", "5", "1", "2", "4", "2", "3", "6",
"5", "5", "3"), AD_IRRITATING_1 = c("3", "2", "2", "1", "7",
"5", "6", "4", "5", "5", "1", "5", "4", "3", "5", "6", "5", "2",
"2", "4", "5", "3", "2", "4", "3", "4", "1", "2", "4", "5", "4",
"4", "7", "4", "2"), AD_DISTURBING_1 = c("3", "1", "3", "3",
"4", "1", "3", "2", "2", "4", "1", "3", "4", "2", "1", "4", "2",
"2", "2", "4", "1", "5", "1", "2", "2", "2", "1", "2", "4", "2",
"4", "2", "4", "6", "2"), AD_CREDIBLE_1 = c("5", "5", "3", "2",
"1", "2", "6", "3", "6", "3", "5", "4", "2", "3", "4", "1", "5",
"3", "3", "2", "1", "3", "5", "3", "2", "4", "6", "6", "3", "1",
"5", "6", "2", "3", "5"), AD_GOOD_1 = c("5", "5", "3", "2", "2",
"5", "3", "4", "5", "2", "5", "2", "1", "5", "4", "2", "2", "5",
"5", "2", "3", "5", "4", "4", "4", "4", "6", "4", "3", "2", "4",
"4", "1", "4", "5"), AD_HONEST_1 = c("5", "3", "3", "2", "2",
"1", "4", "3", "5", "2", "6", "1", "2", "2", "3", "2", "4", "3",
"2", "2", "2", "3", "2", "4", "1", "3", "4", "3", "2", "2", "3",
"5", "1", "4", "3"), AD_TRUTHFUL_1 = c("5", "3", "4", "2", "2",
"1", "5", "3", "5", "2", "5", "2", "2", "3", "3", "2", "5", "3",
"2", "1", "2", "2", "4", "5", "1", "3", "4", "4", "4", "1", "2",
"3", "1", "1", "3"), AD_LIKEABLE_1 = c("5", "4", "3", "2", "2",
"6", "2", "4", "5", "4", "4", "3", "3", "4", "3", "4", "5", "6",
"7", "1", "2", "2", "2", "4", "1", "3", "6", "6", "2", "4", "1",
"4", "1", "3", "5"), AD_ENJOYABLE_1 = c("5", "5", "3", "2", "2",
"4", "2", "4", "5", "4", "5", "3", "2", "6", "3", "2", "5", "6",
"7", "2", "2", "2", "4", "5", "2", "3", "7", "6", "3", "4", "4",
"3", "1", "3", "4"), LIKE_1 = c("6", "5", "3", "2", "1", "4",
"2", "3", "5", "3", "4", "3", "1", "4", "3", "3", "5", "5", "7",
"1", "4", "5", "4", "4", "2", "4", "6", "6", "4", "3", "4", "4",
"1", "2", "5")), row.names = c(NA, -35L), class = c("tbl_df",
"tbl", "data.frame"))

The rows of the main dataset are just the n. of observations and every item score is in the columns.

Another problem is I have no idea how to properly plot them all together to be compared in a simple barplot like for example the picture below:

I tried with items of the same length using this code:

prova <- data.frame(table(A_DF_GIL$AD_BORING_1), table(A_DF_GIL$AD_IRRITATING_1))
barplot(as.matrix(prova))

but still the result is not the one I need. Can anybody help me please? Thank youu

Body:
Here's an updated response with your more full dataset now that I understand your goal better.

In processing the data I used a renaming function with a regex to clean up the names but this is optional. I also converted the scores to a factor so  it's easy to treat them as ordinal discrete data (which they are) rather than continuous. However I convert back to continuous data in the bottom example to calculate a mean() which is one option for decrowding the plot.

Given the large volume, I opted for a stacked bar plot using geom_bar(position = "stack"), but try "dodge" to see for yourself.

Also I commented out the line to facet by LIKE but you should try it out to see if that is more informative.

I also applied some aesthetics that I subjectively like but mostly to demonstrate that there's a lot of control in {ggplot2} that you can customize.

I applied likert scale labels to the color scale which you can customize if that's helpful or just omit by dropping the labels = likert_scale.

library(tidyverse)

d <- structure(list(AD_BORING_1 = c("3", "2", "4", "1", "6", "3", "7", "6", "2", "3", "5", "4", "6", "5", "5", "6", "5", "2", "2", "6", "2", "3", "5", "4", "5", "5", "1", "2", "4", "2", "3", "6", "5", "5", "3"), AD_IRRITATING_1 = c("3", "2", "2", "1", "7", "5", "6", "4", "5", "5", "1", "5", "4", "3", "5", "6", "5", "2", "2", "4", "5", "3", "2", "4", "3", "4", "1", "2", "4", "5", "4", "4", "7", "4", "2"), AD_DISTURBING_1 = c("3", "1", "3", "3", "4", "1", "3", "2", "2", "4", "1", "3", "4", "2", "1", "4", "2", "2", "2", "4", "1", "5", "1", "2", "2", "2", "1", "2", "4", "2", "4", "2", "4", "6", "2"), AD_CREDIBLE_1 = c("5", "5", "3", "2", "1", "2", "6", "3", "6", "3", "5", "4", "2", "3", "4", "1", "5", "3", "3", "2", "1", "3", "5", "3", "2", "4", "6", "6", "3", "1", "5", "6", "2", "3", "5"), AD_GOOD_1 = c("5", "5", "3", "2", "2", "5", "3", "4", "5", "2", "5", "2", "1", "5", "4", "2", "2", "5", "5", "2", "3", "5", "4", "4", "4", "4", "6", "4", "3", "2", "4", "4", "1", "4", "5"), AD_HONEST_1 = c("5", "3", "3", "2", "2", "1", "4", "3", "5", "2", "6", "1", "2", "2", "3", "2", "4", "3", "2", "2", "2", "3", "2", "4", "1", "3", "4", "3", "2", "2", "3", "5", "1", "4", "3"), AD_TRUTHFUL_1 = c("5", "3", "4", "2", "2", "1", "5", "3", "5", "2", "5", "2", "2", "3", "3", "2", "5", "3", "2", "1", "2", "2", "4", "5", "1", "3", "4", "4", "4", "1", "2", "3", "1", "1", "3"), AD_LIKEABLE_1 = c("5", "4", "3", "2", "2", "6", "2", "4", "5", "4", "4", "3", "3", "4", "3", "4", "5", "6", "7", "1", "2", "2", "2", "4", "1", "3", "6", "6", "2", "4", "1", "4", "1", "3", "5"), AD_ENJOYABLE_1 = c("5", "5", "3", "2", "2", "4", "2", "4", "5", "4", "5", "3", "2", "6", "3", "2", "5", "6", "7", "2", "2", "2", "4", "5", "2", "3", "7", "6", "3", "4", "4", "3", "1", "3", "4"), LIKE_1 = c("6", "5", "3", "2", "1", "4", "2", "3", "5", "3", "4", "3", "1", "4", "3", "3", "5", "5", "7", "1", "4", "5", "4", "4", "2", "4", "6", "6", "4", "3", "4", "4", "1", "2", "5")), row.names = c(NA, -35L), class = c("tbl_df", "tbl", "data.frame"))

# make labels in case that helps
likert_breaks <- c("Strongly Disagree", "Somewhat Disagree", "Slightly Disagree", "Neutral", "Slightly Agree", "Somewhat Agree", "Strongly Agree")

# process and plot as stacked bar plot with optional faceting
d %>%
  rename_with(~str_extract(.x, "(?<=_)(.*)(?=_)"), contains("AD")) %>%
  rename(LIKE = LIKE_1) %>%
  mutate(across(everything(), as.integer)) %>%
  mutate(respondent = row_number()) %>%
  pivot_longer(-c(respondent, LIKE), names_to = "adjective", values_to = "likert") %>%
  mutate(likert = factor(likert)) %>%
  ggplot(aes(adjective, fill = likert)) +
  geom_bar(stat = "count", position = "stack") +
  # facet_wrap(~LIKE) +
  scale_fill_viridis_d(option = "A", begin = 0, end = 0.85, labels = likert_breaks) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90))

Another option to keep things more compact is just to show the mean score for each adjective. In this case you need to leave it as a numeric so you can apply a summarizing function like mean().

# just show mean likert scores for each
d %>%
  rename_with(~str_extract(.x, "(?<=_)(.*)(?=_)"), contains("AD")) %>%
  rename(LIKE = LIKE_1) %>%
  mutate(across(everything(), as.integer)) %>%
  mutate(respondent = row_number()) %>%
  pivot_longer(-c(respondent, LIKE), names_to = "adjective", values_to = "likert") %>%
  group_by(adjective) %>%
  summarise(likert = mean(likert)) %>%
  ggplot(aes(reorder(adjective, -likert), likert)) +
  geom_col() +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90))

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


问:
Vim Command Mode
I'm using gVIM which defaults to insert mode. When I press the Esc key (or Ctrl+C) to enter command mode, nothing happens. I've searched for an alternative route to enter command mode. Does anyone know what the problem may be or another way to enter command mode?

Note: I'm running Windows 7 64-bit and gVim Easy 7.3

答:
If you MUST use gVim Easy and command mode:

C-o:echo "Woot!"Enter

will do what you expect; Also,

to enter command line history edit window:

C-oq:  (leave history window with C-c)

to enter multiple command mode commands in sequence:

C-oQ (leave Ex mode with viEnter)

I sometimes use tricks like this to manipulate undo information or to record mini macros on the fly (C-oqq e.g.)

Title: Vim Command Mode


问:
Is the use of while loops ok here? Or it's excesive
I want to know if it is ok to use as much while loops as I want or it is just not conventional. Also searhing for another solution to check only if the user enters the two symbols of the tic tac toe (X, O), but only one user can have each of them.

In other words, when the user is prompted for choosing the symbol he wants for playing, if he introduces an invalid one, keep asking till it's one of the both above. Then, for the second player he can only choose, for example, the 'O' if the first player have chosen the 'X', and also ensuring it's only one of the two symbols and not an invalid one.

```<code>    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String playerName, playerMove;

        System.out.print("Introduce el nombre del primer jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        playerMove = playerMove.toUpperCase();

        Player player1 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player1.name + "!");

        System.out.println();
        System.out.print("Introduce el nombre del segundo jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        while (playerMove.equalsIgnoreCase(player1.moveType)) {
            System.out.print("Introduce un símbolo distinto al del otro jugador: ");
            playerMove = sc.next();

            while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
                System.out.print("Introduce un símbolo válido: ");
                playerMove = sc.next();
            }
        }

        playerMove = playerMove.toUpperCase();

        Player player2 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player2.name + "!");
        System.out.println();

        System.out.println("El símbolo de " + player1.name + " es " + player1.moveType + ".");
        System.out.println("El símbolo de " + player2.name + " es " + player2.moveType + ".");

        System.out.println();

        Board board = new Board();

        System.out.println("El tablero es: ");
        System.out.println();

        board.displayBoard();
        System.out.println();
    }
}
</code>```

答: Of course there are other efficient ways for this type of problems as your question is concern that it not conventional. most of the developers are using it but nested loops are not a good choice performance wise.</p>

Body:
I want to know if it is ok to use as much while loops as I want or it is just not conventional. Also searhing for another solution to check only if the user enters the two symbols of the tic tac toe (X, O), but only one user can have each of them.

In other words, when the user is prompted for choosing the symbol he wants for playing, if he introduces an invalid one, keep asking till it's one of the both above. Then, for the second player he can only choose, for example, the 'O' if the first player have chosen the 'X', and also ensuring it's only one of the two symbols and not an invalid one.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String playerName, playerMove;

        System.out.print("Introduce el nombre del primer jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        playerMove = playerMove.toUpperCase();

        Player player1 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player1.name + "!");

        System.out.println();
        System.out.print("Introduce el nombre del segundo jugador: ");
        playerName = sc.next();
        playerName = playerName.substring(0, 1).toUpperCase() + playerName.substring(1);

        System.out.print("Introduce el símbolo que quieres jugar ('X', 'O'): ");
        playerMove = sc.next();

        while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
            System.out.print("Introduce un símbolo válido: ");
            playerMove = sc.next();
        }

        while (playerMove.equalsIgnoreCase(player1.moveType)) {
            System.out.print("Introduce un símbolo distinto al del otro jugador: ");
            playerMove = sc.next();

            while (!playerMove.equalsIgnoreCase("X") && !playerMove.equalsIgnoreCase("O")) {
                System.out.print("Introduce un símbolo válido: ");
                playerMove = sc.next();
            }
        }

        playerMove = playerMove.toUpperCase();

        Player player2 = new Player(playerName, playerMove);
        System.out.println();
        System.out.println("¡Bienvenido " + player2.name + "!");
        System.out.println();

        System.out.println("El símbolo de " + player1.name + " es " + player1.moveType + ".");
        System.out.println("El símbolo de " + player2.name + " es " + player2.moveType + ".");

        System.out.println();

        Board board = new Board();

        System.out.println("El tablero es: ");
        System.out.println();

        board.displayBoard();
        System.out.println();
    }
}


问:
How to remove flex layout
I have a folder path in the source code, which is in visual studio web spectrum project. How can I proceed  remove flex layout in the code. Do I need to run a simple command in the terminal or edit code?</p>

答:
If you want to remove completely flex layout form your project you need to do these:
1- Uninstall flex layout. Run this command;

```<code>npm uninstall flex-layout
</code>```

When you run this command you'll see in your package.json that flex layout dependency was removed.

2- In your app.module.ts file or any module file that you are using for flex layout, remove the import.

That's all for me.
Let me know if you fix it.

Title: How to remove flex layout

Body:
If you want to remove completely flex layout form your project you need to do these:
1- Uninstall flex layout. Run this command;

npm uninstall flex-layout

When you run this command you'll see in your package.json that flex layout dependency was removed.

2- In your app.module.ts file or any module file that you are using for flex layout, remove the import.

That's all for me.
Let me know if you fix it.


问:
How can i pile balls in a box starting from the bottom?
I'm trying to do like a stack of balls inside a box (div/container) but when I try the balls start to stack from the top, and I want the same thing but starting from the bottom of the box.

Here is the HTML & CSS code:

#target1 {
  width: 205px;
  height: 180px;
  border: 5px solid rgb(30, 87, 212);
  border-top-color: white;
}

.prueba {
  display: inline-block;
  height: 40px;
  width: 40px;
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='target1'>
  <div class='prueba'></div>
  <div class='prueba'></div>
  <div class='prueba'></div>
  <div class='prueba'></div>
  <div class='prueba'></div>
  <div class='prueba'></div>
</div></code>```

Output of the code

答: Css likes to fill that way. You could try just accepting that and use a transform to turn the box upside down.</p>

Body:
I'm trying to do like a stack of balls inside a box (div/container) but when I try the balls start to stack from the top, and I want the same thing but starting from the bottom of the box.

Here is the HTML & CSS code:

#target1 {
  width: 205px;
  height: 180px;
  border: 5px solid rgb(30, 87, 212);
  border-top-color: white;
}

.prueba {
  display: inline-block;
  height: 40px;
  width: 40px;
  background-color: black;
}

Output of the code


问:
Play multiple tracks <audio>
I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But in the end, the very first track plays in a circle. How can this be fixed?

```<code><audio id="audio" preload="" autoplay="" loop="">
  <source type="audio/mp3" src="music/mus1.mp3">
  <source type="audio/mp3" src="music/mus.mp3">
</audio>
</code>```
```<code><script type="text/javascript">
var audio = document.getElementById("audio");

function pVid() {
    audio.paused ? audio.play() : audio.pause();
}
</script>
</code>```

答:
Try this: (jQuery)</p>
```<code>function skipAndplayNext() {
    sounds[currentAudio].pause();
    $("#currentAudio").classList.remove('paused');
    $("#currentAudio").classList.remove('playing');
    currentAudio++;
    if (currentAudio > (sounds.length - 1)) {
      currentAudio = 0
    }
    sounds[currentAudio].play();
    $("#currentAudio").classList.add('playing');
}
</code>```

Title: Play multiple tracks <audio>

Body:
I'm trying to use the <audio> tag, and I want to have as many tracks playing as I add. But in the end, the very first track plays in a circle. How can this be fixed?

<audio id="audio" preload="" autoplay="" loop="">
  <source type="audio/mp3" src="music/mus1.mp3">
  <source type="audio/mp3" src="music/mus.mp3">
</audio>

Body:
Try this: (jQuery)

function skipAndplayNext() {
    sounds[currentAudio].pause();
    $("#currentAudio").classList.remove('paused');
    $("#currentAudio").classList.remove('playing');
    currentAudio++;
    if (currentAudio > (sounds.length - 1)) {
      currentAudio = 0
    }
    sounds[currentAudio].play();
    $("#currentAudio").classList.add('playing');
}