问:
What if we dont have Quartz Schedulers tables
Need help with a very basic question (actually I am very beginner to Quartz Scheduling just today started learning from https://flylib.com/books/en/2.65.1/ since one of migration project I am working is using this.)

Problem statement-

1) We are using JobStoreCMT with two WebLogic data sources, do we really need Persistent Job Store tables (those basic 12 quartz schedulers tables)?

2) I ran QuartzScheduler but do not see any insertions / updation in JobStore Tables, is something wrong here?

3) Before running Quartz Scheduler Job do we need to do any configuration in quartz persistent job store tables like qrtz_job_details?

4) Any other configurations, if required.

Quick help would be highly appreciated.

答:
I also start using the library aproximatelly a month ago, and I suggest you to read the official docs. They are really helpful

1) JobStoreCMT is a implemetation of persistent job store. so the answer is yes, you need quartz tables
From docs http://www.quartz-scheduler.org/documentation/2.3.1-SNAPSHOT/introduction.html

Transactions

  Quartz can participate in JTA transactions, via the use
  of JobStoreCMT (a subclass of JDBCJobStore).

2) If you do not schedule any jobs, there will be no new records. Also you may not configured you quartz scheduller correctly. When initializing, you need for example provide, quartz properties file, with location of you quartz tables.
Docs
http://www.quartz-scheduler.org/documentation/2.3.1-SNAPSHOT/quick-start-guide.html#the-properties-file

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-09.html#TutorialLesson9-JDBCJobStore

Generally, when you start you application, you will have one record with scheduler id in you quartz scheduler table.
Once you created job with trigger, you will see info in jobs table and in triggers table

3) you shouldn't do anything manually with quart tables, you need to interact with quartz only with scheduler api
Check this lessons to start
http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/index.html

4) for basic usage, no additional configuration is required


来源: stackexchange

问:
Spring JPA: Issue with shared PK in one-to-one relationship
I am trying to create a relationship one-to-one with a shared PK, but I am straggled after trying many things...

I will try to provide all the possible information:

Technologies that I am using:

Spring Boot 2.1.5

Spring JPA

Flyway

Datasource configuration:

```<code>spring.datasource.url = jdbc:mysql://localhost:3306/customers?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username = admin
spring.datasource.password = root

spring.jpa.database-platform = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql = true
</code>```

Database models:

```<code>@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "customer", schema = "customers")
public class Customer {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "customer_id", columnDefinition = "BINARY(16)")
    private UUID customerId;

    @OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
    private Address address;
}

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "address", schema = "customers")
public class Address {

    @Id
    @Column(name = "address_id", columnDefinition = "BINARY(16)")
    private UUID addressId;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Customer customer;
}
</code>```

Flyway migration files:

```<code>CREATE SCHEMA IF NOT EXISTS CUSTOMERS;

CREATE TABLE CUSTOMERS.CUSTOMER
(
    customer_id BINARY(16) NOT NULL PRIMARY KEY,
) ENGINE = InnoDB;

CREATE TABLE CUSTOMERS.ADDRESS
(
    address_id BINARY(16) NOT NULL PRIMARY KEY,
) ENGINE = InnoDB;

ALTER table CUSTOMERS.ADDRESS
ADD CONSTRAINT fk_customer_address
FOREIGN KEY (address_id)
REFERENCES CUSTOMERS.CUSTOMER (customer_id);
</code>```

Integration test:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryIntegrationTest {

    @Autowired
    private CustomerRepository cut;

    @Test
        public void testSaveAndDeleteCustomer() {
            Address address = new Address();
            Customer customer = new Customer();
            customer.setAddress(address);

            cut.save(customer);

            Customer retrievedCustomer = cut.findAll().get(0);
            assertEquals(customer, retrievedCustomer);
        }
}
</code>```

Error:

```<code>ERROR] testSaveAndDeleteCustomer(com.foxhound.customers.repositories.CustomerRepositoryIntegrationTest)  Time elapsed: 0.034 s  <<< ERROR!
org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [com.foxhound.customers.models.Address.customer]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.foxhound.customers.models.Address.customer]
    at com.foxhound.customers.repositories.CustomerRepositoryIntegrationTest.testSaveAndDeleteCustomer(CustomerRepositoryIntegrationTest.java:47)
Caused by: org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.foxhound.customers.models.Address.customer]
    at com.foxhound.customers.repositories.CustomerRepositoryIntegrationTest.testSaveAndDeleteCustomer(CustomerRepositoryIntegrationTest.java:47)
</code>```

Thank you in advance for the help.

Cheers!

答:
You don't understand how bidirectional mapping is working, so you need to think through that. The code

```<code>@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Customer customer;
</code>```

in Address makes the mapping unidirectional. Normally in order to save this you will need to set the customer field and save it.

```<code>address.setCustomer(customer);
addressRepo.save(address);
</code>```

However you have defined a bidirectional mapping and provided a cascading annotation.

```<code>@OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
private Address address;
</code>```

The cascading annotation alleviates you from having to do two persistence operations (in your code), but it does not mean you do not have to set the customer field in address. Additionally, as you have noticed, in order for the cascade operation to work you need to set the address field of customer.

```<code>customer.setAddress(address);
</code>```

So, for the code to work properly you need to change it to set the customer in address.

```<code>Address address = new Address();
Customer customer = new Customer();
customer.setAddress(address);
address.setCustomer(customer);
customerRepo.save(customer);
</code>```

With a bidirectional mapping you have to manage both sides of the relationship or use it in a unidirectional manner for persisting and a bidirectional manner for retrieving. If you add a cascade annotation then you have to manage both sides of the relationship for persisting as well.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a relationship one-to-one with a shared PK, but I am straggled after trying many things...

I will try to provide all the possible information:

Technologies that I am using:

Spring Boot 2.1.5

Spring JPA

Flyway

Datasource configuration:

spring.datasource.url = jdbc:mysql://localhost:3306/customers?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username = admin
spring.datasource.password = root

spring.jpa.database-platform = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql = true

Database models:

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "customer", schema = "customers")
public class Customer {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "customer_id", columnDefinition = "BINARY(16)")
    private UUID customerId;

    @OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
    private Address address;
}

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "address", schema = "customers")
public class Address {

    @Id
    @Column(name = "address_id", columnDefinition = "BINARY(16)")
    private UUID addressId;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Customer customer;
}

Flyway migration files:

CREATE SCHEMA IF NOT EXISTS CUSTOMERS;

CREATE TABLE CUSTOMERS.CUSTOMER
(
    customer_id BINARY(16) NOT NULL PRIMARY KEY,
) ENGINE = InnoDB;

CREATE TABLE CUSTOMERS.ADDRESS
(
    address_id BINARY(16) NOT NULL PRIMARY KEY,
) ENGINE = InnoDB;

ALTER table CUSTOMERS.ADDRESS
ADD CONSTRAINT fk_customer_address
FOREIGN KEY (address_id)
REFERENCES CUSTOMERS.CUSTOMER (customer_id);

Integration test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryIntegrationTest {

    @Autowired
    private CustomerRepository cut;

    @Test
        public void testSaveAndDeleteCustomer() {
            Address address = new Address();
            Customer customer = new Customer();
            customer.setAddress(address);

            cut.save(customer);

            Customer retrievedCustomer = cut.findAll().get(0);
            assertEquals(customer, retrievedCustomer);
        }
}

Error:

ERROR] testSaveAndDeleteCustomer(com.foxhound.customers.repositories.CustomerRepositoryIntegrationTest)  Time elapsed: 0.034 s  <<< ERROR!
org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [com.foxhound.customers.models.Address.customer]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.foxhound.customers.models.Address.customer]
    at com.foxhound.customers.repositories.CustomerRepositoryIntegrationTest.testSaveAndDeleteCustomer(CustomerRepositoryIntegrationTest.java:47)
Caused by: org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.foxhound.customers.models.Address.customer]
    at com.foxhound.customers.repositories.CustomerRepositoryIntegrationTest.testSaveAndDeleteCustomer(CustomerRepositoryIntegrationTest.java:47)

Thank you in advance for the help.

Cheers!

Body:
You don't understand how bidirectional mapping is working, so you need to think through that. The code

@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Customer customer;

in Address makes the mapping unidirectional. Normally in order to save this you will need to set the customer field and save it.

address.setCustomer(customer);
addressRepo.save(address);

However you have defined a bidirectional mapping and provided a cascading annotation.

@OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
private Address address;

The cascading annotation alleviates you from having to do two persistence operations (in your code), but it does not mean you do not have to set the customer field in address. Additionally, as you have noticed, in order for the cascade operation to work you need to set the address field of customer.

customer.setAddress(address);

So, for the code to work properly you need to change it to set the customer in address.

Address address = new Address();
Customer customer = new Customer();
customer.setAddress(address);
address.setCustomer(customer);
customerRepo.save(customer);

With a bidirectional mapping you have to manage both sides of the relationship or use it in a unidirectional manner for persisting and a bidirectional manner for retrieving. If you add a cascade annotation then you have to manage both sides of the relationship for persisting as well.


问:
How can I animate several elements on the same orbital path in sequence?
I want to create an animation showing a few circles moving one after another in orbit. Currently, I created three circles but they appear on separate lines and thus move in a circular movement, but as a line. How can I change the code to achieve the movement that I want? Here's a codepen with the current status.

Here's the code that I use:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Lato', sans-serif;
  font-size: 18px;
  line-height: 1.6;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  min-height: 100vh;
}

.loader {
  height: 50px;
  animation: rotate 6s linear infinite;
}

.circle {
  display: inline-block;
  background-color: purple;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  transform: scale(0);
  animation: grow 1.5s linear infinite;
  margin: -20p;
}

.circle:nth-child(2) {
  background-color: palevioletred;
  transform: scale(0);
  animation-delay: 0.20s;
}

@keyframes rotate {
  to {
    transform: rotate(360deg)
  }
}

@keyframes grow {
  50% {
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader">
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
</div></code>```

答:
I'm creating full-size "plates" which I can set to an initial rotation point. The circles end up as pseudo-elements on the plates (to avoid extra markup). Modify the initial rotation values to bring the circles closer together.

.loader {
  width: 100px;
  height: 100px;
  animation: rotate 6s linear infinite;
  position: relative;
}

.plate {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.plate:nth-child(2) {
  transform: rotate(120deg);
}

.plate:nth-child(3) {
  transform: rotate(240deg);
}

.plate:before {
  content: '';
  position: absolute;
  background-color: red;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  transform: scale(0);
  animation: grow 1.5s linear infinite;
}

.plate:nth-child(2):before {
  background: green;
}

.plate:nth-child(3):before {
  background: blue;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

@keyframes grow {
  50% {
    transform: scale(1);
  }
}

* {
  box-sizing: bordr-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: "Lato", sans-serif;
  font-size: 18px;
  line-height: 1.6;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  min-height: 100vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="loader">
    <div class="plate"></div>
    <div class="plate"></div>
    <div class="plate"></div>
  </div>
</body></code>```

Body:
I'm creating full-size "plates" which I can set to an initial rotation point. The circles end up as pseudo-elements on the plates (to avoid extra markup). Modify the initial rotation values to bring the circles closer together.

.loader {
  width: 100px;
  height: 100px;
  animation: rotate 6s linear infinite;
  position: relative;
}

.plate {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.plate:nth-child(2) {
  transform: rotate(120deg);
}

.plate:nth-child(3) {
  transform: rotate(240deg);
}

.plate:before {
  content: '';
  position: absolute;
  background-color: red;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  transform: scale(0);
  animation: grow 1.5s linear infinite;
}

.plate:nth-child(2):before {
  background: green;
}

.plate:nth-child(3):before {
  background: blue;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

@keyframes grow {
  50% {
    transform: scale(1);
  }
}

* {
  box-sizing: bordr-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: "Lato", sans-serif;
  font-size: 18px;
  line-height: 1.6;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  min-height: 100vh;
}

<body>
  <div class="loader">
    <div class="plate"></div>
    <div class="plate"></div>
    <div class="plate"></div>
  </div>
</body>


问:
Using VIM on Windows to access windows server share directory
In Windows Explorer I can navigate to "\\servername\shared_directory". Is there any way I can navigate to the same directory using VIM and NERDTree?

Example:

:NERDTree \\servername\shared_drirectory

答:
I don't use NERDTree, but both :browse e \\servername\shared_directory and :e \\servername\shared_directory\filename.txt work fine for me in gvim.

Playing with this a bit more, I see that the forward-slash syntax seems to even work with tab-completion (after I get the server and initial directory right, of course).

If NERDTree doesn't want to work with either //servername/directory or \\servername\directory, you might want to try executing a :lcd //servername/directory first, followed by :NERDTree ..

ContentLicense: CC BY-SA 3.0


问:
Python importing from a higher directory in same project
I am having a issue importing a python file from another directory. Below is my project layout.

```<code>project/
   include/
     networking/
       ssl.py
     process.py
</code>```

Inside my ssl.py file I am trying to access a function inside process.py

I have tried

```<code>from include.process import procfunction
</code>```

This returns a error

```<code>cannot import name 'procfunction' from 'include.process'
</code>```

答:
You may need to move back up into your include directory. If you're on a Linux this can be done via </p>

```<code>import os
os.system("cd ..")
from process import procfunction
</code>```

<p>My apologies if this does not help. </p>

Body:
I am having a issue importing a python file from another directory. Below is my project layout.

project/
   include/
     networking/
       ssl.py
     process.py

Inside my ssl.py file I am trying to access a function inside process.py

I have tried

from include.process import procfunction

This returns a error

cannot import name 'procfunction' from 'include.process'

Body:
You may need to move back up into your include directory. If you're on a Linux this can be done via

import os
os.system("cd ..")
from process import procfunction

My apologies if this does not help.


问:
PHP generate random directory for fileupload
I need to generate random directories for user file uploads.
Is it wise to use the following function for this?

```<code>hash('md5', time())
</code>```

I don't want PHP to tamper with the filenames, that's why I thought about using directories for this.

答:
How many users and files you are going to process?
Remember about an effect of many files/folders living in the same folder: if you have few hundreds or thousands files in the same directory, working with that directory becomes slow.
My advice: split the generated hash into few parts and create directory structure like this:
/uploads/user/f4/a9/f4a94637deabc55/file.jpg</p>

Body:
I need to generate random directories for user file uploads.
Is it wise to use the following function for this?

hash('md5', time())

I don't want PHP to tamper with the filenames, that's why I thought about using directories for this.


问:
Component will not wait for API response before rendering
I have tried conditional rendering with a flag set after the API call and also using componentDidMount but cannot get this component to wait for an API response before rendering. I know the API response is valid because it is logging ok in the console. I'm new to react, could you tell me what I'm doing wrong? I have looked at the similar questions on Stackoverflow and can't find a fix. Many thanks!

I have cut some methods out of the code snippet to make it more readable.

```<code>import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react';

import {
  SAMPLE_SERVER_BASE_URL,
} from './config';

export default class CallPane extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: null,
      connection: 'Connecting',
      publishVideo: true,
      apiKey: '',
      sessionId: '',
      token: '',
      isLoaded: false,
    };

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        console.log(data)
        this.setState({ apiKey: data.apiKey })
        console.log(data.apiKey)
        this.setState({ sessionId: data.sessionId })
        console.log(data.sessionId)
        this.setState({ token: data.token })
        console.log(data.token)
        this.setState({ isLoaded: true })
      })
      .catch((err) => {
        console.error('Failed to get session credentials', err);
        alert('Failed to get opentok sessionId and token. Make sure you have updated the config.js file.');
      });
  }

  render() {

    const { error, connection, publishVideo } = this.state;
    // const { apiKey, sessionId, token } = this.state;

    return (
      // (isLoaded)
      <div>
        <div id="sessionStatus">Session Status: {connection}</div>
        {error ? (
          <div className="error">
            <strong>Error:</strong> {error}
          </div>
        ) : null}
        <OTSession
          apiKey={this.apiKey}
          sessionId={this.sessionId}
          token={this.token}
          onError={this.onSessionError}
          eventHandlers={this.sessionEventHandlers}
        >
          <button id="videoButton" onClick={this.toggleVideo}>
            {publishVideo ? 'Disable' : 'Enable'} Video
          </button>
          <OTPublisher
            properties={{ publishVideo, width: 250, height: 250, }}
            onPublish={this.onPublish}
            onError={this.onPublishError}
            eventHandlers={this.publisherEventHandlers}
          />
          <OTStreams>
            <OTSubscriber
              properties={{ width: 300, height: 300 }}
              onSubscribe={this.onSubscribe}
              onError={this.onSubscribeError}
              eventHandlers={this.subscriberEventHandlers}
            />
          </OTStreams>
        </OTSession>
      </div>
    );
  }
}
</code>```

答:
You can use a simple if statement, where you check, if the resource is ready yet. If not, render a loading bar or something similar. From the react documentation:

```<code>class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      externalData: null,
    };
  }

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        this.setState({ externalData: data });
      });
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}
</code>```

You could also use something like the following, to make sure that another component is always rendered.

```<code>class ExampleComponent extends  React.Component {

  constructor(props) {
    super(props);

    this.state = {
      externalData: null,
    };
  }

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        this.setState({ externalData: data });
      });
  }

  //This render is begin called even before props getting updated
  render() {
      return (
          <div>
          <h1>{'This will always render yay '}</h1>
          { this.state && this.state.externalData &&
              <div>{'This will just render after the return of the async call'}</div>
          }
          </div>
      )
  }
}
</code>```

Body:
I have tried conditional rendering with a flag set after the API call and also using componentDidMount but cannot get this component to wait for an API response before rendering. I know the API response is valid because it is logging ok in the console. I'm new to react, could you tell me what I'm doing wrong? I have looked at the similar questions on Stackoverflow and can't find a fix. Many thanks!

I have cut some methods out of the code snippet to make it more readable.

import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react';

import {
  SAMPLE_SERVER_BASE_URL,
} from './config';

export default class CallPane extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: null,
      connection: 'Connecting',
      publishVideo: true,
      apiKey: '',
      sessionId: '',
      token: '',
      isLoaded: false,
    };

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        console.log(data)
        this.setState({ apiKey: data.apiKey })
        console.log(data.apiKey)
        this.setState({ sessionId: data.sessionId })
        console.log(data.sessionId)
        this.setState({ token: data.token })
        console.log(data.token)
        this.setState({ isLoaded: true })
      })
      .catch((err) => {
        console.error('Failed to get session credentials', err);
        alert('Failed to get opentok sessionId and token. Make sure you have updated the config.js file.');
      });
  }

  render() {

    const { error, connection, publishVideo } = this.state;
    // const { apiKey, sessionId, token } = this.state;

    return (
      // (isLoaded)

Session Status: {connection}

        {error ? (

            Error: {error}

        ) : null}
        <OTSession
          apiKey={this.apiKey}
          sessionId={this.sessionId}
          token={this.token}
          onError={this.onSessionError}
          eventHandlers={this.sessionEventHandlers}
        >
          <button id="videoButton" onClick={this.toggleVideo}>
            {publishVideo ? 'Disable' : 'Enable'} Video
          </button>
          <OTPublisher
            properties={{ publishVideo, width: 250, height: 250, }}
            onPublish={this.onPublish}
            onError={this.onPublishError}
            eventHandlers={this.publisherEventHandlers}
          />
          <OTStreams>
            <OTSubscriber
              properties={{ width: 300, height: 300 }}
              onSubscribe={this.onSubscribe}
              onError={this.onSubscribeError}
              eventHandlers={this.subscriberEventHandlers}
            />
          </OTStreams>
        </OTSession>

    );
  }
}

Body:
You can use a simple if statement, where you check, if the resource is ready yet. If not, render a loading bar or something similar. From the react documentation:

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      externalData: null,
    };
  }

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        this.setState({ externalData: data });
      });
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

You could also use something like the following, to make sure that another component is always rendered.

class ExampleComponent extends  React.Component {

  constructor(props) {
    super(props);

    this.state = {
      externalData: null,
    };
  }

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        this.setState({ externalData: data });
      });
  }

  //This render is begin called even before props getting updated
  render() {
      return (
          <div>
          <h1>{'This will always render yay '}</h1>
          { this.state && this.state.externalData &&
              <div>{'This will just render after the return of the async call'}</div>
          }
          </div>
      )
  }
}


问:
How to convert DWORD to string in Python
I am working on a C++ SDK using Python. One of the APIs looks like this

API

```<code>DWORD NET_DVR_GetSDKVersion(
);
</code>```

Documentation

2 higher bytes mean the major version, 2 lower bytes mean the minor version, e.g. 0x00030000 means version 3.0.

It returns a DWORD value. I did some research and it seems like DWORD equals to ctypes.c_ulong in Python.

However, all I get from the API is an integer 393216 that does not make much sense.

Code

```<code>sdk = cdll.LoadLibrary("sdk.so")
sdk.NET_DVR_GetSDKVersion.restype = ctypes.c_long
result = sdk.NET_DVR_GetSDKVersion()
</code>```

I have setting the return value type using c_char_p and several other types but results don't really make much sense.

答:
Post process your number to extract the upper and lower 16 bits and format them as a string.  Below are examples using Python 3.6+ f-strings:</p>

```<code>>>> dword = 393216
>>> hex(dword)
'0x60000'
>>> f'{dword>>16}.{dword&0xFFFF}'
'6.0'
>>> dword = 0x00020003
>>> f'{dword>>16}.{dword&0xFFFF}'
'2.3'
</code>```

Body:
I am working on a C++ SDK using Python. One of the APIs looks like this

API

DWORD NET_DVR_GetSDKVersion(
);

Documentation

2 higher bytes mean the major version, 2 lower bytes mean the minor version, e.g. 0x00030000 means version 3.0.

It returns a DWORD value. I did some research and it seems like DWORD equals to ctypes.c_ulong in Python.

However, all I get from the API is an integer 393216 that does not make much sense.

Code

sdk = cdll.LoadLibrary("sdk.so")
sdk.NET_DVR_GetSDKVersion.restype = ctypes.c_long
result = sdk.NET_DVR_GetSDKVersion()

I have setting the return value type using c_char_p and several other types but results don't really make much sense.

Body:
Post process your number to extract the upper and lower 16 bits and format them as a string.  Below are examples using Python 3.6+ f-strings:

>>> dword = 393216
>>> hex(dword)
'0x60000'
>>> f'{dword>>16}.{dword&0xFFFF}'
'6.0'
>>> dword = 0x00020003
>>> f'{dword>>16}.{dword&0xFFFF}'
'2.3'


问:
Swift - Accessing AppDelegate window from viewController
I make walkthrough (onboarding flow) in my app and I'd like to have a skip button.
The button is located on viewController, so I figured out that the best way to move to another viewController would be access app delegate window.

However, it keeps getting me an error that AppDelegate.Type does not have a member called "window".

```<code>@IBAction func skipWalkthrough(sender: AnyObject) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    AppDelegate.window!.rootViewController = RootViewController
}
</code>```

Is there anything wrong with such approach?

Thanks in advance!

答:
You can access tab bar anywhere from the app. Use below:</p>

```<code>let appDelegate = UIApplication.shared.delegate as! AppDelegate

if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController {
    if let tabItems = tabBarController.tabBar.items {
       let tabItem = tabItems[2]
       tabItem.badgeValue = "5" //enter any value
    }
}
</code>```

Body:
I make walkthrough (onboarding flow) in my app and I'd like to have a skip button.
The button is located on viewController, so I figured out that the best way to move to another viewController would be access app delegate window.

However, it keeps getting me an error that AppDelegate.Type does not have a member called "window".

@IBAction func skipWalkthrough(sender: AnyObject) {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    AppDelegate.window!.rootViewController = RootViewController
}

Is there anything wrong with such approach?

Thanks in advance!

Body:
You can access tab bar anywhere from the app. Use below:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController {
    if let tabItems = tabBarController.tabBar.items {
       let tabItem = tabItems[2]
       tabItem.badgeValue = "5" //enter any value
    }
}


问:
How to use typespecs and Dialyzer with Behaviours?
In Elixir how can I document that a function will return a module that implements a specific behaviour?

To use a trivial example, say I have created a GreeterBehaviour behaviour that is implemented by two modules:

```<code>defmodule GreeterBehaviour do
  @callback say_hello(String.t) :: String.t
end

defmodule FormalGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Good day to you #{name}"
  end
end

defmodule CasualGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Hey #{name}"
  end
end
</code>```

I then want to easily swap out either of those implementations by retrieving the Greeter via a function:

```<code>defmodule MyApp do
  def main do
    greeter().say_hello("Pete") |> IO.puts
  end

  @spec greeter() :: GreeterBehaviour # This doesn't work with dialyzer
  def greeter do
    FormalGreeter # Can easily be swapped to CasualGreeter
  end
end
</code>```

Dialyzer will successfully check that both CasualGreeter and FormalGreeter correctly implement the GreeterBehaviour behaviour. However, how can I define a typespec so that Dialyzer will check that greeter/0 returns a module that does in fact implement GreeterBehaviour?

Using @spec greeter() :: GreeterBehaviour doesn't work as Dialyzer will throw a warning:

```<code>lib/my_app.ex:19: Invalid type specification for function 'Elixir.MyApp':greeter/0. The success typing is () -> 'Elixir.FormalGreeter'
</code>```

答:
In your behaviour you could define a type for say_hello:

```<code>@type f :: (String.t() -> String.t())
</code>```

Your greeter function could return a module + function: &module.say_hello/1

And the spec would be:

```<code>@spec greeter() :: GreeterBehaviour.f()
</code>```

```<code>defmodule GreeterBehaviour do
  @type f :: (String.t() -> String.t())
  @callback say_hello(String.t()) :: String.t()
end

defmodule FormalGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Good day to you #{name}"
  end
end

defmodule CasualGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Hey #{name}"
  end
end

defmodule MyApp do
  def main do
    greeter().("Pete") |> IO.puts()
  end

  # This will work with dialyzer
  @spec greeter() :: GreeterBehaviour.f()
  def greeter do
    # Can easily be swapped to CasualGreeter
    &FormalGreeter.say_hello/1
  end
end
</code>```

Body:
In Elixir how can I document that a function will return a module that implements a specific behaviour?

To use a trivial example, say I have created a GreeterBehaviour behaviour that is implemented by two modules:

defmodule GreeterBehaviour do
  @callback say_hello(String.t) :: String.t
end

defmodule FormalGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Good day to you #{name}"
  end
end

defmodule CasualGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Hey #{name}"
  end
end

I then want to easily swap out either of those implementations by retrieving the Greeter via a function:

defmodule MyApp do
  def main do
    greeter().say_hello("Pete") |> IO.puts
  end

  @spec greeter() :: GreeterBehaviour # This doesn't work with dialyzer
  def greeter do
    FormalGreeter # Can easily be swapped to CasualGreeter
  end
end

Dialyzer will successfully check that both CasualGreeter and FormalGreeter correctly implement the GreeterBehaviour behaviour. However, how can I define a typespec so that Dialyzer will check that greeter/0 returns a module that does in fact implement GreeterBehaviour?

Using @spec greeter() :: GreeterBehaviour doesn't work as Dialyzer will throw a warning:

lib/my_app.ex:19: Invalid type specification for function 'Elixir.MyApp':greeter/0. The success typing is () -> 'Elixir.FormalGreeter'

Body:
In your behaviour you could define a type for say_hello:

@type f :: (String.t() -> String.t())

Your greeter function could return a module + function: &module.say_hello/1

And the spec would be:

@spec greeter() :: GreeterBehaviour.f()

defmodule GreeterBehaviour do
  @type f :: (String.t() -> String.t())
  @callback say_hello(String.t()) :: String.t()
end

defmodule FormalGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Good day to you #{name}"
  end
end

defmodule CasualGreeter do
  @behaviour GreeterBehaviour

  def say_hello(name) do
    "Hey #{name}"
  end
end

defmodule MyApp do
  def main do
    greeter().("Pete") |> IO.puts()
  end

  # This will work with dialyzer
  @spec greeter() :: GreeterBehaviour.f()
  def greeter do
    # Can easily be swapped to CasualGreeter
    &FormalGreeter.say_hello/1
  end
end


问:
Wpf shared image memory
I want to optimize the memory usage in my WPF app.
I want to load from the disk an jpg image and show it with its real size.
And then I want to show 5 cropped square section of the original image loaded from the disk.
(No resize is applied on any image).
I want to do all this by loading the original image once and sharing that data among the image controls, in such a way that no memory is wasted and all controls fetch data from the same memory location.

I tried by using a memory stream object but in the end due to some convertions between bitmap and bitmapimage I ended up copying the data.

答:
I found an interesting way to crop an image from a BitmapImage here that I think will solve your problem. Doing it this way, you can display all of your images just using a single BitmapImage

In your xaml your full resolution image would just be a regular image element, but your cropped images would be a rectangle element using an image brush with a specific viewbox. Just define the rectangle with the height and width of the cropped image that you want, and then the viewbox is defined as "x y width height" (in my example it is "10 20 100 200") and remember that x starts at 0 for left and is positive moving right, and y starts at 0 for the top and is positive moving down.

    <Image Source="{Binding Image}"></Image>
    <Rectangle Height="200" Width="100">
        <Rectangle.Fill>
            <ImageBrush ViewboxUnits="Absolute" Viewbox="10,20,100,200" ImageSource="{Binding Image}"></ImageBrush>
        </Rectangle.Fill>
    </Rectangle>
```

Note that the binding for the Image and the ImageBrush are the same, so you only need to define Image once, and it is used across both elements.

Title: Wpf shared image memory

Body:
I found an interesting way to crop an image from a BitmapImage here that I think will solve your problem. Doing it this way, you can display all of your images just using a single BitmapImage

In your xaml your full resolution image would just be a regular image element, but your cropped images would be a rectangle element using an image brush with a specific viewbox. Just define the rectangle with the height and width of the cropped image that you want, and then the viewbox is defined as "x y width height" (in my example it is "10 20 100 200") and remember that x starts at 0 for left and is positive moving right, and y starts at 0 for the top and is positive moving down.

    <Image Source="{Binding Image}"></Image>
    <Rectangle Height="200" Width="100">
        <Rectangle.Fill>
            <ImageBrush ViewboxUnits="Absolute" Viewbox="10,20,100,200" ImageSource="{Binding Image}"></ImageBrush>
        </Rectangle.Fill>
    </Rectangle>

Note that the binding for the Image and the ImageBrush are the same, so you only need to define Image once, and it is used across both elements.


问:
Haskell with emacs org-mode: Variable not in scope
After wandering off in frustration from before, I've decided to try Haskell in Emacs org-mode again. I'm using Haskell stack-ghci (8.6.3), Emacs 26.2, org-mode 9.2.3 set up with intero. This code block

```<code>#+begin_src haskell :results raw :session *haskell*
pyth2 :: Int -> [(Int, Int, Int)]
pyth2 n =
  [ (x, y, z)
  | x <- [1 .. n]
  , y <- [x .. n]
  , z <- [y .. n]
  , x ^ 2 + y ^ 2 == z ^ 2
  ]
#+end_src
</code>```

produces this RESULTS:

```<code>*Main| *Main| *Main| *Main| *Main|
<interactive>:59:16: error: Variable not in scope: n
<interactive>:60:16: error: Variable not in scope: n
<interactive>:61:16: error: Variable not in scope: n
</code>```

However, this

```<code>#+begin_src haskell :results raw
tripleMe x = x + x + x
#+end_src
</code>```

works fine. I've added the :set +m to both ghci.conf and the individual code block to no effect. This code works fine in a separate hs file run in a separate REPL. The pyth2 code in a separate file also can be called from the org-mode started REPL and run just fine as well. Not sure how to proceed. Can include Emacs init info if necessary.

答:
Over on the org-mode mailing list I got an answer that basically is saying the same as you, D. Gillis. He had a similar work-around that actually is more org-mode-centric. Under a heading where your code blocks will be put this "drawer"

```<code>:PROPERTIES:
:header-args:haskell: :prologue ":{\n" :epilogue ":}\n"
:END:
</code>```

and then (possibly in a local variable) run

```<code>#+begin_src haskell :results output
:set prompt-cont ""
#+end_src
</code>```

For reasons unknown I've had to include the :results output otherwise a cryptic error of "expecting a string" happens.

On a few other notes, haskell babel doesn't respond/care about the :session option, i.e., when you run a code block, a REPL *haskell* starts and that will be the sole REPL. Also, a haskell-mode started REPL doesn't play well with an existing org-mode initiated REPL, i.e., if you start a REPL from haskell-mode, it kills the original org-mode *haskkell*REPL, and any new attempt to run org-mode code blocks can't see this new, non-*haskell*REPL. Then if you kill the haskell-mode REPL and try to run org-mode blocks, you get

```<code>executing Haskell code block...
inferior-haskell-start-process: List contains a loop: ("--no-build" "--no-load" "--ghci-options=-ferror-spans" "--no-build" "--no-load" . #2)
</code>```

... you're hosed -- and nothing seems to shake it, not any restart/refresh, nor killing, reloading the file, i.e., a complete restart of Emacs is necessary. Anyone knowing a better solution, please tells usses.

Body:
After wandering off in frustration from before, I've decided to try Haskell in Emacs org-mode again. I'm using Haskell stack-ghci (8.6.3), Emacs 26.2, org-mode 9.2.3 set up with intero. This code block

#+begin_src haskell :results raw :session *haskell*
pyth2 :: Int -> [(Int, Int, Int)]
pyth2 n =
  [ (x, y, z)
  | x <- [1 .. n]
  , y <- [x .. n]
  , z <- [y .. n]
  , x ^ 2 + y ^ 2 == z ^ 2
  ]
#+end_src

produces this RESULTS:

*Main| *Main| *Main| *Main| *Main|
<interactive>:59:16: error: Variable not in scope: n
<interactive>:60:16: error: Variable not in scope: n
<interactive>:61:16: error: Variable not in scope: n

However, this

#+begin_src haskell :results raw
tripleMe x = x + x + x
#+end_src

works fine. I've added the :set +m to both ghci.conf and the individual code block to no effect. This code works fine in a separate hs file run in a separate REPL. The pyth2 code in a separate file also can be called from the org-mode started REPL and run just fine as well. Not sure how to proceed. Can include Emacs init info if necessary.

Body:
Over on the org-mode mailing list I got an answer that basically is saying the same as you, D. Gillis. He had a similar work-around that actually is more org-mode-centric. Under a heading where your code blocks will be put this "drawer"

:PROPERTIES:
:header-args:haskell: :prologue ":{\n" :epilogue ":}\n"
:END:

and then (possibly in a local variable) run

#+begin_src haskell :results output
:set prompt-cont ""
#+end_src

For reasons unknown I've had to include the :results output otherwise a cryptic error of "expecting a string" happens.

On a few other notes, haskell babel doesn't respond/care about the :session option, i.e., when you run a code block, a REPL *haskell* starts and that will be the sole REPL. Also, a haskell-mode started REPL doesn't play well with an existing org-mode initiated REPL, i.e., if you start a REPL from haskell-mode, it kills the original org-mode *haskkell*REPL, and any new attempt to run org-mode code blocks can't see this new, non-*haskell*REPL. Then if you kill the haskell-mode REPL and try to run org-mode blocks, you get

executing Haskell code block...
inferior-haskell-start-process: List contains a loop: ("--no-build" "--no-load" "--ghci-options=-ferror-spans" "--no-build" "--no-load" . #2)

... you're hosed -- and nothing seems to shake it, not any restart/refresh, nor killing, reloading the file, i.e., a complete restart of Emacs is necessary. Anyone knowing a better solution, please tells usses.


问:
How can I do a screen capture in Windows PowerShell?
How can I capture the screen in Windows PowerShell?   I need to be able to save the screen to disk.</p>

答:
Here is my solution for multi-monitor, which is a bit simpler than the current answer. It also will render screens properly if the user has a strange monitor config (stacked vertical, etc) without black bars.</p>

```<code>Add-Type -AssemblyName System.Windows.Forms,System.Drawing

$screens = [Windows.Forms.Screen]::AllScreens

$top    = ($screens.Bounds.Top    | Measure-Object -Minimum).Minimum
$left   = ($screens.Bounds.Left   | Measure-Object -Minimum).Minimum
$width  = ($screens.Bounds.Right  | Measure-Object -Maximum).Maximum
$height = ($screens.Bounds.Bottom | Measure-Object -Maximum).Maximum

$bounds   = [Drawing.Rectangle]::FromLTRB($left, $top, $width, $height)
$bmp      = New-Object System.Drawing.Bitmap ([int]$bounds.width), ([int]$bounds.height)
$graphics = [Drawing.Graphics]::FromImage($bmp)

$graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size)

$bmp.Save("$env:USERPROFILE\test.png")

$graphics.Dispose()
$bmp.Dispose()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is my solution for multi-monitor, which is a bit simpler than the current answer. It also will render screens properly if the user has a strange monitor config (stacked vertical, etc) without black bars.

Add-Type -AssemblyName System.Windows.Forms,System.Drawing

$screens = [Windows.Forms.Screen]::AllScreens

$top    = ($screens.Bounds.Top    | Measure-Object -Minimum).Minimum
$left   = ($screens.Bounds.Left   | Measure-Object -Minimum).Minimum
$width  = ($screens.Bounds.Right  | Measure-Object -Maximum).Maximum
$height = ($screens.Bounds.Bottom | Measure-Object -Maximum).Maximum

$bounds   = [Drawing.Rectangle]::FromLTRB($left, $top, $width, $height)
$bmp      = New-Object System.Drawing.Bitmap ([int]$bounds.width), ([int]$bounds.height)
$graphics = [Drawing.Graphics]::FromImage($bmp)

$graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size)

$bmp.Save("$env:USERPROFILE\test.png")

$graphics.Dispose()
$bmp.Dispose()


问:
How to read json payload of a large response?
I am developing some code that will read a large json payload returned by the Export API of Mailchimp.

```<code>        var response = caller.PostAsync(endpoint, data).Result;

        var exportedData = response.Content.ReadAsStringAsync().Result;
</code>```

I am currently using the Visual Studio 2017 debugger to try and view the response but I keep getting an error that says:

Cannot obtain value of the local variable or argument because there is not enough memory available.

I ultimately want to extract information from each 'row' of this json data and do operations on them.  What do I need to do so that I can view this data without running out of memory?

答:
try

```<code>var exportedData = await response.Content.ReadAsAsync<model>();
</code>```

also make sure your method is async

```<code>public async Task<returntype> MethodName()
</code>```

let "model", in ReadAsAsync, be the name of the object model you're going to map the data to and let "returntype", next to Task in the method name, be whatever datatype your method is returning

can you update your question and show the entire method. I would like to take a closer look at it

Body:
I am developing some code that will read a large json payload returned by the Export API of Mailchimp.

        var response = caller.PostAsync(endpoint, data).Result;

        var exportedData = response.Content.ReadAsStringAsync().Result;

I am currently using the Visual Studio 2017 debugger to try and view the response but I keep getting an error that says:

Cannot obtain value of the local variable or argument because there is not enough memory available.

I ultimately want to extract information from each 'row' of this json data and do operations on them.  What do I need to do so that I can view this data without running out of memory?

Body:
try

var exportedData = await response.Content.ReadAsAsync<model>();

also make sure your method is async

public async Task<returntype> MethodName()

let "model", in ReadAsAsync, be the name of the object model you're going to map the data to and let "returntype", next to Task in the method name, be whatever datatype your method is returning

can you update your question and show the entire method. I would like to take a closer look at it


问:
Wait for element to be clickable using python and Selenium
There are ways to wait for an object e.g. a button to be clickable in selenium python. I use time.sleep() and/or WebDriverWait...until, it works fine.

However, when there are hundreds of objects, is there a way to set a default time lag globally, instead of implementing it on each object?

The click() action should have a conditional wait time?

答:
is there a way to set a default time lag globally,
  instead of implementing it on each object?

Yes, that's exactly what setting an Implicit Wait does.  The implicit wait is used for the life of the WebDriver.

example:

driver.implicitly_wait(10)

info:

https://www.seleniumhq.org/docs/04_webdriver_advanced.jsp#implicit-waits


问:
Grid search for SVC : IndexError: too many indices for array
I'm trying to use GridSearchCV to find the best params for SVC.

```<code>from sklearn.svm import SVC
from sklearn import svm, grid_search
from sklearn.model_selection import GridSearchCV

param_grid = [
        {'C': [1,5,10,100]},
        ]
algo = SVC(kernel="poly",  degree=5, coef0=2)
grid_search = GridSearchCV(algo, param_grid, cv=3, scoring='neg_mean_squared_error')
grid_search.fit(X_train, y_train)
print(grid_search.best_params_) #line 162
</code>```

I get the following error:

```<code>  File "main.py", line 162, in <module>
  IndexError: too many indices for array
</code>```

When I don't use GridSearchCV it works:

```<code>from sklearn.svm import SVC
from sklearn import svm, grid_search
from sklearn.model_selection import GridSearchCV

algo = SVC(kernel="poly", C=1, degree=5, coef0=2)
algo.fit(X_train, y_train)
predict_test = algo.predict(X_test)
mse = mean_squared_error(y_test, predict_test)
rmse = np.sqrt(mse)
print(rmse)
</code>```

I get a score.

答:
GridSearchCV.fit() accepts target values as an array-like y of shape [n_samples] or [n_samples, n_output].

In your case, (892,). Therefore, reshape y_train:

```<code>y_train = y_train.reshape(892,)
</code>```

Body:
I'm trying to use GridSearchCV to find the best params for SVC.

from sklearn.svm import SVC
from sklearn import svm, grid_search
from sklearn.model_selection import GridSearchCV

param_grid = [
        {'C': [1,5,10,100]},
        ]
algo = SVC(kernel="poly",  degree=5, coef0=2)
grid_search = GridSearchCV(algo, param_grid, cv=3, scoring='neg_mean_squared_error')
grid_search.fit(X_train, y_train)
print(grid_search.best_params_) #line 162

I get the following error:

  File "main.py", line 162, in <module>
  IndexError: too many indices for array

When I don't use GridSearchCV it works:

from sklearn.svm import SVC
from sklearn import svm, grid_search
from sklearn.model_selection import GridSearchCV

algo = SVC(kernel="poly", C=1, degree=5, coef0=2)
algo.fit(X_train, y_train)
predict_test = algo.predict(X_test)
mse = mean_squared_error(y_test, predict_test)
rmse = np.sqrt(mse)
print(rmse)

I get a score.

Body:
GridSearchCV.fit() accepts target values as an array-like y of shape [n_samples] or [n_samples, n_output].

In your case, (892,). Therefore, reshape y_train:

y_train = y_train.reshape(892,)


问:
EF 4.1 Code First - OnModelCreating call time
When I debug my application this method seems not to be executing in constructor context of DbContext. So when it is called then?</p>

答: This method is called when EF needs to access database for the first time (so it is not during context instancing). If the database doesn't exists it uses information from compiled model to create it. The model is created only once per application (it is cached internally) so even if you dispose the context your model will be still reused for the next instance.</p>


问:
Firebase hosting does not send custom HTTP headers
According to Firebase Hosting docs, I should be able to set custom headers on responses received from the server. I am trying to set the X-Frame-Options header on all html files, but the server simply does not want to send this header! Here's my firebase.json file, please let me know if I am doing anything wrong:

```<code>{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [
      {
        "source": "**/*.html",
        "headers": [
          {
            "key": "X-Frame-Options",
            "value": "SAMEORIGIN"
          }
        ]
      }
    ]
  }
}
</code>```

答:
I just went through a lot of trial and error on the same issue.  I noticed a small little section in the firebase documentation:

A source value that Hosting matches against the original request path, regardless of any rewrite rules.

If your setup is like mine, you probably have this in your firebase.json file:

```<code>  "rewrites": [{
    "source": "**",
    "destination": "/index.html"
  }]
</code>```

However, while you may be returning index.html, the original request path was simply "/", so on your headers section use this:

```<code>"source": "/"
</code>```

This is what worked for me.

Body:
According to Firebase Hosting docs, I should be able to set custom headers on responses received from the server. I am trying to set the X-Frame-Options header on all html files, but the server simply does not want to send this header! Here's my firebase.json file, please let me know if I am doing anything wrong:

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [
      {
        "source": "**/*.html",
        "headers": [
          {
            "key": "X-Frame-Options",
            "value": "SAMEORIGIN"
          }
        ]
      }
    ]
  }
}

Body:
I just went through a lot of trial and error on the same issue.  I noticed a small little section in the firebase documentation:

A source value that Hosting matches against the original request path, regardless of any rewrite rules.

If your setup is like mine, you probably have this in your firebase.json file:

  "rewrites": [{
    "source": "**",
    "destination": "/index.html"
  }]

However, while you may be returning index.html, the original request path was simply "/", so on your headers section use this:

"source": "/"

This is what worked for me.


问:
python logging.Logger: overriding makeRecord
I have a formatter that expects special attribute in the record, "user_id", that not always there(sometimes I add it to records using special logging.Filter).
I tried to override the makeRecord method of logging.Logger like so:

```<code>import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)-15s user_id=%(user_id)s %(filename)s:%(lineno)-15s: %(message)s')

class OneTestLogger(logging.Logger):
    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        rv = logging.Logger.makeRecord(self, name, level, fn, lno,
                                       msg, args, exc_info,
                                       func, extra)
        rv.__dict__.setdefault('user_id', 'master')
        return rv

if __name__ == '__main__':

    logger = OneTestLogger('main')
    print logger
    logger.info('Starting test')
</code>```

But that doesn't seem to work and I keep getting:

<main.MyLogger instance at 0x7f31a6a5b638>

No handlers could be found for logger "main"

What am I doing wrong?
Thanks.

答:
Following the guideline provided in Logging Cookbook. Just the first part, I did not implement Filter (which does not appear in the below quote either).

This has usually meant that if you need to do anything special with a LogRecord, you’ve had to do one of the following.

Create your own Logger subclass, which overrides Logger.makeRecord(), and set it using setLoggerClass() before any loggers that you care about are instantiated.

I have simplifed your exampled just to add the 'hostname':

```<code>import logging
from socket import gethostname

logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(hostname)s - %(message)s')

class NewLogger(logging.Logger):
    def makeRecord(self, *args, **kwargs):
        rv = super(NewLogger, self).makeRecord(*args, **kwargs)
        # updating the rv value of the original makeRecord
        # my idea is to use the same logic than a decorator by
        # intercepting the value return by the original makeRecord
        # and expanded with what I need
        rv.__dict__['hostname'] = gethostname()
        # by curiosity I am checking what is in this dictionary
        # print(rv.__dict__)
        return rv

logging.setLoggerClass(NewLogger)

logger = logging.getLogger(__name__)
logger.info('Hello World!')
</code>```

Note that this code worked on python 2.7

Body:
I have a formatter that expects special attribute in the record, "user_id", that not always there(sometimes I add it to records using special logging.Filter).
I tried to override the makeRecord method of logging.Logger like so:

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)-15s user_id=%(user_id)s %(filename)s:%(lineno)-15s: %(message)s')

class OneTestLogger(logging.Logger):
    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
        rv = logging.Logger.makeRecord(self, name, level, fn, lno,
                                       msg, args, exc_info,
                                       func, extra)
        rv.__dict__.setdefault('user_id', 'master')
        return rv

if __name__ == '__main__':

    logger = OneTestLogger('main')
    print logger
    logger.info('Starting test')

But that doesn't seem to work and I keep getting:

<main.MyLogger instance at 0x7f31a6a5b638>

No handlers could be found for logger "main"

What am I doing wrong?
Thanks.

Body:
Following the guideline provided in Logging Cookbook. Just the first part, I did not implement Filter (which does not appear in the below quote either).

This has usually meant that if you need to do anything special with a LogRecord, you’ve had to do one of the following.

Create your own Logger subclass, which overrides Logger.makeRecord(), and set it using setLoggerClass() before any loggers that you care about are instantiated.

I have simplifed your exampled just to add the 'hostname':

import logging
from socket import gethostname

logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(hostname)s - %(message)s')

class NewLogger(logging.Logger):
    def makeRecord(self, *args, **kwargs):
        rv = super(NewLogger, self).makeRecord(*args, **kwargs)
        # updating the rv value of the original makeRecord
        # my idea is to use the same logic than a decorator by
        # intercepting the value return by the original makeRecord
        # and expanded with what I need
        rv.__dict__['hostname'] = gethostname()
        # by curiosity I am checking what is in this dictionary
        # print(rv.__dict__)
        return rv

logging.setLoggerClass(NewLogger)

logger = logging.getLogger(__name__)
logger.info('Hello World!')

Note that this code worked on python 2.7


问:
Why is my code not working on more than one thread?
I have been trying to multi-thread my code, it still works, but only uses 15% of my cpu (i have 8 threads, so thats 1 thread).

I have tried many scripts to multi-thread from stack overflow and youtube, but none worked.

```<code>import threading

n=2

def crazy():
    global n
    while True:
        n = n*2
        print(n)

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()
</code>```

The ouput is as expected, but only running on one thread.

答:
Maybe something like:</p>

```<code>from multiprocessing.dummy import Pool

n = 2

def crazy(_):
    global n
    while True:
        n = n * 2
        print(n)

threads = []
pool = Pool(8)
pool.map(crazy, range(8))
pool.close()
pool.join()
</code>```

Body:
I have been trying to multi-thread my code, it still works, but only uses 15% of my cpu (i have 8 threads, so thats 1 thread).

I have tried many scripts to multi-thread from stack overflow and youtube, but none worked.

import threading

n=2

def crazy():
    global n
    while True:
        n = n*2
        print(n)

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()

The ouput is as expected, but only running on one thread.

Body:
Maybe something like:

from multiprocessing.dummy import Pool

n = 2

def crazy(_):
    global n
    while True:
        n = n * 2
        print(n)

threads = []
pool = Pool(8)
pool.map(crazy, range(8))
pool.close()
pool.join()


问:
Listing the contexts for a session and updating the values of the parameters of the contexts
I'm planning to use the dialogflow_v2 SDK of python, I have an intention of resetting the parameters in a context,
let me explain the scenario -  I have an intent which accepts start and end date one by one, as I'm using the webhook slot filling, I would like to validate if the end date falls after the start date and if condition fails, I would like to get the start and end date again with new values after showing the slot filling response.

Is this possible using the v2 SDK?

I have checked the usage code given in
https://github.com/googleapis/dialogflow-python-client-v2/blob/master/dialogflow_v2/gapic/contexts_client.py
to list the contexts and update the contexts.
I have also followed https://dialogflow.com/docs/reference/v2-auth-setup to set the key.json for authentication. I used a service account with the role as API client and ADMIN to generate authentication key JSON.

Any help would be appreciated.

答:
I was working on a use case where I wanted to set the parameters as mentioned in the above question to validate the parameter values captured in the intent and resend it.
I found a way to do it by using the events in the dialog flow, you need to actually attach an event to the intent and update it with the validated parameters.

You can refer the following link,
https://dialogflow.com/docs/events/custom-events

Hope, It will help others who are facing this issue.

Thanks a lot.


问:
How to use array filter criteria agaist object in lodash?
How to filter object ageist another object in lodash? but the criteria object is array..

```<code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);
</code>```

The results should be xyz and abc:

```<code>results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]
</code>```

Is it something I can do using filter method?

答:
If you reduce your items to an object map where items can be found by a combination of the type and name then it can be a simple map by key with or without lodash:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
].reduce((r,c) => (r[`${c.type}-${c.name}`] = c, r), {}) // convert to object map

let result = form.type.map(t => items[`${t}-${form.name}`]) // map by key

console.log(result)```
</div>
</div>
</p>

<p>With lodash you can use <code>_.keyBy</code> and <code>_.map</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = _.keyBy([
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
], x => `${x.type}-${x.name}`)

let result = _.map(form.type, t => items[`${t}-${form.name}`])

console.log(result)</code>```

```

This way from performance stand point you are in the O(N) territory.

Body:
How to filter object ageist another object in lodash? but the criteria object is array..

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);

The results should be xyz and abc:

results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]

Is it something I can do using filter method?

Body:
If you reduce your items to an object map where items can be found by a combination of the type and name then it can be a simple map by key with or without lodash:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
].reduce((r,c) => (r[`${c.type}-${c.name}`] = c, r), {}) // convert to object map

let result = form.type.map(t => items[`${t}-${form.name}`]) // map by key

console.log(result)

With lodash you can use _.keyBy and _.map:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = _.keyBy([
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
], x => `${x.type}-${x.name}`)

let result = _.map(form.type, t => items[`${t}-${form.name}`])

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

This way from performance stand point you are in the O(N) territory.


问:
Type Punning with Unions and Heap
I have read a lot about type punning and how it is not good to just use a cast.

```<code>oldType* data = malloc(sizeof(oldType));
((newtype*)data)->newElement;
</code>```

This results in undefined behavior. So the solution is to use union so that the compiler knows that these two pointers are linked to one another so it doesn't do funny things with strict aliasing.

That being said the unions also looked like:

```<code>union testing
{
    struct test1 e;
    struct test2 f;
}
</code>```

Is it defined behavior if pointers are used in the union?

```<code>union testing
{
    struct test1* e;
    struct test2* f;
}
</code>```

Here is a full example:

```<code>#include <stdio.h>
#include <stdlib.h>

struct test1
{
    int a;
    char b;
};

struct test2
{
    int c;
    char d;
};

union testing
{
    struct test1* e;
    struct test2* f;
};

void printer(const struct test2* value);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    printer(((union testing)aQuickTest).f);
    ((union testing)aQuickTest.f)->c = 111; // using -> not .
    return 0;
}

void printer(const struct test2* value)
{
    printf("Int: %i Char: %c",value->c, value->d);
}
</code>```

Or would I need to use unions without pointers. And then use printer(&(((union testing)aQuickTest).f)); (with the &) to get the address of f.

答:
Suppose you want to type pun types X and Y, you should use the union -

```<code>typedef union {
    X x;
    Y y;
}X_Y;
</code>```

This allows you to share the bit representation of X with Y and vice versa.
If you use -

```<code>typedef union {
    X* x;
    Y* y;
}X_Y_p;
</code>```

you are sharing the bit representations for the pointer. For a system that uses the same bit representation for all pointer, you are essentially casting pointer of X to pointer of Y, which you identified causes Undefined Behaviour.

It is not illegal to have something X_Y_p because X* and Y* are types by themselves. But they achieve something different. They let you type pun pointers, which is not what you want to do (and not necessary in most cases, because pointers share representation on most systems). A cast should be fine there.

Title: Type Punning with Unions and Heap

Body:
I have read a lot about type punning and how it is not good to just use a cast.

oldType* data = malloc(sizeof(oldType));
((newtype*)data)->newElement;

This results in undefined behavior. So the solution is to use union so that the compiler knows that these two pointers are linked to one another so it doesn't do funny things with strict aliasing.

That being said the unions also looked like:

union testing
{
    struct test1 e;
    struct test2 f;
}

Is it defined behavior if pointers are used in the union?

union testing
{
    struct test1* e;
    struct test2* f;
}

Here is a full example:

#include <stdio.h>
#include <stdlib.h>

struct test1
{
    int a;
    char b;
};

struct test2
{
    int c;
    char d;
};

union testing
{
    struct test1* e;
    struct test2* f;
};

void printer(const struct test2* value);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    printer(((union testing)aQuickTest).f);
    ((union testing)aQuickTest.f)->c = 111; // using -> not .
    return 0;
}

void printer(const struct test2* value)
{
    printf("Int: %i Char: %c",value->c, value->d);
}

Or would I need to use unions without pointers. And then use printer(&(((union testing)aQuickTest).f)); (with the &) to get the address of f.

Body:
Suppose you want to type pun types X and Y, you should use the union -

typedef union {
    X x;
    Y y;
}X_Y;

This allows you to share the bit representation of X with Y and vice versa.
If you use -

typedef union {
    X* x;
    Y* y;
}X_Y_p;

you are sharing the bit representations for the pointer. For a system that uses the same bit representation for all pointer, you are essentially casting pointer of X to pointer of Y, which you identified causes Undefined Behaviour.

It is not illegal to have something X_Y_p because X* and Y* are types by themselves. But they achieve something different. They let you type pun pointers, which is not what you want to do (and not necessary in most cases, because pointers share representation on most systems). A cast should be fine there.


答:
This is in fact using threads (all 4 of them). You can test by implementing a pause in your code:

```<code>import threading
import time

n = 2

def crazy():
    global n
    while True:
        n = n*2
        print(n)
        time.sleep(1) # pause

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()
</code>```

Where at first it prints:

```<code>4
8
16
32
</code>```

Then a second later prints

```<code>64
128
256
512
</code>```

The fact that it prints in groups of 4 is evidence that 4 threads are running, and each is encountering a pause in execution. If you are trying to maximize CPU usage, perhaps multiprocessing is more along the lines of what you are looking for? threading simply imitates multiple things happening at once, while multiprocessing actually makes multiple things happen at once. Note that multiprocessing is a bit trickier, as you have to be clever to avoid deadlock.

Title: Why is my code not working on more than one thread?

Body:
This is in fact using threads (all 4 of them). You can test by implementing a pause in your code:

import threading
import time

n = 2

def crazy():
    global n
    while True:
        n = n*2
        print(n)
        time.sleep(1) # pause

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()

Where at first it prints:

4
8
16
32

Then a second later prints

64
128
256
512

The fact that it prints in groups of 4 is evidence that 4 threads are running, and each is encountering a pause in execution. If you are trying to maximize CPU usage, perhaps multiprocessing is more along the lines of what you are looking for? threading simply imitates multiple things happening at once, while multiprocessing actually makes multiple things happen at once. Note that multiprocessing is a bit trickier, as you have to be clever to avoid deadlock.


问:
Hibernate PersistentList and ArrayList
Dear All,
I have a problem with an ArrayList annotated with @ElementCollection.

I need it to be an ArrayList, and when Hibernate load the object from the session, it is a hibernate Persistent List.

How can I solve the issue? I am using Hibernate with hibernate annotations, no JPA, so I can't do any @PostLoad

Best Regards

答:
Use a List instead of ArrayList:

```<code>@ElementCollection(..)
private List elements;
</code>```

If you then want to do something with an ArrayList specifically, you can create a copy:

```<code>ArrayList list = new ArrayList(elements);
</code>```

You need to use interfaces, because ORMs use custom implementations of these interfaces to achieve orm-specific functionality, e.g. lazy loading. Hibernate doesn't have a specific subclass of ArrayList, it has a PersistentList, which is justa List.

Title: Hibernate PersistentList and ArrayList

Body:
Use a List instead of ArrayList:

@ElementCollection(..)
private List elements;

If you then want to do something with an ArrayList specifically, you can create a copy:

ArrayList list = new ArrayList(elements);

You need to use interfaces, because ORMs use custom implementations of these interfaces to achieve orm-specific functionality, e.g. lazy loading. Hibernate doesn't have a specific subclass of ArrayList, it has a PersistentList, which is justa List.


问:
Adding UUIDs to my Django app yields a NoReverseMatch error
I have a books app using a UUID with a listview of all books and detailview of individual books. I keep getting the following error message:

```<code>NoReverseMatch at /books/
Reverse for 'book_detail' with arguments '('/books/71fcfae7-bf2d-41b0-abc8-c6773930a44c',)' not found. 1 pattern(s) tried: ['books/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$']
</code>```

Here is the models.py file:

```<code># books/models.py
import uuid
from django.db import models
from django.urls import reverse

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book_detail', args=[str(self.id)])
</code>```

The urls.py file where I'm using  to convert the id from the model to a uuid.

```<code> # books/urls.py
 from django.urls import path

from .views import BookListView, BookDetailView

urlpatterns = [
    path('', BookListView.as_view(), name='book_list'),
    path('<uuid:pk>', BookDetailView.as_view(), name='book_detail'),
]
</code>```

The top-level urls.py file looks like this and adds a books/ route.

```<code># urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', include('books.urls')),
</code>```

The views.py file:

```<code>from django.views.generic import ListView, DetailView
from .models import Book

class BookListView(ListView):
    model = Book
    context_object_name = 'book_list'
    template_name = 'books/book_list.html'

class BookDetailView(DetailView):
    model = Book
    context_object_name = 'book'
    template_name = 'books/book_detail.html'
</code>```

And the relevant templates file.

```<code><!-- templates/book_detail.html -->
{% extends '_base.html' %}

{% block content %}
{% for book in book_list %}
<div>
  <h2><a href="{% url 'book_detail' book.get_absolute_url %}">{{ book.title }}</a></h2>
</div>
  {% endfor %}
{% endblock content %}
</code>```

I believe I'm implementing this correctly but the URL is not liking my UUID. What is amiss?

答:
The problem is not "adding uuid". The problem is that you are doing the URL reversal twice: once in get_absolute_url and once in the {% url %} tag. Use one or the other, not both.

Either:

```<code><a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a>
</code>```

Or:

```<code><a href="{{ book.get_absolute_url }}">{{ book.title }}</a>
</code>```

Body:
I have a books app using a UUID with a listview of all books and detailview of individual books. I keep getting the following error message:

NoReverseMatch at /books/
Reverse for 'book_detail' with arguments '('/books/71fcfae7-bf2d-41b0-abc8-c6773930a44c',)' not found. 1 pattern(s) tried: ['books/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$']

Here is the models.py file:

# books/models.py
import uuid
from django.db import models
from django.urls import reverse

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book_detail', args=[str(self.id)])

The urls.py file where I'm using  to convert the id from the model to a uuid.

 # books/urls.py
 from django.urls import path

from .views import BookListView, BookDetailView

urlpatterns = [
    path('', BookListView.as_view(), name='book_list'),
    path('<uuid:pk>', BookDetailView.as_view(), name='book_detail'),
]

The top-level urls.py file looks like this and adds a books/ route.

# urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', include('books.urls')),

The views.py file:

from django.views.generic import ListView, DetailView
from .models import Book

class BookListView(ListView):
    model = Book
    context_object_name = 'book_list'
    template_name = 'books/book_list.html'

class BookDetailView(DetailView):
    model = Book
    context_object_name = 'book'
    template_name = 'books/book_detail.html'

And the relevant templates file.

{% extends '_base.html' %}

{% block content %}
{% for book in book_list %}

{{ book.title }}

  {% endfor %}
{% endblock content %}

I believe I'm implementing this correctly but the URL is not liking my UUID. What is amiss?

Body:
The problem is not "adding uuid". The problem is that you are doing the URL reversal twice: once in get_absolute_url and once in the {% url %} tag. Use one or the other, not both.

Either:

<a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a>

Or:

<a href="{{ book.get_absolute_url }}">{{ book.title }}</a>


问:
MongoDB Atlas connection working but not displaying data in Heroku
I want to display the users from my database in MongoDB Atlas. I have successfully created a connection but am not able to show the users. It's my first time using MongoDB Atlas as well as Express.

It's working completely fine on my system with MongoDB on my system but not with MongoDB Atlas.

Here are some codes that I wrote to connect and display the users.

```<code>mongoose.connect("mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/test?retryWrites=true&w=majority" ,{useNewUrlParser: true, useCreateIndex: true})
.then(()=>{
    console.log("connected to db");
})
.catch((err)=>{
    console.log("error:",err);
})
</code>```

```<code>let userSchema = new mongoose.Schema({
    name: String,
    email: String,
    credits: Number
})

let User = mongoose.model("user", userSchema);
</code>```

```<code>app.get("/users", function (req, res) {
    // finding the information about all users from the database
    User.find({}, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.render("users.ejs", { result: response });

        }

    })
})
</code>```

I have given 0.0.0.0/0 as an IP address in MongoDB Atlas so that anyone can excess it.

A view of my MongoDB atlas collection:

Expected output:

Given output by Heroku:

What is it that I am doing wrong?

答: You may need to update your IP Whitelist in ATLAS.

Body:
I want to display the users from my database in MongoDB Atlas. I have successfully created a connection but am not able to show the users. It's my first time using MongoDB Atlas as well as Express.

It's working completely fine on my system with MongoDB on my system but not with MongoDB Atlas.

Here are some codes that I wrote to connect and display the users.

mongoose.connect("mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/test?retryWrites=true&w=majority" ,{useNewUrlParser: true, useCreateIndex: true})
.then(()=>{
    console.log("connected to db");
})
.catch((err)=>{
    console.log("error:",err);
})

let userSchema = new mongoose.Schema({
    name: String,
    email: String,
    credits: Number
})

let User = mongoose.model("user", userSchema);

app.get("/users", function (req, res) {
    // finding the information about all users from the database
    User.find({}, function (err, response) {
        if (err) {
            console.log(err);
        }
        else {
            res.render("users.ejs", { result: response });

        }

    })
})

I have given 0.0.0.0/0 as an IP address in MongoDB Atlas so that anyone can excess it.

A view of my MongoDB atlas collection:

Expected output:

Given output by Heroku:

What is it that I am doing wrong?


问:
SQL how to select multiple rows with the same ID based on criteria of the other columns?
I would like to select the rows whose ID meets the criteria in column 2: first Apple then Orange. The desired answer would be the first 2 rows with ID = 1.

ID,Column11,Column12, Column2

1, 1, 0, Apple

1, 0, 1, Orange

2, 1, 0, Apple

2, 0, 1, Apple

I added two supporting columns Column11 and column12 to label which row for one ID is the first, and which row is the second. Below is my code, but no rows are selected.

```<code>SELECT * FROM table WHERE Column11=1 and Column2=’Apple’ AND Column12=1 AND Column2=’Orange’
</code>```

If I only use below, i got row 1

```<code>SELECT * FROM table WHERE Column11=1 and Column2=’Apple’
</code>```

If I only use below, I got row 2

```<code>SELECT * FROM table WHERE Column12=1 AND Column2=’Orange’
</code>```

Why put them together, I got nothing? Please help. Thanks!

答:
Try this-</p>

```<code>SELECT * FROM your_table
WHERE ID IN
(
    SELECT ID FROM your_table
    WHERE Column2 IN ('Apple','Orange')
    GROUP BY ID
    HAVING COUNT(Column2) = COUNT(DISTINCT Column2)
)
AND
(
    (Column11=1 and Column2='Apple')
    OR (Column12=1 AND Column2='Orange')
)
</code>```

Body:
I would like to select the rows whose ID meets the criteria in column 2: first Apple then Orange. The desired answer would be the first 2 rows with ID = 1.

ID,Column11,Column12, Column2

1, 1, 0, Apple

1, 0, 1, Orange

2, 1, 0, Apple

2, 0, 1, Apple

I added two supporting columns Column11 and column12 to label which row for one ID is the first, and which row is the second. Below is my code, but no rows are selected.

SELECT * FROM table WHERE Column11=1 and Column2=’Apple’ AND Column12=1 AND Column2=’Orange’

If I only use below, i got row 1

SELECT * FROM table WHERE Column11=1 and Column2=’Apple’

If I only use below, I got row 2

SELECT * FROM table WHERE Column12=1 AND Column2=’Orange’

Why put them together, I got nothing? Please help. Thanks!

Body:
Try this-

SELECT * FROM your_table
WHERE ID IN
(
    SELECT ID FROM your_table
    WHERE Column2 IN ('Apple','Orange')
    GROUP BY ID
    HAVING COUNT(Column2) = COUNT(DISTINCT Column2)
)
AND
(
    (Column11=1 and Column2='Apple')
    OR (Column12=1 AND Column2='Orange')
)


问:
How to call function separately for each tab?
I want to call function for each tabs separately.
Like function openCity(event, 'London') and function openCity(event, 'Paris')

I am new in JavaScript and trying find a solution.
Here is my code and it works fine this way.How can I do it separately?

function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that    opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Tab links -->
<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
</div>

<!-- Tab content -->
<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div></code>```

答:
hello!!
I think you must setup two script files in the head tag to add Ajax functionality according to your article. just like this....

```<code><script type="text/javascript" src="javascript/ajax_openCity.js"> </script>
</code>```

This script links link the AJAX function script commands to the current main page.so on this method must not make any changes to the php file.

I think you must refer to this book.. I recommend you this book named : "Scriptin' with JavaScript and Ajax" by Charles Wyke-Smith.

Body:
I want to call function for each tabs separately.
Like function openCity(event, 'London') and function openCity(event, 'Paris')

I am new in JavaScript and trying find a solution.
Here is my code and it works fine this way.How can I do it separately?

function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that    opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

  <button class="tablinks" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>

London

London is the capital city of England.

Paris

Paris is the capital of France.

Body:
hello!!
I think you must setup two script files in the head tag to add Ajax functionality according to your article. just like this....

<script type="text/javascript" src="javascript/ajax_openCity.js"> </script>

This script links link the AJAX function script commands to the current main page.so on this method must not make any changes to the php file.

I think you must refer to this book.. I recommend you this book named : "Scriptin' with JavaScript and Ajax" by Charles Wyke-Smith.


问:
Child setState does not work when calling Parent method
I am new to React so sorry if this is a bad question. I am having trouble with changing the state of a child component then calling a method that changes the state of the parent component. Right now when I trigger the method that is supposed to change states the parent state changes as it should but the child state does not change at all.

When I remove the state change on the Parent component the child component changes as it should.

Here is the parent component (edited to remove code not related to the problem)

```<code>class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginModalName: "Log in"
        }
        this.bindedUpdateModalName = this.updateModalName.bind(this)
    }

    updateModalName(name) {
        console.log(name);
        this.setState({
            loginModalName: name
        });
    };

    render() {
        return (
            <Child loginSwitch = {this.bindedUpdateModalName}/>
        );
    }
}
</code>```

and here is the child component

```<code>class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggingIn: true
        }
    }

    toggleLoggingIn = () => {
        this.setState({
            isLoggingIn: !this.state.isLoggingIn
        });
        console.log(this.state.isLoggingIn);
        this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
    };

    render() {
        return (
            <Button onClick={this.toggleLoggingIn} type="link" style={{paddingLeft: 0}}>register now!</Button>
        );
    }
</code>```

There are no error messages, but my logs show

```<code>true
Log In
</code>```

every time I click the button

答:
This is because setState is async. You need to wait for the state change to happen (second callback option for setState, or componentDidUpdate) or you can use a variable like isLogin to hold the new state value. Change your handler to this

```<code>toggleLoggingIn = () => {
    const isLogin = !this.state.isLoggingIn
    this.setState({
        isLoggingIn: isLogin
    });
    console.log(this.props.loginSwitch);
    this.props.loginSwitch(isLogin ? "Log in" : "Register");
};
</code>```

Check it out in action!

The issue you were experiencing is trying to use local state on an antd form. You should either use parent state and pass as a prop, or use the antd way of updating "state" on the HOC

Body:
I am new to React so sorry if this is a bad question. I am having trouble with changing the state of a child component then calling a method that changes the state of the parent component. Right now when I trigger the method that is supposed to change states the parent state changes as it should but the child state does not change at all.

When I remove the state change on the Parent component the child component changes as it should.

Here is the parent component (edited to remove code not related to the problem)

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginModalName: "Log in"
        }
        this.bindedUpdateModalName = this.updateModalName.bind(this)
    }

    updateModalName(name) {
        console.log(name);
        this.setState({
            loginModalName: name
        });
    };

    render() {
        return (
            <Child loginSwitch = {this.bindedUpdateModalName}/>
        );
    }
}

and here is the child component

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggingIn: true
        }
    }

    toggleLoggingIn = () => {
        this.setState({
            isLoggingIn: !this.state.isLoggingIn
        });
        console.log(this.state.isLoggingIn);
        this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
    };

    render() {
        return (
            <Button onClick={this.toggleLoggingIn} type="link" style={{paddingLeft: 0}}>register now!</Button>
        );
    }

There are no error messages, but my logs show

true
Log In

every time I click the button

Body:
This is because setState is async. You need to wait for the state change to happen (second callback option for setState, or componentDidUpdate) or you can use a variable like isLogin to hold the new state value. Change your handler to this

toggleLoggingIn = () => {
    const isLogin = !this.state.isLoggingIn
    this.setState({
        isLoggingIn: isLogin
    });
    console.log(this.props.loginSwitch);
    this.props.loginSwitch(isLogin ? "Log in" : "Register");
};

Check it out in action!

The issue you were experiencing is trying to use local state on an antd form. You should either use parent state and pass as a prop, or use the antd way of updating "state" on the HOC


问:
excel formula for date loop and backwords logic
Hi I have a problem developing formula to calculate following logic in Excel. I need to identify patients visits within 30 days interval and then within the identified 30 days interval the most latest date for prescribed medication.
lets say patients first visit was on 18Dec2018, this should count as New visit. so all visits until 18Jan2019 are considired as within 30days visits. This calculation I have solved nicely with this formula.

```<code>=OM(OCH(ELLER(C3=C2;C3=C4);ANTAL.OM(C:C;C3)>1;ANTAL.OM(C$2:C3;C3)>1;DAGAR(A3;A2)<30;DAGAR(A3;A4)<30;DAGAR(A:A;A3)<30);"Within 30dgr";"New Visit")
</code>```

And I get in Kolumn G.

No I however within period 18Dec to 18 Jan need to identify latest date for Recepee Registered Date which is available in Kolumn F and I got stack which formula even to start with trying.

答:
For the first part of your problem, there is a small error in your formula - the last row should not be New Visit since the difference is less than 30.

To keep things understandable, I have created 1 extra column as described below:

Date Difference from latest new entry:  this will be

a. 0 if - first entry of patient ;

b. difference between row's date - previous new entry date

c. reset when the difference exceeds 30 - for ex: in row 5 the diff > 30 thus in row 6 it gets reset and the difference is calculated between row6 and row5 instead of row6 and row1

Unique Visit: marks whether the visit is new or within 30 days

Formula for date difference(put in row 1):

```<code>=IF(D2<>D1,0,IF(I1="New",B2-B1,B2-B1+H1))
</code>```

Formula for Unique Visit:

```<code>=IF(D2=D1,IF(H2<30,"Within 30","New"),"New")
</code>```

Put these formulas in first row and drag down to auto-fill.

Latest Recipee Register Date: Captures Recepee register date if the entry is last in entry of 30 days.

Formula:

```<code>=IF(D2<>D3,G2,IF(I3="New",G2,""))
</code>```

Note: I see that your data is sorted with respect to date and other dates are sorted in ascending order as well. These above formulas will work when the data is sorted in ascending order for the all the dates. For other sorting the formulas will need to change.

Body:
Hi I have a problem developing formula to calculate following logic in Excel. I need to identify patients visits within 30 days interval and then within the identified 30 days interval the most latest date for prescribed medication.
lets say patients first visit was on 18Dec2018, this should count as New visit. so all visits until 18Jan2019 are considired as within 30days visits. This calculation I have solved nicely with this formula.

=OM(OCH(ELLER(C3=C2;C3=C4);ANTAL.OM(C:C;C3)>1;ANTAL.OM(C$2:C3;C3)>1;DAGAR(A3;A2)<30;DAGAR(A3;A4)<30;DAGAR(A:A;A3)<30);"Within 30dgr";"New Visit")

And I get in Kolumn G.

No I however within period 18Dec to 18 Jan need to identify latest date for Recepee Registered Date which is available in Kolumn F and I got stack which formula even to start with trying.

Body:
For the first part of your problem, there is a small error in your formula - the last row should not be New Visit since the difference is less than 30.

To keep things understandable, I have created 1 extra column as described below:

Date Difference from latest new entry:  this will be

a. 0 if - first entry of patient ;

b. difference between row's date - previous new entry date

c. reset when the difference exceeds 30 - for ex: in row 5 the diff > 30 thus in row 6 it gets reset and the difference is calculated between row6 and row5 instead of row6 and row1

Unique Visit: marks whether the visit is new or within 30 days

Formula for date difference(put in row 1):

=IF(D2<>D1,0,IF(I1="New",B2-B1,B2-B1+H1))

Formula for Unique Visit:

=IF(D2=D1,IF(H2<30,"Within 30","New"),"New")

Put these formulas in first row and drag down to auto-fill.

Latest Recipee Register Date: Captures Recepee register date if the entry is last in entry of 30 days.

Formula:

=IF(D2<>D3,G2,IF(I3="New",G2,""))

Note: I see that your data is sorted with respect to date and other dates are sorted in ascending order as well. These above formulas will work when the data is sorted in ascending order for the all the dates. For other sorting the formulas will need to change.