问:
Creating queries using Criteria API (JPA 2.0)
I'm trying to create a query with the Criteria API from JPA 2.0, but I can't make it work.

The problem is with the "between" conditional method. I read some documentation to know how I have to do it, but since I'm discovering JPA, I don't understand why it does not work.

First, I can't see "creationDate" which should appear when I write "Transaction_."

I thought it was maybe normal, since I read the metamodel was generated at runtime, so I tried to use 'Foo_.getDeclaredSingularAttribute("value")' instead of 'Foo_.value', but it still doesn't work at all.

Here is my code :

```<code>public List<Transaction> getTransactions(Date startDate, Date endDate) {
    EntityManager em = getEntityManager();
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
        Metamodel m = em.getMetamodel();
        EntityType<Transaction> Transaction_ = m.entity(Transaction.class);
        Root<Transaction> transaction = cq.from(Transaction.class);

        // Error here. cannot find symbol. symbol: variable creationDate
        cq.where(cb.between(transaction.get(Transaction_.creationDate), startDate, endDate));

        // I also tried this:
        // cq.where(cb.between(Transaction_.getDeclaredSingularAttribute("creationDate"), startDate, endDate));

        List<Transaction> result = em.createQuery(cq).getResultList();
        return result;
    } finally {
        em.close();
    }
}
</code>```

Can someone help me to figure this out? Thanks.

EDIT : here is the Transaction source (almost nothing in it, since it was automatically generated by Netbeans, from my database)

```<code>package projetjava.db;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "transaction")
@NamedQueries({
    @NamedQuery(name = "Transaction.findAll", query = "SELECT t FROM Transaction t"),
    @NamedQuery(name = "Transaction.findById", query = "SELECT t FROM Transaction t WHERE t.id = :id"),
    @NamedQuery(name = "Transaction.findByIDAccount", query = "SELECT t FROM Transaction t WHERE t.iDAccount = :iDAccount"),
    @NamedQuery(name = "Transaction.findByDescription", query = "SELECT t FROM Transaction t WHERE t.description = :description"),
    @NamedQuery(name = "Transaction.findByCreationDate", query = "SELECT t FROM Transaction t WHERE t.creationDate = :creationDate"),
    @NamedQuery(name = "Transaction.findByAmount", query = "SELECT t FROM Transaction t WHERE t.amount = :amount")})
public class Transaction implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "IDAccount")
    private int iDAccount;
    @Basic(optional = false)
    @Column(name = "Description")
    private String description;
    @Basic(optional = false)
    @Column(name = "CreationDate")
    @Temporal(TemporalType.DATE)
    private Date creationDate;
    @Basic(optional = false)
    @Column(name = "Amount")
    private double amount;

    public Transaction() {
    }

    public Transaction(Integer id) {
        this.id = id;
    }

    public Transaction(Integer id, int iDAccount, String description, Date creationDate, double amount) {
        this.id = id;
        this.iDAccount = iDAccount;
        this.description = description;
        this.creationDate = creationDate;
        this.amount = amount;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public int getIDAccount() {
        return iDAccount;
    }

    public void setIDAccount(int iDAccount) {
        this.iDAccount = iDAccount;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Transaction)) {
            return false;
        }
        Transaction other = (Transaction) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "projetjava.db.Transaction[id=" + id + "]";
    }

}
</code>```

答:
QUERY FOR START DATE AND END DATE IN JPA</p>

```<code>public List<Student> findStudentByReports(String className, Date startDate, Date endDate) {
    System.out
    .println("call findStudentMethd******************with this pattern"
            + className
            + startDate
            + endDate
            + "*********************************************");

    return em
    .createQuery(
            "select attendence from Attendence attendence where lower(attendence.className) like '"
            + className + "' or attendence.admissionDate BETWEEN : startdate AND endDate " + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a query with the Criteria API from JPA 2.0, but I can't make it work.

The problem is with the "between" conditional method. I read some documentation to know how I have to do it, but since I'm discovering JPA, I don't understand why it does not work.

First, I can't see "creationDate" which should appear when I write "Transaction_."

I thought it was maybe normal, since I read the metamodel was generated at runtime, so I tried to use 'Foo_.getDeclaredSingularAttribute("value")' instead of 'Foo_.value', but it still doesn't work at all.

Here is my code :

public List<Transaction> getTransactions(Date startDate, Date endDate) {
    EntityManager em = getEntityManager();
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
        Metamodel m = em.getMetamodel();
        EntityType<Transaction> Transaction_ = m.entity(Transaction.class);
        Root<Transaction> transaction = cq.from(Transaction.class);

        // Error here. cannot find symbol. symbol: variable creationDate
        cq.where(cb.between(transaction.get(Transaction_.creationDate), startDate, endDate));

        // I also tried this:
        // cq.where(cb.between(Transaction_.getDeclaredSingularAttribute("creationDate"), startDate, endDate));

        List<Transaction> result = em.createQuery(cq).getResultList();
        return result;
    } finally {
        em.close();
    }
}

Can someone help me to figure this out? Thanks.

EDIT : here is the Transaction source (almost nothing in it, since it was automatically generated by Netbeans, from my database)

package projetjava.db;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "transaction")
@NamedQueries({
    @NamedQuery(name = "Transaction.findAll", query = "SELECT t FROM Transaction t"),
    @NamedQuery(name = "Transaction.findById", query = "SELECT t FROM Transaction t WHERE t.id = :id"),
    @NamedQuery(name = "Transaction.findByIDAccount", query = "SELECT t FROM Transaction t WHERE t.iDAccount = :iDAccount"),
    @NamedQuery(name = "Transaction.findByDescription", query = "SELECT t FROM Transaction t WHERE t.description = :description"),
    @NamedQuery(name = "Transaction.findByCreationDate", query = "SELECT t FROM Transaction t WHERE t.creationDate = :creationDate"),
    @NamedQuery(name = "Transaction.findByAmount", query = "SELECT t FROM Transaction t WHERE t.amount = :amount")})
public class Transaction implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "IDAccount")
    private int iDAccount;
    @Basic(optional = false)
    @Column(name = "Description")
    private String description;
    @Basic(optional = false)
    @Column(name = "CreationDate")
    @Temporal(TemporalType.DATE)
    private Date creationDate;
    @Basic(optional = false)
    @Column(name = "Amount")
    private double amount;

    public Transaction() {
    }

    public Transaction(Integer id) {
        this.id = id;
    }

    public Transaction(Integer id, int iDAccount, String description, Date creationDate, double amount) {
        this.id = id;
        this.iDAccount = iDAccount;
        this.description = description;
        this.creationDate = creationDate;
        this.amount = amount;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public int getIDAccount() {
        return iDAccount;
    }

    public void setIDAccount(int iDAccount) {
        this.iDAccount = iDAccount;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Transaction)) {
            return false;
        }
        Transaction other = (Transaction) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "projetjava.db.Transaction[id=" + id + "]";
    }

}

Body:
QUERY FOR START DATE AND END DATE IN JPA

public List<Student> findStudentByReports(String className, Date startDate, Date endDate) {
    System.out
    .println("call findStudentMethd******************with this pattern"
            + className
            + startDate
            + endDate
            + "*********************************************");

    return em
    .createQuery(
            "select attendence from Attendence attendence where lower(attendence.className) like '"
            + className + "' or attendence.admissionDate BETWEEN : startdate AND endDate " + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();
}


来源: stackexchange

问:
How to 1). put a div , 2). render a component without Route inside <Routes> with React Router in v6 React?
I want to put a div inside <Routes>  and also Render a <Topbar /> and <Sidebar /> component inside <Routes> without <Route> tag for them.

My code is as follows:-

```<code>const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="login" element={<Login />} />
        <Topbar />
        <div className="container">
          <Sidebar />
          <Route path="/" element={<Home />} />
          <Route path="users" element={<UserList />} />
        </div>
      </Routes>
    </Router>
  );
};
</code>```

I want to implement <Topbar /> and <Sidebar /> for all the routes.
But for an exception of login Page (Topbar and Sidebar should not be shown on the login page).
That's why I had put login Route at the top of Topbar and Sidebar.

The console is showing error as:

Uncaught Error: [Topbar] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

How to implement this functionality?

答:
In react-router-dom v6 only Route and React.Fragment components are valid children for the Routes component.

Use layout components to render the Topbar and Sidebar components along with an Outlet for nested routes for the routes you want to render these components.

Example:

```<code>import { Routes, Route, Outlet } from 'react-router-dom';

const Layout = () => (
  <>
    <Topbar />
    <div className="container">
      <Sidebar />
      <Outlet />
    </div>
  </>
);

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route element={<Layout />}>
          <Route path="/" element={<Home />} />
          <Route path="users" element={<UserList />} />
        </Route>
      </Routes>
    </Router>
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to put a div inside <Routes>  and also Render a <Topbar /> and <Sidebar /> component inside <Routes> without <Route> tag for them.

My code is as follows:-

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="login" element={<Login />} />
        <Topbar />

          <Sidebar />
          <Route path="/" element={<Home />} />
          <Route path="users" element={<UserList />} />

      </Routes>
    </Router>
  );
};

I want to implement <Topbar /> and <Sidebar /> for all the routes.
But for an exception of login Page (Topbar and Sidebar should not be shown on the login page).
That's why I had put login Route at the top of Topbar and Sidebar.

The console is showing error as:

Uncaught Error: [Topbar] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

How to implement this functionality?

Body:
In react-router-dom v6 only Route and React.Fragment components are valid children for the Routes component.

Use layout components to render the Topbar and Sidebar components along with an Outlet for nested routes for the routes you want to render these components.

Example:

import { Routes, Route, Outlet } from 'react-router-dom';

const Layout = () => (
  <>
    <Topbar />
    <div className="container">
      <Sidebar />
      <Outlet />
    </div>
  </>
);

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route element={<Layout />}>
          <Route path="/" element={<Home />} />
          <Route path="users" element={<UserList />} />
        </Route>
      </Routes>
    </Router>
  );
};


问:
HTML .gitignore
I currently have my api keys and list id sitting in my app.js file. I am trying to add those API keys to another file and hide the file using .gitignore. But how do I do that and even if I hide the file in the new secret file how do I get those keys back in my original app.js file</p>

答:
What you should do is use an Environment File.
Environment files start with .env and allow you to save things that are specific to your working environment (such as sensitive keys).
If you are using nodejs, you can easily import the data from a .env file using require('dotenv').config().
These files are also ignored by the default .gitignore configuration.</p>

Title: HTML .gitignore


问:
Replace values from a string if they are present in an array of variables
Having the following array of objects:

```<code>const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];
</code>```

And the input string:

```<code>const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;
</code>```

The function should take as arguments variables and inputString and return the following sting:

```<code>'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'
</code>```

Here is the function so far:

```<code>function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}
</code>```

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?

答:
We can do a regex replacement with the help of a callback function:

var variables = [
                   {name: '%NAME%', value: 'joe'},
                   {name: '%EMAIL%', value: 'joe@mail.com'},
                   {name: '%HOBBY%', value: 'tennis'}
                  ];
var regex = new RegExp("(" + variables.map(x => x.name).join("|") + ")", "g");
var inputString = "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";
var output = inputString.replace(regex, (m) => {
    return variables.filter(x => x.name == m)[0].value;
});
console.log(output);```

The strategy here is to first build a regex alternation of names from the map.  We do a global regex search for these names in the input string.  For each match, the callback function replaces the name with the value from the map.

Body:
Having the following array of objects:

const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];

And the input string:

const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;

The function should take as arguments variables and inputString and return the following sting:

'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'

Here is the function so far:

function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?

Body:
We can do a regex replacement with the help of a callback function:

var variables = [
                   {name: '%NAME%', value: 'joe'},
                   {name: '%EMAIL%', value: 'joe@mail.com'},
                   {name: '%HOBBY%', value: 'tennis'}
                  ];
var regex = new RegExp("(" + variables.map(x => x.name).join("|") + ")", "g");
var inputString = "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";
var output = inputString.replace(regex, (m) => {
    return variables.filter(x => x.name == m)[0].value;
});
console.log(output);

The strategy here is to first build a regex alternation of names from the map.  We do a global regex search for these names in the input string.  For each match, the callback function replaces the name with the value from the map.


问:
org.apache.flink.streaming.util.serialization.JSONKeyValueDeserializationSchema cannot be converted to ObjectNode
When I used the following code:

```<code>    KafkaSource<ObjectNode> source = KafkaSource.<ObjectNode>builder()
            .setProperties(kafkaProps)
            .setProperty("ssl.truststore.type",trustStoreType)
            .setProperty("ssl.truststore.password",trustStorePassword)
            .setProperty("ssl.truststore.location",trustStoreLocation)
            .setProperty("security.protocol",securityProtocol)
            .setProperty("partition.discovery.interval.ms", partitionDiscoveryIntervalMs)
            .setProperty("commit.offsets.on.checkpoint", commitOffsetsOnCheckpoint)
            .setGroupId(groupId)
            .setTopics(kafkaInputTopic)
            .setDeserializer(new JSONKeyValueDeserializationSchema(false))
            .setStartingOffsets
             (OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
            .build();
</code>```

I get the following error during build
incompatible types: org.apache.flink.streaming.util.serialization.JSONKeyValueDeserializationSchema cannot be converted to org.apache.flink.connector.kafka.source.reader.deserializer.KafkaRecordDeserializationSchema<org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode>

```<code>                .setDeserializer(new JSONKeyValueDeserializationSchema(false))
</code>```

Someone a clue as to what is wrong?

答:
The solution is:</p>
```<code>    KafkaSource<ObjectNode> source = KafkaSource.<ObjectNode>builder()
            .setProperties(kafkaProps)
            .setProperty("ssl.truststore.type",trustStoreType)
            .setProperty("ssl.truststore.password",trustStorePassword)
            .setProperty("ssl.truststore.location",trustStoreLocation)
            .setProperty("security.protocol",securityProtocol)
            .setProperty("partition.discovery.interval.ms", partitionDiscoveryIntervalMs)
            .setProperty("commit.offsets.on.checkpoint", commitOffsetsOnCheckpoint)
            .setGroupId(groupId)
            .setTopics(kafkaInputTopic)
            .setDeserializer(KafkaRecordDeserializationSchema.of(new JSONKeyValueDeserializationSchema(fetchMetadata)))
            .setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
            .build();
</code>```

Body:
When I used the following code:

    KafkaSource<ObjectNode> source = KafkaSource.<ObjectNode>builder()
            .setProperties(kafkaProps)
            .setProperty("ssl.truststore.type",trustStoreType)
            .setProperty("ssl.truststore.password",trustStorePassword)
            .setProperty("ssl.truststore.location",trustStoreLocation)
            .setProperty("security.protocol",securityProtocol)
            .setProperty("partition.discovery.interval.ms", partitionDiscoveryIntervalMs)
            .setProperty("commit.offsets.on.checkpoint", commitOffsetsOnCheckpoint)
            .setGroupId(groupId)
            .setTopics(kafkaInputTopic)
            .setDeserializer(new JSONKeyValueDeserializationSchema(false))
            .setStartingOffsets
             (OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
            .build();

I get the following error during build
incompatible types: org.apache.flink.streaming.util.serialization.JSONKeyValueDeserializationSchema cannot be converted to org.apache.flink.connector.kafka.source.reader.deserializer.KafkaRecordDeserializationSchema<org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode>

                .setDeserializer(new JSONKeyValueDeserializationSchema(false))

Someone a clue as to what is wrong?

Body:
The solution is:

    KafkaSource<ObjectNode> source = KafkaSource.<ObjectNode>builder()
            .setProperties(kafkaProps)
            .setProperty("ssl.truststore.type",trustStoreType)
            .setProperty("ssl.truststore.password",trustStorePassword)
            .setProperty("ssl.truststore.location",trustStoreLocation)
            .setProperty("security.protocol",securityProtocol)
            .setProperty("partition.discovery.interval.ms", partitionDiscoveryIntervalMs)
            .setProperty("commit.offsets.on.checkpoint", commitOffsetsOnCheckpoint)
            .setGroupId(groupId)
            .setTopics(kafkaInputTopic)
            .setDeserializer(KafkaRecordDeserializationSchema.of(new JSONKeyValueDeserializationSchema(fetchMetadata)))
            .setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
            .build();


问:
Laravel 8 Migrate:rollback and migrate error
While I run php artisan:fresh. It rollback all the table in my database and the I run php artisan migrate it will show the error:

```<code>SQLSTATE[HY000]: General error: 1005 Can't create table `online`.`appointps` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `appointps` add constraint `appointps_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
</code>```

答:
It seems the program trying to find foreign key (user_id).

Run the command: php artisan migrate:refresh to drop and migrate all tables.

Warning: This command will drop all tables in DB and re-create them. Use this command only if you are in a test DB.

Body:
While I run php artisan:fresh. It rollback all the table in my database and the I run php artisan migrate it will show the error:

SQLSTATE[HY000]: General error: 1005 Can't create table `online`.`appointps` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `appointps` add constraint `appointps_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)


问:
Not able to align divs' inside a parent div in react
Here is the picture. I want to align the div's (with blue border) from top. I just want the CSS code for this. I tried to use margin but its not working. Also when more content is inserted inside these div's they expand from bottom to top, seems like bottom for these div's  is fixed or something.

what I want is that the Inner div's (with blue border) should be top aligned not bottom aligned and when more text is added inside these div's it should expand from top top to bottom.

here is the CSS code. propertiesContainer class is the parent div with red border and properties class are the inner div's

```<code>propertiesContainer: {
  paddingTop: "26px",
  background: " #EAEAFA",
  border: "1px solid red",
  opacity: 1,
},
properties: {
  bottom: "100px",
  margin: "19px",
  width: "auto",
  border: "2px solid blue",
  height: "262px",
},
</code>```

Reactjs code for this

```<code><section className={classes.propertiesContainer}>
  <HorizontalScroll
    itemClass="MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12"
    data={
      mobile_footer_data &&
      mobile_footer_data.map((data, index) => {
        const { header, body } = data;
        console.log("dataa", data);

        const text = body.map((item, index) => {
          return <div key={index}>{item}</div>;
        });

        return (
          <div key={index} className={classes.properties}>
            <CommonHeaderText
              text={<span>{header}</span>}
              variant="h1"
              style={{
                fontSize: "16px",
                fontWeight: "bold",
                fontFamily: "Open Sans",
                color: "##363636",
                height: "19px",
                marginBottom: "25px",
              }}
            />

            <div>{text}</div>
          </div>
        );
      })
    }
  />
</section>;
</code>```

答:
suppose your parent div has className "parent"
and it has two children "child1" and "child2"
so the css will look like this

```<code>.parent{
   display:flex;
   justify-content:space-between;
   align-items:flex-start;
}
</code>```

Trying applying this to the parent div , hope this solves your issue .

Body:
Here is the picture. I want to align the div's (with blue border) from top. I just want the CSS code for this. I tried to use margin but its not working. Also when more content is inserted inside these div's they expand from bottom to top, seems like bottom for these div's  is fixed or something.

what I want is that the Inner div's (with blue border) should be top aligned not bottom aligned and when more text is added inside these div's it should expand from top top to bottom.

here is the CSS code. propertiesContainer class is the parent div with red border and properties class are the inner div's

propertiesContainer: {
  paddingTop: "26px",
  background: " #EAEAFA",
  border: "1px solid red",
  opacity: 1,
},
properties: {
  bottom: "100px",
  margin: "19px",
  width: "auto",
  border: "2px solid blue",
  height: "262px",
},

Reactjs code for this

  <HorizontalScroll
    itemClass="MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12"
    data={
      mobile_footer_data &&
      mobile_footer_data.map((data, index) => {
        const { header, body } = data;
        console.log("dataa", data);

        const text = body.map((item, index) => {
          return
{item}
;
        });

        return (

            <CommonHeaderText
              text={{header}}
              variant="h1"
              style={{
                fontSize: "16px",
                fontWeight: "bold",
                fontFamily: "Open Sans",
                color: "##363636",
                height: "19px",
                marginBottom: "25px",
              }}
            />

{text}

        );
      })
    }
  />

;

Body:
suppose your parent div has className "parent"
and it has two children "child1" and "child2"
so the css will look like this

.parent{
   display:flex;
   justify-content:space-between;
   align-items:flex-start;
}

Trying applying this to the parent div , hope this solves your issue .


问:
How can I re-render an instance of an element generated while mapping an array in react js?
I'm working on this trivia game, fetching the trivia from Trivia Open DB API. The questions are multiple choice, the correct_answer is a key / value pair, while the incorrect_answer is a key with a value of an array with three incorrect answers, therefore I created a new array with the incorrect answer and randomly inserted the correct answer to that array.

I mapped that array to render once instance for each element of the array and I want to only re-render (change the background color) of the clicked answer, but can't figure out how to do this. I console logged my solution to determine if you clicked the correct answer or not, and it works, but can't figure out how to re-render just the instance that was clicked instead of all the jsx elements of the array. Here's my code:

```<code>import React, {useState, useEffect} from 'react'
import { nanoid } from 'nanoid'

export default function Question(){
    const [questions, setQuestions] = useState("")

    useEffect(function() {

    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
        .then(res => res.json())
        .then(data => setQuestions(data.results.map(triviaQuestion =>{

        const randomPosition = Math.floor(Math.random()*4)
        const questionDisplayed = triviaQuestion.question;
        const incorrectAnswersArray = triviaQuestion.incorrect_answers;
        incorrectAnswersArray.splice(randomPosition, 0, triviaQuestion.correct_answer)
        const possibleAnsewrs = incorrectAnswersArray.map(answer => answer)
        function selectAnswer(event){
            event.target.id == possibleAnsewrs.indexOf(triviaQuestion.correct_answer) ? console.log("Correct!!") : console.log("Incorrect, the answer is: "+triviaQuestion.correct_answer + " " + possibleAnsewrs.indexOf(triviaQuestion.correct_answer))
                }
        const allAnswers = incorrectAnswersArray.map(answer =>
            <p
                id={possibleAnsewrs.indexOf(answer)}
                key={nanoid()}
                onClick={selectAnswer}
                className="question--answers"
                >
                {answer}
            </p>)

        return (
        <div
            key={nanoid()} className='question--container'
            >
            <h3 key={nanoid()} className="question" >{questionDisplayed}</h3>
            <div
                key={nanoid()} className='question--answer-container'>
            {allAnswers}
            </div>
        </div>
        )
    }
        )))
},[])
    return(
            <div>
             {questions}
            </div>
    )
}
</code>```

答:
You are tracking your answers by assigning them an ID, but you're not doing the same for your questions, so we have no way of knowing which question's answer needs to be updated.

You could have two seperate state, one for questions and the other for answers, and for the answers state you could assign an ID that is linked to it's question, but I prefer to simply nest the answers inside the question itself.

Here is my implementation:

```<code>import React, { useState, useEffect } from "react";
import { nanoid } from "nanoid";
import "./style.css";

function shuffle(array) {
  let currentIndex = array.length,
    randomIndex;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex],
      array[currentIndex],
    ];
  }

  return array;
}

function parseClass(answerData) {
  if (answerData.clicked) {
    if (answerData.correct) {
      console.log("Returning correct answer");
      return "correct_answer";
    } else {
      console.log("Returning incorrect answer");
      return "incorrect_answer";
    }
  }
}

export default function Question() {
  const [questions, setQuestions] = useState([]);

  function handleAnswerClick(questionID, answerID) {
    const questionIndex = questions.findIndex(
      (question) => question.ID === questionID
    );
    const answerIndex = questions[questionIndex].answers.findIndex(
      (answer) => answer.ID === answerID
    );
    const newQuestions = [...questions];
    // Update the clicked property
    newQuestions[questionIndex].answers[answerIndex].clicked = true;
    setQuestions(newQuestions);
  }

  useEffect(function () {
    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
      .then((res) => res.json())
      .then((data) => {
        const questionsData = data.results.map(
          (questionData, questionIndex) => {
            // Map the incorrect answers into an array and give them a property "correct" that is assigned to false, and "clicked" that is assigned to false
            let answers = questionData.incorrect_answers.map((answer) => ({
              answer,
              correct: false,
              clicked: false,
            }));

            // Push the correct answer and give it property "correct" assigned to true, and "clicked" that is assigned to false
            answers.push({
              answer: questionData.correct_answer,
              correct: true,
              clicked: false,
            });
            // Shuffle the answers array using above helper function
            answers = shuffle(answers);

            answers = answers.map((answer, answerIndex) => ({
              // Spread the values of each object in answers array
              ...answer,
              // Add an ID property to each answer
              ID: `${questionIndex}-${answerIndex}`,
            }));

            return {
              // Spread the values of each object in data.results array
              ...questionData,
              // Add the answers array we created earlier
              answers,
              // Add property, call it ID
              ID: questionIndex,
            };
          }
        );
        setQuestions(questionsData);
      });
  }, []);

  return (
    <div>
      {questions.length &&
        questions.map((questionData) => (
          <div key={questionData.ID}>
            <p>{questionData.question}</p>
            <br />
            <ul>
              {questionData.answers.map((answerData) => (
                <li
                  key={answerData.ID}
                  onClick={() =>
                    handleAnswerClick(questionData.ID, answerData.ID)
                  }
                  className={parseClass(answerData)}
                >
                  {answerData.answer}
                </li>
              ))}
            </ul>
          </div>
        ))}
    </div>
  );
}
</code>```

Body:
I'm working on this trivia game, fetching the trivia from Trivia Open DB API. The questions are multiple choice, the correct_answer is a key / value pair, while the incorrect_answer is a key with a value of an array with three incorrect answers, therefore I created a new array with the incorrect answer and randomly inserted the correct answer to that array.

I mapped that array to render once instance for each element of the array and I want to only re-render (change the background color) of the clicked answer, but can't figure out how to do this. I console logged my solution to determine if you clicked the correct answer or not, and it works, but can't figure out how to re-render just the instance that was clicked instead of all the jsx elements of the array. Here's my code:

import React, {useState, useEffect} from 'react'
import { nanoid } from 'nanoid'

export default function Question(){
    const [questions, setQuestions] = useState("")

    useEffect(function() {

    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
        .then(res => res.json())
        .then(data => setQuestions(data.results.map(triviaQuestion =>{

        const randomPosition = Math.floor(Math.random()*4)
        const questionDisplayed = triviaQuestion.question;
        const incorrectAnswersArray = triviaQuestion.incorrect_answers;
        incorrectAnswersArray.splice(randomPosition, 0, triviaQuestion.correct_answer)
        const possibleAnsewrs = incorrectAnswersArray.map(answer => answer)
        function selectAnswer(event){
            event.target.id == possibleAnsewrs.indexOf(triviaQuestion.correct_answer) ? console.log("Correct!!") : console.log("Incorrect, the answer is: "+triviaQuestion.correct_answer + " " + possibleAnsewrs.indexOf(triviaQuestion.correct_answer))
                }
        const allAnswers = incorrectAnswersArray.map(answer =>

                {answer}

)

        return (

{questionDisplayed}

            {allAnswers}

        )
    }
        )))
},[])
    return(

             {questions}

    )
}

Body:
You are tracking your answers by assigning them an ID, but you're not doing the same for your questions, so we have no way of knowing which question's answer needs to be updated.

You could have two seperate state, one for questions and the other for answers, and for the answers state you could assign an ID that is linked to it's question, but I prefer to simply nest the answers inside the question itself.

Here is my implementation:

import React, { useState, useEffect } from "react";
import { nanoid } from "nanoid";
import "./style.css";

function shuffle(array) {
  let currentIndex = array.length,
    randomIndex;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex],
      array[currentIndex],
    ];
  }

  return array;
}

function parseClass(answerData) {
  if (answerData.clicked) {
    if (answerData.correct) {
      console.log("Returning correct answer");
      return "correct_answer";
    } else {
      console.log("Returning incorrect answer");
      return "incorrect_answer";
    }
  }
}

export default function Question() {
  const [questions, setQuestions] = useState([]);

  function handleAnswerClick(questionID, answerID) {
    const questionIndex = questions.findIndex(
      (question) => question.ID === questionID
    );
    const answerIndex = questions[questionIndex].answers.findIndex(
      (answer) => answer.ID === answerID
    );
    const newQuestions = [...questions];
    // Update the clicked property
    newQuestions[questionIndex].answers[answerIndex].clicked = true;
    setQuestions(newQuestions);
  }

  useEffect(function () {
    fetch(`https://opentdb.com/api.php?amount=10&category=26&type=multiple`)
      .then((res) => res.json())
      .then((data) => {
        const questionsData = data.results.map(
          (questionData, questionIndex) => {
            // Map the incorrect answers into an array and give them a property "correct" that is assigned to false, and "clicked" that is assigned to false
            let answers = questionData.incorrect_answers.map((answer) => ({
              answer,
              correct: false,
              clicked: false,
            }));

            // Push the correct answer and give it property "correct" assigned to true, and "clicked" that is assigned to false
            answers.push({
              answer: questionData.correct_answer,
              correct: true,
              clicked: false,
            });
            // Shuffle the answers array using above helper function
            answers = shuffle(answers);

            answers = answers.map((answer, answerIndex) => ({
              // Spread the values of each object in answers array
              ...answer,
              // Add an ID property to each answer
              ID: `${questionIndex}-${answerIndex}`,
            }));

            return {
              // Spread the values of each object in data.results array
              ...questionData,
              // Add the answers array we created earlier
              answers,
              // Add property, call it ID
              ID: questionIndex,
            };
          }
        );
        setQuestions(questionsData);
      });
  }, []);

  return (
    <div>
      {questions.length &&
        questions.map((questionData) => (
          <div key={questionData.ID}>
            <p>{questionData.question}</p>
            <br />
            <ul>
              {questionData.answers.map((answerData) => (
                <li
                  key={answerData.ID}
                  onClick={() =>
                    handleAnswerClick(questionData.ID, answerData.ID)
                  }
                  className={parseClass(answerData)}
                >
                  {answerData.answer}
                </li>
              ))}
            </ul>
          </div>
        ))}
    </div>
  );
}


问:
Last characters trimmed in codeigniter captcha when image default width decreased
I am using codeIgniter 3.1.11.

Default width of captcha image is 150 that contains all the words inside the captcha image.

But when I changed the img_width to 50 according to my need, it is trimming last characters.

Code is as follows:

```<code>$vals = array(
        'word'          => '',
        'img_path'      => './assets/captcha/',
        'img_url'       => base_url().'assets/captcha/',
        'font_path'     => base_url().'assets/fonts/FontAwesome.ttf',
        'img_width'     => 50, // Default is 150 & less than 150 crops last characters
        'img_height'    => 30,
        'expiration'    => 7200,
        'word_length'   => 4,
        'font_size'     => 100,
        'img_id'        => 'cap_img',
        'pool'          => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',

        // White background and border, black text and red grid
        'colors'        => array(
                'background' => array(255, 255, 255),
                'border' => array(255, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
        )
);

$cap = create_captcha($vals);

$data = array(
  'captcha_time'  => $cap['time'],
  'ip_address'    => $this->input->ip_address(),
  'word'          => $cap['word']
);

echo $cap['image'];
</code>```

This is output image

答:
Simple...

You have to do one thing
Go to Captcha_helper.php and search

instead of

```<code>        $x = mt_rand(0, $img_width / ($length / 3));

</code>```

Do Like this

```<code>        $x = mt_rand(0, $img_width / ($length / 1));
</code>```

Body:
I am using codeIgniter 3.1.11.

Default width of captcha image is 150 that contains all the words inside the captcha image.

But when I changed the img_width to 50 according to my need, it is trimming last characters.

Code is as follows:

$vals = array(
        'word'          => '',
        'img_path'      => './assets/captcha/',
        'img_url'       => base_url().'assets/captcha/',
        'font_path'     => base_url().'assets/fonts/FontAwesome.ttf',
        'img_width'     => 50, // Default is 150 & less than 150 crops last characters
        'img_height'    => 30,
        'expiration'    => 7200,
        'word_length'   => 4,
        'font_size'     => 100,
        'img_id'        => 'cap_img',
        'pool'          => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',

        // White background and border, black text and red grid
        'colors'        => array(
                'background' => array(255, 255, 255),
                'border' => array(255, 255, 255),
                'text' => array(0, 0, 0),
                'grid' => array(255, 40, 40)
        )
);

$cap = create_captcha($vals);

$data = array(
  'captcha_time'  => $cap['time'],
  'ip_address'    => $this->input->ip_address(),
  'word'          => $cap['word']
);

echo $cap['image'];

This is output image

Body:
Simple...

You have to do one thing
Go to Captcha_helper.php and search

instead of

        $x = mt_rand(0, $img_width / ($length / 3));

Do Like this

        $x = mt_rand(0, $img_width / ($length / 1));


问:
py-cord: How do I delete the last n messages of a user?
I am writing an anti-spam bot in py-cord and I would like to delete a users last n messages automatically once they reach the pressure limit (= too much spam). My code for just deleting the messages so far is:

```<code>95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1
</code>```

and the error that I get is

```<code>Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Username\OneDrive\Desktop\Dateien\Python\MessageCheck\messagecheck.py", line 98, in on_message
    for msg in channel.messages:
AttributeError: 'CategoryChannel' object has no attribute 'messages'
</code>```

I tried searching for similar questions on StackOverflow, but the closest I got was 50301090, which doesn't quite answer my question as I don't want to use a command for this and it seems like it could put some strain onto the cache if it's run for some time.

答:
message.guild.channels iterates over all channels, categories and voice channels included. Since you can't send a message in either of the mentioned channel types, they don't have the channel.messages attribute, resulting in the error you are getting.

You should iterate over the guild's text channels instead: message.guild.text_channels. That way, the attribute will always be set and you won't get this error anymore

That said, your code does in no way delete the user's last 10 messages. It will search the text channels from top to bottom. If a user wrote 10 messages in the first text channel of the server 2 years ago and spammed 100 in the second text channel right now, your bot will delete the 2 year old messages and leave the spam untouched.

Since you're already using the on_message event, why not keep track of any user's last 10 messages? You could achieve that quite easily by storing the channel and message IDs in a dictionary keyed to the guild and user IDs. That way, if a user exceeds the pressure limit, you can simply iterate over those 10 messages and delete them. Your deletion code would then look something like this (USER_MESSAGES being a placeholder for the offending user's last 10 channel/message ID pairs and assuming your bot client is called bot):

for chl_id, msg_id in USER_MESSAGES:
    msg = await bot.get_channel(chl_id).fetch_message(msg_id)
    await msg.delete()
```

Body:
I am writing an anti-spam bot in py-cord and I would like to delete a users last n messages automatically once they reach the pressure limit (= too much spam). My code for just deleting the messages so far is:

95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1

and the error that I get is

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Username\OneDrive\Desktop\Dateien\Python\MessageCheck\messagecheck.py", line 98, in on_message
    for msg in channel.messages:
AttributeError: 'CategoryChannel' object has no attribute 'messages'

I tried searching for similar questions on StackOverflow, but the closest I got was 50301090, which doesn't quite answer my question as I don't want to use a command for this and it seems like it could put some strain onto the cache if it's run for some time.


问:
How to loop over nested JSON array and filter out search Query in Angular?
I have a complex nested JSON Array and I want to filter it(name property) through based on what user enters in input tag and show it as an autocomplete. A basic of it I have created here on stackblitz click here for the code. I have two entries of name "Tom" in two different objects so when user types Tom it should appear twice in the autocomplete as of now it shows only once. So if I press letter "T" it should show me all the names starting with "T". Here in this case "Tom" twice if I press "To" and if I press just "T" then Tiffany and Tom 2 times. Could you please help me here in the code ?
Any help is appreciated.  Thanks much!

答:
You were on a good path. The only missing thing in this recursive walk is keeping state of matches like this:

filter(arr, term, matches) {
    if (term.length == 0) {
      matches = [];
      document.getElementById('list').innerHTML = '';
    }
    arr.forEach((i) => {
      if (i.name.includes(term)) {
        matches.push(i);
      }
      if (i.children.length > 0) {
        this.filter(i.children, term, matches);
      }
    });
    console.log(matches);

    if (matches.length > 0) {
      document.getElementById('list').innerHTML = matches[0].name;
    }
  }```


问:
JavaFX WebView font issue on Mac
Some sites show gibberish characters instead of the correct text. It only happens on Macs.

For example with GMapsFX:

Online site:

Might be related to OS X 10.11 or 10.12. I tested it with Java 1.8.0_121.

Is there any fix or workaround for this issue?

答:
There is a specific build of OpenJDK that doesn't seem to have these problems. If you are among the affected Mac users, please switch to that version of OpenJDK by following the instructions below.

Download and install the Azul build of OpenJDK 11 version found here (scroll to the bottom of the page) Remember to choose the JDK FX version (not any other versions).

Recommended: Remove the other versions of OpenJDK so that you do not accidentally launch the JAR using the wrong version (this video shows how)

After installation, the command java --version should give the following output:

```<code>openjdk 11.0.12 2021-07-20 LTS
OpenJDK Runtime Environment Zulu11.50+19-CA (build 11.0.12+7-LTS)
OpenJDK 64-Bit Server VM Zulu11.50+19-CA (build 11.0.12+7-LTS, mixed mode)
And `whereis java` should output `/usr/bin/java`
</code>```

Recommended: Set the JAVA_HOME/JDK_HOME system variables to point to /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home

ContentLicense: CC BY-SA 3.0

Title: JavaFX WebView font issue on Mac

Body:
There is a specific build of OpenJDK that doesn't seem to have these problems. If you are among the affected Mac users, please switch to that version of OpenJDK by following the instructions below.

Download and install the Azul build of OpenJDK 11 version found here (scroll to the bottom of the page) Remember to choose the JDK FX version (not any other versions).

Recommended: Remove the other versions of OpenJDK so that you do not accidentally launch the JAR using the wrong version (this video shows how)

After installation, the command java --version should give the following output:

openjdk 11.0.12 2021-07-20 LTS
OpenJDK Runtime Environment Zulu11.50+19-CA (build 11.0.12+7-LTS)
OpenJDK 64-Bit Server VM Zulu11.50+19-CA (build 11.0.12+7-LTS, mixed mode)
And `whereis java` should output `/usr/bin/java`

Recommended: Set the JAVA_HOME/JDK_HOME system variables to point to /Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home


问:
React-native google signin gives Developer Error
I am trying Google login using React-native-google-signin plugin but it gives me a Developer_Error.I have done exctly same as mention in its document.here is my code ans steps.

1.Installed react-native-google-signin plugin using npm i react-native-google-signin.
2.Then have linked it with react-native link react-native-google-signin
3.After that i did setup of build.gradle file as they mention it in the documents.

```<code>    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
        googlePlayServicesAuthVersion = "15.0.1"
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:3.2.1'
    }
    allprojects {
        repositories {
                mavenLocal()
                google()
                maven {url "https://maven.google.com"}
                jcenter()
                maven {
                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                url "$rootDir/../node_modules/react-native/android"
                }
                maven {
                    url 'https://maven.google.com/'
                    name 'Google'
                }
        }
    }
</code>```

4.Updated android/app/build.gradle,

```<code>    dependencies {

        implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
        implementation project(':react-native-fbsdk')
        compile project(':react-native-vector-icons')
        compile project(':react-native-fused-location')
        compile project(':react-native-fs')
        compile project(':react-native-image-resizer')
        compile project(':react-native-geocoder')
        compile project(':react-native-device-info')
        compile project(':react-native-image-picker')
        compile fileTree(dir: "libs", include: ["*.jar"])
        compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
        compile "com.facebook.react:react-native:+"  // From node_modules
        implementation project(":react-native-google-signin")
        compile (project(':react-native-maps')){
            exclude group: "com.google.android.gms"
        }
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.google.android.gms:play-services-maps:15.0.1'
        implementation 'com.google.android.gms:play-services-location:15.0.1'
        implementation 'com.google.android.gms:play-services-base:15.0.1'

    }

    task copyDownloadableDepsToLibs(type: Copy) {
        from configurations.compile
        into 'libs'
    }
    apply plugin: 'com.google.gms.google-services'
</code>```

5.Then generate SHA1 key using android studion debug.keystore and generate google-services.json file in firebase.

6.Then setting up login.js page like this.

```<code>    async componentDidMount() {
        this._configureGoogleSignIn();

    }
    _configureGoogleSignIn() {
        GoogleSignin.configure({
            webClientId: '775060548127-5nfj43q15l75va9pfav2jettkha7hm2a.apps.googleusercontent.com',// my clientID
            offlineAccess: false
        });
    }
    async GoogleSignin() {
    try {
        await GoogleSignin.hasPlayServices();
        const userInfo = await GoogleSignin.signIn();
        // this.setState({ userInfo, error: null });
        Alert.alert("success:" + JSON.stringify(userInfo));

    } catch (error) {
        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            // sign in was cancelled
            Alert.alert('cancelled');
        } else if (error.code === statusCodes.IN_PROGRESS) {
            // operation in progress already
            Alert.alert('in progress');
        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            Alert.alert('play services not available or outdated');
        } else {
            Alert.alert('Something went wrong', error.toString());
            this.setState({
                error,
            });
        }
    }
}
</code>```

These are my details so please someone help me on this i cannot find the appropriate solution online.and yes my SHA1 and clientID is correct i have cheked it already.

答:
What happened with me can be extremely rare but still posting here incase someone face it too because I spent a whole day in this.
So for me my SHA1 keys were also fine on both google cloud locally and firebase everything was perfect still it was only working on debug build and on release builds I was getting a DEVELOPER ERROR.

after spending lot of time we got to know that whatever we were changing was not getting included in the release build instead we were getting a cached version every time. and finally we get it solved by clearing the cache by doing this .

Body:
I am trying Google login using React-native-google-signin plugin but it gives me a Developer_Error.I have done exctly same as mention in its document.here is my code ans steps.

1.Installed react-native-google-signin plugin using npm i react-native-google-signin.
2.Then have linked it with react-native link react-native-google-signin
3.After that i did setup of build.gradle file as they mention it in the documents.

    ext {
        buildToolsVersion = "27.0.3"
        minSdkVersion = 16
        compileSdkVersion = 27
        targetSdkVersion = 26
        supportLibVersion = "27.1.1"
        googlePlayServicesAuthVersion = "15.0.1"
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'com.google.gms:google-services:3.2.1'
    }
    allprojects {
        repositories {
                mavenLocal()
                google()
                maven {url "https://maven.google.com"}
                jcenter()
                maven {
                // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
                url "$rootDir/../node_modules/react-native/android"
                }
                maven {
                    url 'https://maven.google.com/'
                    name 'Google'
                }
        }
    }

4.Updated android/app/build.gradle,

    dependencies {

        implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
        implementation project(':react-native-fbsdk')
        compile project(':react-native-vector-icons')
        compile project(':react-native-fused-location')
        compile project(':react-native-fs')
        compile project(':react-native-image-resizer')
        compile project(':react-native-geocoder')
        compile project(':react-native-device-info')
        compile project(':react-native-image-picker')
        compile fileTree(dir: "libs", include: ["*.jar"])
        compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
        compile "com.facebook.react:react-native:+"  // From node_modules
        implementation project(":react-native-google-signin")
        compile (project(':react-native-maps')){
            exclude group: "com.google.android.gms"
        }
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.google.android.gms:play-services-maps:15.0.1'
        implementation 'com.google.android.gms:play-services-location:15.0.1'
        implementation 'com.google.android.gms:play-services-base:15.0.1'

    }

    task copyDownloadableDepsToLibs(type: Copy) {
        from configurations.compile
        into 'libs'
    }
    apply plugin: 'com.google.gms.google-services'

5.Then generate SHA1 key using android studion debug.keystore and generate google-services.json file in firebase.

6.Then setting up login.js page like this.

    async componentDidMount() {
        this._configureGoogleSignIn();

    }
    _configureGoogleSignIn() {
        GoogleSignin.configure({
            webClientId: '775060548127-5nfj43q15l75va9pfav2jettkha7hm2a.apps.googleusercontent.com',// my clientID
            offlineAccess: false
        });
    }
    async GoogleSignin() {
    try {
        await GoogleSignin.hasPlayServices();
        const userInfo = await GoogleSignin.signIn();
        // this.setState({ userInfo, error: null });
        Alert.alert("success:" + JSON.stringify(userInfo));

    } catch (error) {
        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            // sign in was cancelled
            Alert.alert('cancelled');
        } else if (error.code === statusCodes.IN_PROGRESS) {
            // operation in progress already
            Alert.alert('in progress');
        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            Alert.alert('play services not available or outdated');
        } else {
            Alert.alert('Something went wrong', error.toString());
            this.setState({
                error,
            });
        }
    }
}

These are my details so please someone help me on this i cannot find the appropriate solution online.and yes my SHA1 and clientID is correct i have cheked it already.


问:
Convert from String to either LocalDateTime or ZonedDateTime
Hi I want to convert String value 2020-12-16T19:20:30+01:00 UTC to either LocalDateTime or ZonedDateTime in java

I tried solution:

```<code>DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-DDThh:mm:ssTZD", Locale.ENGLISH);
final String responseTimeStamp = "2020-12-16T19:20:30+01:00 UTC";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
</code>```

Which gives me the error

Exception in thread "main" java.lang.IllegalArgumentException: Unknown pattern letter: T at java.base/java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1815) at java.base/java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1712) at java.base/java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:588) at learning/learning.SpringDemo.main(SpringDemo.java:21)

答:
tl;dr

```<code>OffsetDateTime
.parse(
    "2020-12-16T19:20:30+01:00 UTC"
    .replace( " UTC" , "" )
)
.withZoneSameInstant(
    ZoneId.of( "America/Edmonton" )
)
</code>```

ISO 8601

Your input string:

2020-12-16T19:20:30+01:00 UTC

… nearly complies with the ISO 8601 standard for data-exchange date-time formats. To fully comply, delete the SPACE and UTC from the end. The +01:00 at the end means “one hour ahead of UTC", so the UTC at the end is redundant.

String input = "2020-12-16T19:20:30+01:00 UTC".replace( " UTC" , "" ) ;

Offset versus time zone

Parse as an OffsetDateTime because your input indicates small offset from UTC, not a time zone.

An offset is merely a number of hours-minutes-seconds ahead/behind the prime meridian of UTC. A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians. A time zone has a name in format of Continent/Region, such as Europe/Paris and Africa/Tunis.

OffsetDateTime

So the other Answer’s suggestion to use ZonedDateTime for parsing is misguided as no time zone is indicated. Your input has only an offset, therefore use OffsetDateTime.

No need to specify a formatting pattern. Our modified input complies with ISO 8601, and the java.time classes use those standard formats by default when parsing/generating strings.

```<code>OffsetDateTime odt = OffsetDateTime.parse( input ) ;
</code>```

LocalDateTime

You asked how to get a LocalDateTime. That class lacks any concept of offset or time zone. So beware, if you convert from OffsetDateTime, you are discarding valuable information.

So while I don’t recommend doing this, here is the code.

```<code>LocalDateTime ldt = odt.toLocalDateTime() ;
</code>```

ZonedDateTime

You asked how to adjust into a time zone.

To adjust from our offset to a time zone, merely specify the desired time zone.

```<code>ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = odt.withZoneSameInstant( z ) ;
</code>```

Body:
Hi I want to convert String value 2020-12-16T19:20:30+01:00 UTC to either LocalDateTime or ZonedDateTime in java

I tried solution:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-DDThh:mm:ssTZD", Locale.ENGLISH);
final String responseTimeStamp = "2020-12-16T19:20:30+01:00 UTC";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);

Which gives me the error

Exception in thread "main" java.lang.IllegalArgumentException: Unknown pattern letter: T at java.base/java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1815) at java.base/java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1712) at java.base/java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:588) at learning/learning.SpringDemo.main(SpringDemo.java:21)

Body:
tl;dr

OffsetDateTime
.parse(
    "2020-12-16T19:20:30+01:00 UTC"
    .replace( " UTC" , "" )
)
.withZoneSameInstant(
    ZoneId.of( "America/Edmonton" )
)

ISO 8601

Your input string:

2020-12-16T19:20:30+01:00 UTC

… nearly complies with the ISO 8601 standard for data-exchange date-time formats. To fully comply, delete the SPACE and UTC from the end. The +01:00 at the end means “one hour ahead of UTC", so the UTC at the end is redundant.

String input = "2020-12-16T19:20:30+01:00 UTC".replace( " UTC" , "" ) ;

Offset versus time zone

Parse as an OffsetDateTime because your input indicates small offset from UTC, not a time zone.

An offset is merely a number of hours-minutes-seconds ahead/behind the prime meridian of UTC. A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region as decided by their politicians. A time zone has a name in format of Continent/Region, such as Europe/Paris and Africa/Tunis.

OffsetDateTime

So the other Answer’s suggestion to use ZonedDateTime for parsing is misguided as no time zone is indicated. Your input has only an offset, therefore use OffsetDateTime.

No need to specify a formatting pattern. Our modified input complies with ISO 8601, and the java.time classes use those standard formats by default when parsing/generating strings.

OffsetDateTime odt = OffsetDateTime.parse( input ) ;

LocalDateTime

You asked how to get a LocalDateTime. That class lacks any concept of offset or time zone. So beware, if you convert from OffsetDateTime, you are discarding valuable information.

So while I don’t recommend doing this, here is the code.

LocalDateTime ldt = odt.toLocalDateTime() ;

ZonedDateTime

You asked how to adjust into a time zone.

To adjust from our offset to a time zone, merely specify the desired time zone.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = odt.withZoneSameInstant( z ) ;


问:
How to move fast after fetching data from api on pressing button Flutter
I want to ask if there is a future function who gives data from api and i want to get that data when i pressed the button and i want some particular data like id of user i am using function like

```<code>onPressed: () async {
     var data = await getLogin()
     if(data.id == 0){
       Navigator.push(context,
                      MaterialPageRoute(builder: ((context) => Login())));
     else {
        Navigator.push(context,
                      MaterialPageRoute(builder: ((context) => Order())));
      }
}
</code>```

Can you tell me why it is taking time when i am pressing button to open new screen and can any one tell me the solution

答:
it is taking time because it await for data. It is a async function and this await keyword wait until you didn't get the data back..

Problem is that if you not use await keyword then data.id throw a null safety error....

So solution is Future Provider... Call the api using the any state management solution like provider and navigate without checking the condition... Then update Ui after getting data from Provider..

Body:
I want to ask if there is a future function who gives data from api and i want to get that data when i pressed the button and i want some particular data like id of user i am using function like

onPressed: () async {
     var data = await getLogin()
     if(data.id == 0){
       Navigator.push(context,
                      MaterialPageRoute(builder: ((context) => Login())));
     else {
        Navigator.push(context,
                      MaterialPageRoute(builder: ((context) => Order())));
      }
}

Can you tell me why it is taking time when i am pressing button to open new screen and can any one tell me the solution


问:
How Could I replace Text in a PPP with Python pptx?
I want to replace the text in a textbox in Powerpoint with Python-pptx.
Everything I found online didn't work for me and the documentation isn't that helpful for me.

So I have a Textbox with the Text:

$$Name 1$$

$$Name 2$$

and I want to change the $$Name1 $$  to Tom.

How can I achieve that?

答:
In order to keep original formatting, we need to replace the text at the run level.</p>
```<code>from pptx import Presentation
ppt = Presentation(file_path_of_pptx)
search_str = '$$Name1$$'
replace_str = 'Tom'

for slide in ppt.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            for paragraph in shape.text_frame.paragraphs:
                for run in paragraph.runs:
                    print(run.text)
                    if(run.text.find(search_str))!=-1:
                        run.text = run.text.replace(search_str, replace_str)

ppt.save(file_path_of_new_pptx)
</code>```

Body:
In order to keep original formatting, we need to replace the text at the run level.

from pptx import Presentation
ppt = Presentation(file_path_of_pptx)
search_str = '$$Name1$$'
replace_str = 'Tom'

for slide in ppt.slides:
    for shape in slide.shapes:
        if shape.has_text_frame:
            for paragraph in shape.text_frame.paragraphs:
                for run in paragraph.runs:
                    print(run.text)
                    if(run.text.find(search_str))!=-1:
                        run.text = run.text.replace(search_str, replace_str)

ppt.save(file_path_of_new_pptx)


问:
application for mobile devices
there are so many platfroms mac/Andriod/windows. can we make one application which will work on all platform  I don't want make seperate binaries for all platforms. will j2me help us in achieving this?</p>

答:
The opinion of this does not sound very high from what I have herd.

There are options such as PhoneGap (based on HTML5). There are others also on the market.

There are compilers which can build native applications for most platforms by adobe (flash & flex based).

Title: application for mobile devices


问:
How do I clear a c variable after use to use it again?
If I send a message over serial the first time it receves the right code it works but after that it stops working.

```<code>    const unsigned int MAX_MESSAGE_LENGTH = 32;
    const char EMPTY[1] = {'\0'};

    void setup() {
      Serial.begin(9600);//bPS
    }

    String readserial(){
      char message[MAX_MESSAGE_LENGTH];
      static unsigned int message_pos = 0;
      while (Serial.available() > 0 ){

        char inbyte = Serial.read();
        if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
          message[message_pos] = inbyte;
          message_pos += 1;
        } else {
          message[message_pos] = '\0';
          //Serial.println(message);
          return message;
        }
      }
      return EMPTY;
    }

    void loop() {
      static String message;
      message = readserial();

      if(message == "Hi"){
        Serial.println("Hello");
      }else{
        //Serial.println(message);
      }
    }
</code>```

the output shows hello only if I say Hi first if I put anything else it just doesn't work.
I have tried looking for an answer elsewhere but I am stuck.

答:
Your message length message_posisn't being reset to zero. Whatever value it has, the value will be "kept" because you have declared it as static.  If you remove the statickeyword, message_pos will be reset to zero every time you call readserial().

You can also, as pointed out, set message_posto zero as you return the string.

However, because you don't actually use (or need) message_pos as static I suggest you simply remove the keyword.

Body:
If I send a message over serial the first time it receves the right code it works but after that it stops working.

    const unsigned int MAX_MESSAGE_LENGTH = 32;
    const char EMPTY[1] = {'\0'};

    void setup() {
      Serial.begin(9600);//bPS
    }

    String readserial(){
      char message[MAX_MESSAGE_LENGTH];
      static unsigned int message_pos = 0;
      while (Serial.available() > 0 ){

        char inbyte = Serial.read();
        if(inbyte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1)){
          message[message_pos] = inbyte;
          message_pos += 1;
        } else {
          message[message_pos] = '\0';
          //Serial.println(message);
          return message;
        }
      }
      return EMPTY;
    }

    void loop() {
      static String message;
      message = readserial();

      if(message == "Hi"){
        Serial.println("Hello");
      }else{
        //Serial.println(message);
      }
    }

the output shows hello only if I say Hi first if I put anything else it just doesn't work.
I have tried looking for an answer elsewhere but I am stuck.


问:
InvalidArguementError: Cannot add tensor to the batch: number of elements does not match
I have a csv file which looks liks this:

I want to load the image (from df['Image_location']) and text (from df['Content']) together, so I did the following operations:

```<code>df = pd.read_csv(csv_data_dir, encoding= 'cp1252')
features = df[['Content', 'Image_location']]
labels = df['Sentiment']
dataset = tf.data.Dataset.from_tensor_slices((features, labels))

def process_path(x):
  content, image_path = x[0],  x[1]
  print(image_path)
  img = tf.io.read_file(image_path)
  img = tf.io.decode_jpeg(img, channels=3)
  return content, img

dataset = dataset.map(lambda x, y: (process_path(x), y))

dataset = dataset.batch(32, drop_remainder = True)
</code>```

Upon running the training loop:

```<code>for step , (x, y) in enumerate(dataset):
  print(f"Step:{step}")
</code>```
```<code>InvalidArgumentError                      Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19112/3450653832.py in <module>
      1 import matplotlib.pyplot as plt
----> 2 for step , (x, y) in enumerate(dataset):
      3   print(f"Step:{step}")
      4   content = x[0]
      5   image = x[1]

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py in __next__(self)
    798   def __next__(self):
    799     try:
--> 800       return self._next_internal()
    801     except errors.OutOfRangeError:
    802       raise StopIteration

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py in _next_internal(self)
    781     # to communicate that there is no more data to iterate over.
    782     with context.execution_mode(context.SYNC):
--> 783       ret = gen_dataset_ops.iterator_get_next(
    784           self._iterator_resource,
    785           output_types=self._flat_output_types,

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\ops\gen_dataset_ops.py in iterator_get_next(iterator, output_types, output_shapes, name)
   2842       return _result
   2843     except _core._NotOkStatusException as e:
-> 2844       _ops.raise_from_not_ok_status(e, name)
   2845     except _core._FallbackException:
   2846       pass

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\framework\ops.py in raise_from_not_ok_status(e, name)
   7105 def raise_from_not_ok_status(e, name):
   7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None  # pylint: disable=protected-access
   7108
   7109

InvalidArgumentError: Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [344,500,3], [batch]: [500,333,3] [Op:IteratorGetNext]
</code>```

Any idea where I'm going wrong or how to batch this dataset properly as without dataset = dataset.batch(32, drop_remainder = True), the code works fine.

答:
I can imagine that not all images have the same shape and that is why you are getting mismatches when batch_size > 1. I would recommend resizing all images to the same size. Here is an example:

def process_path(x):
  content, image_path = x[0], x[1]
  img = tf.io.read_file(image_path)
  img = tf.io.decode_png(img, channels=3)
  img = tf.image.resize(img,[120, 120], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
  return content, img
```

Otherwise, you will have to sort your batches by image size and also take care of the labels.

Body:
I have a csv file which looks liks this:

I want to load the image (from df['Image_location']) and text (from df['Content']) together, so I did the following operations:

df = pd.read_csv(csv_data_dir, encoding= 'cp1252')
features = df[['Content', 'Image_location']]
labels = df['Sentiment']
dataset = tf.data.Dataset.from_tensor_slices((features, labels))

def process_path(x):
  content, image_path = x[0],  x[1]
  print(image_path)
  img = tf.io.read_file(image_path)
  img = tf.io.decode_jpeg(img, channels=3)
  return content, img

dataset = dataset.map(lambda x, y: (process_path(x), y))

dataset = dataset.batch(32, drop_remainder = True)

Upon running the training loop:

for step , (x, y) in enumerate(dataset):
  print(f"Step:{step}")

InvalidArgumentError                      Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_19112/3450653832.py in <module>
      1 import matplotlib.pyplot as plt
----> 2 for step , (x, y) in enumerate(dataset):
      3   print(f"Step:{step}")
      4   content = x[0]
      5   image = x[1]

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py in __next__(self)
    798   def __next__(self):
    799     try:
--> 800       return self._next_internal()
    801     except errors.OutOfRangeError:
    802       raise StopIteration

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\data\ops\iterator_ops.py in _next_internal(self)
    781     # to communicate that there is no more data to iterate over.
    782     with context.execution_mode(context.SYNC):
--> 783       ret = gen_dataset_ops.iterator_get_next(
    784           self._iterator_resource,
    785           output_types=self._flat_output_types,

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\ops\gen_dataset_ops.py in iterator_get_next(iterator, output_types, output_shapes, name)
   2842       return _result
   2843     except _core._NotOkStatusException as e:
-> 2844       _ops.raise_from_not_ok_status(e, name)
   2845     except _core._FallbackException:
   2846       pass

~\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\framework\ops.py in raise_from_not_ok_status(e, name)
   7105 def raise_from_not_ok_status(e, name):
   7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None  # pylint: disable=protected-access
   7108
   7109

InvalidArgumentError: Cannot add tensor to the batch: number of elements does not match. Shapes are: [tensor]: [344,500,3], [batch]: [500,333,3] [Op:IteratorGetNext]

Any idea where I'm going wrong or how to batch this dataset properly as without dataset = dataset.batch(32, drop_remainder = True), the code works fine.

Body:
I can imagine that not all images have the same shape and that is why you are getting mismatches when batch_size > 1. I would recommend resizing all images to the same size. Here is an example:

def process_path(x):
  content, image_path = x[0], x[1]
  img = tf.io.read_file(image_path)
  img = tf.io.decode_png(img, channels=3)
  img = tf.image.resize(img,[120, 120], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
  return content, img

Otherwise, you will have to sort your batches by image size and also take care of the labels.


问:
How can I get query string values in JavaScript?
Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?

答:
Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.

```<code>var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p=a[i].split('=', 2);
        if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));
</code>```

IMPORTANT! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the current URL.

So what exactly changed? With url http://sb.com/reg/step1?param= results will be same. But with url http://sb.com/reg/step1?param Bruno's solution returns an object without keys, while mine returns an object with key param and undefined value.

Body:
Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.

var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p=a[i].split('=', 2);
        if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));

IMPORTANT! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the current URL.

So what exactly changed? With url http://sb.com/reg/step1?param= results will be same. But with url http://sb.com/reg/step1?param Bruno's solution returns an object without keys, while mine returns an object with key param and undefined value.


问:
Python - error 98 Adress already in use, how to make it faster? So that on kill and quick restart it does not fail?
I have a Python protocol running under CentOS 6.4/64-bit. Where i am having TCP server port 7007. In some cases like update new version or maintenance or on the fly restart to refresh buffer i need to restart the application as:

server.py:

```<code>class AServer(threading.Thread):
  def __init__(self, port):
    threading.Thread.__init__(self)
    self.port = port

  def run(self):
    host = ''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, self.port))
    print bgcolors.BOOT
    s.listen(1)
    conn, addr = s.accept()
    print bgcolors.OK + 'contact', addr, 'on', self.now()

    while 1:
      try:
        data = conn.recv(1024)
      except socket.error:
        print bgcolors.OK + 'lost', addr, 'waiting..'
        s.listen(1)
        conn, addr = s.accept()
        print bgcolors.OK + 'contact', addr, 'on', self.now()
        continue
      if not data:
        .....
      ...

t = AServer(7007)
t.start()
</code>```

Restart urgent on the fly (expecting to run within 1 second) but fails:

```<code>$ ps aux | awk '/server.py/ {print $2}' | head -1 | xargs kill -9;
$ nohup python /var/tmp/py-protocol/server.py &
[root@IPSecVPN protocol]# python server.py
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "server.py", line 236, in run
    s.bind((host, self.port))
  File "<string>", line 1, in bind
error: [Errno 98] Address already in use
</code>```

答:
Open your terminal:

```<code>ps aux || grep
</code>```

list all running services and find the id you want to kill.

```<code>sudo kill -9 <id you want to kill>
</code>```

Body:
I have a Python protocol running under CentOS 6.4/64-bit. Where i am having TCP server port 7007. In some cases like update new version or maintenance or on the fly restart to refresh buffer i need to restart the application as:

server.py:

class AServer(threading.Thread):
  def __init__(self, port):
    threading.Thread.__init__(self)
    self.port = port

  def run(self):
    host = ''
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, self.port))
    print bgcolors.BOOT
    s.listen(1)
    conn, addr = s.accept()
    print bgcolors.OK + 'contact', addr, 'on', self.now()

    while 1:
      try:
        data = conn.recv(1024)
      except socket.error:
        print bgcolors.OK + 'lost', addr, 'waiting..'
        s.listen(1)
        conn, addr = s.accept()
        print bgcolors.OK + 'contact', addr, 'on', self.now()
        continue
      if not data:
        .....
      ...

t = AServer(7007)
t.start()

Restart urgent on the fly (expecting to run within 1 second) but fails:

$ ps aux | awk '/server.py/ {print $2}' | head -1 | xargs kill -9;
$ nohup python /var/tmp/py-protocol/server.py &
[root@IPSecVPN protocol]# python server.py
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
    self.run()
  File "server.py", line 236, in run
    s.bind((host, self.port))
  File "<string>", line 1, in bind
error: [Errno 98] Address already in use

Body:
Open your terminal:

ps aux || grep

list all running services and find the id you want to kill.

sudo kill -9 <id you want to kill>


问:
MapBox markers Move on zooming
I'm working on MapBoxgl and I want to add several markers.

Here is my index.html:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
        <link href=" /assets/css/bootstrap.min.css " rel="stylesheet" />
        <link href=" /assets/css/mapbox-gl.css " rel="stylesheet" />
        <link href=" /assets/css/main.css " rel="stylesheet" />
</head>
<body>
        <div id="map"></div>

<script src="/assets/js/mapbox-gl.js"></script>
<script src="/assets/js/map-style.js"></script>

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

This is map-style.js:

```<code>var map = new mapboxgl.Map({
  container: 'map',
  center: [57.3221, 33.5928],
  zoom: 5,
  style: style
});

var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
  type: 'Point',
coordinates: [30.61, 46.28]
},
properties: {
  title: 'point 1',
  description: 'point 1 Description',
  message: 'point1',
  iconSize: [25, 25]
}
},
{
type: 'Feature',
geometry: {
  type: 'Point',
coordinates: [30.62, 46.2845]
},
properties: {
  title: 'point 2',
  description: 'point 2 Description',
  message: 'point 2',
  iconSize: [25, 25]
 }
  }]
};

map.on('load', function () {
// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'markers';
el.style.backgroundImage = 'url(assets/marker-azure.png)';
//el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';

el.addEventListener('click', function() {
    window.alert(marker.properties.message);
});

// add marker to map
new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);
});
});
</code>```

And following is main.css portion related to map and marker:

```<code>#map { position:absolute; top:0; bottom:0; width:100% }

.markers {
    display: absolute;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    padding: 0;
}
</code>```

So, my problem is that when I add width property to markers, their icon be displayed correctly (with a bit stretch) but they are in wrong coordinate and move on zoom, like picture below:

On the other hand, if width property is eliminated, they are in right place and does not move on zooming, but they are very stretched and in fact as wide as screen (following image):

It's noteworthy that I've used bootstrap. Can it be the reason of this? If not, what's the problem?

Thanks

答:
In my case the svg I used had some space around the real content. That way it seemed for me that the marker was moving. A simple fix was to remove the space around the content (e.g. with the "Resize page to drawing or selection" option of inkscape: https://graphicdesign.stackexchange.com/a/21638)

Also it is important to set display: block on the svg-marker. See: https://stackoverflow.com/a/39716426/11603006

Title: MapBox markers Move on zooming

Body:
I'm working on MapBoxgl and I want to add several markers.

Here is my index.html:

<!DOCTYPE html>

    <meta charset="UTF-8" />
        <link href=" /assets/css/bootstrap.min.css " rel="stylesheet" />
        <link href=" /assets/css/mapbox-gl.css " rel="stylesheet" />
        <link href=" /assets/css/main.css " rel="stylesheet" />

This is map-style.js:

var map = new mapboxgl.Map({
  container: 'map',
  center: [57.3221, 33.5928],
  zoom: 5,
  style: style
});

var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
  type: 'Point',
coordinates: [30.61, 46.28]
},
properties: {
  title: 'point 1',
  description: 'point 1 Description',
  message: 'point1',
  iconSize: [25, 25]
}
},
{
type: 'Feature',
geometry: {
  type: 'Point',
coordinates: [30.62, 46.2845]
},
properties: {
  title: 'point 2',
  description: 'point 2 Description',
  message: 'point 2',
  iconSize: [25, 25]
 }
  }]
};

map.on('load', function () {
// add markers to map
geojson.features.forEach(function(marker) {
// create a DOM element for the marker
var el = document.createElement('div');
el.className = 'markers';
el.style.backgroundImage = 'url(assets/marker-azure.png)';
//el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';

el.addEventListener('click', function() {
    window.alert(marker.properties.message);
});

// add marker to map
new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);
});
});

And following is main.css portion related to map and marker:

#map { position:absolute; top:0; bottom:0; width:100% }

.markers {
    display: absolute;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    padding: 0;
}

So, my problem is that when I add width property to markers, their icon be displayed correctly (with a bit stretch) but they are in wrong coordinate and move on zoom, like picture below:

On the other hand, if width property is eliminated, they are in right place and does not move on zooming, but they are very stretched and in fact as wide as screen (following image):

It's noteworthy that I've used bootstrap. Can it be the reason of this? If not, what's the problem?

Thanks


问:
Is there a function for closing app on mouse or keyboard movement in Python
I want my Tkinter app to close when keyboard or mouse movement is detected. I made a simple version in console, and it works as expected. However, when implementing this into a window app, it does not detect anything, only when I close the app in ALT+F4. Below was the implantation for console. I want this to work specifically in a window as I am trying to build a screensaver type app.

```<code>for i in range(100):
    a = int(win32api.GetLastInputInfo())
    print(win32api.GetLastInputInfo())
    time.sleep(0.5)

    if win32api.GetLastInputInfo() == a:
        print("Idle")
    else:
        print("Mouse or keyboard input received!")
</code>```

答:
You can automate movements of mouse and keyboard using pyautogui module in python. This module is not preloaded with python. So to install it run the following command:
pip3 install pyautogui

For quitting the running code we can use this..
pyautogui.hotkey('ctrl','c')

Body:
I want my Tkinter app to close when keyboard or mouse movement is detected. I made a simple version in console, and it works as expected. However, when implementing this into a window app, it does not detect anything, only when I close the app in ALT+F4. Below was the implantation for console. I want this to work specifically in a window as I am trying to build a screensaver type app.

for i in range(100):
    a = int(win32api.GetLastInputInfo())
    print(win32api.GetLastInputInfo())
    time.sleep(0.5)

    if win32api.GetLastInputInfo() == a:
        print("Idle")
    else:
        print("Mouse or keyboard input received!")


问:
how to delete object from the array of objects in mongoose

I have notes nested in userSchema I am trying to delete one object by _id but deleteOne is removing the whole user object so how can I can delete the one with _id

```<code>const keeperSchema = mongoose.Schema({
    noteName:String,
    noteContent:String,
    })

const userSchema = mongoose.Schema({
    email:String,
    password:String,
    notes:[keeperSchema]
    })

app.post("/delete",(req,res)=>{
    const id=req.body.id
    const email=req.body.email
    console.log(id)

    Keeper.deleteOne({"notes._id":id}).then(()=>{
        Keeper.find({email:email},(err,results)=>{
            if(results){
                console.log(results)
           }
        })
    })

   })
</code>```

答:
you can do it like so:

```<code>  userModel.updateOne({_id: idofUser}, {$pull: {notes: {_id: idofnote}}})
</code>```

you should query on your userModel because you want to pull an element from keeper array which is stored in user so you have to determine from which user you want to delete your note thats why you need to have the id of user. if you want to delete a specific note from all of the users just clear your condition like so:

```<code>  userModel.updateMany({}, {$pull: {notes: {_id: idofnote}}})
</code>```

Body:
I have notes nested in userSchema I am trying to delete one object by _id but deleteOne is removing the whole user object so how can I can delete the one with _id

const keeperSchema = mongoose.Schema({
    noteName:String,
    noteContent:String,
    })

const userSchema = mongoose.Schema({
    email:String,
    password:String,
    notes:[keeperSchema]
    })

app.post("/delete",(req,res)=>{
    const id=req.body.id
    const email=req.body.email
    console.log(id)

    Keeper.deleteOne({"notes._id":id}).then(()=>{
        Keeper.find({email:email},(err,results)=>{
            if(results){
                console.log(results)
           }
        })
    })

   })

Body:
you can do it like so:

  userModel.updateOne({_id: idofUser}, {$pull: {notes: {_id: idofnote}}})

you should query on your userModel because you want to pull an element from keeper array which is stored in user so you have to determine from which user you want to delete your note thats why you need to have the id of user. if you want to delete a specific note from all of the users just clear your condition like so:

  userModel.updateMany({}, {$pull: {notes: {_id: idofnote}}})