问:
Assigning default value to Autocomplete in MaterialUI and React.js
I would like to display default value to my Autocomplete TextField component from Material UI in React.js. A pre-populated value that is automatically loaded from the users' profile and that can be changed with another one from the list.

Here is my code:

```<code>import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

export const ComboBox =() => {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1974 },
  { title: 'The Dark Knight', year: 2008 }
]
</code>```

I only see the input field with the label on it.
defaultValue is listed as an API of both TextField and Autocomplete and I also tried to move it directly under Autocomplete. Still not working.

答:
If you use multiple so you should set defaultValue in list like blow

```<code><Autocomplete multiple id="tags-standard" options={categoryList}
    defaultValue={[{ title: "cat1", id: 1 }, { title: "cat2", id: 2 }]}

    getOptionLabel={(option) => option.title}
    renderInput={(params) => (
    <TextField {...params} variant="standard" label="Category" />
    )}
    onChange={handleCategory}

    />

</code>```

Body:
I would like to display default value to my Autocomplete TextField component from Material UI in React.js. A pre-populated value that is automatically loaded from the users' profile and that can be changed with another one from the list.

Here is my code:

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

export const ComboBox =() => {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Combo box" defaultValue="The Godfather" variant="outlined" />}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1974 },
  { title: 'The Dark Knight', year: 2008 }
]

I only see the input field with the label on it.
defaultValue is listed as an API of both TextField and Autocomplete and I also tried to move it directly under Autocomplete. Still not working.

Body:
If you use multiple so you should set defaultValue in list like blow

<Autocomplete multiple id="tags-standard" options={categoryList}
    defaultValue={[{ title: "cat1", id: 1 }, { title: "cat2", id: 2 }]}

    getOptionLabel={(option) => option.title}
    renderInput={(params) => (
    <TextField {...params} variant="standard" label="Category" />
    )}
    onChange={handleCategory}

    />


来源: stackexchange

问:
How do you configure Ktor to enable JWT Authentication?
For context, I am new to Java, Kotlin and Ktor (coming from a C# background).

I am receiving the following error from my build:

```<code>Exception in thread "main" io.ktor.server.application.MissingApplicationPluginException: Application plugin Authentication is not installed
</code>```

The offending section of code is:

```<code>    authenticate("auth-jwt") {
        get("/hello") {
            val principal = call.principal<JWTPrincipal>()
            val username = principal!!.payload.getClaim("username").asString()
            val expiresAt = principal.expiresAt?.time?.minus(System.currentTimeMillis())
            call.respondText("Hello, $username! Token is expired at $expiresAt ms.")
        }
    }
</code>```

It fails at the line with authenticate

Per the documentation, I have added the required plugins in my build.gradle.kts file:

```<code>dependencies {
    implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-host-common-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
    implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version")
    implementation("io.ktor:ktor-serialization-gson-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-auth:$ktor_version")
    implementation("io.ktor:ktor-server-auth-jwt:$ktor_version")
    implementation("ch.qos.logback:logback-classic:$logback_version")
    testImplementation("io.ktor:ktor-server-test-host:$ktor_version")
    testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
}
</code>```

Here is my configureSecurity method (taken from the online examples):

```<code>fun Application.configureSecurity() {
    val secret = System.getenv("JWT_SECRET")
    val issuer = environment.config.property("jwt.issuer").getString()
    val audience = environment.config.property("jwt.audience").getString()
    val myRealm = environment.config.property("jwt.realm").getString()

    authentication {
        jwt("auth-jwt") {
            verifier(
                JWT
                    .require(Algorithm.HMAC256(secret))
                    .withAudience(audience)
                    .withIssuer(issuer)
                    .build()
            )
            validate { credential ->
                if (credential.payload.getClaim("username").asString() != "") {
                    JWTPrincipal(credential.payload)
                } else {
                    null
                }
            }
        }
    }
}
</code>```

I have been working to fix this for the last nine hours, searching the web exhaustively, and this is my last resort.

I am using Beta 2.0 sample code created from the project creation wizard in IntelliJ IDEA.

How do you properly configure JWT auth on ktor server?

答:
The problem is that configuration for a routing goes before the installation of the Authentication plugin. To fix it swap configureRouting() and configureSecurity() calls so it will look like this:

```<code>embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
    configureSecurity()
    configureRouting()
}.start(wait = true)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For context, I am new to Java, Kotlin and Ktor (coming from a C# background).

I am receiving the following error from my build:

Exception in thread "main" io.ktor.server.application.MissingApplicationPluginException: Application plugin Authentication is not installed

The offending section of code is:

    authenticate("auth-jwt") {
        get("/hello") {
            val principal = call.principal<JWTPrincipal>()
            val username = principal!!.payload.getClaim("username").asString()
            val expiresAt = principal.expiresAt?.time?.minus(System.currentTimeMillis())
            call.respondText("Hello, $username! Token is expired at $expiresAt ms.")
        }
    }

It fails at the line with authenticate

Per the documentation, I have added the required plugins in my build.gradle.kts file:

dependencies {
    implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-host-common-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
    implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version")
    implementation("io.ktor:ktor-serialization-gson-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
    implementation("io.ktor:ktor-server-auth:$ktor_version")
    implementation("io.ktor:ktor-server-auth-jwt:$ktor_version")
    implementation("ch.qos.logback:logback-classic:$logback_version")
    testImplementation("io.ktor:ktor-server-test-host:$ktor_version")
    testImplementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
}

Here is my configureSecurity method (taken from the online examples):

fun Application.configureSecurity() {
    val secret = System.getenv("JWT_SECRET")
    val issuer = environment.config.property("jwt.issuer").getString()
    val audience = environment.config.property("jwt.audience").getString()
    val myRealm = environment.config.property("jwt.realm").getString()

    authentication {
        jwt("auth-jwt") {
            verifier(
                JWT
                    .require(Algorithm.HMAC256(secret))
                    .withAudience(audience)
                    .withIssuer(issuer)
                    .build()
            )
            validate { credential ->
                if (credential.payload.getClaim("username").asString() != "") {
                    JWTPrincipal(credential.payload)
                } else {
                    null
                }
            }
        }
    }
}

I have been working to fix this for the last nine hours, searching the web exhaustively, and this is my last resort.

I am using Beta 2.0 sample code created from the project creation wizard in IntelliJ IDEA.

How do you properly configure JWT auth on ktor server?

Body:
The problem is that configuration for a routing goes before the installation of the Authentication plugin. To fix it swap configureRouting() and configureSecurity() calls so it will look like this:

embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
    configureSecurity()
    configureRouting()
}.start(wait = true)


问:
Why is there only a static/shared version of ForEach for arrays?
Could someone please be kind enough to explain why there is only a static/shared version of ForEach for arrays?

```<code>IE: ForEach<T>(T array[], System.Action(Of T) action[])
</code>```

I assume this has something to do with the type inference requirements of implementing an instance method, but when you declare your array you provide type right?

答:
You provide T to tell what the array can contain in it. So since Array implements ienumerable, hence it gets ForEach extension method on it.

Is there any thing else your looking for?

Wondering if Erics post helps you http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

ContentLicense: CC BY-SA 3.0

Body:
Could someone please be kind enough to explain why there is only a static/shared version of ForEach for arrays?

IE: ForEach<T>(T array[], System.Action(Of T) action[])

I assume this has something to do with the type inference requirements of implementing an instance method, but when you declare your array you provide type right?


问:
React limits the number of renders to prevent an infinite loop Error
Below is my code

```<code>function App() {
    const [isImportant, setIsImportant] = useState("Yes")

    function handleClick() {
        setIsImportant("No")
    }

    return (
        <div className="state">
            <h1 className="state--title">Is state important to know?</h1>
            <div className="state--value" onClick ={setIsImportant("No")} >
              {isImportant}
            </div>
        </div>
    )
}
</code>```

However I get the error which says 'Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.'

If someone can explain why the error is happening it would be grateful!!

答:
Problem

Looking at your current code, this part:

```<code>onClick ={setIsImportant("No")}
</code>```

is calling setIsImportant every time your page renders, and because this function modifies state of your component, it tries to re-render the same component again, causing an infinite loop.

Solution

There are two ways of solving this issue, either by wrapping setIsImportant method in a wrapper:

```<code> <div className="state--value" onClick ={() => setIsImportant("No")} >
                  {isImportant}
    </div>
</code>```

or by simply using the function you just created:

```<code><div className="state--value" onClick ={handleClick} >
              {isImportant}
</div>
</code>```

Body:
Below is my code

function App() {
    const [isImportant, setIsImportant] = useState("Yes")

    function handleClick() {
        setIsImportant("No")
    }

    return (

Is state important to know?

              {isImportant}

    )
}

However I get the error which says 'Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.'

If someone can explain why the error is happening it would be grateful!!

Body:
Problem

Looking at your current code, this part:

onClick ={setIsImportant("No")}

is calling setIsImportant every time your page renders, and because this function modifies state of your component, it tries to re-render the same component again, causing an infinite loop.

Solution

There are two ways of solving this issue, either by wrapping setIsImportant method in a wrapper:

 <div className="state--value" onClick ={() => setIsImportant("No")} >
                  {isImportant}
    </div>

or by simply using the function you just created:

<div className="state--value" onClick ={handleClick} >
              {isImportant}
</div>


问:
Autoincrementing table in phpmyadmin
I want to auto_increment an existing table in phpmyadmin. The table consists of the following columns. Id,gallery_id,image,created_at,updated_at. Now, I want to auto_increment the column gallery_id but when running the following command, 'ALTER TABLE gallery_images MODIFY gallery_id bigint NOT NULL AUTO_INCREMENT PRIMARY_KEY' it show me an error 'Incorrect table definition; there can be only one auto column and it must be defined as a key'. How can I get rid of this error and auto_increment the column gallery_id on the table called gallery_images. I just want to auto_increment the single column.</p>

答:
Primary_key should not be underbarred

correct syntax is

```<code>ALTER TABLE gallery_images MODIFY gallery_id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY;
</code>```

NB not null is unnecessary.

Title: Autoincrementing table in phpmyadmin

Body:
Primary_key should not be underbarred

correct syntax is

ALTER TABLE gallery_images MODIFY gallery_id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY;

NB not null is unnecessary.


问:
heading tag won't work in alignment attribute
```<code><html>
    <head>
        <title> my's info </title>
    </head>
    <body>
        <p align="center">
            <h1>ABOUT ME</h1>
        </p>
        <p> this is a paragraph  </p>
        <h3> this is a heading </h3>
        <p> this is a paragraph </p>

    </body>
</html>
</code>```

why does not the ABOUT ME is not align in the center when i used the heading tag?
does heading tag doesn't work in alignments ?

答:
It works like this. heading tags are supposed to mark that as heading and some specific styling by default. center property always works related to div it inside or section.

        <title> my's info </title>

ABOUT ME

 this is a paragraph

 this is a heading

 this is a paragraph

```

Body:
        <title> my's info </title>

ABOUT ME

 this is a paragraph

 this is a heading

 this is a paragraph

why does not the ABOUT ME is not align in the center when i used the heading tag?
does heading tag doesn't work in alignments ?

Body:
It works like this. heading tags are supposed to mark that as heading and some specific styling by default. center property always works related to div it inside or section.

<html>
    <head>
        <title> my's info </title>
    </head>
    <body>
        <div style="text-align:center;">
            <h1>ABOUT ME</h1>
        </div>
        <p> this is a paragraph  </p>
        <h3> this is a heading </h3>
        <p> this is a paragraph </p>

    </body>
</html>


问:
How to interact with interfaces through HardHat?
how can I interact with interfaces through hardhat.

For example in brownie you can just call function from an interface like this:

```<code>def main():
    weth = interface.IWeth("weth_address")
    tx = weth.deposit({"from": account, "value": "value"})
</code>```

and that's it.

Is there a way to do the same in hardhat? I've been siting on this problem for couple of hours and for the life of me I can't figure out how to do this.

If it's not possible how do I get weth through solidity.

答:
In hardhat, you can achieve it using the attachment.

Go to hardhat console: npx hardhat console

Get the contract factory: factory = await ethers.getContractFactory('YourContractName')

Attach to address weth = await factory.attach('weth_address')

Do your function call e.g:

```<code>signer = await ethers.getSigner();
await signer.sendTransaction({ to: tokenAddress, value: ethers.utils.parseEther("5.0") });
</code>```

Body:
how can I interact with interfaces through hardhat.

For example in brownie you can just call function from an interface like this:

def main():
    weth = interface.IWeth("weth_address")
    tx = weth.deposit({"from": account, "value": "value"})

and that's it.

Is there a way to do the same in hardhat? I've been siting on this problem for couple of hours and for the life of me I can't figure out how to do this.

If it's not possible how do I get weth through solidity.

Body:
In hardhat, you can achieve it using the attachment.

Go to hardhat console: npx hardhat console

Get the contract factory: factory = await ethers.getContractFactory('YourContractName')

Attach to address weth = await factory.attach('weth_address')

Do your function call e.g:

signer = await ethers.getSigner();
await signer.sendTransaction({ to: tokenAddress, value: ethers.utils.parseEther("5.0") });


问:
How to solve this issue "distributed update operation failed; rollback required"?
I have a package that calls 2 procedures and I'm using dblink to call them.

I tried running first individually the procedures if it's working and they are both running.

```<code>exec proc1@dblink;
exec proc2@dblink;
</code>```

So when I put them in my package, I'm getting these errors:

ORA-02055: distributed update operation failed; rollback required

ORA-02041: client database did not begin a transaction

I need to call those procedures but how?

答: The problem is solved! There was a missing commit in the proc1@dblink.</p>

Body:
I have a package that calls 2 procedures and I'm using dblink to call them.

I tried running first individually the procedures if it's working and they are both running.

exec proc1@dblink;
exec proc2@dblink;

So when I put them in my package, I'm getting these errors:

ORA-02055: distributed update operation failed; rollback required

ORA-02041: client database did not begin a transaction

I need to call those procedures but how?


问:
How to create grafana dashboard without time range?
I want to remove time range selector from grafana dashboard to not query for specific selected time range. I am using influxdb and I want to load all data without selecting specific time range and query with some where clausess. Is it possible?</p>

答: In the dahboard setting enable Hide time picker and all InfluxDB queries write in the raw mode without time conditon ($timeFilter macro).


问:
After removing .php and adding / file not loading (object not found)
I was trying to remove the .php extension and add a / as normal websites have. Example http://example.com/category/.

I use .htaccess to remove .php. Here is the code:

```<code>RewriteEngine On
RewriteBase /

# hide .php extension snippet
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R,L]

# add a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]
</code>```

This code does its task. It removes .php and adds / but the PHP page is now not loading.

This is a screenshot (file name test.php):

How to solve this?

答:
It is because you're missing an internal rule to add .php silently to such redirect URIs.

You can add this rule in the end for that habndling:

RewriteEngine On
RewriteBase /

# hide .php extension snippet
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1/ [R=301,NE,L]

# add a trailing slash if needed
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/$ $1.php [L]
```

Body:
I was trying to remove the .php extension and add a / as normal websites have. Example http://example.com/category/.

I use .htaccess to remove .php. Here is the code:

RewriteEngine On
RewriteBase /

# hide .php extension snippet
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R,L]

# add a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

This code does its task. It removes .php and adds / but the PHP page is now not loading.

This is a screenshot (file name test.php):

How to solve this?


问:
Swift String variable
```<code>//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)
</code>```

I get the same output no matter which of the two I use. What's the difference between them?

答:
These two variable are same but with different names :

```<code>var myVar

var str
</code>```

in swift Type doesn't matter that defined because, swift based on value it recognizes what type it is.

Title: Swift String variable

Body:
//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)

I get the same output no matter which of the two I use. What's the difference between them?

Body:
These two variable are same but with different names :

var myVar

var str

in swift Type doesn't matter that defined because, swift based on value it recognizes what type it is.


问:
Certificate has expired error in Insomnia REST client
I'm using Insomnia REST client to work with api's.

I want to connect to Git on gitlab/github but I have this error:

```<code>Error: certificate has expired
    at TLSSocket.onConnectSecure (_tls_wrap.js:1501:34)
    at TLSSocket.emit (events.js:315:20)
    at TLSSocket._finishInit (_tls_wrap.js:936:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:710:12)
</code>```

答: you can workaround the issue by disabling Validate Certificates in insomnia preferences.

Body:
I'm using Insomnia REST client to work with api's.

I want to connect to Git on gitlab/github but I have this error:

Error: certificate has expired
    at TLSSocket.onConnectSecure (_tls_wrap.js:1501:34)
    at TLSSocket.emit (events.js:315:20)
    at TLSSocket._finishInit (_tls_wrap.js:936:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:710:12)


问:
I am trying a data visualization using R Studio and need all points in X and Y axis
sample image pic

I am new to R programming and trying a simple data visualization using ggplot2. I am trying to display night price distribution of Airbnb hotels on X axis. 'Price' is on X-axis and I am trying to display all prices in that column(instead of just 0,100,200,300) like 0,10,20,30,.....Can someone please help.

答:
Take a look at the tidyverse R packages, especially dplyr and ggplot2:

library(tidyverse)

# create example data
set.seed(1337)
prices <- tibble(
  id = seq(100),
  price = rnorm(mean = 100, sd = 50, 100) %>% abs()
)

filtered_prices <- filter(prices, price < 100)
qplot(price, data = filtered_prices, geom = "histogram")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
```
<p><img src="https://i.imgur.com/420CfrB.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code>qplot(price, data = filtered_prices, geom = "density")
</code>```

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

Body:
Take a look at the tidyverse R packages, especially dplyr and ggplot2:

library(tidyverse)

# create example data
set.seed(1337)
prices <- tibble(
  id = seq(100),
  price = rnorm(mean = 100, sd = 50, 100) %>% abs()
)

filtered_prices <- filter(prices, price < 100)
qplot(price, data = filtered_prices, geom = "histogram")
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

qplot(price, data = filtered_prices, geom = "density")

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


问:
Could not load file or assembly 'System.Net.Http
In my diagnostic view of my build output shows this conflict

There was a conflict between "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Net.Http, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". (TaskId:20)
   "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "System.Net.Http, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not. (TaskId:20)
    References which depend on "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.6.1\System.Net.Http.dll]. (TaskId:20)

I got here by adding the RestSharp nuget package.  I was not having an issue until I installed this and I think one of the pieces that came with it may have caused this issue.  I tried to uninstall it but that did not work.

答:
Not so good but alternate solution than using bindingRedirect-
If you have-

```<code><startup useLegacyV2RuntimeActivationPolicy="true" >
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" /></startup>
</code>```

in App.config, then removing "useLegacyV2RuntimeActivationPolicy" property helps by not reverting to old CLR.

Body:
Not so good but alternate solution than using bindingRedirect-
If you have-

<startup useLegacyV2RuntimeActivationPolicy="true" >
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" /></startup>

in App.config, then removing "useLegacyV2RuntimeActivationPolicy" property helps by not reverting to old CLR.


问:
Pass in bash terminal variables to a bash script
If I am in a Linux terminal and I start setting variables such as export AGE=45.

Then I have a script to read user data from terminal variables and process it, is this possible to do?

```<code>IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE
</code>```

#echo output

```<code>echo "your age is: " $scriptAGE"
</code>```

#should say your age is: 45

答:
There is no such thing as a terminal variable. read just assigns a string to your variable scriptAGE.

If this string contains some $NAME you want to expand, you could apply eval to it, but this is of course extremely dangerous because of possible code injection.

A safer way to do this is using envsubst, but this requires that the variables to be substituted must be environment variables. In your case, AGE is in the environment, so this condition is met.

In your case, you would have to do therefore a

```<code>envsubst <<<"$scriptAGE"
</code>```

which would print on stdout the content of scriptAGE with all environment variables in it substituted.

Body:
If I am in a Linux terminal and I start setting variables such as export AGE=45.

Then I have a script to read user data from terminal variables and process it, is this possible to do?

IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE

#echo output

echo "your age is: " $scriptAGE"

#should say your age is: 45

Body:
There is no such thing as a terminal variable. read just assigns a string to your variable scriptAGE.

If this string contains some $NAME you want to expand, you could apply eval to it, but this is of course extremely dangerous because of possible code injection.

A safer way to do this is using envsubst, but this requires that the variables to be substituted must be environment variables. In your case, AGE is in the environment, so this condition is met.

In your case, you would have to do therefore a

envsubst <<<"$scriptAGE"

which would print on stdout the content of scriptAGE with all environment variables in it substituted.


问:
Getting Undefined error at the end of sets Iteration in JavaScript
I am getting an undefined error after logging each element of the set.
please have a look at the code snippet bellow</p>
```<code>  let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

const itrate = fruits.forEach(fruit =>{
    console.log(fruit);

});

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

答:
Please do mention what your use case is when asking the question.

According to the documentation, forEach returns undefined.

console.log is also undefined as it does not explicitly return anything.

You can essentially write your function like this to understand it better.

```<code>let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

fruits.forEach(fruit =>{
    console.log(fruit);
});
</code>```

This will print all the values in your set. If you copy-paste this snippet into a browser's console such as Chrome, it will log the result of the function as well. In this case, forEach returns undefined so undefined will be printed at the end.

Body:
I am getting an undefined error after logging each element of the set.
please have a look at the code snippet bellow

  let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

const itrate = fruits.forEach(fruit =>{
    console.log(fruit);

});

console.log(itrate);

Body:
Please do mention what your use case is when asking the question.

According to the documentation, forEach returns undefined.

console.log is also undefined as it does not explicitly return anything.

You can essentially write your function like this to understand it better.

let arrayFruits = ['apple', 'banana', 'orange', 'plum', 'peach', 'strawberry', 'raspberry'];

const fruits = new Set(arrayFruits);

fruits.forEach(fruit =>{
    console.log(fruit);
});

This will print all the values in your set. If you copy-paste this snippet into a browser's console such as Chrome, it will log the result of the function as well. In this case, forEach returns undefined so undefined will be printed at the end.


问:
Shopware - Not able to show my page in My apps
I created Shopware App. I wanted to show my app in Iframe. But always showing "Whoops! You’ve moved too fast and lost orientation."

This is my manifest.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/platform/trunk/src/Core/Framework/App/Manifest/Schema/manifest-1.0.xsd">
    <meta>
        <name>TF</name>
        <label>TF</label>
        <label lang="de-DE">TF</label>
        <author>TF</author>
        <copyright></copyright>
        <version>1.0.0</version>
        <license>MIT</license>
    </meta>
    <setup>
        <secret>test</secret>
        <registrationUrl>https://example.com/shopware/register</registrationUrl>
    </setup>
    <permissions>
        <read>order</read>
        <read>product</read>
    </permissions>
    <admin>
        <main-module source="https://example.com/app/shopware"/>
    </admin>
</manifest>
</code>```

I am using Laravel for my site. And I created route like

```<code>Route::get('/app/shopware', 'ShopwareController@showApp');
</code>```

and my function is

```<code>public function showApp(Request $request)
{
   echo 'Showing TF';
}
</code>```

If I access this URL directly its working fine, but in Shopware showing error like this

How to solve this issue?

Thanks

答:
I think you need to add script code in the response html</p>
```<code><script>
    window.onload = function () {
        window.parent.postMessage('sw-app-loaded', '*');
    }
</script>
</code>```

Body:
I created Shopware App. I wanted to show my app in Iframe. But always showing "Whoops! You’ve moved too fast and lost orientation."

This is my manifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/platform/trunk/src/Core/Framework/App/Manifest/Schema/manifest-1.0.xsd">
    <meta>
        <name>TF</name>
        TF
        TF
        <author>TF</author>
        <copyright></copyright>
        <version>1.0.0</version>
        <license>MIT</license>
    </meta>
    <setup>
        <secret>test</secret>
        <registrationUrl>https://example.com/shopware/register</registrationUrl>
    </setup>
    <permissions>
        <read>order</read>
        <read>product</read>
    </permissions>
    <admin>

    </admin>
</manifest>

I am using Laravel for my site. And I created route like

Route::get('/app/shopware', 'ShopwareController@showApp');

and my function is

public function showApp(Request $request)
{
   echo 'Showing TF';
}

If I access this URL directly its working fine, but in Shopware showing error like this

How to solve this issue?

Thanks

Body:
I think you need to add script code in the response html

<script>
    window.onload = function () {
        window.parent.postMessage('sw-app-loaded', '*');
    }
</script>


问:
How to disable autofix for specific rules in eslint using CLI?
I want to be able to disable the rules that --fix fixes when running eslint in a console for a repo. The reason for this is because --fix leads to undesirable behavior for our jsdoc eslint rules. It creates invalid or sometimes empty jsdoc in our project- which typically leads to even more eslint rules (due to our configuration) and leads to tons of manual fixing or removal.

I want to just run --fix without it touching any jsdoc rules so that I can complete jsdoc manually- while eslint fixes all the rest of the rules.

I came across this SO question- but package mentioned in the answer does not support non-core plugins.

ESLint autofix ignore rule

Is there anything I can do short of modifying my eslintrc file every time I run the linter or using vscode for linting and modifying the config for the web editor instead? Its not a big deal for newer files- but linting legacy files is a chore when there's hundreds of spacing errors that I can't automatically fix easily.

答:
Using an .eslintrc.js file you can do something like this:

```<code>const isFixMode = process.argv.includes('--fix');

const config = {
  rules: {
    'no-console': 'error',
    ...(isFixMode && {
      'no-console': 'warn',
    }),
  },
};

module.exports = config;
</code>```

Body:
Using an .eslintrc.js file you can do something like this:

const isFixMode = process.argv.includes('--fix');

const config = {
  rules: {
    'no-console': 'error',
    ...(isFixMode && {
      'no-console': 'warn',
    }),
  },
};

module.exports = config;


问:
Hawtio Compatibility with Camel 3.x
We have recently upgraded Camel version in our application from 2.20.2 to 3.11.2. Hawtio web console used to show some Camel related details with Camel 2.20.2 which are missing after the upgrade to 3.11.2. After doing some analysis, I found that Hawtio is trying to access some MBeans which Camel used to expose before, but not now after the upgrade.

MBean not available

I just want to check if Hawtio is compatible with Camel 3.x or not, or is there anything else that I'm missing.

Currently we are using:

Camel 3.11.2 with Spring DSL

Hawtio 2.13.0

答:
You are probably missing one dependency.
Here is the full list of mines - ok probably too much as components are included in this list, but you will also find some basic one (like "camel-base-engine-3.9.0.jar").</p>
```<code>camel-api-3.9.0.jar
camel-base-3.9.0.jar
camel-base-engine-3.9.0.jar
camel-bean-3.9.0.jar
camel-bindy-3.9.0.jar
camel-catalog-3.9.0.jar
camel-cdi-3.9.0.jar
camel-core-3.9.0.jar
camel-core-catalog-3.9.0.jar
camel-core-engine-3.9.0.jar
camel-core-languages-3.9.0.jar
camel-core-model-3.9.0.jar
camel-core-processor-3.9.0.jar
camel-core-reifier-3.9.0.jar
camel-core-xml-3.9.0.jar
camel-csv-3.9.0.jar
camel-direct-3.9.0.jar
camel-directvm-3.9.0.jar
camel-file-3.9.0.jar
camel-ftp-3.9.0.jar
camel-health-3.9.0.jar
camel-http-3.9.0.jar
camel-http-base-3.9.0.jar
camel-http-common-3.9.0.jar
camel-jackson-3.9.0.jar
camel-jaxb-3.9.0.jar
camel-json-validator-3.9.0.jar
camel-jsonpath-3.9.0.jar
camel-jta-3.9.0.jar
camel-log-3.9.0.jar
camel-main-3.9.0.jar
camel-management-3.9.0.jar
camel-management-api-3.9.0.jar
camel-microprofile-config-3.9.0.jar
camel-microprofile-health-3.9.0.jar
camel-microprofile-metrics-3.9.0.jar
camel-mock-3.9.0.jar
camel-seda-3.9.0.jar
camel-sjms-3.9.0.jar
camel-sjms2-3.9.0.jar
camel-support-3.9.0.jar
camel-timer-3.9.0.jar
camel-util-3.9.0.jar
camel-xml-jaxb-3.9.0.jar
camel-xml-jaxp-3.9.0.jar
camel-xpath-3.9.0.jar
</code>```

Title: Hawtio Compatibility with Camel 3.x

Body:
You are probably missing one dependency.
Here is the full list of mines - ok probably too much as components are included in this list, but you will also find some basic one (like "camel-base-engine-3.9.0.jar").

camel-api-3.9.0.jar
camel-base-3.9.0.jar
camel-base-engine-3.9.0.jar
camel-bean-3.9.0.jar
camel-bindy-3.9.0.jar
camel-catalog-3.9.0.jar
camel-cdi-3.9.0.jar
camel-core-3.9.0.jar
camel-core-catalog-3.9.0.jar
camel-core-engine-3.9.0.jar
camel-core-languages-3.9.0.jar
camel-core-model-3.9.0.jar
camel-core-processor-3.9.0.jar
camel-core-reifier-3.9.0.jar
camel-core-xml-3.9.0.jar
camel-csv-3.9.0.jar
camel-direct-3.9.0.jar
camel-directvm-3.9.0.jar
camel-file-3.9.0.jar
camel-ftp-3.9.0.jar
camel-health-3.9.0.jar
camel-http-3.9.0.jar
camel-http-base-3.9.0.jar
camel-http-common-3.9.0.jar
camel-jackson-3.9.0.jar
camel-jaxb-3.9.0.jar
camel-json-validator-3.9.0.jar
camel-jsonpath-3.9.0.jar
camel-jta-3.9.0.jar
camel-log-3.9.0.jar
camel-main-3.9.0.jar
camel-management-3.9.0.jar
camel-management-api-3.9.0.jar
camel-microprofile-config-3.9.0.jar
camel-microprofile-health-3.9.0.jar
camel-microprofile-metrics-3.9.0.jar
camel-mock-3.9.0.jar
camel-seda-3.9.0.jar
camel-sjms-3.9.0.jar
camel-sjms2-3.9.0.jar
camel-support-3.9.0.jar
camel-timer-3.9.0.jar
camel-util-3.9.0.jar
camel-xml-jaxb-3.9.0.jar
camel-xml-jaxp-3.9.0.jar
camel-xpath-3.9.0.jar


问:
Serialize model for custom jsonapi resource in rails
When I make a request to a custom route in my rails project using jsonapi-resources, I get:

```<code>NoMethodError: undefined method `each_key' for nil:NilClass

  0) ArticlesController when requesting latest_article succeeds
     Failure/Error: serializer.serialize_to_hash(Article.latest)

     NoMethodError:
       undefined method `each_key' for nil:NilClass
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/bundler/gems/jsonapi-resources-bf4b4cd7d79d/lib/jsonapi/resource_set.rb:37:in `populate!'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/bundler/gems/jsonapi-resources-bf4b4cd7d79d/lib/jsonapi/resource_serializer.rb:49:in `serialize_to_hash'
     # ./app/controllers/articles_controller.rb:4:in `latest'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/actiontext-6.1.4.4/lib/action_text/rendering.rb:20:in `with_renderer'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/actiontext-6.1.4.4/lib/action_text/engine.rb:59:in `block (4 levels) in <class:Engine>'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/etag.rb:27:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/conditional_get.rb:27:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/head.rb:12:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/rack/logger.rb:37:in `call_app'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/rack/logger.rb:26:in `block in call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/rack/logger.rb:26:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/runtime.rb:22:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/sendfile.rb:110:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/engine.rb:539:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-test-1.1.0/lib/rack/mock_session.rb:29:in `request'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-test-1.1.0/lib/rack/test.rb:266:in `process_request'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-test-1.1.0/lib/rack/test.rb:119:in `request'
     # ./spec/requests/articles_controller_spec.rb:22:in `block (3 levels) in <top (required)>'
</code>```

What am I doing wrong here? And more importantly, how do I fix it?

For the purposes of this question, I have a Rails project with Article and Comment models. I use jsonapi-resources to generate all of the CRUD routes:

```<code>Rails.application.routes.draw do
  jsonapi_resources :articles do
    collection do
      get :latest
    end
  end
  jsonapi_resources :comments
end
</code>```

I added a custom articles/latest route to return the most recent article. I'm using JSONAPI::ResourceSerializer to serialize the Article object following the serializer documentation

```<code>class ArticlesController < JSONAPI::ResourceController
  def latest
    serializer = JSONAPI::ResourceSerializer.new(ArticleResource)
    serializer.serialize_to_hash(Article.latest)
  end
end
</code>```

I wrote a spec to duplicate the error:

```<code>describe 'ArticlesController' do
  let!(:articles) { create_list(:article, 10)}

  context 'when requesting articles' do
    it 'succeeds' do
      get articles_path
      expect(response).to have_http_status(:ok)
    end
  end

  context 'when requesting latest_article' do
    it 'succeeds' do
      get latest_articles_path
      expect(response).to have_http_status(:ok)
    end
  end
end
</code>```

For anyone that made it this far, I have a complete MCVE project on my GitHub.

From what I can tell from debugging,  serializer.serialize_to_hash creates a JSONAPI::ResourceSet with resource_set = JSONAPI::ResourceSet.new(source, include_related, options).

Here is JSONAPI::initialize:

```<code>    def initialize(source, include_related = nil, options = nil)
      @populated = false
      tree = if source.is_a?(JSONAPI::ResourceTree)
               source
             elsif source.class < JSONAPI::BasicResource
               JSONAPI::PrimaryResourceTree.new(resource: source, include_related: include_related, options: options)
             elsif source.is_a?(Array)
               JSONAPI::PrimaryResourceTree.new(resources: source, include_related: include_related, options: options)
             end

      if tree
        @resource_klasses = flatten_resource_tree(tree)
      end
    end
</code>```

I don't understand the cases in the if...elsif chain, but none of the conditions is true for me, so tree is nil and so @resource_classes is also nil.

After this, serialize_to_hash calls resource_set.populate! which in turn calls @resource_klasses.each_key, but @resource_classes is nil.

My current assumption is that I'm doing something wrong that causes ResourceSet.initialize to skip initializing @resource_klasses. But I'm not sure how to fix it. Any ideas or suggestions?

答:
The problem here is that serialize_to_hash does not accept an ActiveRecord object as an argument. Instead, I need to pass it a resource such as with the following:

```<code>    serializer.serialize_to_hash(ArticleResource.new(Article.latest, {}))
</code>```

I feel like jsonapi-resources could give a meaningful error message here rather than blowing up with NoMethodError.

Body:
When I make a request to a custom route in my rails project using jsonapi-resources, I get:

NoMethodError: undefined method `each_key' for nil:NilClass

  0) ArticlesController when requesting latest_article succeeds
     Failure/Error: serializer.serialize_to_hash(Article.latest)

     NoMethodError:
       undefined method `each_key' for nil:NilClass
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/bundler/gems/jsonapi-resources-bf4b4cd7d79d/lib/jsonapi/resource_set.rb:37:in `populate!'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/bundler/gems/jsonapi-resources-bf4b4cd7d79d/lib/jsonapi/resource_serializer.rb:49:in `serialize_to_hash'
     # ./app/controllers/articles_controller.rb:4:in `latest'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/actiontext-6.1.4.4/lib/action_text/rendering.rb:20:in `with_renderer'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/actiontext-6.1.4.4/lib/action_text/engine.rb:59:in `block (4 levels) in <class:Engine>'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/etag.rb:27:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/conditional_get.rb:27:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/head.rb:12:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/rack/logger.rb:37:in `call_app'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/rack/logger.rb:26:in `block in call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/rack/logger.rb:26:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/runtime.rb:22:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-2.2.3/lib/rack/sendfile.rb:110:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/railties-6.1.4.4/lib/rails/engine.rb:539:in `call'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-test-1.1.0/lib/rack/mock_session.rb:29:in `request'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-test-1.1.0/lib/rack/test.rb:266:in `process_request'
     # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/gems/rack-test-1.1.0/lib/rack/test.rb:119:in `request'
     # ./spec/requests/articles_controller_spec.rb:22:in `block (3 levels) in <top (required)>'

What am I doing wrong here? And more importantly, how do I fix it?

For the purposes of this question, I have a Rails project with Article and Comment models. I use jsonapi-resources to generate all of the CRUD routes:

Rails.application.routes.draw do
  jsonapi_resources :articles do
    collection do
      get :latest
    end
  end
  jsonapi_resources :comments
end

I added a custom articles/latest route to return the most recent article. I'm using JSONAPI::ResourceSerializer to serialize the Article object following the serializer documentation

class ArticlesController < JSONAPI::ResourceController
  def latest
    serializer = JSONAPI::ResourceSerializer.new(ArticleResource)
    serializer.serialize_to_hash(Article.latest)
  end
end

I wrote a spec to duplicate the error:

describe 'ArticlesController' do
  let!(:articles) { create_list(:article, 10)}

  context 'when requesting articles' do
    it 'succeeds' do
      get articles_path
      expect(response).to have_http_status(:ok)
    end
  end

  context 'when requesting latest_article' do
    it 'succeeds' do
      get latest_articles_path
      expect(response).to have_http_status(:ok)
    end
  end
end

For anyone that made it this far, I have a complete MCVE project on my GitHub.

From what I can tell from debugging,  serializer.serialize_to_hash creates a JSONAPI::ResourceSet with resource_set = JSONAPI::ResourceSet.new(source, include_related, options).

Here is JSONAPI::initialize:

    def initialize(source, include_related = nil, options = nil)
      @populated = false
      tree = if source.is_a?(JSONAPI::ResourceTree)
               source
             elsif source.class < JSONAPI::BasicResource
               JSONAPI::PrimaryResourceTree.new(resource: source, include_related: include_related, options: options)
             elsif source.is_a?(Array)
               JSONAPI::PrimaryResourceTree.new(resources: source, include_related: include_related, options: options)
             end

      if tree
        @resource_klasses = flatten_resource_tree(tree)
      end
    end

I don't understand the cases in the if...elsif chain, but none of the conditions is true for me, so tree is nil and so @resource_classes is also nil.

After this, serialize_to_hash calls resource_set.populate! which in turn calls @resource_klasses.each_key, but @resource_classes is nil.

My current assumption is that I'm doing something wrong that causes ResourceSet.initialize to skip initializing @resource_klasses. But I'm not sure how to fix it. Any ideas or suggestions?

Body:
The problem here is that serialize_to_hash does not accept an ActiveRecord object as an argument. Instead, I need to pass it a resource such as with the following:

    serializer.serialize_to_hash(ArticleResource.new(Article.latest, {}))

I feel like jsonapi-resources could give a meaningful error message here rather than blowing up with NoMethodError.


问:
Multiple Telegraf Daemons trying to write to same DB in InfluxDB
I have two telegraf daemons running.

Daemon 1 : Input = kafka topic : sample_topic, Output = InfluxDb : DB = telegraf, MEASUREMENT = KI1

Daemon 2 : Input = kafka topic : sample_topic2, Output = InfluxDb : DB = telegraf, MEASUREMENT = KI2

The two daemons read different kafka topics and writes to two different measurements in InfluxDB database "telegraf"

What I observe is that both the measurements KI1 and KI2 are not created simultaneously. Only one measurement is created. When I kill the daemon which has already created the measurement, then the other measurement gets created in the db by the other daemon.

Is simultaneous writes to different measurement allowed in InfluxDb?

I even tried the same by writing to two different InfluxDb databases, telegraf and telegraf2. I observed the same behavior.

Also, is it possible to do all this using only one daemon? Where in I have multiple input plugins to read different kafka topics and different output plugins to write where ever required.

Daemon 1 :

```<code>[tags]
    topic = "sample_topic"

# OUTPUTS
[outputs]
[outputs.influxdb]
    # The full HTTP endpoint URL for your InfluxDB instance
    url = "http://localhost:8086" # EDIT THIS LINE
    # The target database for metrics. This database must already exist
    database = "telegraf" # required.
    skip_database_creation = true
    database_tag = "KI1"

#INPUTS
# Read metrics from Kafka topic(s)
[[inputs.kafka_consumer_legacy]]

    name_override = "KI1"
    ## topic(s) to consume
    topics = ["sample_topic"]
    ## an array of Zookeeper connection strings
    zookeeper_peers = ["localhost:2181"]
    ## Zookeeper Chroot
    zookeeper_chroot = ""
    ## the name of the consumer group
    consumer_group = "sample"
    ## Offset (must be either "oldest" or "newest")
    offset = "oldest"
    ## Data format to consume.
    ## Each data format has its own unique set of configuration options, read
    ## more about them here:
    ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
    data_format = "value"
    data_type = "string"
    ## Maximum length of a message to consume, in bytes (default 0/unlimited);
    ## larger messages are dropped
    max_message_len = 65536
</code>```

Daemon 2 :

```<code>[tags]
    topic = "sample_topic2"

# OUTPUTS
[outputs]
[outputs.influxdb]
    # The full HTTP endpoint URL for your InfluxDB instance
    url = "http://localhost:8086" # EDIT THIS LINE
    # The target database for metrics. This database must already exist
    database = "telegraf" # required.
    skip_database_creation = true
    database_tag = "KI2"

#INPUTS
# Read metrics from Kafka topic(s)
[[inputs.kafka_consumer_legacy]]

    name_override = "KI2"
    ## topic(s) to consume
    topics = ["sample_topic2"]
    ## an array of Zookeeper connection strings
    zookeeper_peers = ["localhost:2181"]
    ## Zookeeper Chroot
    zookeeper_chroot = ""
    ## the name of the consumer group
    consumer_group = "sample"
    ## Offset (must be either "oldest" or "newest")
    offset = "oldest"
    ## Data format to consume.
    ## Each data format has its own unique set of configuration options, read
    ## more about them here:
    ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
    data_format = "value"
    data_type = "string"
    ## Maximum length of a message to consume, in bytes (default 0/unlimited);
    ## larger messages are dropped
    max_message_len = 65536
</code>```

答:
You should try to use different consumer groups in each Telegraf instance

instance 1

```<code>[[inputs.kafka_consumer]]
...
consumer_group = "sample-1"
...
</code>```

instance 2

```<code>[[inputs.kafka_consumer]]
...
consumer_group = "sample-2"
...
</code>```

So in the case of using the same consumer_group for both instances, that means both instances are in the same group. Only one instance in each group is allowed to consume the data. If one instance is down, another instance in the same group will take the responsibility in consuming the data from Kafka topics.

It would be late to answer, but it should be the solution for the same problem.

Body:
I have two telegraf daemons running.

Daemon 1 : Input = kafka topic : sample_topic, Output = InfluxDb : DB = telegraf, MEASUREMENT = KI1

Daemon 2 : Input = kafka topic : sample_topic2, Output = InfluxDb : DB = telegraf, MEASUREMENT = KI2

The two daemons read different kafka topics and writes to two different measurements in InfluxDB database "telegraf"

What I observe is that both the measurements KI1 and KI2 are not created simultaneously. Only one measurement is created. When I kill the daemon which has already created the measurement, then the other measurement gets created in the db by the other daemon.

Is simultaneous writes to different measurement allowed in InfluxDb?

I even tried the same by writing to two different InfluxDb databases, telegraf and telegraf2. I observed the same behavior.

Also, is it possible to do all this using only one daemon? Where in I have multiple input plugins to read different kafka topics and different output plugins to write where ever required.

Daemon 1 :

[tags]
    topic = "sample_topic"

# OUTPUTS
[outputs]
[outputs.influxdb]
    # The full HTTP endpoint URL for your InfluxDB instance
    url = "http://localhost:8086" # EDIT THIS LINE
    # The target database for metrics. This database must already exist
    database = "telegraf" # required.
    skip_database_creation = true
    database_tag = "KI1"

#INPUTS
# Read metrics from Kafka topic(s)
[[inputs.kafka_consumer_legacy]]

    name_override = "KI1"
    ## topic(s) to consume
    topics = ["sample_topic"]
    ## an array of Zookeeper connection strings
    zookeeper_peers = ["localhost:2181"]
    ## Zookeeper Chroot
    zookeeper_chroot = ""
    ## the name of the consumer group
    consumer_group = "sample"
    ## Offset (must be either "oldest" or "newest")
    offset = "oldest"
    ## Data format to consume.
    ## Each data format has its own unique set of configuration options, read
    ## more about them here:
    ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
    data_format = "value"
    data_type = "string"
    ## Maximum length of a message to consume, in bytes (default 0/unlimited);
    ## larger messages are dropped
    max_message_len = 65536

Daemon 2 :

[tags]
    topic = "sample_topic2"

# OUTPUTS
[outputs]
[outputs.influxdb]
    # The full HTTP endpoint URL for your InfluxDB instance
    url = "http://localhost:8086" # EDIT THIS LINE
    # The target database for metrics. This database must already exist
    database = "telegraf" # required.
    skip_database_creation = true
    database_tag = "KI2"

#INPUTS
# Read metrics from Kafka topic(s)
[[inputs.kafka_consumer_legacy]]

    name_override = "KI2"
    ## topic(s) to consume
    topics = ["sample_topic2"]
    ## an array of Zookeeper connection strings
    zookeeper_peers = ["localhost:2181"]
    ## Zookeeper Chroot
    zookeeper_chroot = ""
    ## the name of the consumer group
    consumer_group = "sample"
    ## Offset (must be either "oldest" or "newest")
    offset = "oldest"
    ## Data format to consume.
    ## Each data format has its own unique set of configuration options, read
    ## more about them here:
    ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
    data_format = "value"
    data_type = "string"
    ## Maximum length of a message to consume, in bytes (default 0/unlimited);
    ## larger messages are dropped
    max_message_len = 65536

Body:
You should try to use different consumer groups in each Telegraf instance

instance 1

[[inputs.kafka_consumer]]
...
consumer_group = "sample-1"
...

instance 2

[[inputs.kafka_consumer]]
...
consumer_group = "sample-2"
...

So in the case of using the same consumer_group for both instances, that means both instances are in the same group. Only one instance in each group is allowed to consume the data. If one instance is down, another instance in the same group will take the responsibility in consuming the data from Kafka topics.

It would be late to answer, but it should be the solution for the same problem.


问:
Is it possible to compress the rtmp vedio streaming on the transit nodes of a networking?
I want to do some labtory work using a network like this:

I want to transmit rtmp video streaming packets from the "server" node to the "client" node. The rtmp packets will be transmitted through node1 or node2 or node3 between the server node and the client node.

Is it possible that I compress the rtmp video streaming on node1/node2/node3? If it is possible, how? Do I have to capture the rtmp packets one node1/node2/node3 and then compress them and then resend the packets out from node1/node2/node3 to the client? Can I just do the compress work on lower layers (network layer/ data-link layer) of the network?

I am really curious about this. I will be really grateful if anybody can help!!

答:
The approach for a server network, generally tries to solve:

Capacity: Extends the capacity of system, for example, to serve 100k clients.

Quality: Deliver stream to client as near as possible, for normally distributed clients, whatever the number of clients. For example, you got 10 clients to serve, but they are in total different provinces or even countries.

For Quality, a reverse proxy like nginx works very well, like this;

```<code>client ---<--RTMP---   Nginx ----<--RTMP--- Server
</code>```

Note that the Proxy never increase the system capacity, the maximum clients is limited by the Server. So if you wants to increase the capacity, generally it also play like but more than a proxy, please use media cluster, like Edge of SRS:

```<code>1k client -<--RTMP--- SRS(Edge) --<--RTMP---+- SRS Origin Server
...                                         |
1k client  -<--RTMP--- SRS(Edge) --<--RTMP--+
...                                         |
1k client  -<--RTMP--- SRS(Edge) --<--RTMP--+
</code>```

Each Origin Server could serve about 1k SRS Edge server, and each Edge Server serves about 1k~3k clients.

Body:
The approach for a server network, generally tries to solve:

Capacity: Extends the capacity of system, for example, to serve 100k clients.

Quality: Deliver stream to client as near as possible, for normally distributed clients, whatever the number of clients. For example, you got 10 clients to serve, but they are in total different provinces or even countries.

For Quality, a reverse proxy like nginx works very well, like this;

client ---<--RTMP---   Nginx ----<--RTMP--- Server

Note that the Proxy never increase the system capacity, the maximum clients is limited by the Server. So if you wants to increase the capacity, generally it also play like but more than a proxy, please use media cluster, like Edge of SRS:

1k client -<--RTMP--- SRS(Edge) --<--RTMP---+- SRS Origin Server
...                                         |
1k client  -<--RTMP--- SRS(Edge) --<--RTMP--+
...                                         |
1k client  -<--RTMP--- SRS(Edge) --<--RTMP--+

Each Origin Server could serve about 1k SRS Edge server, and each Edge Server serves about 1k~3k clients.


问:
Has MySQL always supported shorthand validation for fields?
I am currently writing a lot of MySQL queries and noticed that I can use shorthand validation, like so:

```<code>SELECT id, content, date_added FROM table WHERE date_added
</code>```

(where date_added is a default NULL timestamp and I don't have to ask specifically if it IS NOT NULL to return all results that have a timestamp)

I just need to know if this is advised against, or if this shorthand functionality became available at a certain MySQL version, as I would like to retain backwards compatibility.
I was previously certain that this didn't work and I had to write out the whole conditional, but now I cannot confirm.

答:
I wouldn't exactly call this "shorthand validation". I'm not sure where you're getting that from.

The WHERE clause is just going to check for truthiness. NULL is not a TRUE value, all other non-zero values are TRUE.

Even though this works for you, I would still strongly advise against it. I favor very explicit database queries. We don't need any added voodoo sorcery here...

Stick with

SELECT id, content, date_added
FROM table
WHERE date_added IS NOT NULL;
```

Body:
I am currently writing a lot of MySQL queries and noticed that I can use shorthand validation, like so:

SELECT id, content, date_added FROM table WHERE date_added

(where date_added is a default NULL timestamp and I don't have to ask specifically if it IS NOT NULL to return all results that have a timestamp)

I just need to know if this is advised against, or if this shorthand functionality became available at a certain MySQL version, as I would like to retain backwards compatibility.
I was previously certain that this didn't work and I had to write out the whole conditional, but now I cannot confirm.


问:
select dropdown option set to default when click reset button on react js
I am working on a dropdown select filter and there is a reset button, so I want to reset data whenever I click on it.
this is my select dropdown where I am filtering data

```<code><select
    className={style.input}
    name="categoryId"
    onChange={e => handleCategory(e.target.value)}
>
    <option value="" disabled selected>
        Select A Categtory
    </option>
    {props.category_list && props.category_list.length > 0
        ? props.category_list.map((item, index) => (
              <option value={item.categoryId}>{item.categoryName}</option>
          ))
        : null}
</select>
</code>```

this is onChange method of select

```<code> const handleCategory = (value) => {
    setErrorMsg(null);
    setCategoryID(value);
    props.getSubCategoryList(value);
  };
</code>```

and this is a reset button, I tried to make

```<code>  const handleReset = (value) => {
    setReset(true);
    setCategoryID('');
    setSkillID('');
    setLocationId('');
    props.getSubCategoryList(1);
  };
</code>```

but the problem is when I click on reset it resets, but the value doesn't change to default one in options also if I change it in  {item.categoryName} then three same values appear under options. hope this information is enough.

答:
You need to bind the selected value to select element.

Provide categoryID as a prop to your component.

Set it as the value property of select.

```<code><select
    ...
    ...
    value={props.categoryID}
    onChange={e => handleCategory(e.target.value)}
></select>
</code>```

Body:
I am working on a dropdown select filter and there is a reset button, so I want to reset data whenever I click on it.
this is my select dropdown where I am filtering data

<select
    className={style.input}
    name="categoryId"
    onChange={e => handleCategory(e.target.value)}
>
    <option value="" disabled selected>
        Select A Categtory
    </option>
    {props.category_list && props.category_list.length > 0
        ? props.category_list.map((item, index) => (
              <option value={item.categoryId}>{item.categoryName}</option>
          ))
        : null}
</select>

this is onChange method of select

 const handleCategory = (value) => {
    setErrorMsg(null);
    setCategoryID(value);
    props.getSubCategoryList(value);
  };

and this is a reset button, I tried to make

  const handleReset = (value) => {
    setReset(true);
    setCategoryID('');
    setSkillID('');
    setLocationId('');
    props.getSubCategoryList(1);
  };

but the problem is when I click on reset it resets, but the value doesn't change to default one in options also if I change it in  {item.categoryName} then three same values appear under options. hope this information is enough.

Body:
You need to bind the selected value to select element.

Provide categoryID as a prop to your component.

Set it as the value property of select.

<select
    ...
    ...
    value={props.categoryID}
    onChange={e => handleCategory(e.target.value)}
></select>


问:
Seat Reservation System two-dimensional array - Java
I am tasked to create a seat reservation system using two-dimensional arrays. The program specifications are the ff:

Use two-dimensional array with size 7 columns and 5 rows.

Seat numbers are populated during run-time and not hard-coded.

User is asked to input a seat number.

The chosen seat number is replaced by the letter X.

Program displays a remark “Seat successfully reserved” when reservation is
done.

The user is not allowed to reserve a previously reserved seat. Display “Seat is
taken” remarks.

The user is not allowed to enter an invalid seat number. Display an error
message.

The program continuously loops.

The program works at the start but when it loops again the next seat number doesn't get reserved and just displays the seat is taken.

The code:

```<code>
public class SeatReservation_Andaya {

    // create 2d array w/ 7 columns and 5 rows
    static int[][] seatArray = new int[5][7];

    // create another array
    static String[][] stringArray = new String[5][7];

    // declare variables
    static int seatNum = 1;
    static int i, j;

    static boolean chkData() {  // Method that will check for reservation availability
        for (i = 0; i < 5; ++i) {
            for (j = 0; j < 7; ++j) {
                if (stringArray[i][j].equals("X")) {
                    return true;
                }
            }
        }
        return false;
    }

    static void replaceWithX(int numRes) {
        // replaces the seat chosen with "X"
        switch (numRes) {
            case 1:
                stringArray[0][0] = "X";
                break;

            case 2:
                stringArray[0][1] = "X";
                break;

            case 3:
                stringArray[0][2] = "X";
                break;

            case 4:
                stringArray[0][3] = "X";
                break;

            case 5:
                stringArray[0][4] = "X";
                break;

            case 6:
                stringArray[0][5] = "X";
                break;

            case 7:
                stringArray[0][6] = "X";
                break;

            case 8:
                stringArray[1][0] = "X";
                break;

            case 9:
                stringArray[1][1] = "X";
                break;

            case 10:
                stringArray[1][2] = "X";
                break;

            case 11:
                stringArray[1][3] = "X";
                break;

            case 12:
                stringArray[1][4] = "X";
                break;

            case 13:
                stringArray[1][5] = "X";
                break;

            case 14:
                stringArray[1][6] = "X";
                break;

            case 15:
                stringArray[2][0] = "X";
                break;

            case 16:
                stringArray[2][1] = "X";
                break;

            case 17:
                stringArray[2][2] = "X";
                break;

            case 18:
                stringArray[2][3] = "X";
                break;

            case 19:
                stringArray[2][4] = "X";
                break;

            case 20:
                stringArray[2][5] = "X";
                break;

            case 21:
                stringArray[2][6] = "X";
                break;

            case 22:
                stringArray[3][0] = "X";
                break;

            case 23:
                stringArray[3][1] = "X";
                break;

            case 24:
                stringArray[3][2] = "X";
                break;

            case 25:
                stringArray[3][3] = "X";
                break;

            case 26:
                stringArray[3][4] = "X";
                break;

            case 27:
                stringArray[3][5] = "X";
                break;

            case 28:
                stringArray[3][6] = "X";
                break;

            case 29:
                stringArray[4][0] = "X";
                break;

            case 30:
                stringArray[4][1] = "X";
                break;

            case 31:
                stringArray[4][2] = "X";
                break;

            case 32:
                stringArray[4][3] = "X";
                break;

            case 33:
                stringArray[4][4] = "X";
                break;

            case 34:
                stringArray[4][5] = "X";
                break;

            case 35:
                stringArray[4][6] = "X";
                break;
        }
    }

    public static void main(String[] args) {
        // create scanner tool
        Scanner input = new Scanner(System.in);

        // declare values of int array
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                seatArray[i][j] = seatNum;
                seatNum++;
            }
        }

        // puts int array values into string
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                stringArray[i][j] = Integer.toString(seatArray[i][j]);
            }
        }

        // prints the array
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                System.out.print(stringArray[i][j] + "\t");
            }
            System.out.println();
        }

        // loops reservation system
        while (true) {
            // asks for seat number
            System.out.print("Enter seat number to reserve: ");

            // reads input
            int numRes = Integer.valueOf(input.nextLine());

            // check if input is invalid
            if (numRes > 35 || numRes <1) {
                System.out.println("ERROR: INVALID SEAT NUMBER");
            } else {
                // checks if seat is reserved
                if (chkData()) {
                    System.out.println("Seat is taken");
                }
                // reserves seat if not reserved
                else {
                    replaceWithX(numRes);
                    System.out.println("Seat successfully reserved");
                }
            }
            // prints new array
            for (int i = 0; i < 5; i++) { // loop through all rows
                for (int j = 0; j < 7; j++) { // loop through all elements of current row
                    System.out.print(stringArray[i][j] + "\t");
                }
                System.out.println();
            }
        }
    }
}
</code>```

The output is like this looks like this:

1   2   3   4   5   6   7

8   9   10  11  12  13  14

15  16  17  18  19  20  21

22  23  24  25  26  27  28

29  30  31  32  33  34  35

Enter seat number to reserve: 1
Seat successfully reserved

X   2   3   4   5   6   7

8   9   10  11  12  13  14

15  16  17  18  19  20  21

22  23  24  25  26  27  28

29  30  31  32  33  34  35

Enter seat number to reserve: 2
Seat is taken

X   2   3   4   5   6   7

8   9   10  11  12  13  14

15  16  17  18  19  20  21

22  23  24  25  26  27  28

29  30  31  32  33  34  35

Enter seat number to reserve:

Can you guys give me tips on where the problem in the code is? Thank you!

答:
You can make your code more cleaner by calculating row and column number from seat number, here is one way you can do it:</p>
```<code>public class SeatReservation_Andaya {

    // create 2d array w/ 7 columns and 5 rows
    // create another array
    static String[][] stringArray = new String[5][7];

    // declare variables
    static int seatNum = 1;
    static int i, j;

    static void replaceWithX(int numRes) {
        // replaces the seat chosen with "X"
        int rowNum = (numRes-1)/7;
        int colNum = (numRes-1)%7;
        stringArray[rowNum][colNum] = "X";
    }

    public static void main(String[] args) {
        // create scanner tool
        Scanner input = new Scanner(System.in);

        // puts int array values into string
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                stringArray[i][j] = Integer.toString(seatNum);
                seatNum++;
            }
        }

        // prints the array
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                System.out.print(stringArray[i][j] + "\t");
            }
            System.out.println();
        }

        // loops reservation system
        while (true) {
            // asks for seat number
            System.out.print("Enter seat number to reserve: ");

            // reads input
            int numRes = Integer.valueOf(input.nextLine());

            // check if input is invalid
            if (numRes > 35 || numRes <1) {
                System.out.println("ERROR: INVALID SEAT NUMBER");
            } else {
                // checks if seat is reserved
                int rowNum = (numRes-1)/7;
                int colNum = (numRes-1)%7;
                if (stringArray[rowNum][colNum].equals("X")) {
                    System.out.println("Seat is taken");
                }
                // reserves seat if not reserved
                else {
                    replaceWithX(numRes);
                    System.out.println("Seat successfully reserved");
                }
            }
            // prints new array
            for (int i = 0; i < 5; i++) { // loop through all rows
                for (int j = 0; j < 7; j++) { // loop through all elements of current row
                    System.out.print(stringArray[i][j] + "\t");
                }
                System.out.println();
            }
        }
    }
}
</code>```

Body:
I am tasked to create a seat reservation system using two-dimensional arrays. The program specifications are the ff:

Use two-dimensional array with size 7 columns and 5 rows.

Seat numbers are populated during run-time and not hard-coded.

User is asked to input a seat number.

The chosen seat number is replaced by the letter X.

Program displays a remark “Seat successfully reserved” when reservation is
done.

The user is not allowed to reserve a previously reserved seat. Display “Seat is
taken” remarks.

The user is not allowed to enter an invalid seat number. Display an error
message.

The program continuously loops.

The program works at the start but when it loops again the next seat number doesn't get reserved and just displays the seat is taken.

The code:

public class SeatReservation_Andaya {

    // create 2d array w/ 7 columns and 5 rows
    static int[][] seatArray = new int[5][7];

    // create another array
    static String[][] stringArray = new String[5][7];

    // declare variables
    static int seatNum = 1;
    static int i, j;

    static boolean chkData() {  // Method that will check for reservation availability
        for (i = 0; i < 5; ++i) {
            for (j = 0; j < 7; ++j) {
                if (stringArray[i][j].equals("X")) {
                    return true;
                }
            }
        }
        return false;
    }

    static void replaceWithX(int numRes) {
        // replaces the seat chosen with "X"
        switch (numRes) {
            case 1:
                stringArray[0][0] = "X";
                break;

            case 2:
                stringArray[0][1] = "X";
                break;

            case 3:
                stringArray[0][2] = "X";
                break;

            case 4:
                stringArray[0][3] = "X";
                break;

            case 5:
                stringArray[0][4] = "X";
                break;

            case 6:
                stringArray[0][5] = "X";
                break;

            case 7:
                stringArray[0][6] = "X";
                break;

            case 8:
                stringArray[1][0] = "X";
                break;

            case 9:
                stringArray[1][1] = "X";
                break;

            case 10:
                stringArray[1][2] = "X";
                break;

            case 11:
                stringArray[1][3] = "X";
                break;

            case 12:
                stringArray[1][4] = "X";
                break;

            case 13:
                stringArray[1][5] = "X";
                break;

            case 14:
                stringArray[1][6] = "X";
                break;

            case 15:
                stringArray[2][0] = "X";
                break;

            case 16:
                stringArray[2][1] = "X";
                break;

            case 17:
                stringArray[2][2] = "X";
                break;

            case 18:
                stringArray[2][3] = "X";
                break;

            case 19:
                stringArray[2][4] = "X";
                break;

            case 20:
                stringArray[2][5] = "X";
                break;

            case 21:
                stringArray[2][6] = "X";
                break;

            case 22:
                stringArray[3][0] = "X";
                break;

            case 23:
                stringArray[3][1] = "X";
                break;

            case 24:
                stringArray[3][2] = "X";
                break;

            case 25:
                stringArray[3][3] = "X";
                break;

            case 26:
                stringArray[3][4] = "X";
                break;

            case 27:
                stringArray[3][5] = "X";
                break;

            case 28:
                stringArray[3][6] = "X";
                break;

            case 29:
                stringArray[4][0] = "X";
                break;

            case 30:
                stringArray[4][1] = "X";
                break;

            case 31:
                stringArray[4][2] = "X";
                break;

            case 32:
                stringArray[4][3] = "X";
                break;

            case 33:
                stringArray[4][4] = "X";
                break;

            case 34:
                stringArray[4][5] = "X";
                break;

            case 35:
                stringArray[4][6] = "X";
                break;
        }
    }

    public static void main(String[] args) {
        // create scanner tool
        Scanner input = new Scanner(System.in);

        // declare values of int array
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                seatArray[i][j] = seatNum;
                seatNum++;
            }
        }

        // puts int array values into string
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                stringArray[i][j] = Integer.toString(seatArray[i][j]);
            }
        }

        // prints the array
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                System.out.print(stringArray[i][j] + "\t");
            }
            System.out.println();
        }

        // loops reservation system
        while (true) {
            // asks for seat number
            System.out.print("Enter seat number to reserve: ");

            // reads input
            int numRes = Integer.valueOf(input.nextLine());

            // check if input is invalid
            if (numRes > 35 || numRes <1) {
                System.out.println("ERROR: INVALID SEAT NUMBER");
            } else {
                // checks if seat is reserved
                if (chkData()) {
                    System.out.println("Seat is taken");
                }
                // reserves seat if not reserved
                else {
                    replaceWithX(numRes);
                    System.out.println("Seat successfully reserved");
                }
            }
            // prints new array
            for (int i = 0; i < 5; i++) { // loop through all rows
                for (int j = 0; j < 7; j++) { // loop through all elements of current row
                    System.out.print(stringArray[i][j] + "\t");
                }
                System.out.println();
            }
        }
    }
}

The output is like this looks like this:

1   2   3   4   5   6   7

8   9   10  11  12  13  14

15  16  17  18  19  20  21

22  23  24  25  26  27  28

29  30  31  32  33  34  35

Enter seat number to reserve: 1
Seat successfully reserved

X   2   3   4   5   6   7

8   9   10  11  12  13  14

15  16  17  18  19  20  21

22  23  24  25  26  27  28

29  30  31  32  33  34  35

Enter seat number to reserve: 2
Seat is taken

X   2   3   4   5   6   7

8   9   10  11  12  13  14

15  16  17  18  19  20  21

22  23  24  25  26  27  28

29  30  31  32  33  34  35

Enter seat number to reserve:

Can you guys give me tips on where the problem in the code is? Thank you!

Body:
You can make your code more cleaner by calculating row and column number from seat number, here is one way you can do it:

public class SeatReservation_Andaya {

    // create 2d array w/ 7 columns and 5 rows
    // create another array
    static String[][] stringArray = new String[5][7];

    // declare variables
    static int seatNum = 1;
    static int i, j;

    static void replaceWithX(int numRes) {
        // replaces the seat chosen with "X"
        int rowNum = (numRes-1)/7;
        int colNum = (numRes-1)%7;
        stringArray[rowNum][colNum] = "X";
    }

    public static void main(String[] args) {
        // create scanner tool
        Scanner input = new Scanner(System.in);

        // puts int array values into string
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                stringArray[i][j] = Integer.toString(seatNum);
                seatNum++;
            }
        }

        // prints the array
        for (int i = 0; i < 5; i++) { // loop through all rows
            for (int j = 0; j < 7; j++) { // loop through all elements of current row
                System.out.print(stringArray[i][j] + "\t");
            }
            System.out.println();
        }

        // loops reservation system
        while (true) {
            // asks for seat number
            System.out.print("Enter seat number to reserve: ");

            // reads input
            int numRes = Integer.valueOf(input.nextLine());

            // check if input is invalid
            if (numRes > 35 || numRes <1) {
                System.out.println("ERROR: INVALID SEAT NUMBER");
            } else {
                // checks if seat is reserved
                int rowNum = (numRes-1)/7;
                int colNum = (numRes-1)%7;
                if (stringArray[rowNum][colNum].equals("X")) {
                    System.out.println("Seat is taken");
                }
                // reserves seat if not reserved
                else {
                    replaceWithX(numRes);
                    System.out.println("Seat successfully reserved");
                }
            }
            // prints new array
            for (int i = 0; i < 5; i++) { // loop through all rows
                for (int j = 0; j < 7; j++) { // loop through all elements of current row
                    System.out.print(stringArray[i][j] + "\t");
                }
                System.out.println();
            }
        }
    }
}


问:
Flutter Error: No named parameter with the name 'displayLarge'
I am working on an app, I posted last update on git 2 days ago and haven't touched the code since. Now, I opened android studio and it was giving me this error when I tried to run it... I tried deleting repository from my computer and then cloning it again but it didn't work. I have also tried searching for similar problems, and found out there was a similar problem with speed-dial package and one comment said something about broken package versions. Anyways, this is the error I am getting after I try running my app:

These are first few lines of the error it's giving me, but there is more than a thousand lines following these.

I also tried running flutter doctor and it gave me the following:

答:
google_fonts: ^2.3.1 has also solved the problems left in google_fonts: 2.3.0

Well! This issue will be raised in all projects using the google_fonts with a caret sign (^).

The caret sign (^) is used for pub dependencies in Dart to indicate a range of version numbers that are allowed. Specifically, any version from the specified version up to (but not including) the next non-breaking version is ok.

So google_fonts: ^2.2.0 is the same as '>=2.2.0 <3.0.0', It's shorthand for the longer form. The ^ is saying, I want to automatically use the most up-to-date package from Pub as long as that update won't break anything in my app. The google_fonts: 2.3.0 has some issues with this as of now.

Solution Steps :

Remove (^) from your current google_fonts. max can be set as google_fonts: 2.2.0.

To make sure, this does not conflict with any other dependency, for once do 'pub get'.

Try to invalidate caches and restart. This should clean error, else do flutter clean to remove old updated google_fonts and pub get.

Done! You are good to go. Happy Codding!!!


问:
C - incompatible integer to pointer conversion - Substitution question from CS50
I am trying to convert a single character to the appropriate index character in a 26 letter cipher. I tried to convert the character 'oc' to an integer because the array 'cipher' needs an integer for the index, but I am getting errors which I don't understand.

```<code>char conversion(char c, string cipher)
{
    // Only change alphabetical characters
    if (isalpha(c) == 0)
    {
        return c;
    }

    char oc;

    // If upper case
    if (isupper(c))
    {
        oc = c - 65;

        int ocint = atoi(oc);

        oc = cipher[ocint];

        oc = oc + 65;

        return oc;
    }
</code>```

I get the errors:

```<code>error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
        int ocint = atoi(oc);
                         ^~
                         &
/usr/include/stdlib.h:104:30: note: passing argument to parameter '__nptr' here
extern int atoi (const char *__nptr)
</code>```

What does 'take the address with &' mean?

And also '__nptr'?

答:
atoi is used for converting whole strings. If you want to convert an individual character A to Z into the corresponding number, then oc = c - 65; does that already. Preferably write oc = c - 'A';.

So in this specific case you don't even need atoi. In the general case, atoi should never be used either, because it's an incorrectly designed function without error handling. Always use strtol instead.

Body:
I am trying to convert a single character to the appropriate index character in a 26 letter cipher. I tried to convert the character 'oc' to an integer because the array 'cipher' needs an integer for the index, but I am getting errors which I don't understand.

char conversion(char c, string cipher)
{
    // Only change alphabetical characters
    if (isalpha(c) == 0)
    {
        return c;
    }

    char oc;

    // If upper case
    if (isupper(c))
    {
        oc = c - 65;

        int ocint = atoi(oc);

        oc = cipher[ocint];

        oc = oc + 65;

        return oc;
    }

I get the errors:

error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
        int ocint = atoi(oc);
                         ^~
                         &
/usr/include/stdlib.h:104:30: note: passing argument to parameter '__nptr' here
extern int atoi (const char *__nptr)

What does 'take the address with &' mean?

And also '__nptr'?


问:
Cannot find declaration file error in one file
I am getting error 'Cannot find declaration file' in one file but not in other. I have the following directory structure

Error appears in /src/contentScripts/views/App.vue but not in /src/components/LogoIcon.vue

I have the following configuration

```<code>{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
  "exclude": ["src/**/__tests__/*"],
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
    "types": ["unplugin-icons/types/vue"]
    }
  },

  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ]
}
</code>```

答: Try adding this library with the following command yarn add @types/icons -D

Body:
I am getting error 'Cannot find declaration file' in one file but not in other. I have the following directory structure

Error appears in /src/contentScripts/views/App.vue but not in /src/components/LogoIcon.vue

I have the following configuration

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
  "exclude": ["src/**/__tests__/*"],
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
    "types": ["unplugin-icons/types/vue"]
    }
  },

  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ]
}


问:
Cypress: Test if element does not exist
I want to be able to click on a check box and test that an element is no longer in the DOM in Cypress. Can someone suggest how you do it?

// This is the Test when the checkbox is clicked and the element is there

cy.get('[type="checkbox"]').click();
cy.get('.check-box-sub-text').contains('Some text in this div.')
```

I want to do the opposite of the test above.

So when I click it again the div with the class check-box-sub-text should not be in the DOM.

答:
I would use :

cy.get('.check-box-sub-text').should('not.be.visible');

This is safer than

cy.get('.check-box-sub-text').should('not.exist');

( The element can be present in the DOM but not visible with display: none or opacity: 0 )

Title: Cypress: Test if element does not exist

Body:
I want to be able to click on a check box and test that an element is no longer in the DOM in Cypress. Can someone suggest how you do it?

// This is the Test when the checkbox is clicked and the element is there

cy.get('[type="checkbox"]').click();
cy.get('.check-box-sub-text').contains('Some text in this div.')

I want to do the opposite of the test above.

So when I click it again the div with the class check-box-sub-text should not be in the DOM.


问:
Is Camel Testcontainers deprecated? What replaces it?
The Camel testing with Testcontainers page directs one to declare a test class to extend ContainerAwareTestSupport. I did that but the compiler is warning that ContainerAwareTestSupport is deprecated (this is Camel version 3.14.1).

What replaces this?

答:
Based on these mails the plan is to encourage users to move on to test-infra modules.

Related blog post: Good bye Camel-Testcontainers! Hello Camel's test-infra


问:
How to recover grants for root user in mysql
I accidentally removed all privileges for root user. How can I recover it ?</p>

答:
Check out this part of the MySQL-Documentation, they've dedicated a whole chapter to this:
http://dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html</p>


问:
How can I show "empty" if data is not there?
Because of this

```<code><v-card-subtitle class="py-0 my-0">{{ vc_rule.url }}</v-card-subtitle>
</code>```

where this.vc_rule could be empty or null. Sometimes, I got this error on my console.

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'url')

Instead of getting this error, how can I tell Vue.js to show "empty" if data is not there?

I envision something like this :

Hint: ?

```<code><v-card-subtitle class="py-0 my-0">{{ vc_rule?.url }}</v-card-subtitle>
</code>```

答:
If I understand your requirement correctly, we can achieve that in the HTML template itself via use of Optional chaining (?.) along with Nullish coalescing operator (??).

Working Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      vc_rule: null
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-card-subtitle class="py-0 my-0">{{ vc_rule?.url ?? 'empty' }}</v-card-subtitle>
</div></code>```

Body:
Because of this

<v-card-subtitle class="py-0 my-0">{{ vc_rule.url }}</v-card-subtitle>

where this.vc_rule could be empty or null. Sometimes, I got this error on my console.

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'url')

Instead of getting this error, how can I tell Vue.js to show "empty" if data is not there?

I envision something like this :

Hint: ?

<v-card-subtitle class="py-0 my-0">{{ vc_rule?.url }}</v-card-subtitle>

Body:
If I understand your requirement correctly, we can achieve that in the HTML template itself via use of Optional chaining (?.) along with Nullish coalescing operator (??).

Working Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      vc_rule: null
    }
  }
})

<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-card-subtitle class="py-0 my-0">{{ vc_rule?.url ?? 'empty' }}</v-card-subtitle>
</div>


问:
CSS vertical scrollbar padding left/right in UL possible?
Is it possible to add padding or margin around the scrollbar item or scrollbar-track?  I've tried and can only get padding top/bottom.  Adding padding to the UL has no effect on scrollbar.  Negative margins on scrollbar have no effect.  Ideas?  JS Fiddle here.</p>

```<code>::-webkit-scrollbar {
width: 12px;
margin:10px;
}

::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
-webkit-border-radius: 10px;
border-radius: 10px;
padding: 10px
}

::-webkit-scrollbar-thumb {
-webkit-border-radius: 10px;
border-radius: 10px;
background: rgba(255,0,0,0.8);
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
background: rgba(255,0,0,0.4);
</code>```

答:
Simply use the margin-block

```<code>::-webkit-scrollbar-track {
   box-shadow: inset 0 0 5px F2F2F2;
   border-radius: 0px;
   margin-block: 15px;
}
</code>```

#container{
    height:400px;
    background-color:white;
    overflow-y:scroll;
    border-radius:25px;
}

#content{
    height:700px;
    background-color:yellow;
    padding:25px;
}

::-webkit-scrollbar{
    width: 5px;
}

  /* Track */
::-webkit-scrollbar-track{
    box-shadow: inset 0 0 5px F2F2F2;
    border-radius: 0px;
    margin-block: 25px;
}

  /* Handle */
::-webkit-scrollbar-thumb{
     background: #8B8B8B;
     border-radius: 27px;
     border: 4px solid rgba(0, 0, 0, 0);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="content">
    <br>
    Click to type...
    <br>
  </div>
</div></code>```

Body:
Is it possible to add padding or margin around the scrollbar item or scrollbar-track?  I've tried and can only get padding top/bottom.  Adding padding to the UL has no effect on scrollbar.  Negative margins on scrollbar have no effect.  Ideas?  JS Fiddle here.

::-webkit-scrollbar {
width: 12px;
margin:10px;
}

::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
-webkit-border-radius: 10px;
border-radius: 10px;
padding: 10px
}

::-webkit-scrollbar-thumb {
-webkit-border-radius: 10px;
border-radius: 10px;
background: rgba(255,0,0,0.8);
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
background: rgba(255,0,0,0.4);

Body:
Simply use the margin-block

::-webkit-scrollbar-track {
   box-shadow: inset 0 0 5px F2F2F2;
   border-radius: 0px;
   margin-block: 15px;
}

#container{
    height:400px;
    background-color:white;
    overflow-y:scroll;
    border-radius:25px;
}

#content{
    height:700px;
    background-color:yellow;
    padding:25px;
}

::-webkit-scrollbar{
    width: 5px;
}

  /* Track */
::-webkit-scrollbar-track{
    box-shadow: inset 0 0 5px F2F2F2;
    border-radius: 0px;
    margin-block: 25px;
}

  /* Handle */
::-webkit-scrollbar-thumb{
     background: #8B8B8B;
     border-radius: 27px;
     border: 4px solid rgba(0, 0, 0, 0);
 }

<div id="container">
  <div id="content">
    <br>
    Click to type...
    <br>
  </div>
</div>


问:
How to write a SQL query with dynamic LIMIT
SELECT * FROM user LIMIT (SELECT group_limit FROM groups WHERE groupid = 7471);

答:
Since MySQL 8.0.2, the ROW_NUMBER() window function has been supported. With the help of a subquery, this means you can do something close to what the question is asking for:

```<code>SELECT * FROM (
  SELECT ROW_NUMBER() OVER(PARTITION BY 1) rownum, u.* FROM user u
) t
WHERE t.rownum <= (SELECT group_limit FROM groups WHERE groupid = 7471);
</code>```

This is also supported in MariaDB since 10.2.0.

Body:
Since MySQL 8.0.2, the ROW_NUMBER() window function has been supported. With the help of a subquery, this means you can do something close to what the question is asking for:

SELECT * FROM (
  SELECT ROW_NUMBER() OVER(PARTITION BY 1) rownum, u.* FROM user u
) t
WHERE t.rownum <= (SELECT group_limit FROM groups WHERE groupid = 7471);

This is also supported in MariaDB since 10.2.0.