问:
Unhandled Runtime Errors, Seo component in Gatsby
I'm learning to make Seo component in Gatsby, I wrote this code copied this method from Gatsby starter, but I have a problem of showing this error with 3 Unhandled Runtime Errors?

this is My Seo code

```<code>import * as React from "react"
import PropTypes from "prop-types"
import { Helmet } from "react-helmet"
import { useStaticQuery, graphql } from "gatsby"

const Seo = ({ description, lang, meta, title }) => {
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
            description
            social {
              twitter
            }
          }
        }
      }
    `
  )

  const metaDescription = description || site.siteMetadata.description
  const defaultTitle = site.siteMetadata?.title

  return (
    <Helmet
      htmlAttributes={{
        lang,
      }}
      title={title}
      titleTemplate={defaultTitle ? `%s | ${defaultTitle}` : null}
      meta={[
        {
          name: `description`,
          content: metaDescription,
        },
        {
          property: `og:title`,
          content: title,
        },
        {
          property: `og:description`,
          content: metaDescription,
        },
        {
          property: `og:type`,
          content: `website`,
        },
        {
          name: `twitter:card`,
          content: `summary`,
        },
        {
          name: `twitter:creator`,
          content: site.siteMetadata?.social?.twitter || ``,
        },
        {
          name: `twitter:title`,
          content: title,
        },
        {
          name: `twitter:description`,
          content: metaDescription,
        },
      ].concat(meta)}
    />
  )
}

Seo.defaultProps = {
  lang: `en`,
  meta: [],
  description: ``,
}

Seo.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.arrayOf(PropTypes.object),
  title: PropTypes.string.isRequired,
}

export default Seo

</code>```

another issue that also below snippet of this code is not reachable

```<code>    />
  )
}

Seo.defaultProps = {
  lang: `en`,
  meta: [],
  description: ``,
}

Seo.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.arrayOf(PropTypes.object),
  title: PropTypes.string.isRequired,
}

export default Seo

</code>```

here also my index.js where I tried to import Seo

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

export default function Home({ data }) {
  const siteTitle = data.site.siteMetadata.title
  const siteDescription = data.site.siteMetadata.description
  return (
    <Layout>
      <Seo title={siteTitle} description={siteDescription} />
      <section className={styles.header}>
        <div className={styles.content}>
          <h2>hello world!</h2>
          <h3>Let's turn some ideas into websites.</h3>
          <p>I'm a Freelancer Web Developer,</p>
          <p>
            Ready to help individual customers or small startups build their
            perfect Website.
          </p>
          <Link to="/projects" className={styles.btn}>
            My Projects
          </Link>
        </div>
        <div className={styles.img}>
          <StaticImage
            src="../images/header1.jpg"
            placeholder="blurred"
            layout="fullWidth"
            alt="Banner"
          />
        </div>
      </section>
    </Layout>
  )
}

export const HomeQuery = graphql`
  query HomeQuery {
    site {
      siteMetadata {
        title
        description
        social {
          twitter
        }
      }
    }
  }
`
</code>```

here as well I imported Seo

```<code>import React from "react"
import { Link } from "gatsby"
import Seo from "../Seo"
import styled from "styled-components"
import icon from "../../images/svg/logo-icon.svg"

const LogoWrap = styled.div`
  display: flex;
  color: var(--alpha-color);
  align-items: center:
  text-align: left;
  letter-spacing: 1px;
  text-transform: uppercase;
  }

  img {
    display: inline;
    margin-right: 3px;
  }
`

const Logo = () => {
  const { title } = Seo()

  return (
    <LogoWrap as={Link} to="/">
      <img src={icon} alt={title} width="40" height="30"></img>
      {title}
    </LogoWrap>
  )
}

export default Logo
</code>```

need help what I'm doing wrong!?

答:
Well, it's quite self-explanatory. In the Seo component you are destructuring the props as description, lang, meta, and title respectively at:

```<code>const Seo = ({ description, lang, meta, title })
</code>```

As is, all fields are inferred as mandatory so, the issue rises up because, in some of the uses of Seo, the description is null or undefined (check also the rest).

Check the pages where you are rendering the Seo component to check how the props are being drilled down. Ideally, it should be:

```<code><Seo description={'Some description'} lang={'Some lang'} ... />
</code>```

Note: this will differ depending on how the props are being passed.

You can bypass this by adding some default values in your destructuring like:

```<code>const Seo = ({ description = '', lang = '', meta=[], title='' })
</code>```

Adding the default values will make your Seo component to take them if no one is passed via props, avoiding the code-breaking.

Body:
I'm learning to make Seo component in Gatsby, I wrote this code copied this method from Gatsby starter, but I have a problem of showing this error with 3 Unhandled Runtime Errors?

this is My Seo code

import * as React from "react"
import PropTypes from "prop-types"
import { Helmet } from "react-helmet"
import { useStaticQuery, graphql } from "gatsby"

const Seo = ({ description, lang, meta, title }) => {
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
            description
            social {
              twitter
            }
          }
        }
      }
    `
  )

  const metaDescription = description || site.siteMetadata.description
  const defaultTitle = site.siteMetadata?.title

  return (
    <Helmet
      htmlAttributes={{
        lang,
      }}
      title={title}
      titleTemplate={defaultTitle ? `%s | ${defaultTitle}` : null}
      meta={[
        {
          name: `description`,
          content: metaDescription,
        },
        {
          property: `og:title`,
          content: title,
        },
        {
          property: `og:description`,
          content: metaDescription,
        },
        {
          property: `og:type`,
          content: `website`,
        },
        {
          name: `twitter:card`,
          content: `summary`,
        },
        {
          name: `twitter:creator`,
          content: site.siteMetadata?.social?.twitter || ``,
        },
        {
          name: `twitter:title`,
          content: title,
        },
        {
          name: `twitter:description`,
          content: metaDescription,
        },
      ].concat(meta)}
    />
  )
}

Seo.defaultProps = {
  lang: `en`,
  meta: [],
  description: ``,
}

Seo.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.arrayOf(PropTypes.object),
  title: PropTypes.string.isRequired,
}

export default Seo

another issue that also below snippet of this code is not reachable

    />
  )
}

Seo.defaultProps = {
  lang: `en`,
  meta: [],
  description: ``,
}

Seo.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.arrayOf(PropTypes.object),
  title: PropTypes.string.isRequired,
}

export default Seo

here also my index.js where I tried to import Seo

import { graphql, Link } from "gatsby"
import React from "react"
import Layout from "../components/Layout"
import * as styles from "../styles/home.module.css"
import { StaticImage } from "gatsby-plugin-image"
import Seo from "../components/Seo"

export default function Home({ data }) {
  const siteTitle = data.site.siteMetadata.title
  const siteDescription = data.site.siteMetadata.description
  return (
    <Layout>
      <Seo title={siteTitle} description={siteDescription} />

hello world!

Let's turn some ideas into websites.

I'm a Freelancer Web Developer,

            Ready to help individual customers or small startups build their
            perfect Website.

          <Link to="/projects" className={styles.btn}>
            My Projects
          </Link>

          <StaticImage
            src="../images/header1.jpg"
            placeholder="blurred"
            layout="fullWidth"
            alt="Banner"
          />

    </Layout>
  )
}

export const HomeQuery = graphql`
  query HomeQuery {
    site {
      siteMetadata {
        title
        description
        social {
          twitter
        }
      }
    }
  }
`

here as well I imported Seo

import React from "react"
import { Link } from "gatsby"
import Seo from "../Seo"
import styled from "styled-components"
import icon from "../../images/svg/logo-icon.svg"

const LogoWrap = styled.div`
  display: flex;
  color: var(--alpha-color);
  align-items: center:
  text-align: left;
  letter-spacing: 1px;
  text-transform: uppercase;
  }

  img {
    display: inline;
    margin-right: 3px;
  }
`

const Logo = () => {
  const { title } = Seo()

  return (
    <LogoWrap as={Link} to="/">

      {title}
    </LogoWrap>
  )
}

export default Logo

need help what I'm doing wrong!?

Body:
Well, it's quite self-explanatory. In the Seo component you are destructuring the props as description, lang, meta, and title respectively at:

const Seo = ({ description, lang, meta, title })

As is, all fields are inferred as mandatory so, the issue rises up because, in some of the uses of Seo, the description is null or undefined (check also the rest).

Check the pages where you are rendering the Seo component to check how the props are being drilled down. Ideally, it should be:

<Seo description={'Some description'} lang={'Some lang'} ... />

Note: this will differ depending on how the props are being passed.

You can bypass this by adding some default values in your destructuring like:

const Seo = ({ description = '', lang = '', meta=[], title='' })

Adding the default values will make your Seo component to take them if no one is passed via props, avoiding the code-breaking.


来源: stackexchange

问:
Flutter callback / passing function as a parameter problem
I'm trying to pass a function as a parameter. My code runs but the function doesn't fire.

I have a Holiday class

```<code>  final VoidCallback callback;
  Holiday(this.holidayStart, this.holidayEnd, this.holidayDuration, this.callback);
</code>```

Inside the Holiday class I have a function to build a widget with a button. here I use...

```<code>   onPressed: () {
       callback;
   },
</code>```

In my main.dart file when I create a new instance of Holiday I pass a function like this....

```<code>holidays.add(Holiday(startSelected, endSelected, stay, () { print('pressed'); }))
</code>```

Everything compiles fine but pressed is never printed. Any ideas what I'm doing wrong here?

Thanks in advance.

答:
In your case, you passed function that does nothing because you put callback but don't call it (via () at the end or .call()).
You should write onPressed: callback,
or onPressed: () {  callback(); },

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to pass a function as a parameter. My code runs but the function doesn't fire.

I have a Holiday class

  final VoidCallback callback;
  Holiday(this.holidayStart, this.holidayEnd, this.holidayDuration, this.callback);

Inside the Holiday class I have a function to build a widget with a button. here I use...

   onPressed: () {
       callback;
   },

In my main.dart file when I create a new instance of Holiday I pass a function like this....

holidays.add(Holiday(startSelected, endSelected, stay, () { print('pressed'); }))

Everything compiles fine but pressed is never printed. Any ideas what I'm doing wrong here?

Thanks in advance.


问:
Use element to style inside

The emb is not a class but an element. Can I use this element to style the div or, the only way to do it is making emb a class such as .emb?

  Hello

```

答:
No, you cant use things like that to style element.
Here, style is a attribute to div tag. You can use it directly to style your div.

```<code><div style="font-weight: 500;
       font-style: italic;
       background: transparent;
       font-size: 18px;">
Hello
</div>
</code>```

But inorder to define class or id, you need to use class or id attribute. Or you can use tagname to style.

```<code><div class='emb'>
Hello
</div>

<style>

   .emb {
       font-weight: 500;
       font-style: italic;
       background: transparent;
       font-size: 18px
    }

</style>
</code>```

Title: Use element to style inside <div>

Body:
No, you cant use things like that to style element.
Here, style is a attribute to div tag. You can use it directly to style your div.

<div style="font-weight: 500;
       font-style: italic;
       background: transparent;
       font-size: 18px;">
Hello
</div>

But inorder to define class or id, you need to use class or id attribute. Or you can use tagname to style.

<div class='emb'>
Hello
</div>

<style>

   .emb {
       font-weight: 500;
       font-style: italic;
       background: transparent;
       font-size: 18px
    }

</style>


问:
How to save current cmd-output
Is there a way to get whats currently displayed on the windows command prompt?

For example:

```<code>print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'
</code>```

答:
@Rick_2650 here is an improved version of the function as you wanted</p>
```<code># log function prints message and
# saves the output in log.txt of
# the current working directory
# sample usage [green text ANSI 1;32]:-
#     >>> log("hello", "world", colour="1;32")
#
# @param   objects  *args    objects we want to print
# @param   string   colour   ANSI style colour codes
# @param   string   sep      Separator for __str__ of objects
# @param   string   end      String to be added at lineend
# @param   string   logfile  name of logfile
# @return  void
def log(*args, sep=" ", colour="0", end="\n", logfile="log.txt"):

    printable_array = []
    colour = "\033[" + colour + "m"

    with open(logfile, "a") as file:
        for each in args:
            printable_array.append(colour+each+"\033[0m")
            file.write(each+sep) # seperator will effect the final entry
        file.write(end)

    print(*printable_array, sep=sep, end=end, flush=True)
</code>```

Title: How to save current cmd-output

Body:
Is there a way to get whats currently displayed on the windows command prompt?

For example:

print('some text')
print('some different text')

>>> some text
>>> some different text

a = save_whats_on_cmd()
>>> a = 'some text \n some different text'

Body:
@Rick_2650 here is an improved version of the function as you wanted

# log function prints message and
# saves the output in log.txt of
# the current working directory
# sample usage [green text ANSI 1;32]:-
#     >>> log("hello", "world", colour="1;32")
#
# @param   objects  *args    objects we want to print
# @param   string   colour   ANSI style colour codes
# @param   string   sep      Separator for __str__ of objects
# @param   string   end      String to be added at lineend
# @param   string   logfile  name of logfile
# @return  void
def log(*args, sep=" ", colour="0", end="\n", logfile="log.txt"):

    printable_array = []
    colour = "\033[" + colour + "m"

    with open(logfile, "a") as file:
        for each in args:
            printable_array.append(colour+each+"\033[0m")
            file.write(each+sep) # seperator will effect the final entry
        file.write(end)

    print(*printable_array, sep=sep, end=end, flush=True)


问:
How to convert deeply nested array with one object to object in mongodb aggregation?
The requirement is to convert all sales array properties to objects with their first elements' quantity value. The collection name is branches and the example data is below.

```<code>[
{
    "_id": 111,
    "recs": [
        {
            "date": "01-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 14,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        },
        {
            "date": "02-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 23,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        }
    ]
},
{
    "_id": 21,
    "recs": [
        {
            "date": "01-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 11,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        },
        {
            "date": "02-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 31,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        }
    ]
}]
</code>```

The expected response is below.

```<code>[
{
    "_id": 111,
    "recs": [
        {
            "date": "01-01-2021",
            "sale": {
                "P": 14,
                "K": 0,
                "U": 0
            }
        }
    ]
}]
</code>```

I tried $map, $addFields but no way I couldn't find a solution.

答:
In $map, you need:

$first to query the first sales.quantity object in recs.sales array.

$mergeObject to merge the current document in recs array with the document from (1).

```<code>db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      recs: {
        "$map": {
          "input": "$recs",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                sales: {
                  $first: "$$this.sales.quantity"
                }
              }
            ]
          }
        }
      }
    }
  }
])
</code>```

Sample Mongo Playground

Body:
The requirement is to convert all sales array properties to objects with their first elements' quantity value. The collection name is branches and the example data is below.

[
{
    "_id": 111,
    "recs": [
        {
            "date": "01-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 14,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        },
        {
            "date": "02-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 23,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        }
    ]
},
{
    "_id": 21,
    "recs": [
        {
            "date": "01-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 11,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        },
        {
            "date": "02-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 31,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        }
    ]
}]

The expected response is below.

[
{
    "_id": 111,
    "recs": [
        {
            "date": "01-01-2021",
            "sale": {
                "P": 14,
                "K": 0,
                "U": 0
            }
        }
    ]
}]

I tried $map, $addFields but no way I couldn't find a solution.

Body:
In $map, you need:

$first to query the first sales.quantity object in recs.sales array.

$mergeObject to merge the current document in recs array with the document from (1).

db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      recs: {
        "$map": {
          "input": "$recs",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                sales: {
                  $first: "$$this.sales.quantity"
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground


问:
Cannot convert Binding<Type> to Binding<Protocol>
Cannot convert Binding<Type> to Binding<Protocol> is the specific error message, but the underlying question is: What's a good architecture for holding a reference, then mutating & reading from the underlying object?

Examples:

In an RPG, your character has a currentArmor. You want it to take damage.

In Pokemon, you track a currentPokemon. It needs to level up.

In Instagram, you have a selectedPost, you want the like button to mutate the underlying post.

Here's a concrete example showing what I tried: This app has several Animals. You can use the app to edit the currentAnimal's name.

The error Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>':

```<code>protocol Animal {
    var name: String { get set }
}

struct Cow: Animal {
    var name: String
}

struct Dog: Animal {
    var name: String
}

class Model: ObservableObject {
    @Published var dog: Dog = Dog(name: "dog 1")
    // ** THIS IS THE IMPORTANT PART ** //
    @Published var currentAnimal: Binding<Animal> = .constant(Cow(name: "cow 1"))
}

struct ContentView: View {
    @StateObject var model = Model()

    var body: some View {
        VStack {
            Text(model.dog.name) // Show the underlying Dog
        }
            .onAppear {
                model.currentAnimal = $model.dog // Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
            }
            .onTapGesture {
                model.currentAnimal.wrappedValue.name = "dog 2" // Mutate state here
            }
    }
}
</code>```

Yes, I'm aware of https://developer.apple.com/forums/thread/652064 But I don't think doing a force as! case is a good idea. Is there some way that generics instead of protocols could solve this problem? Or class inheritance instead of protocols? Or some other architecture?

答:
EDIT: With Classes it works:</p>
```<code>protocol Animal {
    var name: String { get set }
}

class Cow: Animal {
    var name: String

    init(name: String) {
        self.name = name
    }
}

class Dog: Animal {
    var name: String

    init(name: String) {
        self.name = name
    }
}

class Model: ObservableObject {
    @Published var dog: Dog = Dog(name: "dog 1")
    // ** THIS IS THE IMPORTANT PART ** //
    @Published var currentAnimal: Animal = Cow(name: "cow 1")
}

struct ContentView: View {
    @StateObject var model = Model()

    var body: some View {
        VStack {
            Text(model.dog.name) // Show the underlying Dog
        }
        .onAppear {
            model.currentAnimal = model.dog // Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
        }
        .onTapGesture {
            model.currentAnimal.name = "dog 2" // Mutate state here
        }
    }
}
</code>```

Body:
Cannot convert Binding<Type> to Binding<Protocol> is the specific error message, but the underlying question is: What's a good architecture for holding a reference, then mutating & reading from the underlying object?

Examples:

In an RPG, your character has a currentArmor. You want it to take damage.

In Pokemon, you track a currentPokemon. It needs to level up.

In Instagram, you have a selectedPost, you want the like button to mutate the underlying post.

Here's a concrete example showing what I tried: This app has several Animals. You can use the app to edit the currentAnimal's name.

The error Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>':

protocol Animal {
    var name: String { get set }
}

struct Cow: Animal {
    var name: String
}

struct Dog: Animal {
    var name: String
}

class Model: ObservableObject {
    @Published var dog: Dog = Dog(name: "dog 1")
    // ** THIS IS THE IMPORTANT PART ** //
    @Published var currentAnimal: Binding<Animal> = .constant(Cow(name: "cow 1"))
}

struct ContentView: View {
    @StateObject var model = Model()

    var body: some View {
        VStack {
            Text(model.dog.name) // Show the underlying Dog
        }
            .onAppear {
                model.currentAnimal = $model.dog // Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
            }
            .onTapGesture {
                model.currentAnimal.wrappedValue.name = "dog 2" // Mutate state here
            }
    }
}

Yes, I'm aware of https://developer.apple.com/forums/thread/652064 But I don't think doing a force as! case is a good idea. Is there some way that generics instead of protocols could solve this problem? Or class inheritance instead of protocols? Or some other architecture?

Body:
EDIT: With Classes it works:

protocol Animal {
    var name: String { get set }
}

class Cow: Animal {
    var name: String

    init(name: String) {
        self.name = name
    }
}

class Dog: Animal {
    var name: String

    init(name: String) {
        self.name = name
    }
}

class Model: ObservableObject {
    @Published var dog: Dog = Dog(name: "dog 1")
    // ** THIS IS THE IMPORTANT PART ** //
    @Published var currentAnimal: Animal = Cow(name: "cow 1")
}

struct ContentView: View {
    @StateObject var model = Model()

    var body: some View {
        VStack {
            Text(model.dog.name) // Show the underlying Dog
        }
        .onAppear {
            model.currentAnimal = model.dog // Cannot assign value of type 'Binding<Dog>' to type 'Binding<Animal>'
        }
        .onTapGesture {
            model.currentAnimal.name = "dog 2" // Mutate state here
        }
    }
}


问:
How to disable mobile data connection in android programmatically?
I would like to know if there is any way to disable mobile data connection in android programmatically. Since there is a class known as WifiManager to handle the wifi

```<code>WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifi.setWifiEnabled(false);
</code>```

Is there are any such class for handling mobile data connection? How to disable it programmatically in android?

答: See ConnectivityManager.</p>

ContentLicense: CC BY-SA 3.0

Body:
I would like to know if there is any way to disable mobile data connection in android programmatically. Since there is a class known as WifiManager to handle the wifi

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifi.setWifiEnabled(false);

Is there are any such class for handling mobile data connection? How to disable it programmatically in android?

Body: See ConnectivityManager.


问:
React app fetch() response is empty although API endpoint returns data when sending a GET request from somewhere else
This is what my API call looks like:

```<code>export async function getTasks(): Promise<Task[]> {
  if (process.env.NODE_ENV === "test") {
    return new Promise<Task[]>((resolve) =>
      setTimeout(() => resolve(DefaultTasksArray), 1500)
    );
  } else {
    return (await fetch("/api/tasks").then(
      (response) => response.json
    )) as unknown as Task[];
  }
}
</code>```

GET action in the controller in the API

```<code>[HttpGet]
async public Task<IActionResult> Get()
{
    var tasks = await _service.GetAsync();

    return Ok(tasks);
}
</code>```

The service in the API

```<code>private readonly IMongoCollection<TaskObject> _tasksCollection;

public TaskService(IOptions<TaskManagerDbSettings> taskManagerDbSettings)
{
    var mongoClient = new MongoClient(taskManagerDbSettings.Value.ConnectionString);
    var mongoDatabase = mongoClient.GetDatabase(taskManagerDbSettings.Value.DatabaseName);
    _tasksCollection = mongoDatabase.GetCollection<TaskObject>(taskManagerDbSettings.Value.TasksCollectionName);
}

async public Task<List<TaskObject>> GetAsync() =>
    await _tasksCollection.Find(_ => true).ToListAsync();
</code>```

When I send a GET request in Postman or in a browser, I get a JSON object like:

```<code>[
  {
    *data*
  },
  {
    *data*
  },
  ...
]
</code>```

But the fetch() returns an empty response. What might be the cause?
I don't see any errors in the browser when I open the app.

upd:
I see the response in the Network tab in the browser, it has code 200 and all the data. But in the app itself the response is empty.

答:
It turned out that it was actually caused by a small difference between the API output model and the UI response model. After I changed that, it's working as expected.

Also I shouldn't use "unknown as Task[]"
And yeah, response.json()

Body:
This is what my API call looks like:

export async function getTasks(): Promise<Task[]> {
  if (process.env.NODE_ENV === "test") {
    return new Promise<Task[]>((resolve) =>
      setTimeout(() => resolve(DefaultTasksArray), 1500)
    );
  } else {
    return (await fetch("/api/tasks").then(
      (response) => response.json
    )) as unknown as Task[];
  }
}

GET action in the controller in the API

[HttpGet]
async public Task<IActionResult> Get()
{
    var tasks = await _service.GetAsync();

    return Ok(tasks);
}

The service in the API

private readonly IMongoCollection<TaskObject> _tasksCollection;

public TaskService(IOptions<TaskManagerDbSettings> taskManagerDbSettings)
{
    var mongoClient = new MongoClient(taskManagerDbSettings.Value.ConnectionString);
    var mongoDatabase = mongoClient.GetDatabase(taskManagerDbSettings.Value.DatabaseName);
    _tasksCollection = mongoDatabase.GetCollection<TaskObject>(taskManagerDbSettings.Value.TasksCollectionName);
}

async public Task<List<TaskObject>> GetAsync() =>
    await _tasksCollection.Find(_ => true).ToListAsync();

When I send a GET request in Postman or in a browser, I get a JSON object like:

[
  {
    *data*
  },
  {
    *data*
  },
  ...
]

But the fetch() returns an empty response. What might be the cause?
I don't see any errors in the browser when I open the app.

upd:
I see the response in the Network tab in the browser, it has code 200 and all the data. But in the app itself the response is empty.


问:
Getting SSL error "Unsupported protocol" when running in Visual Studio
I am trying to build a Blazor application and I always get the following error :
"This site can’t provide a secure connectionlocalhost uses an unsupported protocol.
ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Unsupported protocol
The client and server don't support a common SSL protocol version or cipher suite."

My Chrome browser is up to date. I tried with Edge but the same error !
I tried the following link, too :
https://phoenixnap.com/kb/fix-err-ssl-version-or-cipher-mismatch

Until a day all was working fine and I don't know what happened...
If I run the same application on another Windows 7 PC, it is working fine...
Can you help me, please ?
I will put here a screen capture :

答:
Same problem for me.

Working with VS19

Tried a lot of things such as:

deleting localhost certificates,

repairing IIS Express 10,

clearing browser data and certificates cache,

deleting .vs folder,

allowing every TLS and SSL options in the browser

My .NET Core web apps are working under IE. So my guess is also that it's a Chrome update problem. But I haven't found how to fix that. :-(


问:
How to combine array in php to dynamically?
I have code like this

```<code>$a =[
      [1,2],
      [4,6],
      [10,24]
    ];
</code>```

i want a output like this

```<code>    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )
</code>```

and i use code like this

```<code>print_r(array_merge($a[0],$a[1],$a[2]));
</code>```

if a have code like this and have more data

```<code>    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )
</code>```

writing like this is not good

```<code>print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));
</code>```

how to use array_merge in dinamic in there?

答:
u can use this:</p>
```<code>$a =[
      7,
      [1,2],
      [4,6],
      [10,24],
      [[30,40],[2,9]]
    ];

function mrg($array){
    $out = [];
    foreach($array as $b){
        if(is_array($b))
            $out = array_merge($out, mrg($b));
        else
            $out[] = $b;
    }
    return $out;
}

print_r(mrg($a));
</code>```

Body:
I have code like this

$a =[
      [1,2],
      [4,6],
      [10,24]
    ];

i want a output like this

    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )

and i use code like this

print_r(array_merge($a[0],$a[1],$a[2]));

if a have code like this and have more data

    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     )

writing like this is not good

print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));

how to use array_merge in dinamic in there?

Body:
u can use this:

$a =[
      7,
      [1,2],
      [4,6],
      [10,24],
      [[30,40],[2,9]]
    ];

function mrg($array){
    $out = [];
    foreach($array as $b){
        if(is_array($b))
            $out = array_merge($out, mrg($b));
        else
            $out[] = $b;
    }
    return $out;
}

print_r(mrg($a));


问:
VBA Excel: How to assign values to empty slots in an array through a function
Currently I'm working on a little interpolation code (Newton's Divided Difference). Problem is I'm having trouble assigning the table values that I've calculated in a function to my initial array that has the f(x) values. I keep getting the error "Can't assign to array". Any help would be greatly appreciated

Here is a little snippet of the code in question and how I declared the variables

```<code>'Dim our variables, arrays
`Dim n, i, order As Integer
Dim x(9), y(9, 9), xi As Double

n = 9

'select our x data

For i = 0 To n
    x(i) = Worksheets("Newton").Range("B" & i + 4)
Next

'select our y data

For i = 0 To n
    y(i, 0) = Worksheets("Newton").Range("D" & i + 4)
Next

'select the value at which we want to interpolate
xi = Range("E1")

'This is where the problem is
y = divided_Table(x, y, n)

'Message the output
MsgBox "The estimate of f(x) is " & applyNewton(xi, x, y, n)

End Sub

Function divided_Table(x, y, n)
Dim i, j As Integer
    For i = 1 To n
        For j = 0 To n - i
            y(j, i) = ((y(j, i - 1) - y(j + 1, i - 1)) / (x(j) - x(i + j)))

            Next j
        Next i

End Function

</code>```

答:
Would be nice to know at which line you get the error. But here are two items you may not know...

When you say:

Dim x(9), y(9, 9), xi As Double

the system will dim x() and y() as variants and NOT as doubles. The xi will be a double.

And if you dim  x(9)  the array does not have 9 slots - it has 10 (0-9).

Can't say that either of these items is your problem, but it is still good to be in the know.

Body:
Currently I'm working on a little interpolation code (Newton's Divided Difference). Problem is I'm having trouble assigning the table values that I've calculated in a function to my initial array that has the f(x) values. I keep getting the error "Can't assign to array". Any help would be greatly appreciated

Here is a little snippet of the code in question and how I declared the variables

'Dim our variables, arrays
`Dim n, i, order As Integer
Dim x(9), y(9, 9), xi As Double

n = 9

'select our x data

For i = 0 To n
    x(i) = Worksheets("Newton").Range("B" & i + 4)
Next

'select our y data

For i = 0 To n
    y(i, 0) = Worksheets("Newton").Range("D" & i + 4)
Next

'select the value at which we want to interpolate
xi = Range("E1")

'This is where the problem is
y = divided_Table(x, y, n)

'Message the output
MsgBox "The estimate of f(x) is " & applyNewton(xi, x, y, n)

End Sub

Function divided_Table(x, y, n)
Dim i, j As Integer
    For i = 1 To n
        For j = 0 To n - i
            y(j, i) = ((y(j, i - 1) - y(j + 1, i - 1)) / (x(j) - x(i + j)))

            Next j
        Next i

End Function


问:
re.sub with a .group() - Unable to replace in python
With Python, I am trying to use re.sub to replace some items in svg_text

Expected Output:
Substitute  RoundShapes_group_match.group() with classes_removed_text in svg_text

Actual Output:
svg_text stays the same -- RoundShapes_group_match.group() remains unchanged

Here is the code.
I know people suggest lxml but I can't get that to work either and would still like to figure out why the re.sub isn't working.

I think it has to do with the RoundShapes_group_match.group() because even if I try to replace with ' ' instead of classes_removed_text it doesn't work.

Question:

Is re.sub not able to find a .group() or .group(0) string?

My python spacing is correct, and it is not throwing errors... it doesn't look correct on Stack Overflow though...

import re

def remove_RoundShapes_group_classes(svg_text):
    """
    Within <g id="RoundShapes"> and before SquareShapes, remove all path class names.  Do not modify class names
    in other groups outside of RoundShapes.
    """
    # RoundShapes_group_match = re.search(r"""<g\s+id\s*=\s*"\S*?RoundShapes.*?</g>""", svg_text, flags=re.I | re.DOTALL)
    # Change to SquareShapes to search to next group
    RoundShapes_group_match = re.search(r"""<g\s+id\s*=\s*"\S*?RoundShapes.*?SquareShapes""", svg_text,
                                        flags=re.I | re.DOTALL)

    if RoundShapes_group_match is None:
        print("Could not find the RoundShapes group.", file=stderr)
        return svg_text

    classes_removed_text = re.sub(r'''class\s*=\s*".*?"''', '', RoundShapes_group_match.group(), flags=re.I)
    # print(classes_removed_text)

    RoundShapes_to_replace = (RoundShapes_group_match.group(0))

    ##RoundShapes_group_match.group() is what is not working.  Are there extra returns?
    svg_text = re.sub(RoundShapes_group_match.group(), classes_removed_text, svg_text, 1)
    return svg_text
```

答:
I don't know why this resolved the issue,
but instead of using re.sub I used replace

```<code>svg_text = svg_text.replace(RoundShapes_group_match.group(0), classes_removed_text)
return svg_text
</code>```

It now works!

Body:
I don't know why this resolved the issue,
but instead of using re.sub I used replace

svg_text = svg_text.replace(RoundShapes_group_match.group(0), classes_removed_text)
return svg_text

It now works!


问:
Im getting an error "No such file or directory" when installing Composer Globally
I am trying to install Composer globally but I get an error when I do
sudo mv composer.phar /usr/local/bin/composer
The error reads

```<code>mv: composer.phar: No such file or directory
</code>```

When I try and instal Laravel

```<code>composer global require laravel/installer
</code>```

And after I try to run

```<code>Laravel
</code>```

I get

```<code>zsh: command not found: laravel
</code>```

答:
This command worked in creating a new directory:

```<code>sudo mkdir -p /usr/local/bin
</code>```

After I moved the composer.phar to the new directory using :

```<code>sudo mv composer.phar /usr/local/bin/composer
</code>```

This command didn't work for me:

```<code>alias composer='/usr/local/bin/composer'
</code>```

Body:
I am trying to install Composer globally but I get an error when I do
sudo mv composer.phar /usr/local/bin/composer
The error reads

mv: composer.phar: No such file or directory

When I try and instal Laravel

composer global require laravel/installer

And after I try to run

Laravel

I get

zsh: command not found: laravel

Body:
This command worked in creating a new directory:

sudo mkdir -p /usr/local/bin

After I moved the composer.phar to the new directory using :

sudo mv composer.phar /usr/local/bin/composer

This command didn't work for me:

alias composer='/usr/local/bin/composer'


问:
How can I update just one atribute in my MySQL database using js?
I have a little question about updating just one attribute and not all like in this code.

```<code>router.put("/update/:id", (req, res) => {
    const id = req.params.id;
    Account.update(req.body, {
            where: { id: id },
        })
        .then((num) => {
            if (num == 1) {
                res.send({
                    message: "Informatiile au fost actualizate cu succes.",
                });
            } else {
                res.send({
                    message: `Nu pot actualiza informatiile pentru contul cu id=${id}.`,
                });
            }
        })
        .catch((err) => {
            res.status(500).send({
                message: "Eroare actualizare date pentru id=" + id,
            });
        });
});
</code>```

One register from my database looks like this:

```<code>{
  name: 'x',
  password: 'x',
  activated: 0
}
</code>```

All I want to do is to make that 0 in 1 and I don't know what I have to change in my code because if I use this code, I will update all parameters (name, password, activated) and I want to update just one.

答:
It looks like you are using sequelize. In sequelize to update only one field you would pass an object with only one field into the .update method as it can be seen in the following snippet.</p>
```<code>router.put("/update/:id", (req, res) => {
    const id = req.params.id;
    Account.update(
        {
          activated: req.body.activated
        }, {
            where: { id: id },
        })
        .then((num) => {
            if (num == 1) {
                res.send({
                    message: "Informatiile au fost actualizate cu succes.",
                });
            } else {
                res.send({
                    message: `Nu pot actualiza informatiile pentru contul cu id=${id}.`,
                });
            }
        })
        .catch((err) => {
            res.status(500).send({
                message: "Eroare actualizare date pentru id=" + id,
            });
        });
});
</code>```

Body:
I have a little question about updating just one attribute and not all like in this code.

router.put("/update/:id", (req, res) => {
    const id = req.params.id;
    Account.update(req.body, {
            where: { id: id },
        })
        .then((num) => {
            if (num == 1) {
                res.send({
                    message: "Informatiile au fost actualizate cu succes.",
                });
            } else {
                res.send({
                    message: `Nu pot actualiza informatiile pentru contul cu id=${id}.`,
                });
            }
        })
        .catch((err) => {
            res.status(500).send({
                message: "Eroare actualizare date pentru id=" + id,
            });
        });
});

One register from my database looks like this:

{
  name: 'x',
  password: 'x',
  activated: 0
}

All I want to do is to make that 0 in 1 and I don't know what I have to change in my code because if I use this code, I will update all parameters (name, password, activated) and I want to update just one.

Body:
It looks like you are using sequelize. In sequelize to update only one field you would pass an object with only one field into the .update method as it can be seen in the following snippet.

router.put("/update/:id", (req, res) => {
    const id = req.params.id;
    Account.update(
        {
          activated: req.body.activated
        }, {
            where: { id: id },
        })
        .then((num) => {
            if (num == 1) {
                res.send({
                    message: "Informatiile au fost actualizate cu succes.",
                });
            } else {
                res.send({
                    message: `Nu pot actualiza informatiile pentru contul cu id=${id}.`,
                });
            }
        })
        .catch((err) => {
            res.status(500).send({
                message: "Eroare actualizare date pentru id=" + id,
            });
        });
});


问:
Drop pandas rows by index name
I have a dataframe of let say 1000 rows. I want to drop the row store in variable breakval and also next 10 rows.

```<code>breakval=[10,100,500]
for i in breakval:
    df=df.drop(df.index[i:i+10])
</code>```

But after first iteration in which row 10-20 are dropped. I want row 100-110 by index name, not by row number. Because row number is reduced by 10, but row index name remain the same.
I am looking for a way to get index by its name. For example if i do df.index[12] it will return me the value, though i dropped it. For this purpose i used df.loc[22].name, but it worked for a single value

答:
You should:

first collect all index values, for rows to be dropped,

then remove rows with these indices.

For generality, let's define another variable, stating how many rows
should be dropped, starting from each of your locations:

```<code>nToDrop = 10
</code>```

or maybe 11 if you want to drop the indicated row (e.g. 5)
and 10 rows following it.

To collect the index values, you can run e.g.:

```<code>idxToDrop = [item
    for sublist in [df.index[i:i+nToDrop] for i in breakval]
        for item in sublist]
</code>```

Note that [df.index[i:i+nToDrop] for i in breakval] is a list comprehension
generating a list of RangeIndex objects. Conceptually it can be taken as a list of lists.

The whole above expression can also be presented as:

```<code>[item
    for sublist in listOfLists
        for item in sublist]
</code>```

It flattens this list (of lists), getting a plain list of index values
for rows to be dropped.

Finally, to get the expected result, run:

```<code>df.drop(idxToDrop, inplace=True)
</code>```

Edit

Another, maybe faster solution, is to concatenate RangeIndex objects
into a pandasonic Series, but as pd.concat operates e.g. on Series
objects, you must also convert each source RangeIndex object into
a Series.

So you can generate idxToDrop also as:

```<code>idxToDrop = pd.concat([df.index[i:i+nToDrop].to_series() for i in breakval])
</code>```

and then use it in df.drop as above.

Title: Drop pandas rows by index name

Body:
I have a dataframe of let say 1000 rows. I want to drop the row store in variable breakval and also next 10 rows.

breakval=[10,100,500]
for i in breakval:
    df=df.drop(df.index[i:i+10])

But after first iteration in which row 10-20 are dropped. I want row 100-110 by index name, not by row number. Because row number is reduced by 10, but row index name remain the same.
I am looking for a way to get index by its name. For example if i do df.index[12] it will return me the value, though i dropped it. For this purpose i used df.loc[22].name, but it worked for a single value

Body:
You should:

first collect all index values, for rows to be dropped,

then remove rows with these indices.

For generality, let's define another variable, stating how many rows
should be dropped, starting from each of your locations:

nToDrop = 10

or maybe 11 if you want to drop the indicated row (e.g. 5)
and 10 rows following it.

To collect the index values, you can run e.g.:

idxToDrop = [item
    for sublist in [df.index[i:i+nToDrop] for i in breakval]
        for item in sublist]

Note that [df.index[i:i+nToDrop] for i in breakval] is a list comprehension
generating a list of RangeIndex objects. Conceptually it can be taken as a list of lists.

The whole above expression can also be presented as:

[item
    for sublist in listOfLists
        for item in sublist]

It flattens this list (of lists), getting a plain list of index values
for rows to be dropped.

Finally, to get the expected result, run:

df.drop(idxToDrop, inplace=True)

Edit

Another, maybe faster solution, is to concatenate RangeIndex objects
into a pandasonic Series, but as pd.concat operates e.g. on Series
objects, you must also convert each source RangeIndex object into
a Series.

So you can generate idxToDrop also as:

idxToDrop = pd.concat([df.index[i:i+nToDrop].to_series() for i in breakval])

and then use it in df.drop as above.


问:
Cross Validation, scikit-learn, parallel is slower
I am learning how to use scikit-learn.

When testing the cross validation function, if I turn on parallel computing using

```<code>cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1)
</code>```

the result is a lot slower than if I turn it off using

```<code>cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=1)
</code>```

How can I stop this?

I am using PyDev, Anacondas 3.3 on a 64bit Windows 7 machine.  From looking at Task Manager, it appears that the performance hit is caused by many instances of Python being started and stopped.  Why do they not start, and stay started?

答:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

For SVM you for sure would be able to get higher compute efficiency, however for such large datasets this still would be noticeable.

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Body:
I am learning how to use scikit-learn.

When testing the cross validation function, if I turn on parallel computing using

cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1)

the result is a lot slower than if I turn it off using

cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=1)

How can I stop this?

I am using PyDev, Anacondas 3.3 on a 64bit Windows 7 machine.  From looking at Task Manager, it appears that the performance hit is caused by many instances of Python being started and stopped.  Why do they not start, and stay started?

Body:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

For SVM you for sure would be able to get higher compute efficiency, however for such large datasets this still would be noticeable.

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


问:
Exceeded rate limits: too many table update operations for this table in Cloud Function while uploading the data from pubsub topic to BQ
Let me explain the use case which I am trying to solve

I am getting data to the pubsub topic on daily basis in google cloud

I have a written a cloud function with pubsub as a trigger type to trigger and execute the
script inside the cloud function when ever the topic receives the data

The function will trigger and uploads the data to Bigquery tables

Right now I kept the memory of the function as 256mb and max instances to 100

On daily basis I receive very small amount of data like 16 messages to pubsub topic

Even the data is small I observed the cloud function is encountering the following error "too
many table update operations for this table" and I am missing some data

I have retry option which I can use but don't want the cloud function to return any errors, Is
there any workaround for this

sharing the sample code below

答:
It appears that your code is exceeding the maximum rate of table metadata update operations per table which is 5 operations per 10 seconds. So it appears that all your Cloud Pub/Sub messages are coming at the same time (or near the same time). You can follow either of the following solutions for the same:

As suggested in the comments, you can use Streaming inserts. As this limit does not apply to Streaming Inserts.

You can insert a delay in your code for providing time between successive metadata updates. In this case I passed a timeout of 30 seconds to the result for the same. This worked for me.

I tried the second method. I published 19 messages from my publisher code at the same time. I got the same error message as yours (when executing without timeout).

But after Inserting the timeout the execution was successful. (Timeout value can be reduced further as per the requirement)

Complete Code:

```<code>import base64
from google.cloud import bigquery
import json
import io

def hello_pubsub(event, context):
   """Triggered from a message on a Cloud Pub/Sub topic.
   Args:
        event (dict): Event payload.
        context (google.cloud.functions.Context): Metadata for the event.
   """
   client = bigquery.Client()
   pubsub_message = base64.b64decode(event['data']).decode('utf-8')
   print(pubsub_message)
   message = json.loads(pubsub_message)
   result = json.dumps(message)
   source_file = io.StringIO(result)
   table_id="ProjectID.DatasetID.TableName"

   job_config = bigquery.LoadJobConfig(
    autodetect=True,
    write_disposition="WRITE_APPEND",
    source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,
    )
   job = client.load_table_from_file(source_file, table_id, job_config=job_config)
   job.result(timeout=30)  #passing a timeout in the function call

</code>```

Output : (All 19 rows were inserted, I did not notice any loss of data)

Body:
It appears that your code is exceeding the maximum rate of table metadata update operations per table which is 5 operations per 10 seconds. So it appears that all your Cloud Pub/Sub messages are coming at the same time (or near the same time). You can follow either of the following solutions for the same:

As suggested in the comments, you can use Streaming inserts. As this limit does not apply to Streaming Inserts.

You can insert a delay in your code for providing time between successive metadata updates. In this case I passed a timeout of 30 seconds to the result for the same. This worked for me.

I tried the second method. I published 19 messages from my publisher code at the same time. I got the same error message as yours (when executing without timeout).

But after Inserting the timeout the execution was successful. (Timeout value can be reduced further as per the requirement)

Complete Code:

import base64
from google.cloud import bigquery
import json
import io

def hello_pubsub(event, context):
   """Triggered from a message on a Cloud Pub/Sub topic.
   Args:
        event (dict): Event payload.
        context (google.cloud.functions.Context): Metadata for the event.
   """
   client = bigquery.Client()
   pubsub_message = base64.b64decode(event['data']).decode('utf-8')
   print(pubsub_message)
   message = json.loads(pubsub_message)
   result = json.dumps(message)
   source_file = io.StringIO(result)
   table_id="ProjectID.DatasetID.TableName"

   job_config = bigquery.LoadJobConfig(
    autodetect=True,
    write_disposition="WRITE_APPEND",
    source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,
    )
   job = client.load_table_from_file(source_file, table_id, job_config=job_config)
   job.result(timeout=30)  #passing a timeout in the function call

Output : (All 19 rows were inserted, I did not notice any loss of data)


问:
Sequelize: TypeError: Converting circular structure to JSON
I have Orders and Display models. The association works like this

```<code>Display.associate = models => Display.hasOne(models.Orders);
</code>```

The orders table has displayId reference and there is nothing circular in my design. However I get this error below.

```<code>TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Socket'
    |     property '_writableState' -> object with constructor 'WritableState'
    |     property 'afterWriteTickInfo' -> object with constructor 'Object'
    --- property 'stream' closes the circle
    at JSON.stringify (<anonymous>)
</code>```

the error dissapears if I do not include dbDisplay shown below.

```<code>export const getAllOrders = async (req, res) => {
    console.log("GET ALL ORDERS")
    let orders = await dbOrders.findAll({
        include: [{
            model: dbDisplay,
        }]
    }).catch(error => res.status(400).send(error));
    try {
        res.status(200).send(orders) // error here

    } catch (err) {
        console.log(err)
    }
}
</code>```

答:
Don't try to send model instances themselves. Use their get({ plain: true }) method to get plain object(s):

export const getAllOrders = async (req, res) => {
    console.log("GET ALL ORDERS")
    try {
        const orders = await dbOrders.findAll({
        include: [{
            model: dbDisplay,
        }]
        })
        res.status(200).send(orders.map(x => x.get({ plain: true })))
    } catch (err) {
        console.log(err)
        res.status(400).send(err)
    }
}
```

Body:
I have Orders and Display models. The association works like this

Display.associate = models => Display.hasOne(models.Orders);

The orders table has displayId reference and there is nothing circular in my design. However I get this error below.

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Socket'
    |     property '_writableState' -> object with constructor 'WritableState'
    |     property 'afterWriteTickInfo' -> object with constructor 'Object'
    --- property 'stream' closes the circle
    at JSON.stringify (<anonymous>)

the error dissapears if I do not include dbDisplay shown below.

export const getAllOrders = async (req, res) => {
    console.log("GET ALL ORDERS")
    let orders = await dbOrders.findAll({
        include: [{
            model: dbDisplay,
        }]
    }).catch(error => res.status(400).send(error));
    try {
        res.status(200).send(orders) // error here

    } catch (err) {
        console.log(err)
    }
}


问:
import mathjax throws error @types/mathjax/index.d.ts is not a module
I'm trying to import MathJax in a TypeScript file.

You can repro with the following steps:

tsc --init
npm init -y
npm i mathjax @types/mathjax
echo "import { MathJax } from 'mathjax';" > index.ts
```
<p>I've tried all of the following important syntaxes:</p>
<pre class="lang-js prettyprint-override"><code>import { MathJax } from 'mathjax';
import mathjax from "mathjax";
import * as mathjax from "mathjax"
import { * as MathJax } from "mathjax";
</code>```

But all return the following error:

'../node_modules/@types/mathjax/index.d.ts' is not a module.
```
<p>I've also tried adding <code>mathjax</code> to <code>types</code> in my <code>tsconfig.app.json</code> like this (but that hasn't helped either)</p>
<pre class="lang-json prettyprint-override"><code>"types": [
   "mathjax"
]
</code>```

Related Problems

StackOverflow

MathJax is not defined angular 4

Using MathJax inside Typescript/Angular2 component

TypeScript typings give me "index.d.ts is not a module"

Github Issues

Simple Example with Typescript #2310

How to use MathJax in TypeScript project? #2385

答:
This answer is written with the use of MathJax in a web project in mind. If this is not the case for you, much of it still applies since it relates to Typescript, which you clearly use.

1. MathJax is meant to be downloaded in the browser

No matter the situation today, MathJax is historically downloaded in the browser and should not be imported into a project targeting the web like other npm packages. Under Installation and use at https://www.npmjs.com/package/mathjax you can see that you're only supposed to use MathJax in a project like this if you're making a backend Node application, otherwise MathJax should be imported in the frontend with a script. You can host your own MathJax copy as a static file resource on your web server and load it from there in a script tag from the frontend (much like any CDN), but you shouldn't build it into the frontend like you do with regular npm packages by importing it into the source files. Why does this matter ? Because it affects how MathJax is organized, both historically and today, which in turn affects how it is treated in a Typescript project.

2. MathJax packages

MathJax has two versions, MathJax 2 and 3. 2 is very different from version 3 internally and syntactically but is still used even though version 3 is recommended. The package mathjax from npmjs.org is the MathJax 3 package. If you go to the MathJax Github repo, you can download older packages but I don't think they're available as npm packages. On the official MathJax page under Server integration you can read about how to download MathJax in the backend. You also see there that there are two npm packages: mathjax and mathjax-full of which the latter contains the "full source code". MathJax is written with Typescript support so we can expect that there are types. If you visit the npmjs.org entries for these packages (https://www.npmjs.com/package/mathjax and https://www.npmjs.com/package/mathjax-full), you see that mathjax-full contains types which mathjax does not. This can also be seen by expecting the downloaded packages in node_modules.

So what is the package @types/mathjax? Well, upon inspection, we can see that it is connected to MathJax version 2, because its type declarations involve the use of MathJax.Hub which is only used in version 2. Also its index.d.ts, the entrypoint for types when nothing more specific is indicated than

```<code>import mathjax from "mathjax"
</code>```

or

```<code>import * as mathjax from "mathjax"
</code>```

declares a namespace with exports inside of it

```<code>declare namespace MathJax {
    export ...
    export ...
}
</code>```

Namespaces are used in Javascript to organize code into different disjoint components, a sort of earlier alternative to modules, which do the same things without namespaces. In the Typescript documentation (https://www.typescriptlang.org/docs/handbook/modules.html) it literally says that In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. The package @types/mathjax doesn't have that, which results in it not being a module which also your compiler reports.

So except for the fact that @types/mathjax is not connected to the npm package mathjax (which is bad organization I know) due to different versions, it also doesn't support modern module syntax. I would say that it's old too but it had a release quite recently so to be frank, I don't know what it's about, perhaps it has something to do with how MathJax is usually imported or it's supposed to work in some other very particular situation. All I know is that according to the Typescript documentation, this types package is not considered a module (as indicated by your compiler) and its types do not align with MathJax version 3, e.g. I definitely don't think that there is an official affiliation between this package and the package which it is supposed to support.

So given mathjax-full we have types, right? Yes, that is true, but the file organization in mathjax-full is not adapted to your use-case. First of all, it lacks an index, so there is no reasonable entrypoint to use for the kind of import statements earlier described (as said, when no specific resource is targeted, the natural entrypoint is the index file). The package.json included does not contain neither package information nor information about types (you can check this for yourself in node_modules). Even when I try to use it without Typescript, it doesn't work due to errors about require not being defined. All in all, this package is not meant to be used like the average npm package that you use; it should be used for those who wish to work with the source code of MathJax and definitely not in the "average-user-building-a-web-application" use-case. For those, MathJax should be used as a separate black box project that is accessed via a script import (again, due to historical reasons.. this was the way things were 15 years ago or so).

3. How to make it work in your use-case

To make it work in your use-case, and by that I mean to make your compiler accept your import (nothing else), there are a few things you can do. I say this because I sense an interest in how Typescript works here as well.

In the case of the @types/mathjax package, you can go into its index.d.ts in node_modules and add export default MathJax at the bottom (top-level). Now the file has a global export and therefore, import statements like

```<code>import * as mathjax from "mathjax"
import mathjax from "mathjax"
</code>```

will not result in the complaints you saw earlier. It would still not work though because of the require errors I briefly described earlier.

In the case of mathjax-full, by inspecting the code in node_modules you can see that there are indeed Typescript files along the source code in the js sub directory. But since no index is present (also a clear hint that the package should not be used in web projects by means of imports), default imports won't work (compiler will complain about types). If you however target a particular asset, for example

```<code>import { mathjax } from "mathjax-full/js/mathjax"
</code>```

it will find the corresponding types and you will not get an error. You actually get some sort of MathJax object then but I don't know if it would work all the way (try it if you want to). Besides, I suspect you would get quite a lot of extra unneeded files in your bundle (or have to spend a lot of time on customizing tree-shaking) since MathJax is used to determine what files it needs upon usage and it might be hard for the bundler to determine this at build time.

4. So how should you REALLY fix this?

The best way is to use a React package for MathJax. Here I will recommend my own package better-react-mathjax (https://www.npmjs.com/package/better-react-mathjax) but there are others as well. Such packages have tried to bridge the gap between MathJax and React, like the one you are experiencing now.

If you want to do it the more complicated way, you use the source code in the MathJax packages and include them as part of your static files resources, and you then inject a script tag in React that fetches the file with the MathJax start script from your static backend. You could also do it this way and fetch the same file from a CDN if you don't want to host your own copy.

If you really need to use MathJax in the backend, I would investigate the mathjax-full package and try to convert the instructions about using it in Node in the official MathJax docs earlier pointed to, to your usecase, working with explicit imports instead of default ones to get type support.

Recommendations

I detect a certain interest in code organization and modules (perhaps mistakenly) on your behalf which is a complicated subject. Try writing your own package and distribute it via npm to get an understanding of the roles played by npm, Node, Typescript, ecmascript modules, commonjs modules and so on. Understanding the different module formats and how they are allowed to interact in Typescript projects using features like esModuleInterop and allowSyntheticDefaultImports are also important topics and by distributing your own package, you will really get an idea about the differences of source code in a project, and source code in packages.

Body:
I'm trying to import MathJax in a TypeScript file.

You can repro with the following steps:

tsc --init
npm init -y
npm i mathjax @types/mathjax
echo "import { MathJax } from 'mathjax';" > index.ts

I've tried all of the following important syntaxes:

import { MathJax } from 'mathjax';
import mathjax from "mathjax";
import * as mathjax from "mathjax"
import { * as MathJax } from "mathjax";

But all return the following error:

'../node_modules/@types/mathjax/index.d.ts' is not a module.

I've also tried adding mathjax to types in my tsconfig.app.json like this (but that hasn't helped either)

"types": [
   "mathjax"
]

Related Problems

StackOverflow

MathJax is not defined angular 4

Using MathJax inside Typescript/Angular2 component

TypeScript typings give me "index.d.ts is not a module"

Github Issues

Simple Example with Typescript #2310

How to use MathJax in TypeScript project? #2385

Body:
This answer is written with the use of MathJax in a web project in mind. If this is not the case for you, much of it still applies since it relates to Typescript, which you clearly use.

1. MathJax is meant to be downloaded in the browser

No matter the situation today, MathJax is historically downloaded in the browser and should not be imported into a project targeting the web like other npm packages. Under Installation and use at https://www.npmjs.com/package/mathjax you can see that you're only supposed to use MathJax in a project like this if you're making a backend Node application, otherwise MathJax should be imported in the frontend with a script. You can host your own MathJax copy as a static file resource on your web server and load it from there in a script tag from the frontend (much like any CDN), but you shouldn't build it into the frontend like you do with regular npm packages by importing it into the source files. Why does this matter ? Because it affects how MathJax is organized, both historically and today, which in turn affects how it is treated in a Typescript project.

2. MathJax packages

MathJax has two versions, MathJax 2 and 3. 2 is very different from version 3 internally and syntactically but is still used even though version 3 is recommended. The package mathjax from npmjs.org is the MathJax 3 package. If you go to the MathJax Github repo, you can download older packages but I don't think they're available as npm packages. On the official MathJax page under Server integration you can read about how to download MathJax in the backend. You also see there that there are two npm packages: mathjax and mathjax-full of which the latter contains the "full source code". MathJax is written with Typescript support so we can expect that there are types. If you visit the npmjs.org entries for these packages (https://www.npmjs.com/package/mathjax and https://www.npmjs.com/package/mathjax-full), you see that mathjax-full contains types which mathjax does not. This can also be seen by expecting the downloaded packages in node_modules.

So what is the package @types/mathjax? Well, upon inspection, we can see that it is connected to MathJax version 2, because its type declarations involve the use of MathJax.Hub which is only used in version 2. Also its index.d.ts, the entrypoint for types when nothing more specific is indicated than

import mathjax from "mathjax"

or

import * as mathjax from "mathjax"

declares a namespace with exports inside of it

declare namespace MathJax {
    export ...
    export ...
}

Namespaces are used in Javascript to organize code into different disjoint components, a sort of earlier alternative to modules, which do the same things without namespaces. In the Typescript documentation (https://www.typescriptlang.org/docs/handbook/modules.html) it literally says that In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. The package @types/mathjax doesn't have that, which results in it not being a module which also your compiler reports.

So except for the fact that @types/mathjax is not connected to the npm package mathjax (which is bad organization I know) due to different versions, it also doesn't support modern module syntax. I would say that it's old too but it had a release quite recently so to be frank, I don't know what it's about, perhaps it has something to do with how MathJax is usually imported or it's supposed to work in some other very particular situation. All I know is that according to the Typescript documentation, this types package is not considered a module (as indicated by your compiler) and its types do not align with MathJax version 3, e.g. I definitely don't think that there is an official affiliation between this package and the package which it is supposed to support.

So given mathjax-full we have types, right? Yes, that is true, but the file organization in mathjax-full is not adapted to your use-case. First of all, it lacks an index, so there is no reasonable entrypoint to use for the kind of import statements earlier described (as said, when no specific resource is targeted, the natural entrypoint is the index file). The package.json included does not contain neither package information nor information about types (you can check this for yourself in node_modules). Even when I try to use it without Typescript, it doesn't work due to errors about require not being defined. All in all, this package is not meant to be used like the average npm package that you use; it should be used for those who wish to work with the source code of MathJax and definitely not in the "average-user-building-a-web-application" use-case. For those, MathJax should be used as a separate black box project that is accessed via a script import (again, due to historical reasons.. this was the way things were 15 years ago or so).

3. How to make it work in your use-case

To make it work in your use-case, and by that I mean to make your compiler accept your import (nothing else), there are a few things you can do. I say this because I sense an interest in how Typescript works here as well.

In the case of the @types/mathjax package, you can go into its index.d.ts in node_modules and add export default MathJax at the bottom (top-level). Now the file has a global export and therefore, import statements like

import * as mathjax from "mathjax"
import mathjax from "mathjax"

will not result in the complaints you saw earlier. It would still not work though because of the require errors I briefly described earlier.

In the case of mathjax-full, by inspecting the code in node_modules you can see that there are indeed Typescript files along the source code in the js sub directory. But since no index is present (also a clear hint that the package should not be used in web projects by means of imports), default imports won't work (compiler will complain about types). If you however target a particular asset, for example

import { mathjax } from "mathjax-full/js/mathjax"

it will find the corresponding types and you will not get an error. You actually get some sort of MathJax object then but I don't know if it would work all the way (try it if you want to). Besides, I suspect you would get quite a lot of extra unneeded files in your bundle (or have to spend a lot of time on customizing tree-shaking) since MathJax is used to determine what files it needs upon usage and it might be hard for the bundler to determine this at build time.

4. So how should you REALLY fix this?

The best way is to use a React package for MathJax. Here I will recommend my own package better-react-mathjax (https://www.npmjs.com/package/better-react-mathjax) but there are others as well. Such packages have tried to bridge the gap between MathJax and React, like the one you are experiencing now.

If you want to do it the more complicated way, you use the source code in the MathJax packages and include them as part of your static files resources, and you then inject a script tag in React that fetches the file with the MathJax start script from your static backend. You could also do it this way and fetch the same file from a CDN if you don't want to host your own copy.

If you really need to use MathJax in the backend, I would investigate the mathjax-full package and try to convert the instructions about using it in Node in the official MathJax docs earlier pointed to, to your usecase, working with explicit imports instead of default ones to get type support.

Recommendations

I detect a certain interest in code organization and modules (perhaps mistakenly) on your behalf which is a complicated subject. Try writing your own package and distribute it via npm to get an understanding of the roles played by npm, Node, Typescript, ecmascript modules, commonjs modules and so on. Understanding the different module formats and how they are allowed to interact in Typescript projects using features like esModuleInterop and allowSyntheticDefaultImports are also important topics and by distributing your own package, you will really get an idea about the differences of source code in a project, and source code in packages.


问:
Solving maze using recursion in java
I am to solve maze using recursion in java but when I try to run I get a Stack overflow error. A maze starts at a + and the path that leads to the end is also +, ends at a -, walls are X, spaces are potential paths, '.' will mark a dead end path. What I think causes the error is the backtracking step. The code shown is the part that I get the error on. When The maze path is a straight line the maze works fine. Any help is much appreciated.

```<code>/*Sample maze that causes errors
       XXXXXXXXXXXX
       +   XXX    -
       XXX XXX XXXX
       XXX  XX XXXX
       XX         X
       XXXXXXXXXXXX
*/

   public  boolean isValidSpot(int r, int c) { // r and c represent position in 2d array
       if(r < nrow && c < ncol)  //make sure current postion is not out of bounds
       {
        return true;
       }
       return false;
   }

   public  boolean traverse(char[][] maze, int r, int c) {
       if(isValidSpot(r, c)) {
           if(maze[r][c]=='X')
               return false;
           if(maze[r][c]=='-') {
               return true;}

           maze[r][c]='+';

           //right
           if(traverse(maze, r, c+1))
               return true;
           //up
           if(traverse(maze, r-1, c ))//error on this line
               return true;

           //down
           if(traverse(maze, r+1, c))//error on this line
               return true;

           //left
           if(traverse(maze, r, c - 1))
               return true;

           //backtrack
           maze[r][c]='.';
           return false;

       }

       return false;
   }
</code>```

The solved maze look something like this

```<code>/*
        XXXXXXXXXXXX
        ++++XXX++++-
        XXX+XXX+XXXX
        XXX+ XX+XXXX
        XX.+++++...X
        XXXXXXXXXXXX
</code>```

答:
Code to traverse through the maze is below remember '+' represents that it's the start and '*' represent that we have traversed it so we don't traverse it again other wise it will lead to stackoverflow since traverse method will keep on calling it self until overflow happens.

from each cell we are traversing up, down , left and right if there is path we will reach to out goal.

Code:

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

public class Maze{
    //checks weather the spot is valid
    public  static boolean isValidSpot(int r, int c, int nrow, int ncol) {
        return r < nrow && c < ncol && r >= 0 && c >= 0;
    }
    //traverses through the maze
    public static boolean traverse(final char[][] maze, final int r, final int c) {

        int nrow = maze.length, ncol = maze[0].length;

        if(isValidSpot(r, c, nrow, ncol)) {
            if(maze[r][c] == 'X' || maze[r][c] == '.' || maze[r][c] == '*')
                return false;
            if(maze[r][c]=='-') {
                return true;
            }

            maze[r][c]='*';

            //right
            if(traverse(maze, r, c+1))
                return true;
            //up
            if(traverse(maze, r-1, c ))
                return true;

            //down
            if(traverse(maze, r+1, c))
                return true;

            //left
            if(traverse(maze, r, c - 1))
                return true;

            //backtrack
            maze[r][c]='.';
            return false;

        }

        return false;
    }
    ///////////////Main////////////////
    public static void main(String ...$){
        var out = System.out;

        ArrayList<String> list = new ArrayList<>();

        list.add("XXXXXXXXXXXX");
        list.add("+   XXX    -");
        list.add("XXX XXX XXXX");
        list.add("XXX  XX XXXX");
        list.add("XX         X");
        list.add("XXXXXXXXXXXX");

        char[][] maze =new char[list.size()][];
        //converting list of string to a 2D char array
        for(int i=0;i<list.size();i++){
            String str = list.get(i);
            maze[i] = str.toCharArray();
        }
        boolean pathExists = false;
        for(int i =0;i<maze.length;i++)
            for(int j =0;j<maze[i].length;j++)
                if(maze[i][j] == '+'){
                    //out.println("found");
                    pathExists = traverse(maze,i,j);
                }
        out.println(pathExists);
        for(int i =0;i<maze.length;i++){
            for(int j =0;j<maze[i].length;j++)
                out.print(maze[i][j]);
            out.println();
        }

    }
}
</code>```

output:

```<code>$ javac Maze.java && java Maze
true
XXXXXXXXXXXX
****XXX****-
XXX*XXX*XXXX
XXX**XX*XXXX
XX  ****...X
XXXXXXXXXXXX
</code>```

Title: Solving maze using recursion in java

Body:
I am to solve maze using recursion in java but when I try to run I get a Stack overflow error. A maze starts at a + and the path that leads to the end is also +, ends at a -, walls are X, spaces are potential paths, '.' will mark a dead end path. What I think causes the error is the backtracking step. The code shown is the part that I get the error on. When The maze path is a straight line the maze works fine. Any help is much appreciated.

/*Sample maze that causes errors
       XXXXXXXXXXXX
       +   XXX    -
       XXX XXX XXXX
       XXX  XX XXXX
       XX         X
       XXXXXXXXXXXX
*/

   public  boolean isValidSpot(int r, int c) { // r and c represent position in 2d array
       if(r < nrow && c < ncol)  //make sure current postion is not out of bounds
       {
        return true;
       }
       return false;
   }

   public  boolean traverse(char[][] maze, int r, int c) {
       if(isValidSpot(r, c)) {
           if(maze[r][c]=='X')
               return false;
           if(maze[r][c]=='-') {
               return true;}

           maze[r][c]='+';

           //right
           if(traverse(maze, r, c+1))
               return true;
           //up
           if(traverse(maze, r-1, c ))//error on this line
               return true;

           //down
           if(traverse(maze, r+1, c))//error on this line
               return true;

           //left
           if(traverse(maze, r, c - 1))
               return true;

           //backtrack
           maze[r][c]='.';
           return false;

       }

       return false;
   }

The solved maze look something like this

/*
        XXXXXXXXXXXX
        ++++XXX++++-
        XXX+XXX+XXXX
        XXX+ XX+XXXX
        XX.+++++...X
        XXXXXXXXXXXX

Body:
Code to traverse through the maze is below remember '+' represents that it's the start and '*' represent that we have traversed it so we don't traverse it again other wise it will lead to stackoverflow since traverse method will keep on calling it self until overflow happens.

from each cell we are traversing up, down , left and right if there is path we will reach to out goal.

Code:

import java.util.ArrayList;

public class Maze{
    //checks weather the spot is valid
    public  static boolean isValidSpot(int r, int c, int nrow, int ncol) {
        return r < nrow && c < ncol && r >= 0 && c >= 0;
    }
    //traverses through the maze
    public static boolean traverse(final char[][] maze, final int r, final int c) {

        int nrow = maze.length, ncol = maze[0].length;

        if(isValidSpot(r, c, nrow, ncol)) {
            if(maze[r][c] == 'X' || maze[r][c] == '.' || maze[r][c] == '*')
                return false;
            if(maze[r][c]=='-') {
                return true;
            }

            maze[r][c]='*';

            //right
            if(traverse(maze, r, c+1))
                return true;
            //up
            if(traverse(maze, r-1, c ))
                return true;

            //down
            if(traverse(maze, r+1, c))
                return true;

            //left
            if(traverse(maze, r, c - 1))
                return true;

            //backtrack
            maze[r][c]='.';
            return false;

        }

        return false;
    }
    ///////////////Main////////////////
    public static void main(String ...$){
        var out = System.out;

        ArrayList<String> list = new ArrayList<>();

        list.add("XXXXXXXXXXXX");
        list.add("+   XXX    -");
        list.add("XXX XXX XXXX");
        list.add("XXX  XX XXXX");
        list.add("XX         X");
        list.add("XXXXXXXXXXXX");

        char[][] maze =new char[list.size()][];
        //converting list of string to a 2D char array
        for(int i=0;i<list.size();i++){
            String str = list.get(i);
            maze[i] = str.toCharArray();
        }
        boolean pathExists = false;
        for(int i =0;i<maze.length;i++)
            for(int j =0;j<maze[i].length;j++)
                if(maze[i][j] == '+'){
                    //out.println("found");
                    pathExists = traverse(maze,i,j);
                }
        out.println(pathExists);
        for(int i =0;i<maze.length;i++){
            for(int j =0;j<maze[i].length;j++)
                out.print(maze[i][j]);
            out.println();
        }

    }
}

output:

$ javac Maze.java && java Maze
true
XXXXXXXXXXXX
****XXX****-
XXX*XXX*XXXX
XXX**XX*XXXX
XX  ****...X
XXXXXXXXXXXX


问:
Am trying to use https://jsonplaceholder.typicode.com/photos but not displaying am new to this
This is my code not getting any response from jsonplaceholder, what should i do I tried for others like post/comments it worked but am not getting for photos.</p>
```<code>function getPhotos() {
    fetch('https://jsonplaceholder.typicode.com/photos')
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
            let photoLayout = document.querySelector('#photo-layout');
            let html = "";
            data.forEach((e) => {
                // console.log(e)
                html += `
                <div class="col-md-4" >
                    <div class="card h-100 mb-3">
                    <img class="card-img-top" src=${e.thumbnailUrl} alt="photo"/>
                        <div class="card-body">
                            <p class= "id>${e.id}
                            <h5 class="album-title">${e.title}</h5>
                        </div>
                    </div>
                </div>
            `;
                photoLayout.innerHTML = html;
            });
        });

}
getPhotos();
</code>```

答:
You need to move  photoLayout.innerHTML = html; outside of the forEach loop.

```<code>function getPhotos() {
    fetch('https://jsonplaceholder.typicode.com/photos')
        .then((response) => response.json())
        .then((data) => {
            const photoLayout = document.querySelector('#photo-layout');
            let html = "";
            data.forEach((e) => {
                html += `
                <div class="col-md-4" >
                    <div class="card h-100 mb-3">
                    <img class="card-img-top" src=${e.thumbnailUrl} alt="photo"/>
                        <div class="card-body">
                            <p class= "id>${e.id}
                            <h5 class="album-title">${e.title}</h5>
                        </div>
                    </div>
                </div>
            `;
            });
            photoLayout.innerHTML = html;
        });
}
getPhotos();
</code>```

Body:
This is my code not getting any response from jsonplaceholder, what should i do I tried for others like post/comments it worked but am not getting for photos.

function getPhotos() {
    fetch('https://jsonplaceholder.typicode.com/photos')
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
            let photoLayout = document.querySelector('#photo-layout');
            let html = "";
            data.forEach((e) => {
                // console.log(e)
                html += `

${e.id}

${e.title}

            `;
                photoLayout.innerHTML = html;
            });
        });

}
getPhotos();

Body:
You need to move  photoLayout.innerHTML = html; outside of the forEach loop.

function getPhotos() {
    fetch('https://jsonplaceholder.typicode.com/photos')
        .then((response) => response.json())
        .then((data) => {
            const photoLayout = document.querySelector('#photo-layout');
            let html = "";
            data.forEach((e) => {
                html += `
                <div class="col-md-4" >
                    <div class="card h-100 mb-3">
                    <img class="card-img-top" src=${e.thumbnailUrl} alt="photo"/>
                        <div class="card-body">
                            <p class= "id>${e.id}
                            <h5 class="album-title">${e.title}</h5>
                        </div>
                    </div>
                </div>
            `;
            });
            photoLayout.innerHTML = html;
        });
}
getPhotos();


问:
CSS transform vs position
Can some please explain to me the difference in transitioning the positional left or right properties or the -transform: translateX(n), as the both seem to achieve the same thing yet can be applied independently. I understand about the possibility of hardware acceleration but that's dependent on implementation.

```<code>// psuedo code;

#box {
    -transition-property: all;
    -transition-duration: 1s;
}

// javascript

box.style.transform = "translateX(200px)";
vs
box.style.left = "200px";
</code>```

What's the advantage of one over the other?
Thanks,

p

答:
Position is dependant on what the position is set to, transform works from the element itself. So you could see transform as being identical to position:relative;.

However, you can still use transform on an absolutely positioned element (to position it relatively without needing an additional element or resorting to margins), as well as transform being CSS3 so if you can use position instead you should.

Title: CSS transform vs position

Body:
Can some please explain to me the difference in transitioning the positional left or right properties or the -transform: translateX(n), as the both seem to achieve the same thing yet can be applied independently. I understand about the possibility of hardware acceleration but that's dependent on implementation.

// psuedo code;

#box {
    -transition-property: all;
    -transition-duration: 1s;
}

// javascript

box.style.transform = "translateX(200px)";
vs
box.style.left = "200px";

What's the advantage of one over the other?
Thanks,

p


答:
```<code>df['row_index'] = np.arange(df.shape[0])
breakval = [10,100,500]
consequtive_entries_to_remove = 10
for i in breakval:
    for j in range(0, consequtive_entries_to_remove):
        df.drop(df.index[df['row_index'] == i+j], inplace=True)

# Remove column name 'row_index'
df.drop(['row_index'], axis = 1, inplace=True)
</code>```

Title: Drop pandas rows by index name


问:
How to remove all other python versions except for the one carried by the OS X
Before asking this question, I tried a lot of methods. I mainly focus on these posts.

How to find all python installations on mac os x and uninstall all but the native OS X installation

How to clean iPython environment so I can start over with Jupyter and Python 3.x?

I also tried

```<code>conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda3
</code>```

brew  cleanup python3

But I still have a number of python versions left

```<code>GZs-MacBook-Pro:bin gz$ which python
/usr/bin/python
GZs-MacBook-Pro:bin gz$ which python3
/usr/bin/python3
GZs-MacBook-Pro:bin gz$ ls /System/Library/Frameworks/Python.framework/Versions
2.3 2.5 2.6 2.7 Current
GZs-MacBook-Pro:bin gz$ ls /Library/Frameworks/Python.framework/Versions
ls: /Library/Frameworks/Python.framework/Versions: No such file or directory
GZs-MacBook-Pro:bin gz$ ls -l /usr/bin/python*
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
-rwxr-xr-x  1 root  wheel  31456  5 Dec 04:32 /usr/bin/python3
</code>```

How can I remove the others python versions except for the original one on the OS X?

答:
For Mac......

First of all, if Python is running, you are supposed to quit related processes before performing uninstall. And there are multiple ways you can take to exit out of Python:

(1) Right click on its icon on the Dock, and then choose the Quit option;

(2) Open a Python window, and choose Quit from the Apple menu on the left top;

(3) Launch Activity Monitor, select the process with the name of Python in the list, then click the “X” button on the upper left corner, and click Quite button in the pop-up dialog. If the app fails to quit, then try Force Quite in Activity Monitor.

After that you can carry out the standard uninstall, and two options are available here.

Option 1: remove Python from Launchpad
Open Launchpad, and type Python in the search box on the top.
Click and hold Python icon that appears until it starts to wiggle.
Click the “X” icon that appears on the left upper corner of Python icon, and click on the Delete button in the confirmation dialog to execute the uninstallation.

Once you click the Delete button, the uninstall will be handled instantly, and there is no need to empty the Trash afterwards. If you install Python through the App Store and your system is OS X lion or later, you can take this approach to easily uninstall it.

Option 2: delete Python to the Trash
Open the Finder, and click on Applications in the sidebar to navigate to the folder.
Locate and select Python, then drag the icon to the Trash and drop it there.
Right click the Trash icon and choose Empty Trash to perform the uninstall.

Body:
Before asking this question, I tried a lot of methods. I mainly focus on these posts.

How to find all python installations on mac os x and uninstall all but the native OS X installation

How to clean iPython environment so I can start over with Jupyter and Python 3.x?

I also tried

conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda3

brew  cleanup python3

But I still have a number of python versions left

GZs-MacBook-Pro:bin gz$ which python
/usr/bin/python
GZs-MacBook-Pro:bin gz$ which python3
/usr/bin/python3
GZs-MacBook-Pro:bin gz$ ls /System/Library/Frameworks/Python.framework/Versions
2.3 2.5 2.6 2.7 Current
GZs-MacBook-Pro:bin gz$ ls /Library/Frameworks/Python.framework/Versions
ls: /Library/Frameworks/Python.framework/Versions: No such file or directory
GZs-MacBook-Pro:bin gz$ ls -l /usr/bin/python*
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
-rwxr-xr-x  1 root  wheel  31456  5 Dec 04:32 /usr/bin/python3

How can I remove the others python versions except for the original one on the OS X?