问:
how to create multiple templates in Gatsby.js
I was trying to make two template for my projects details and blog post pages, but due to my lake of experience with Graphql & Gatsby I have managed to make it work for my projects, project details and blog posts but I have a bug which I couldn't find on my blog posts article template makes it not working??

here is my .md front matter

```<code>---
title: The Kimo-Coffee
stack: HTML & CSS
slug: the-kimo-coffee
date: 2022/01/03
key: projects
thumb: ../images/thumbs/coffee.png
featuredImg: ../images/featured/coffee-banner.png
---
</code>```

and this is my blog page code (that's working fine)

```<code>import { graphql, Link } from "gatsby"
import React from "react"
import Layout from "../../components/Layout"
import * as styles from "../../styles/blog.module.css"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

const posts = ({ data }) => {
  const posts = data.articles.nodes
  return (
    <Layout>
      <div className={styles.blog}>
        <h2>Blog Posts</h2>

        {posts.map(post => (
          <Link to={"/blog/" + post.frontmatter.slug} key={post.id}>
            <div className={styles.posts}>
              <GatsbyImage
                image={getImage(post.frontmatter.thumb)}
                alt={post.frontmatter.title}
              />
              <h3 className={styles.title}>{post.frontmatter.title}</h3>
              <p className={styles.date}>{post.frontmatter.date}</p>
              <p className={styles.stack}>{post.frontmatter.stack}</p>
              <p className={styles.description}>
                {post.frontmatter.description}
              </p>
            </div>
          </Link>
        ))}
      </div>
    </Layout>
  )
}

export default posts

export const query = graphql`
  query BlogPosts {
    articles: allMdx(
      filter: { frontmatter: { key: { eq: "article" } } }
      sort: { fields: frontmatter___date, order: DESC }
    ) {
      nodes {
        excerpt
        slug
        frontmatter {
          key
          date
          title
          stack
          description
          thumb {
            childImageSharp {
              gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
            }
          }
        }
        id
      }
    }
  }
`

</code>```

here is my blog post details (which is not working)

```<code>import React from "react"
import { graphql, Link } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import Layout from "../components/Layout"
import * as styles from "../styles/blog-details.module.css"

const blogPosts = ({ data, pageContext }) => {
  const { body } = data.article
  const { title, date, stack, featuredImg } = data.article.frontmatter
  const { previous, next } = pageContext

  return (
    <Layout>
      <div className={styles.details}>
        <h2>{title}</h2>
        <p>{date}</p>
        <p>{stack}</p>
        <div className={styles.featured}>
          <GatsbyImage
            image={getImage(featuredImg.childImageSharp.gatsbyImageData)}
            alt={title}
          />
        </div>
        <article className={styles.body}>
          <MDXRenderer>{body}</MDXRenderer>
        </article>
        <React.Fragment>
          {previous && (
            <Link to={previous.frontmatter.slug}>
              <button>{previous.frontmatter.title}</button>
            </Link>
          )}
        </React.Fragment>
        <React.Fragment>
          {next && (
            <Link to={next.frontmatter.slug}>
              <button>{next.frontmatter.title}</button>
            </Link>
          )}
        </React.Fragment>
      </div>
    </Layout>
  )
}

export default blogPosts

export const query = graphql`
  query BlogDetails($slug: String) {
    article: mdx(frontmatter: { slug: { eq: $slug }, key: { eq: "article" } }) {
      body
      frontmatter {
        slug
        key
        title
        date
        stack
        featuredImg {
          childImageSharp {
            gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
          }
        }
      }
    }
  }
`
</code>```

and last this is my code for gatsby-node.js

```<code>const path = require("path")
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `Mdx`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const results1 = await graphql(`
    query content {
      allMdx(filter: { frontmatter: { key: { eq: "projects" } } }) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const results2 = await graphql(`
    query content {
      allMdx(filter: { frontmatter: { key: { eq: "article" } } }) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const projectTemplate = path.resolve(`src/templates/project-details.js`)
  const blogTemplate = path.resolve(`src/templates/blog-details.js`)
  if (results1.errors || results2.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const posts = results2.data.allMdx.nodes

  posts.forEach((post, index) => {
    const previous = index === post.length - 1 ? null : post[index + 1]
    const next = index === 0 ? null : posts[index - 1]
    createPage({
      path: `/blog/${post.frontmatter.slug}`,
      component: blogTemplate,
      context: {
        slug: post.frontmatter.slug,
        previous,
        next,
      },
    })
  })

  results1.data.allMdx.nodes.forEach(node => {
    createPage({
      path: `/projects/${node.frontmatter.slug}`,
      component: projectTemplate,
      context: { slug: node.frontmatter.slug },
    })
  })
}

</code>```

sorry if my code is ugly, I'm pretty new to programming and i started with Gatsby since it makes me feel optimistic after learning javascript and react :)

答:
There are a few things weird in your code that shouldn't be working despite your said it does.

In React, all components must be capitalized, otherwise, React will interpret them as HTML elements, and because normally a component name doesn't match an HTML tag, it will break because it won't exist.

In your case, both templates must be renamed to:

```<code>const Posts = ({ data }) => {}
</code>```

And:

```<code>const BlogPosts = ({ data, pageContext }) => {}
</code>```

The prompted error:

"There's not a page or function yet at /blog/undefined"

This means that the template is not valid because there is not a valid function template. Once capitalized, the issue should be gone.

In addition, double-check the markdowns to ensure that you have a slug field in all of them.

You can also enter to localhost:8000/404 which in development, displays a list of all generated pages. You can check there if all the posts are being created correctly. If so, the issue is in your template. Otherwise, it's in your page generation.

Your issue is in the GraphQL query of the BlogPosts, where the link to the article is not properly set. You have defined a query like:

```<code>  query BlogPosts {
    articles: allMdx(
      filter: { frontmatter: { key: { eq: "article" } } }
      sort: { fields: frontmatter___date, order: DESC }
    ) {
      nodes {
        excerpt
        slug # <-- here's the issue
        frontmatter {
          key
          date
          title
          stack
          description
          thumb {
            childImageSharp {
              gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
            }
          }
        }
        id
      }
    }
  }
</code>```

Where the slug is directly under nodes node. At the same time, you are linking the slug as it was a child of the frontmatter at:

```<code><Link to={"/blog/" + post.frontmatter.slug} key={post.id}>
</code>```

Which results in blog/undefined path. You can check the path just hovering the link and seeing where is it pointing.

Ensure where it should be the slug field according to your data structure. I'd say that it should be inside the frontmatter:

```<code>        frontmatter {
          slug # <-- add it here
          key
          date
          title
          stack
          description
          thumb {
            childImageSharp {
              gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
            }
          }
        }
</code>```

Alternatively, just change the Link structure like:

```<code><Link to={"/blog/" + post.slug} key={post.id}>
</code>```

TL:DR

Because of:

```<code>createNodeField({
  node,
  name: `slug`,
  value: slug,
})
</code>```

You are creating a slug based on the filename, which is being inserted as a node child, that's why the query was working but the references to that wasn't.

Body:
I was trying to make two template for my projects details and blog post pages, but due to my lake of experience with Graphql & Gatsby I have managed to make it work for my projects, project details and blog posts but I have a bug which I couldn't find on my blog posts article template makes it not working??

here is my .md front matter

---
title: The Kimo-Coffee
stack: HTML & CSS
slug: the-kimo-coffee
date: 2022/01/03
key: projects
thumb: ../images/thumbs/coffee.png
featuredImg: ../images/featured/coffee-banner.png
---

and this is my blog page code (that's working fine)

import { graphql, Link } from "gatsby"
import React from "react"
import Layout from "../../components/Layout"
import * as styles from "../../styles/blog.module.css"
import { GatsbyImage, getImage } from "gatsby-plugin-image"

const posts = ({ data }) => {
  const posts = data.articles.nodes
  return (
    <Layout>

Blog Posts

        {posts.map(post => (
          <Link to={"/blog/" + post.frontmatter.slug} key={post.id}>

              <GatsbyImage
                image={getImage(post.frontmatter.thumb)}
                alt={post.frontmatter.title}
              />

{post.frontmatter.title}

{post.frontmatter.date}

{post.frontmatter.stack}

                {post.frontmatter.description}

          </Link>
        ))}

    </Layout>
  )
}

export default posts

export const query = graphql`
  query BlogPosts {
    articles: allMdx(
      filter: { frontmatter: { key: { eq: "article" } } }
      sort: { fields: frontmatter___date, order: DESC }
    ) {
      nodes {
        excerpt
        slug
        frontmatter {
          key
          date
          title
          stack
          description
          thumb {
            childImageSharp {
              gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
            }
          }
        }
        id
      }
    }
  }
`

here is my blog post details (which is not working)

import React from "react"
import { graphql, Link } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import Layout from "../components/Layout"
import * as styles from "../styles/blog-details.module.css"

const blogPosts = ({ data, pageContext }) => {
  const { body } = data.article
  const { title, date, stack, featuredImg } = data.article.frontmatter
  const { previous, next } = pageContext

  return (
    <Layout>

{title}

{date}

{stack}

          <GatsbyImage
            image={getImage(featuredImg.childImageSharp.gatsbyImageData)}
            alt={title}
          />

          <MDXRenderer>{body}</MDXRenderer>

        <React.Fragment>
          {previous && (
            <Link to={previous.frontmatter.slug}>
              <button>{previous.frontmatter.title}</button>
            </Link>
          )}
        </React.Fragment>
        <React.Fragment>
          {next && (
            <Link to={next.frontmatter.slug}>
              <button>{next.frontmatter.title}</button>
            </Link>
          )}
        </React.Fragment>

    </Layout>
  )
}

export default blogPosts

export const query = graphql`
  query BlogDetails($slug: String) {
    article: mdx(frontmatter: { slug: { eq: $slug }, key: { eq: "article" } }) {
      body
      frontmatter {
        slug
        key
        title
        date
        stack
        featuredImg {
          childImageSharp {
            gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
          }
        }
      }
    }
  }
`

and last this is my code for gatsby-node.js

const path = require("path")
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `Mdx`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  const results1 = await graphql(`
    query content {
      allMdx(filter: { frontmatter: { key: { eq: "projects" } } }) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const results2 = await graphql(`
    query content {
      allMdx(filter: { frontmatter: { key: { eq: "article" } } }) {
        nodes {
          frontmatter {
            slug
            title
          }
        }
      }
    }
  `)

  const projectTemplate = path.resolve(`src/templates/project-details.js`)
  const blogTemplate = path.resolve(`src/templates/blog-details.js`)
  if (results1.errors || results2.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  const posts = results2.data.allMdx.nodes

  posts.forEach((post, index) => {
    const previous = index === post.length - 1 ? null : post[index + 1]
    const next = index === 0 ? null : posts[index - 1]
    createPage({
      path: `/blog/${post.frontmatter.slug}`,
      component: blogTemplate,
      context: {
        slug: post.frontmatter.slug,
        previous,
        next,
      },
    })
  })

  results1.data.allMdx.nodes.forEach(node => {
    createPage({
      path: `/projects/${node.frontmatter.slug}`,
      component: projectTemplate,
      context: { slug: node.frontmatter.slug },
    })
  })
}

sorry if my code is ugly, I'm pretty new to programming and i started with Gatsby since it makes me feel optimistic after learning javascript and react :)

Body:
There are a few things weird in your code that shouldn't be working despite your said it does.

In React, all components must be capitalized, otherwise, React will interpret them as HTML elements, and because normally a component name doesn't match an HTML tag, it will break because it won't exist.

In your case, both templates must be renamed to:

const Posts = ({ data }) => {}

And:

const BlogPosts = ({ data, pageContext }) => {}

The prompted error:

"There's not a page or function yet at /blog/undefined"

This means that the template is not valid because there is not a valid function template. Once capitalized, the issue should be gone.

In addition, double-check the markdowns to ensure that you have a slug field in all of them.

You can also enter to localhost:8000/404 which in development, displays a list of all generated pages. You can check there if all the posts are being created correctly. If so, the issue is in your template. Otherwise, it's in your page generation.

Your issue is in the GraphQL query of the BlogPosts, where the link to the article is not properly set. You have defined a query like:

  query BlogPosts {
    articles: allMdx(
      filter: { frontmatter: { key: { eq: "article" } } }
      sort: { fields: frontmatter___date, order: DESC }
    ) {
      nodes {
        excerpt
        slug # <-- here's the issue
        frontmatter {
          key
          date
          title
          stack
          description
          thumb {
            childImageSharp {
              gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
            }
          }
        }
        id
      }
    }
  }

Where the slug is directly under nodes node. At the same time, you are linking the slug as it was a child of the frontmatter at:

<Link to={"/blog/" + post.frontmatter.slug} key={post.id}>

Which results in blog/undefined path. You can check the path just hovering the link and seeing where is it pointing.

Ensure where it should be the slug field according to your data structure. I'd say that it should be inside the frontmatter:

        frontmatter {
          slug # <-- add it here
          key
          date
          title
          stack
          description
          thumb {
            childImageSharp {
              gatsbyImageData(placeholder: BLURRED, layout: FULL_WIDTH)
            }
          }
        }

Alternatively, just change the Link structure like:

<Link to={"/blog/" + post.slug} key={post.id}>

TL:DR

Because of:

createNodeField({
  node,
  name: `slug`,
  value: slug,
})

You are creating a slug based on the filename, which is being inserted as a node child, that's why the query was working but the references to that wasn't.


来源: stackexchange

问:
How to use Future<string> in a dataTable in flutter
i have two future methods

```<code>Future<List> getTrns(String token,int page,) async {

final response = await
http.get(Uri.parse("api1/?params" ),
    headers:{
      ....
    });
final String t = response.body;
List list =jsonDecode(t)['data'];
return list;

}

Future<String> getstate(String code,String token,DateTime now) async {
DateTime start_date = new DateTime(now.year, now.month, now.day);
 String stat='';

final response = await
http.get(Uri.parse("api2/?params" ),
   headers:{
     ...
   });
final String t = response.body;
 List l = jsonDecode(t)['data'];

if(l.length == 0){
   stat = "absent";
}else {
   stat = "present";
}

return stat;

}
</code>```

this first methode will get the list of employee while the second one will use each employee code to find their state from another api.. the two functions are working fine but displaying them in an Datatable gave me an error of

```<code> Instance of future<string>
</code>```

Only in the stat cell while other cells are working fine
here's how i built the table

```<code> body: Column( children: <Widget>[
        FutureBuilder<List>(
        future: getTrns(widget.token,widget.page),
        builder: (ctx,ss){
          if(ss.hasError){
            print("error");
          }
          if(ss.hasData){
            datalist=ss.data!;

            return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: _createDataTable(),

                )
            );
          }else {
            return Center(child: CircularProgressIndicator());
          }
        }
      ),

      MaterialButton(onPressed: () {
        widget.page = widget.page+1;
        print(widget.page);
      },
        child: Text("Next"),
        color: Colors.blue,)
       ]
       )
       )
      );
      }

  DataTable _createDataTable() {
    return DataTable(columns: _createColumns(), rows: _createRows());
  }
  List<DataColumn> _createColumns() {
    return [
      DataColumn(label: Text('ID')),
      DataColumn(label: Text('Full Name')),
      DataColumn(label: Text('State'))
    ];
  }
  List<DataRow> _createRows() {
    return datalist
        .map((list) => DataRow(cells: [
      DataCell(
          Text(list['emp_code'].toString()),
           onTap: (){
             Navigator.of(context).push(
                 MaterialPageRoute(builder: (BuildContext context)=>Details(token: w idget.token, emp:list['emp_code'].toString())
            ));
      }
 ),
 DataCell(
     Text(list['first_name'].toString()+" "+list['last_name'].toString()),
     onTap: (){
     Navigator.of(context).push(
     MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
     ));
     }
 ),
 DataCell(Text( getstate(list['emp_code'], widget.token, widget.now).toString() ),
 onTap: (){
   Navigator.of(context).push(
       MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
       ));
 }
 )
    ]))
        .toList();
  }

 }
</code>```

this is the result
table screenshot

Edit1:  new cell code cell code
the error is random, sometimes in first celland sometimes in a different one
first result
another result

答:
Try this</p>
```<code>final Map<String, dynamic> t = response.body;
list =jsonDecode(t)['data'] as Map<String, dynamic>;
return list;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have two future methods

Future<List> getTrns(String token,int page,) async {

final response = await
http.get(Uri.parse("api1/?params" ),
    headers:{
      ....
    });
final String t = response.body;
List list =jsonDecode(t)['data'];
return list;

}

Future<String> getstate(String code,String token,DateTime now) async {
DateTime start_date = new DateTime(now.year, now.month, now.day);
 String stat='';

final response = await
http.get(Uri.parse("api2/?params" ),
   headers:{
     ...
   });
final String t = response.body;
 List l = jsonDecode(t)['data'];

if(l.length == 0){
   stat = "absent";
}else {
   stat = "present";
}

return stat;

}

this first methode will get the list of employee while the second one will use each employee code to find their state from another api.. the two functions are working fine but displaying them in an Datatable gave me an error of

 Instance of future<string>

Only in the stat cell while other cells are working fine
here's how i built the table

 body: Column( children: <Widget>[
        FutureBuilder<List>(
        future: getTrns(widget.token,widget.page),
        builder: (ctx,ss){
          if(ss.hasError){
            print("error");
          }
          if(ss.hasData){
            datalist=ss.data!;

            return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: _createDataTable(),

                )
            );
          }else {
            return Center(child: CircularProgressIndicator());
          }
        }
      ),

      MaterialButton(onPressed: () {
        widget.page = widget.page+1;
        print(widget.page);
      },
        child: Text("Next"),
        color: Colors.blue,)
       ]
       )
       )
      );
      }

  DataTable _createDataTable() {
    return DataTable(columns: _createColumns(), rows: _createRows());
  }
  List<DataColumn> _createColumns() {
    return [
      DataColumn(label: Text('ID')),
      DataColumn(label: Text('Full Name')),
      DataColumn(label: Text('State'))
    ];
  }
  List<DataRow> _createRows() {
    return datalist
        .map((list) => DataRow(cells: [
      DataCell(
          Text(list['emp_code'].toString()),
           onTap: (){
             Navigator.of(context).push(
                 MaterialPageRoute(builder: (BuildContext context)=>Details(token: w idget.token, emp:list['emp_code'].toString())
            ));
      }
 ),
 DataCell(
     Text(list['first_name'].toString()+" "+list['last_name'].toString()),
     onTap: (){
     Navigator.of(context).push(
     MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
     ));
     }
 ),
 DataCell(Text( getstate(list['emp_code'], widget.token, widget.now).toString() ),
 onTap: (){
   Navigator.of(context).push(
       MaterialPageRoute(builder: (BuildContext context)=>Details(token: widget.token, emp:list['emp_code'].toString())
       ));
 }
 )
    ]))
        .toList();
  }

 }

this is the result
table screenshot

Edit1:  new cell code cell code
the error is random, sometimes in first celland sometimes in a different one
first result
another result

Body:
Try this

final Map<String, dynamic> t = response.body;
list =jsonDecode(t)['data'] as Map<String, dynamic>;
return list;


问:
How to 'narrow' onchange for specific id?
I found this cod on jquery web

```<code>$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();
</code>```

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

答:
If your select is labeled my_id than just swap

select

for

#my_id

in the two places where it occurs in the script.

ContentLicense: CC BY-SA 3.0

Body:
I found this cod on jquery web

$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.


问:
How to set custom timeout duration for captcha solving using puppeteer and recaptcha plugin
I'm using puppeteer with puppeteer-extra-plugin-recaptcha plugin. I want to set a custom timeout for 2captcha solving but I'm having a hard time.
The method I use is:

```<code>await page.solveRecaptchas()
</code>```

But I couldn't find anything timeout-related in the plugin documentation, I tried multilpe guess-kind of solutions page.setDefaultTimeout(x) , page.solveRecaptchas({timeout: x})  but none works.

Any help is much appreciated

答:
Don't use timeout with timer.
Instead check the [aria-checked] of the "checkbox" if this set to true, then continue.</p>
```<code>const frame = page.frames().find(async (frame) => await frame.title() === 'reCAPTCHA')

// You can choose between these two methods below

// Try this lines below
const checkmark = await frame.waitForSelector('#recaptcha-anchor', {visible: true})
while (await frame.evaluateHandle((checkmark) => checkmark.getAttribute('aria-checked') !== 'true', checkmark)) {
    await page.waitForTimeout(100)
}

// Or simply this lines below
await frame.waitForFunction(() => {
    return document.querySelector('#recaptcha-anchor').getAttribute('aria-checked') === 'true'
}, {timeout: 0, polling: 100})

// Then you can check
// reCaptcha solved successfully
</code>```

Body:
I'm using puppeteer with puppeteer-extra-plugin-recaptcha plugin. I want to set a custom timeout for 2captcha solving but I'm having a hard time.
The method I use is:

await page.solveRecaptchas()

But I couldn't find anything timeout-related in the plugin documentation, I tried multilpe guess-kind of solutions page.setDefaultTimeout(x) , page.solveRecaptchas({timeout: x})  but none works.

Any help is much appreciated

Body:
Don't use timeout with timer.
Instead check the [aria-checked] of the "checkbox" if this set to true, then continue.

const frame = page.frames().find(async (frame) => await frame.title() === 'reCAPTCHA')

// You can choose between these two methods below

// Try this lines below
const checkmark = await frame.waitForSelector('#recaptcha-anchor', {visible: true})
while (await frame.evaluateHandle((checkmark) => checkmark.getAttribute('aria-checked') !== 'true', checkmark)) {
    await page.waitForTimeout(100)
}

// Or simply this lines below
await frame.waitForFunction(() => {
    return document.querySelector('#recaptcha-anchor').getAttribute('aria-checked') === 'true'
}, {timeout: 0, polling: 100})

// Then you can check
// reCaptcha solved successfully


问:
React materil-ui/mui data-grid-pro with muliple select in filter definition
See this codesandbox

i tried to add a custom filter operator "oneOf" to the filter on my data-grid based on the example for "between" searches in the mui data-grid doc.

This should allow the user to select multiple values of a "singleSelect" column and filter base on a JS includes() filter.

Using the "or" and chaining multiple rows of filters for the same column would block using an "and" filter for a different column, as the "and"/"or" only works for all filters.
Which is not wanted...

Works somewhat if using native select, with multiple, but then the select options are always shown and doesn't fit in the row of the filter popup for that column.

If using "MenuItem" and mui Select the filter popup and the Select closes as soon as the Select Options are shown.
i assume because of lost "focus" of the filter popup.

The single select works using a TextInput with prop "select", so i assume there the focus remains on the input, even if the select option are shown.

How can i fix this?

Best solution would be to use mui Select and stop the filter popup of closing if the Select is open.

答:
Found one more solution, using Autocompleter as this is an input filed.
Needs some hacks, but see code and the updated sandbox
The filter box is limited in space, and changing that is ugly, see the sass file in the sandbox.

When using the disablePortal mention in comments i have the issue that the drop down is somewhere and i cant place it below the input, and just floating around looks not nice...

PS: i'm still on v4 and sandbox is v5 so the valueOptions are not copied right now in the sandbox...

/**
 * A DataGrid operator to filter a "singleSelect" column by multiple values.
 *
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
function OneOfValues(props) {
  const {item, applyValue, type, apiRef, focusElementRef, ...others} = props;
  const filterTimeout = React.useRef();
  const [inputValue, setInputValue] = useState('');
  const [applying, setIsApplying] = React.useState(false);
  const [options, setOptions] = React.useState([]);
  const [completerState, setCompleterState] = React.useState([]);

  const icon = <CheckBoxOutlineBlankIcon fontSize='small' />;
  const checkedIcon = <CheckBoxIcon fontSize='small' />;

  useEffect(() => {
    setOptions(renderAutoCompleteOptions(apiRef.current.getColumn(item.columnField), apiRef.current).filter((v) => !!v.value));
    return () => {
      clearTimeout(filterTimeout.current);
    };
  }, []);

  const updateFilterValue = (values) => {
    setIsApplying(true);
    applyValue({...item, value: values});
    setIsApplying(false);
  };

  const handleAutoFilterChange = (event, selected) => {
    console.debug('handleAutoFilterChange', selected);
    setCompleterState(selected);
    updateFilterValue(selected.map((o) => o.value));
  };

  const renderAutoCompleteOptions = ({valueOptions, valueFormatter, field}, api) => {
    const iterableColumnValues = typeof valueOptions === 'function' ? ['', ...valueOptions({field})] : ['', ...(valueOptions || [])];
    return iterableColumnValues.map((option) =>
      typeof option === 'object'
        ? {label: option.label, value: option.value}
        : {label: valueFormatter && option !== '' ? valueFormatter({value: option, field, api}) : option, value: option}
    );
  };

  const convertListToOptions = (values, options) => {
    console.debug('huhu', values, options);
    if (!values || !Array.isArray(values)) return [];
    const selected = options.filter((o) => values.includes(o.value));
    console.log('convertListToOptions', values, options, selected);
    return selected;
  };

  React.useEffect(() => {
    const itemValue = item.value ?? [];
    const options = renderAutoCompleteOptions(apiRef.current.getColumn(item.columnField), apiRef.current).filter((v) => !!v.value);
    const state = convertListToOptions(itemValue, options);
    console.log('useEffect', item.value, state);
    setCompleterState(state);
  }, [apiRef, item.columnField, item.value]);
  console.log('completerState', completerState);

  return (
    <Box
      style={{
        display: 'inline-flex',
        flexDirection: 'row',
        alignItems: 'end',
        height: 48,
        pl: '20px',
      }}
    >
      <Autocomplete
        id={`filter-value-autocomplete-${item.columnField}`}
        multiple
        disableCloseOnSelect
        size='small'
        limitTags={3}
        value={completerState}
        inputValue={inputValue}
        options={options}
        getOptionLabel={(option) => option.label}
        getOptionSelected={(option, value) => option.value === value.value}
        onChange={handleAutoFilterChange}
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
        }}
        renderOption={(option, {selected}) => (
          <>
            <Checkbox icon={icon} checkedIcon={checkedIcon} style={{marginRight: 8}} checked={selected} />
            {option.label}
          </>
        )}
        renderTags={(tagValue, getTagProps) =>
          <Chip size='small' label={tagValue.length + " selected"}  key={1} />
        }
        renderInput={(params) => (
          <TextField
            {...params}
            // InputProps={applying ? {endAdornment: <SyncIcon />} : null}
            inputRef={focusElementRef}
            variant='standard'
            label='Values'
          />
        )}
        style={{minWidth: '190px', width: '100%', display: 'inline-flex', flexDirection: 'row', alignItems: 'end', height: 48, pl: '20px'}}
      />
    </Box>
  );
}

OneOfValues.propTypes = {
  apiRef: PropTypes.any.isRequired,
  applyValue: PropTypes.func.isRequired,
  focusElementRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({
      current: PropTypes.any.isRequired,
    }),
  ]),
  item: PropTypes.shape({
    /**
     * The column from which we want to filter the rows.
     */
    columnField: PropTypes.string.isRequired,
    /**
     * Must be unique.
     * Only useful when the model contains several items.
     */ id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    /**
     * The name of the operator we want to apply.
     */ operatorValue: PropTypes.string,
    /**
     * The filtering value.
     * The operator filtering function will decide for each row if the row values is correct compared to this value.
     */ value: PropTypes.any,
  }).isRequired,
};

export const oneOfOperator = [
  {
    label: 'one of',
    value: 'oneOf',
    getApplyFilterFn: (filterItem) => {
      if (!Array.isArray(filterItem.value) || filterItem.value.length !== 2) {
        return null;
      }
      if (Array.isArray(filterItem.value) && filterItem.value.length > 0) {
        return null;
      }
      return ({value}) => {
        return value !== null && filterItem.value.includes(value);
      };
    },
    InputComponent: OneOfValues,
  },
  ...getGridStringOperators(),
];
```


问:
PHP/Laravel - find and read 'key-value pair' from file
I want to store some text informations but I don't want to use database for this. For example there is a file:

```<code>key1: some text information 1
key2: some text information 2
key3: another text information
</code>```

I was wondering, what is the shortest way to find one specific value form this file using PHP or Laravel?

I could use foreach(file('yourfile.txt') as $line) {} loop to store text lines into array and then find the line with specific key, but maybe there is shorter or nicer way to do this.

答:
You can use the function parse_ini_file

It reads a file of name/value pairs into an array so they can be easily accessed, e.g:

```<code>$ini = parse_ini_file("data.ini");
$value = $ini['key1'];
</code>```

data.ini can look like this:

```<code>; This is a comment
key1=value1
</code>```

Body:
I want to store some text informations but I don't want to use database for this. For example there is a file:

key1: some text information 1
key2: some text information 2
key3: another text information

I was wondering, what is the shortest way to find one specific value form this file using PHP or Laravel?

I could use foreach(file('yourfile.txt') as $line) {} loop to store text lines into array and then find the line with specific key, but maybe there is shorter or nicer way to do this.

Body:
You can use the function parse_ini_file

It reads a file of name/value pairs into an array so they can be easily accessed, e.g:

$ini = parse_ini_file("data.ini");
$value = $ini['key1'];

data.ini can look like this:

; This is a comment
key1=value1


问:
Why am I getting an error with this multidimensional array?
I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?

```<code>var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);
</code>```

Yet, this code does not work.

```<code>var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);
</code>```

It also works with occupied[0][0]. Just not anything above 1.

答:
occupied[1][0] = 0; works because the length of occupied is 2. occupied[1] will access the second node, which is an empty array occupied[1][0] = 0; this will assign 0 to the first element of the second node of occupied array.

var occupied = [
  [], // Index 0
  [], // Index 1 => occupied[1][0] will access the first item of empty array in this location
];
occupied[1][0] = 0;
console.log(occupied[1][0]);
console.log(occupied);```
</div>
</div>
</p>
<p><code>occupied[2][0] = 0;</code> this will not work. works because the length of <code>occupied</code> is 2. <code>occupied[2]</code> will try to access the third node <code>occupied</code> array, which donot exist. In this case <code>occupied[2]</code> is undefined. <code>occupied[2][0] = 0;</code> will try to set 0 to zeroth index of an undefined variable, this will throw a refrence errror like</p>
```Uncaught TypeError: Cannot set properties of undefined (setting '0')
```

Body:
I'm still new to Javascript and trying to understand multi-dimensional arrays. Why does the following code work?

var occupied = [[],[]];
occupied[1][0] = 0;
console.log(occupied[1][0]);

Yet, this code does not work.

var occupied = [[],[]];
occupied[2][0] = 0;
console.log(occupied[2][0]);

It also works with occupied[0][0]. Just not anything above 1.

Body:
occupied[1][0] = 0; works because the length of occupied is 2. occupied[1] will access the second node, which is an empty array occupied[1][0] = 0; this will assign 0 to the first element of the second node of occupied array.

var occupied = [
  [], // Index 0
  [], // Index 1 => occupied[1][0] will access the first item of empty array in this location
];
occupied[1][0] = 0;
console.log(occupied[1][0]);
console.log(occupied);

occupied[2][0] = 0; this will not work. works because the length of occupied is 2. occupied[2] will try to access the third node occupied array, which donot exist. In this case occupied[2] is undefined. occupied[2][0] = 0; will try to set 0 to zeroth index of an undefined variable, this will throw a refrence errror like

Uncaught TypeError: Cannot set properties of undefined (setting '0')


问:
How to apply if condition for WPF Project in XAML?
I have TreeView and TreeViewItems. TreeViewItems contain Tags either "type", "class", "subclass", or a Guid in the form "0202-7252-4a4a...".

What I am currently doing is that I am displaying the Tag and Header of those TreeViewItems on the screen with the following code.

(Please do not consider how I am creating the TreeViewItems, it is not relevant for my case)

<TreeView x:Name="treeView"/>

<TextBlock>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>
```
<p>I don't want to write the <code>Tag</code> of a <code>TreeViewItem</code> whose tag is <code>Guid</code> because it doesn't seem pretty in the screen. I want to add an if condition to this code as follows:</p>
```if (TreeViewItem.Tag == "type" or "class" or "subclass")
    write tag and header to screen
else do nothing
```
<p>OR</p>
```if (TreeViewItem.Tag is Guid) then do nothing
```

答:
You can use a Converter for this type of issues.
With this methodology we can manipulate the TreeViewItemsin such a way that "GUID" is not displayed in UI at the end.

1. Create a new Converter Class

During the generation of TreeViewItems it will hit this converter.

This class is implementing the IValueConverter interface. The Convert method will be used from XAML to convert the respectively bound object at runtime.

In the Convert Method you can add your specified if conditions you mentioned in your question.

Something like this should work:

```<code>public class MyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //Some condition to extract only "type", "class" or "subclass" from the tag property of TreeViewItem
            if (value.GetType() == typeof(Guid))
                return "";
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
</code>```

2. Add the Converter to the respectively tag

First of all you need to add the namespace of the Converter Class to the XAML as a resource.

Read more about this here https://stackoverflow.com/a/34351786/17604152

Adding converter as a resource:

```<code><Window x:Class="MyNameSpace.MainWindow"
....
        xmlns:conv="clr-namespace:MyNameSpace.Converter"
>
......
......

    <Window.Resources>
       <conv:MyConverter x:Key="myConverter"/>
    </Window.Resources>

</code>```

Then you can

```<code><TextBlock>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Tag, Converter={conv:myConverter}}"/>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>
</code>```

Body:
I have TreeView and TreeViewItems. TreeViewItems contain Tags either "type", "class", "subclass", or a Guid in the form "0202-7252-4a4a...".

What I am currently doing is that I am displaying the Tag and Header of those TreeViewItems on the screen with the following code.

(Please do not consider how I am creating the TreeViewItems, it is not relevant for my case)

<TreeView x:Name="treeView"/>

<TextBlock>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Tag}"/>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>

I don't want to write the Tag of a TreeViewItem whose tag is Guid because it doesn't seem pretty in the screen. I want to add an if condition to this code as follows:

if (TreeViewItem.Tag == "type" or "class" or "subclass")
    write tag and header to screen
else do nothing

OR

if (TreeViewItem.Tag is Guid) then do nothing

Body:
You can use a Converter for this type of issues.
With this methodology we can manipulate the TreeViewItemsin such a way that "GUID" is not displayed in UI at the end.

1. Create a new Converter Class

During the generation of TreeViewItems it will hit this converter.

This class is implementing the IValueConverter interface. The Convert method will be used from XAML to convert the respectively bound object at runtime.

In the Convert Method you can add your specified if conditions you mentioned in your question.

Something like this should work:

public class MyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //Some condition to extract only "type", "class" or "subclass" from the tag property of TreeViewItem
            if (value.GetType() == typeof(Guid))
                return "";
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

2. Add the Converter to the respectively tag

First of all you need to add the namespace of the Converter Class to the XAML as a resource.

Read more about this here https://stackoverflow.com/a/34351786/17604152

Adding converter as a resource:

<Window x:Class="MyNameSpace.MainWindow"
....
        xmlns:conv="clr-namespace:MyNameSpace.Converter"
>
......
......

    <Window.Resources>
       <conv:MyConverter x:Key="myConverter"/>
    </Window.Resources>

Then you can

<TextBlock>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Tag, Converter={conv:myConverter}}"/>
    <Run text="{Binding ElementName=treeView, Path=SelectedItem.Header}"/>
</TextBlock>


问:
How can I make a cell reference a function of a variable?
I will be using the same macro 24 times, but the ranges will differ (but at a constant rate) every time. Therefore I thought it would be smart to write the references as a function in order to reduce the length of the code, and also make it easier to change.

Now it looks like this:

```<code>    Sheets("Planned time").Select
    Range("I15:NJ32").Select
    Selection.Copy
    Sheets("Diff").Select
    Range("I9").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
</code>```

But I would like it to be something like this:

```<code>    Sheets("Planned time").Select
    Range("I(15+171x):NJ(32+171x)").Select
    Selection.Copy
    Sheets("Diff").Select
    Range("I(9+56x)").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
</code>```

Where the macro loops 24 times, but for each loop, increase the value of x by 1. x would need to be 0 in the first iteration, and 23 in the last one (totalling 24 iterations).

I know the coding is probably far off, but I think it illustrates what I want to accomplish in a good way.

Any assistance would be greatly appreciated.

UPDATE:
Solved

```<code>Dim x As Integer

For x = 0 To 23

Sheets("Planned time").Select

Range("I" & cstr(15+171*x) & ":NJ" & cstr(32+171*x)).Select

Selection.Copy

Sheets("Diff").Select

Range("I" & cstr(9+56*x)).Select

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _

:=False, Transpose:=False

Next x
</code>```

答:
You want to build a string expression that, when evaluated in VBA, will be a valid address:

```<code>Range("I" & cstr(15+171*x) & ":NJ" & cstr(32+171*x)).Select
</code>```

I assume you know how to build a FOR loop.

You can also 'build' range references by using numeric cell(row, column) expressions:

```<code>Range(cell(15+171*x,10),cell(32+171*x,374)).select
</code>```

Body:
I will be using the same macro 24 times, but the ranges will differ (but at a constant rate) every time. Therefore I thought it would be smart to write the references as a function in order to reduce the length of the code, and also make it easier to change.

Now it looks like this:

    Sheets("Planned time").Select
    Range("I15:NJ32").Select
    Selection.Copy
    Sheets("Diff").Select
    Range("I9").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

But I would like it to be something like this:

    Sheets("Planned time").Select
    Range("I(15+171x):NJ(32+171x)").Select
    Selection.Copy
    Sheets("Diff").Select
    Range("I(9+56x)").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

Where the macro loops 24 times, but for each loop, increase the value of x by 1. x would need to be 0 in the first iteration, and 23 in the last one (totalling 24 iterations).

I know the coding is probably far off, but I think it illustrates what I want to accomplish in a good way.

Any assistance would be greatly appreciated.

UPDATE:
Solved

Dim x As Integer

For x = 0 To 23

Sheets("Planned time").Select

Range("I" & cstr(15+171*x) & ":NJ" & cstr(32+171*x)).Select

Selection.Copy

Sheets("Diff").Select

Range("I" & cstr(9+56*x)).Select

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _

:=False, Transpose:=False

Next x

Body:
You want to build a string expression that, when evaluated in VBA, will be a valid address:

Range("I" & cstr(15+171*x) & ":NJ" & cstr(32+171*x)).Select

I assume you know how to build a FOR loop.

You can also 'build' range references by using numeric cell(row, column) expressions:

Range(cell(15+171*x,10),cell(32+171*x,374)).select


问:
NATS request-reply with multitenancy
I am using NATS request-reply fine but I am planning to add multitenancy with accounts. Do I need extra configuration for the replyTo inbox? For example

Tenant A:
listens on rpc.method. This subject is exported as a service to Tenant B.

Tenant B:
initiates a req-reply to rpc.method specifying a replyChannel. Usually this looks like _INBOX.xxxxx.

So, when a subscriber that lives in Tenant A wants to send the response back, will the requestor in Tenant B receive it, given that _INBOX.xxxxx is not exported to Tenant B

答:
Thanks @tbeets!.

I created a simple setup to test the full setup. Imagine two accounts server and client and an exported service called rpc.

Here is what happens:

The client imports the rpc service and does the usual req-rep. It advertises a regular _INBOX.xxx replyTo subject.

However the server, being a different account/tenant, receives the message with the replyTo overwritten to _R_.yyyy. The server replies to _R_.yyy but the client still receives its response on the original topic _IBOX.xxx.

That's pretty slick!

The only change needed is to let the server publish to _R_.> (--allow-pub '_R_.>')

Title: NATS request-reply with multitenancy


问:
Move columns to the right in Pandas
I have dataset:

Stop_ID
On_Demand
Tarif
Heading

1
T100
Station

2
DYes
T101
Gym

3
T101
River

I want to have:

Stop_ID
On_Demand
Tarif
Heading

1
DNo
T100
Station

2
DYes
T101
Gym

3
DNo
T101
River

I tried:

```<code>for index, row in sm.iterrows():
    if not row["On_Demand"].startswith("D"):
        sm.loc[index, "Tarif":] = row["On_Demand":]
        sm.loc[index, "On_Demand"] = "DNo"
</code>```

but it doesnt bring any result. Any idea how can I achieve it?

答:
Use DataFrame.shift with axis=1 only filtered rows by inverted mask by ~ and then set column On_Demand by same mask:

```<code>m = df["On_Demand"].str.startswith("D")

df.loc[~m, "On_Demand":] = df.loc[~m, "On_Demand":].shift(axis=1)
df.loc[~m, "On_Demand"] = "DNo"

print (df)
   Stop_ID On_Demand Tarif  Heading
0        1       DNo  T100  Station
1        2      DYes  T101      Gym
2        3       DNo  T101    River
</code>```

Title: Move columns to the right in Pandas

Body:
I have dataset:

Stop_ID
On_Demand
Tarif
Heading

1
T100
Station

2
DYes
T101
Gym

3
T101
River

I want to have:

Stop_ID
On_Demand
Tarif
Heading

1
DNo
T100
Station

2
DYes
T101
Gym

3
DNo
T101
River

I tried:

for index, row in sm.iterrows():
    if not row["On_Demand"].startswith("D"):
        sm.loc[index, "Tarif":] = row["On_Demand":]
        sm.loc[index, "On_Demand"] = "DNo"

but it doesnt bring any result. Any idea how can I achieve it?

Body:
Use DataFrame.shift with axis=1 only filtered rows by inverted mask by ~ and then set column On_Demand by same mask:

m = df["On_Demand"].str.startswith("D")

df.loc[~m, "On_Demand":] = df.loc[~m, "On_Demand":].shift(axis=1)
df.loc[~m, "On_Demand"] = "DNo"

print (df)
   Stop_ID On_Demand Tarif  Heading
0        1       DNo  T100  Station
1        2      DYes  T101      Gym
2        3       DNo  T101    River


答:
That works fine for select#my_id:

http://jsfiddle.net/ambiguous/wAU5w/

Did you use select #my_id (note the space) my mistake?

The select#my_id selector matches the <select id="my_id"> element, the select #my_id matches anything with and id="my_id" that is a child of a <select>.

Title: How to 'narrow' onchange for specific id?


问:
Replace same occurrence of word with different words using sed
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

```<code>mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>
</code>```

required output will be

```<code>mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123
</code>```

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

答:
I'm sure it's not impossible, but also that you will not be able to figure out how it works once you find an answer. A better solution is to switch to a language which is more human-readable, so you can understand what it does.

```<code>awk 'BEGIN { split("localhost:password123", items, ":") }
    /<<CHANGE_ME>>/ { sub(/<<CHANGE_ME>>/, items[++i]) } 1' input_file >output_file
</code>```

The BEGIN block creates an array items of replacements. The main script then increments i every time we perform a replacement, indexing further into items for the replacement string.

Body:
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>

required output will be

mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

Body:
I'm sure it's not impossible, but also that you will not be able to figure out how it works once you find an answer. A better solution is to switch to a language which is more human-readable, so you can understand what it does.

awk 'BEGIN { split("localhost:password123", items, ":") }
    /<<CHANGE_ME>>/ { sub(/<<CHANGE_ME>>/, items[++i]) } 1' input_file >output_file

The BEGIN block creates an array items of replacements. The main script then increments i every time we perform a replacement, indexing further into items for the replacement string.


问:
If, if else, else doesn't work in cypress
I have the following code, but block with else if doesn't work,
how can I change this code, to make the if else block work?</p>
```<code>cy.get('#cards-list').then((list) => {
    const valueFormList = list.find(`a:contains('${nameForSite}')`)
    const nextArrow = list.find(`li.pagination-next`)
    if (valueFormList.length > 0 && nextArrow.length > 0){
        cy.get(`a:contains('${nameForSite}')`).as('card')
    } else if (valueFormList.length < 0 && nextArrow.length > 0) {
        cy.get('li.pagination-next').click()
        cy.wait(200)
        cy.findCardOnFacebook(nameForSite)
    } else {
        cy.get('h4.learning-opportunities-title').should('contain', 'Learning')
    }
})
</code>```

答:
The error is because of the condition valueFormList.length < 0. The length can never be less than 0. Either it can be zero or more than zero.

cy.get('#cards-list').then((list) => {
  const valueFormList = list.find(`a:contains('${nameForSite}')`)
  const nextArrow = list.find(`li.pagination-next`)

  if (valueFormList.length == 0 && nextArrow.length > 0) {
    cy.get('li.pagination-next').click()
    cy.wait(200)
    cy.findCardOnFacebook(nameForSite)
  } else if (valueFormList.length > 0 && nextArrow.length > 0) {
    cy.get(`a:contains('${nameForSite}')`).as('card')
  } else {
    cy.get('h4.learning-opportunities-title').should('contain', 'Learning')
  }
})
```

Body:
I have the following code, but block with else if doesn't work,
how can I change this code, to make the if else block work?

cy.get('#cards-list').then((list) => {
    const valueFormList = list.find(`a:contains('${nameForSite}')`)
    const nextArrow = list.find(`li.pagination-next`)
    if (valueFormList.length > 0 && nextArrow.length > 0){
        cy.get(`a:contains('${nameForSite}')`).as('card')
    } else if (valueFormList.length < 0 && nextArrow.length > 0) {
        cy.get('li.pagination-next').click()
        cy.wait(200)
        cy.findCardOnFacebook(nameForSite)
    } else {
        cy.get('h4.learning-opportunities-title').should('contain', 'Learning')
    }
})


问:
Gravity/Physics not working in Unity game
I am following Brackey's tutorial on how to create a simple 3D game in Unity (https://www.youtube.com/watch?v=D4I0I3QJAvc&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6&index=8&ab_channel=Brackeys) however I can't seem to get the physics/gravity (rigid body?) to work properly. It was previously working on my main character (the cube) until I added in more grey cubes to be obstacles in a level. All gravity stopped and everything now begins to float into the air when the play button is pressed.

^Player is selected so you can see rigid body settings.

New Behaviour 2 script:

```<code>using UnityEngine;

public class NewBehaviour2 : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sidewaysForce = 500f;
    // Start is called before the first frame update

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if (Input.GetKey("d"))
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
    }
}

</code>```

FollowPlayer script:

```<code>using UnityEngine;

public class FollowPlayer : MonoBehaviour
{

    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position + offset;
    }
}

</code>```

Player Collision script:

```<code>
using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public NewBehaviour2 movement;
    void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;
        }

    }

}

</code>```

Please let me know if you need any more photos. Thank you.

答:
You should use TriggerCollider for the grey boxes (just check the trigger option on the collider component), as they don't need gravity and they only trigger an action (Game Over I suppose). Then the script of the grey box should be changed to:</p>
```<code>using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public NewBehaviour2 movement;
    void OnTriggerEnter (Collider collisionInfo)
    {
        if (collisionInfo.tag == "Obstacle")
        {
            movement.enabled = false;
        }

    }

}
</code>```

Body:
I am following Brackey's tutorial on how to create a simple 3D game in Unity (https://www.youtube.com/watch?v=D4I0I3QJAvc&list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6&index=8&ab_channel=Brackeys) however I can't seem to get the physics/gravity (rigid body?) to work properly. It was previously working on my main character (the cube) until I added in more grey cubes to be obstacles in a level. All gravity stopped and everything now begins to float into the air when the play button is pressed.

^Player is selected so you can see rigid body settings.

New Behaviour 2 script:

using UnityEngine;

public class NewBehaviour2 : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce = 2000f;
    public float sidewaysForce = 500f;
    // Start is called before the first frame update

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if (Input.GetKey("d"))
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
    }
}

FollowPlayer script:

using UnityEngine;

public class FollowPlayer : MonoBehaviour
{

    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position + offset;
    }
}

Player Collision script:

using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public NewBehaviour2 movement;
    void OnCollisionEnter (Collision collisionInfo)
    {
        if (collisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;
        }

    }

}

Please let me know if you need any more photos. Thank you.

Body:
You should use TriggerCollider for the grey boxes (just check the trigger option on the collider component), as they don't need gravity and they only trigger an action (Game Over I suppose). Then the script of the grey box should be changed to:

using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
    public NewBehaviour2 movement;
    void OnTriggerEnter (Collider collisionInfo)
    {
        if (collisionInfo.tag == "Obstacle")
        {
            movement.enabled = false;
        }

    }

}


问:
nifi asking for signin after installation

after running nifi i'm facing signin issue as unauthorized. in commandline it is saying failed to determine the process. can some one please help with the installation

答:
It looks like you are trying to use NiFi 1.6.0 - this is from April 2018.

Please consider using NiFi 1.15.3 which is the latest release and includes the work for the recent log4j vulnerability.

With 1.15.3, security is enabled by default, which includes TLS and authentication.

When you start NiFi, you will instead access https://localhost:8443 and be presented with a proper login form. The Username/Password of an initial admin user will be printed into the nifi-app.log as:

```<code>Generated Username [USERNAME]
Generated Password [PASSWORD]
</code>```

Body:
It looks like you are trying to use NiFi 1.6.0 - this is from April 2018.

Please consider using NiFi 1.15.3 which is the latest release and includes the work for the recent log4j vulnerability.

With 1.15.3, security is enabled by default, which includes TLS and authentication.

When you start NiFi, you will instead access https://localhost:8443 and be presented with a proper login form. The Username/Password of an initial admin user will be printed into the nifi-app.log as:

Generated Username [USERNAME]
Generated Password [PASSWORD]


问:
Linear gradient split in 2?
Scenario

I'm trying to make a linear-gradient of one body, but it is split in 2?
Im confused..

CSS:

```<code>/* Custom properties */
body {
    background: linear-gradient(rgb(53, 53, 255), rgb(248, 117, 139));

}
</code>```

HTML (removed a bits of code, to make it neater)

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="index.css">

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

答:
As CBroe says, define a height for the body:

body {
  background: linear-gradient(rgb(53, 53, 255), rgb(248, 117, 139));
  height: 100vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
</body></code>```

Title: Linear gradient split in 2?

Body:
Scenario

I'm trying to make a linear-gradient of one body, but it is split in 2?
Im confused..

CSS:

/* Custom properties */
body {
    background: linear-gradient(rgb(53, 53, 255), rgb(248, 117, 139));

}

HTML (removed a bits of code, to make it neater)

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="index.css">

Body:
As CBroe says, define a height for the body:

body {
  background: linear-gradient(rgb(53, 53, 255), rgb(248, 117, 139));
  height: 100vh;
}

<body>
</body>


问:
Command CompileXIB failed with a nonzero exit code error

My project runs good in Xcode 11. But when I build it in Xcode 12 gets the above error. I have been struggling for a while and no answers worked for me.
Please help
Thank you

答:
It's quite an old question, but I was struggling with such issue for a few hours today and in my case it was related to the version of the tools that is declared in xib's document structure. To fix it, take a toolsVersion value from any newly created xib file (either in your current project, or a new one), then open failing xib with any code editor (or view its source in Xcode) and replace toolsVersion with the acquired one.
In my case the old version was 18122 and the valid one is 20034.


问:
Is it able to create a sub object from a parent object in Python
I want to create an object with another class object as parent. For example:

```<code>class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child()

class Child(Parent):
    def __init__(self):
        print(self.value)

obj = Parent()
</code>```

Let's say the input is 3, my expected output of print is also 3. But the actual output of above code is 0. The point is that, I want the sub class to inherit the self object of Parent. Not only inheriting the method and class variable from the Parent class, but also those instance variables of an actual called and existed Parent class object.

I know that there is a way to do this, is like below:

```<code>class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self.value)

class Child(Parent):
    def __init__(self, value):
        self.value = value
        print(self.value)

obj = Parent()
</code>```

But this will be so clumsy if there is many instance variable. Also, the value is passing to Child by value, but not reference. So Child cannot get the most update instance variable value from Parent, but is what I want it to be able to implement.

Also, I know there is another way as below:

```<code>class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self)

class Child(Parent):
    def __init__(self, parent):
        self.parent = parent
        print(self.parent.value)

obj = Parent()
</code>```

But this way seems not so concise. Also, some redundant resource will be produced, for example the Parent class' variable value = 0 will be inherited but with no use(the Child class should only interest in the instance variable and method of Parent class object obj). I would like to know if there is better method to achieve my purpose.

I understand there should be somebody already ask similar question, but I don't know what's the name of this technic. Therefore, I cannot find related information and decide to ask.

答:
From your comment, I'd say you need something like this:

class Parent:
    def __init__(self):
        self.value = int(input())

class Child:
    def __init__(self, parent):
        self._parent = parent

    def print_value(self)
        print(self._parent.value)

parent = Parent()  # input a number, for example 17

child1 = Child(parent)
child1.print_value()  # print 17
child2 = Child(parent)
child2.print_value()  # print 17

parent.value = 19
child1.print_value()  # print 19
child2.print_value()  # print 19
```
<p>It is unclear what <code>call_subclass</code> would do. If you want to call something from all children of a parent, then</p>
<pre class="lang-py prettyprint-override"><code>class Parent:
    def __init__(self):
        self.value = int(input())
        self._children = list()

    def register_child(self, child):
        self._children.append(child)

    def call_children_f(self, foo):
        for child in self._children:
            child.f(foo)

class Child:
    def __init__(self, parent, x):
        self._parent = parent
        self.x = x
        self._parent.register_child(self)

    def print_value(self)
        print(self._parent.value)

    def f(self, foo):
        print(f"Parent: {self._parent.value}, foo: {foo}, x: {self.x}")

parent = Parent()  # input a number, for example 17

child1 = Child(parent, 19)
child2 = Child(parent, 23)

parent.call_children_f(29)
</code>```

This will print:

```<code>Parent: 17, foo: 29, x: 19
Parent: 17, foo: 29, x: 23
</code>```

Body:
I want to create an object with another class object as parent. For example:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child()

class Child(Parent):
    def __init__(self):
        print(self.value)

obj = Parent()

Let's say the input is 3, my expected output of print is also 3. But the actual output of above code is 0. The point is that, I want the sub class to inherit the self object of Parent. Not only inheriting the method and class variable from the Parent class, but also those instance variables of an actual called and existed Parent class object.

I know that there is a way to do this, is like below:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self.value)

class Child(Parent):
    def __init__(self, value):
        self.value = value
        print(self.value)

obj = Parent()

But this will be so clumsy if there is many instance variable. Also, the value is passing to Child by value, but not reference. So Child cannot get the most update instance variable value from Parent, but is what I want it to be able to implement.

Also, I know there is another way as below:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self)

class Child(Parent):
    def __init__(self, parent):
        self.parent = parent
        print(self.parent.value)

obj = Parent()

But this way seems not so concise. Also, some redundant resource will be produced, for example the Parent class' variable value = 0 will be inherited but with no use(the Child class should only interest in the instance variable and method of Parent class object obj). I would like to know if there is better method to achieve my purpose.

I understand there should be somebody already ask similar question, but I don't know what's the name of this technic. Therefore, I cannot find related information and decide to ask.

Body:
From your comment, I'd say you need something like this:

class Parent:
    def __init__(self):
        self.value = int(input())

class Child:
    def __init__(self, parent):
        self._parent = parent

    def print_value(self)
        print(self._parent.value)

parent = Parent()  # input a number, for example 17

child1 = Child(parent)
child1.print_value()  # print 17
child2 = Child(parent)
child2.print_value()  # print 17

parent.value = 19
child1.print_value()  # print 19
child2.print_value()  # print 19

It is unclear what call_subclass would do. If you want to call something from all children of a parent, then

class Parent:
    def __init__(self):
        self.value = int(input())
        self._children = list()

    def register_child(self, child):
        self._children.append(child)

    def call_children_f(self, foo):
        for child in self._children:
            child.f(foo)

class Child:
    def __init__(self, parent, x):
        self._parent = parent
        self.x = x
        self._parent.register_child(self)

    def print_value(self)
        print(self._parent.value)

    def f(self, foo):
        print(f"Parent: {self._parent.value}, foo: {foo}, x: {self.x}")

parent = Parent()  # input a number, for example 17

child1 = Child(parent, 19)
child2 = Child(parent, 23)

parent.call_children_f(29)

This will print:

Parent: 17, foo: 29, x: 19
Parent: 17, foo: 29, x: 23


问:
DotNetCore ILogger error parameter logger value cannot be null
I have included Serilog in my project. It works well with other controllers.

When I try to pass the logger reference to a different class(instantiated) I am facing the below error

Message = "Value cannot be null. (Parameter 'logger')"

Below is pseudo code

```<code>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Serilog;
using Serilog.AspNetCore;
using Serilog.Core;
using Serilog.Sinks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;

namespace SomeNameSpace
{
    public class EmployeeDAO : IDisposable
    {
        //DataUpload Service implements IDataUpload
        private readonly IDataUpload dataUpload;

         private readonly ILogger<EmployeeDAO> log;
        public readonly ILogger<DataUploadService> dataLogger;

        public EmployeeDAO(ILogger<EmployeeDAO> logger)
        {
            log = logger;
        }

        private void SaveData(object obj)
        {
            switch (obj.GetType().Name)
            {
                case "SaveData":
                    this.dataupload = new DataUploadService(a, b, obj, dataLogger);
    //Error thrown at above line logger is null
                    break;
                default:
                    log.LogError($"Logging Some Error");
            }
        }
        }
}
</code>```

I this to be done in a different way ?
Please provide a better way to handle this.

答:
You do need to instantiate the field public readonly ILogger<DataUploadService> datalogger; that you pass in as a parameter to the DataUploadService.

Since you inject the other private field for logger you could do the same for dataLogger.

Constructor injection:

```<code>        private readonly ILogger<EmployeeDAO> log;
        public readonly ILogger<DataUploadService> dataLogger;

        public EmployeeDAO(ILogger<EmployeeDAO> logger, ILogger<DataUploadService> dataLogger)
        {
            log = logger;
            dataLogger = dataLogger;
        }
</code>```

You will ofcourse need to register the dependency the same way as your ILogger<EmployeeDAO> logger is registrated.

Body:
I have included Serilog in my project. It works well with other controllers.

When I try to pass the logger reference to a different class(instantiated) I am facing the below error

Message = "Value cannot be null. (Parameter 'logger')"

Below is pseudo code

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Serilog;
using Serilog.AspNetCore;
using Serilog.Core;
using Serilog.Sinks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Logging;

namespace SomeNameSpace
{
    public class EmployeeDAO : IDisposable
    {
        //DataUpload Service implements IDataUpload
        private readonly IDataUpload dataUpload;

         private readonly ILogger<EmployeeDAO> log;
        public readonly ILogger<DataUploadService> dataLogger;

        public EmployeeDAO(ILogger<EmployeeDAO> logger)
        {
            log = logger;
        }

        private void SaveData(object obj)
        {
            switch (obj.GetType().Name)
            {
                case "SaveData":
                    this.dataupload = new DataUploadService(a, b, obj, dataLogger);
    //Error thrown at above line logger is null
                    break;
                default:
                    log.LogError($"Logging Some Error");
            }
        }
        }
}

I this to be done in a different way ?
Please provide a better way to handle this.

Body:
You do need to instantiate the field public readonly ILogger<DataUploadService> datalogger; that you pass in as a parameter to the DataUploadService.

Since you inject the other private field for logger you could do the same for dataLogger.

Constructor injection:

        private readonly ILogger<EmployeeDAO> log;
        public readonly ILogger<DataUploadService> dataLogger;

        public EmployeeDAO(ILogger<EmployeeDAO> logger, ILogger<DataUploadService> dataLogger)
        {
            log = logger;
            dataLogger = dataLogger;
        }

You will ofcourse need to register the dependency the same way as your ILogger<EmployeeDAO> logger is registrated.


问:
calculated date & time column, sharepoint 2007
With the following formula in my calculated column which formats the date & time column:

```<code>=TEXT(DatePublished,"d/m/yyyy")
</code>```

How may i make sure the other dates are disabled when users create a custom list item, ie. users have actually no option to select any other dates?

Or maybe disable the calendar when they click on the calendar icon?

A workaround or am i missing out a lot?

答:
oh my, sorry. I missed out something big, could have used the already available 'Created' field. Then create another calculated column 'DatePublished' with formula:</p>

```<code>=TEXT(Created,"dd/m/yyyy")
</code>```

Body:
With the following formula in my calculated column which formats the date & time column:

=TEXT(DatePublished,"d/m/yyyy")

How may i make sure the other dates are disabled when users create a custom list item, ie. users have actually no option to select any other dates?

Or maybe disable the calendar when they click on the calendar icon?

A workaround or am i missing out a lot?

Body:
oh my, sorry. I missed out something big, could have used the already available 'Created' field. Then create another calculated column 'DatePublished' with formula:

=TEXT(Created,"dd/m/yyyy")


问:
JWT with invalid format
when checking the token on https://jwt.io/ I get Warning: Looks like your JWT signature is not encoded correctly using base64url (https://www.rfc-editor.org/rfc/rfc4648#section-5). Note that padding ("=") must be omitted as per https://www.rfc-editor.org/rfc/rfc7515#section-2

"~" Or "=" should be omitted

@GetAction("login")
@ResponseContentType(H.MediaType.JSON)
public Result login(User user,ActionContext context){
     context.login("admin");
     return jwt();
}
```
<p>return</p>
<pre class="lang-json prettyprint-override"><code>{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpc3N1ZXIiLCJleHAiOjE1NjgzOTAyMjMsImp0aSI6IjY5MDNhZjAwLWE1NGUtNGVkYi1iMjc2LWEwNWZmN2IzZTQ3MyIsInVzZXJuYW1lIjoiYWRtaW4ifQ~~.SFzY3N974wQaP-_x_YxMr4-Nk1k5-TfOl-So_ZB424vl1p5yQ5-wfQhErDmdoVOFL2iRp0G2U_-Igi9Pu6GEWg~~"
}
</code>```

答: My problem was that I pasted the token with "" when i omitted them the error went away.</p>

Title: JWT with invalid format

Body:
when checking the token on https://jwt.io/ I get Warning: Looks like your JWT signature is not encoded correctly using base64url (https://www.rfc-editor.org/rfc/rfc4648#section-5). Note that padding ("=") must be omitted as per https://www.rfc-editor.org/rfc/rfc7515#section-2

"~" Or "=" should be omitted

@GetAction("login")
@ResponseContentType(H.MediaType.JSON)
public Result login(User user,ActionContext context){
     context.login("admin");
     return jwt();
}

return

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpc3N1ZXIiLCJleHAiOjE1NjgzOTAyMjMsImp0aSI6IjY5MDNhZjAwLWE1NGUtNGVkYi1iMjc2LWEwNWZmN2IzZTQ3MyIsInVzZXJuYW1lIjoiYWRtaW4ifQ~~.SFzY3N974wQaP-_x_YxMr4-Nk1k5-TfOl-So_ZB424vl1p5yQ5-wfQhErDmdoVOFL2iRp0G2U_-Igi9Pu6GEWg~~"
}


问:
how to make the GPS function work normally when the app is running in the background
I'm doing a flutter project,my problem is:
how to make the GPS function work normally when the app is running in the background,i use Service,but only when the app is in the foreground can GPS get it.

this is my code:

```<code>    @Override
    public void onCreate()
    {
//
        startService();
        Log.v(tag, "GPSService Started.");
    }
</code>```
```<code>    @TargetApi(Build.VERSION_CODES.M)
    public void startService()
    {
        boolean isOpen = isOPen();
        if (isOpen) {
            initLocation();
            return;
        }
    }
</code>```
```<code>    @TargetApi(Build.VERSION_CODES.M)
    private void initLocation() {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.mainThis, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
            return;
        }

        if (network&&gps){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500,0, listener); // network locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 8, listener); // gps
        }else if(network&&!gps){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500,8, listener); // n
        }else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 8, listener); // g
        }
    }

    LocationListener listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateShow(location);
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }
        @SuppressLint("MissingPermission")
        @Override
        public void onProviderEnabled(String provider) {
            updateShow(locationManager.getLastKnownLocation(provider));
        }
        @Override
        public void onProviderDisabled(String provider) {
            updateShow(null);
        }
    };
</code>```

答:
The article below has the caption "How to fetch user location in background with Flutter".
With subtopics like this,
How to fetch a user location
How to fetch it even if the app is running in the background
The limitations of the system

https://medium.com/@pierre.sabot/how-to-fetch-user-location-in-background-with-flutter-e3494021bdf5

Body:
I'm doing a flutter project,my problem is:
how to make the GPS function work normally when the app is running in the background,i use Service,but only when the app is in the foreground can GPS get it.

this is my code:

    @Override
    public void onCreate()
    {
//
        startService();
        Log.v(tag, "GPSService Started.");
    }

    @TargetApi(Build.VERSION_CODES.M)
    public void startService()
    {
        boolean isOpen = isOPen();
        if (isOpen) {
            initLocation();
            return;
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initLocation() {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.mainThis, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
            return;
        }

        if (network&&gps){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500,0, listener); // network locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 8, listener); // gps
        }else if(network&&!gps){
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500,8, listener); // n
        }else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 8, listener); // g
        }
    }

    LocationListener listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateShow(location);
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }
        @SuppressLint("MissingPermission")
        @Override
        public void onProviderEnabled(String provider) {
            updateShow(locationManager.getLastKnownLocation(provider));
        }
        @Override
        public void onProviderDisabled(String provider) {
            updateShow(null);
        }
    };