问:
Mailer error missing template

Hello,

I have problem with ActionMailer, when I try to execute action:

```<code>rake send_email
</code>```

I get a error:

```<code>    rake aborted!
ActionView::MissingTemplate: Missing template user_mailer/mailer with "mailer". Searched in:
  * "user_mailer"
</code>```

Here's my:

mailers/user_mailer.rb

```<code>class UserMailer < ActionMailer::Base
  default from: "from@example.com"

  def mailer(user)
    @user = user
    mail(to: @user.email, subject: 'Test')
  end

end
</code>```

views/user_mailer/mailer.html.erb

```<code><!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <p>
      Sample mail.
    </p>
  </body>
</html>
</code>```

views/user_mailer/mailer.text.erb

```<code>Sample mail.
</code>```

lib/tasks/emails_task.rake

```<code>desc 'send email'
task send_email: :environment do
  UserMailer.mailer(User.last).deliver!
end
</code>```

config/environments/development.rb

```<code># I recommend using this line to show error
  config.action_mailer.raise_delivery_errors = true

  # ActionMailer Config
  config.action_mailer.delivery_method = :letter_opener

# config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
 :address              => "smtp.gmail.com",
 :port                 => 587,
 :user_name            => ENV['gmail_username'],
 :password             => ENV['gmail_password'],
 :authentication       => "plain",
:enable_starttls_auto => true
}

# Send email in development mode?
config.action_mailer.perform_deliveries = true
</code>```

I searched for the solution on stackoverflow and I tried many of the answers for the similar problem but unfortunately none of them worked for me.

I found solution, when I add body to mailer method like:

```<code>def mailer(user)
  @user = user
  mail(to: @user.email, subject: 'Test', body: 'something')
end
</code>```

Then it does work but I would like to have a body in separate files and make it more complex with user name and other things.

If someone have a idea how to solve this problem then I would be very thankful :)

答: I had a similiar issue. I had missed adding the gem 'haml-rails' in my Gemfile. Check if you are missing the gem.</p>

Title: Mailer error missing template

Body:
Hello,

I have problem with ActionMailer, when I try to execute action:

rake send_email

I get a error:

    rake aborted!
ActionView::MissingTemplate: Missing template user_mailer/mailer with "mailer". Searched in:
  * "user_mailer"

Here's my:

mailers/user_mailer.rb

class UserMailer < ActionMailer::Base
  default from: "from@example.com"

  def mailer(user)
    @user = user
    mail(to: @user.email, subject: 'Test')
  end

end

views/user_mailer/mailer.html.erb

<!DOCTYPE html>

    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />

      Sample mail.

views/user_mailer/mailer.text.erb

Sample mail.

lib/tasks/emails_task.rake

desc 'send email'
task send_email: :environment do
  UserMailer.mailer(User.last).deliver!
end

config/environments/development.rb

# I recommend using this line to show error
  config.action_mailer.raise_delivery_errors = true

  # ActionMailer Config
  config.action_mailer.delivery_method = :letter_opener

# config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
 :address              => "smtp.gmail.com",
 :port                 => 587,
 :user_name            => ENV['gmail_username'],
 :password             => ENV['gmail_password'],
 :authentication       => "plain",
:enable_starttls_auto => true
}

# Send email in development mode?
config.action_mailer.perform_deliveries = true

I searched for the solution on stackoverflow and I tried many of the answers for the similar problem but unfortunately none of them worked for me.

I found solution, when I add body to mailer method like:

def mailer(user)
  @user = user
  mail(to: @user.email, subject: 'Test', body: 'something')
end

Then it does work but I would like to have a body in separate files and make it more complex with user name and other things.

If someone have a idea how to solve this problem then I would be very thankful :)


来源: stackexchange

问:
Enzyme's shallow().text() with React Native doesn't work as I expected
I'm trying to get some basic understanding around React Native tests w/enzyme and react-native-mock.

Not included below: A custom compiler for mocha to get the babel goodness.

My code is as follows:

Block.jsx:

```<code>import React from 'react';
import {View} from 'react-native';

export default ({title, ui}) => (
  <View>
    Title: {title}
  </View>
);
</code>```

Block.test.js

```<code>import { shallow } from 'enzyme';
import { expect } from 'chai';
import {Block} from '../';
import React from 'react';

describe('<Block /> with props: title', () => {

  it('should have correct props', () => {
    expect(
      shallow(<Block title="Something" />).props()
    ).to.deep.equal( {title:"Something"} );
  });

  it('should have correct title', () => {
    expect(
      shallow(<Block title="Something" />).text()
    ).to.equal( "Something" );
  });

});
</code>```

Test results

Mocha command:

```<code>mocha --compilers js:./test/support/compiler.js --require react-native-mock/mock --recursive **/test/*.test.js --watch
</code>```

Mocha test results:

```<code>  <Block /> with props: title
    1) should have correct props
    2) should have correct title

  2 failing

  1) <Block /> with props: title should have correct props <Text />:

      AssertionError: expected { Object (children) } to equal { title: 'Something' }
      + expected - actual

       {
      -  "children": [
      -    "Title: "
      -    "Something"
      -  ]
      +  "title": "Something"
       }

      at Context.<anonymous> (components/test/Block.test.js:24:120)

  2) <Block /> with props: title should have correct title <Text />:

      AssertionError: expected '<View />' to equal 'Something'
      + expected - actual

      -<View />
      +Something

      at Context.<anonymous> (components/test/Block.test.js:28:119)
</code>```

Unexpected behavior

props() seems to get the correct values, but in a different format than described by the api

text() doesnt render the nodes textContent, but instead, the stringified tag "<View />"

Alternative: props().children

Given the component:

```<code>import React from 'react';
import {View, Text} from 'react-native';

export default ({title, ui}) => (
  <View>
    <Text> The title...</Text>
    {title}
  </View>
);
</code>```

props().children is the array [<Text component instance>, "Something"]

So the follow test passes:

```<code>  it('should have correct props', () => {
    expect(
      shallow(<Block title="Something" />).props().children
    ).to.contain( "Something" );
  });
</code>```

Question

Why is Enzyme API behaving differently that described in the docs?

Specifically looking at the docs shallow(<Block title="Something" />).text() should equal something like: The title...Something

Am I doing something incorrect, or is it one the technologies I'm using?

EDIT 1: Other problems

html(), render(), update() also don't seem to work with my setup

EDIT: React native only works with shallow at the moment

答: You can ue expect(wrapper.find(Foo).render().text()).to.equal('Hello World') trick

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get some basic understanding around React Native tests w/enzyme and react-native-mock.

Not included below: A custom compiler for mocha to get the babel goodness.

My code is as follows:

Block.jsx:

import React from 'react';
import {View} from 'react-native';

export default ({title, ui}) => (
  <View>
    Title: {title}
  </View>
);

Block.test.js

import { shallow } from 'enzyme';
import { expect } from 'chai';
import {Block} from '../';
import React from 'react';

describe('<Block /> with props: title', () => {

  it('should have correct props', () => {
    expect(
      shallow(<Block title="Something" />).props()
    ).to.deep.equal( {title:"Something"} );
  });

  it('should have correct title', () => {
    expect(
      shallow(<Block title="Something" />).text()
    ).to.equal( "Something" );
  });

});

Test results

Mocha command:

mocha --compilers js:./test/support/compiler.js --require react-native-mock/mock --recursive **/test/*.test.js --watch

Mocha test results:

  <Block /> with props: title
    1) should have correct props
    2) should have correct title

  2 failing

  1) <Block /> with props: title should have correct props <Text />:

      AssertionError: expected { Object (children) } to equal { title: 'Something' }
      + expected - actual

       {
      -  "children": [
      -    "Title: "
      -    "Something"
      -  ]
      +  "title": "Something"
       }

      at Context.<anonymous> (components/test/Block.test.js:24:120)

  2) <Block /> with props: title should have correct title <Text />:

      AssertionError: expected '<View />' to equal 'Something'
      + expected - actual

      -<View />
      +Something

      at Context.<anonymous> (components/test/Block.test.js:28:119)

Unexpected behavior

props() seems to get the correct values, but in a different format than described by the api

text() doesnt render the nodes textContent, but instead, the stringified tag "<View />"

Alternative: props().children

Given the component:

import React from 'react';
import {View, Text} from 'react-native';

export default ({title, ui}) => (
  <View>
    <Text> The title...</Text>
    {title}
  </View>
);

props().children is the array [<Text component instance>, "Something"]

So the follow test passes:

  it('should have correct props', () => {
    expect(
      shallow(<Block title="Something" />).props().children
    ).to.contain( "Something" );
  });

Question

Why is Enzyme API behaving differently that described in the docs?

Specifically looking at the docs shallow(<Block title="Something" />).text() should equal something like: The title...Something

Am I doing something incorrect, or is it one the technologies I'm using?

EDIT 1: Other problems

html(), render(), update() also don't seem to work with my setup

EDIT: React native only works with shallow at the moment

ContentLicense: CC BY-SA 4.0


问:
Java 8 stream filter local variable
```<code>Obj1 x = null;
String key = null;
while(it.hasNext()){
   x = it.next();
   key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}
</code>```

This is complaining with the following message: "Local variable key must be final or effective final..." I understand the the lambda context is created at runtime and it needs variables that do not change.

How can I use the functional style to find the object in the list?
I want to avoid the old fashion way of iterating over the list with while.

答:
You can simply move the variable declarations to within the loop, thus making them effectively final:

```<code>...
while(it.hasNext()){
   Obj1 x = it.next();
   String key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}
</code>```

JIT/etc makes declaring variables outside of a loop a non-issue, really.

Title: Java 8 stream filter local variable

Body:
Obj1 x = null;
String key = null;
while(it.hasNext()){
   x = it.next();
   key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}

This is complaining with the following message: "Local variable key must be final or effective final..." I understand the the lambda context is created at runtime and it needs variables that do not change.

How can I use the functional style to find the object in the list?
I want to avoid the old fashion way of iterating over the list with while.

Body:
You can simply move the variable declarations to within the loop, thus making them effectively final:

...
while(it.hasNext()){
   Obj1 x = it.next();
   String key = x.getKey();
   listObject.stream().filter(e -> e.getKey().equals(key)).findFirst().get();
}

JIT/etc makes declaring variables outside of a loop a non-issue, really.


问:
Spring Data REST - Why hibernate fetches children entity with FetchType.LAZY?
I have a simple use case where I created 2 entities Account & AccountDetail.

These entities have a one-to-one relationship as shown below:
table relationship

The Account entity:

```<code>@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@EqualsAndHashCode
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;

    @OneToOne(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private AccountDetail accountDetail;

}
</code>```

The AccountDetail entity:

```<code>@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@EqualsAndHashCode
public class AccountDetail {
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @MapsId
    private Account account;

    private String firstName;

    private String lastName;
}
</code>```

I am using Spring Boot (v2.3.0) with following dependencies:
- Spring Data JPA: to persist entities using Hibernate
- Rest Repositories: to expose repositories over REST endpoints

The issue is that Hibernate is fetching the AccountDetail entity even though I specified fetch = FetchType.LAZY.

You can see the 2 sql statements in the log:
hibernate log

What I already tried:

Using Projection:

```<code>@Projection(types = {Account.class})
public interface AccountProjection {
    String getUsername();
}
</code>```

With the following GET request http://localhost:8080/accounts/1?projection=accountProjection, I get:

```<code>   {
      "username": "warrior24",
      "_links": {
        "self": {
          "href": "http://localhost:8080/accounts/1"
        },
        "account": {
          "href": "http://localhost:8080/accounts/1{?projection}",
          "templated": true
        },
        "accountDetail": {
          "href": "http://localhost:8080/accounts/1/accountDetail"
        }
      }
    }
</code>```

Unfortunately, with this solution, it still makes 2 sql requests.

Using Hibernate Bytecode Enhancement with @LazyToOne(LazyToOneOption.NO_PROXY)

```<code>@OneToOne(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@LazyToOne(LazyToOneOption.NO_PROXY)
private AccountDetail accountDetail;
</code>```

Even this solution does not solve the issue.

Conclusion

I am not sure to understand why hibernate is fetching the child. At the moment it is not a big issue, but if the number of database records gets big it could impact on the performance.

Does anybody have a similar issue and maybe know how to solve it?

Update: Including the debug log for a GET request

2020-05-27 15:23:58.414  INFO 2119 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat-3].[localhost].[/]     : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-27 15:23:58.414  INFO 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-05-27 15:23:58.414 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Detected StandardServletMultipartResolver
2020-05-27 15:23:58.415 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-05-27 15:23:58.415  INFO 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
2020-05-27 15:23:58.415 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/accounts/1", parameters={}
2020-05-27 15:23:58.416 DEBUG 2119 --- [nio-8080-exec-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped to org.springframework.data.rest.webmvc.RepositoryEntityController#getItemResource(RootResourceInformation, Serializable, PersistentEntityResourceAssembler, HttpHeaders)
2020-05-27 15:23:58.416 DEBUG 2119 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] stomAnnotationTransactionAttributeSource : Adding transactional method 'findById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Found thread-bound EntityManager [SessionImpl(1137877934<open>)] for JPA transaction
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.jdbc.datasource.DataSourceUtils      : Setting JDBC Connection [HikariProxyConnection@646683728 wrapping conn193: url=jdbc:h2:mem:f0df200a-97ea-4e5b-9f80-050ff9a550f7 user=SA] read-only
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@3a65c273]
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] org.hibernate.SQL                        : select account0_.id as id1_0_0_, account0_.password as password2_0_0_, account0_.username as username3_0_0_ from account account0_ where account0_.id=?
2020-05-27 15:23:58.417 TRACE 2119 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [1]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] org.hibernate.SQL                        : select accountdet0_.account_id as account_3_1_0_, accountdet0_.first_name as first_na1_1_0_, accountdet0_.last_name as last_nam2_1_0_ from account_detail accountdet0_ where accountdet0_.account_id=?
2020-05-27 15:23:58.418 TRACE 2119 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [1]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Initiating transaction commit
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Committing JPA transaction on EntityManager [SessionImpl(1137877934<open>)]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.jdbc.datasource.DataSourceUtils      : Resetting read-only flag of JDBC Connection [HikariProxyConnection@646683728 wrapping conn193: url=jdbc:h2:mem:f0df200a-97ea-4e5b-9f80-050ff9a550f7 user=SA]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Not closing pre-bound JPA EntityManager after transaction
2020-05-27 15:23:58.421 DEBUG 2119 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/hal+json', given [*/*] and supported [application/hal+json]
2020-05-27 15:23:58.421 DEBUG 2119 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [Resource { content: Account(id=1, username=warrior24, password=1234), links: [<http://localhost:8080 (truncated)...]
2020-05-27 15:23:58.421 DEBUG 2119 --- [nio-8080-exec-1] s.d.r.w.j.PersistentEntityJackson2Module : Serializing PersistentEntity org.springframework.data.jpa.mapping.JpaPersistentEntityImpl@45b7be72.
2020-05-27 15:23:58.423 DEBUG 2119 --- [nio-8080-exec-1] .s.ReloadableResourceBundleMessageSource : No properties file found for [classpath:rest-messages] - neither plain properties nor XML
2020-05-27 15:23:58.424 DEBUG 2119 --- [nio-8080-exec-1] .s.ReloadableResourceBundleMessageSource : No properties file found for [classpath:rest-messages_en] - neither plain properties nor XML
2020-05-27 15:23:58.424 DEBUG 2119 --- [nio-8080-exec-1] .s.ReloadableResourceBundleMessageSource : No properties file found for [classpath:rest-messages_en_GB] - neither plain properties nor XML
2020-05-27 15:23:58.426 DEBUG 2119 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-05-27 15:23:58.426 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 200 OK

答:
SOLUTION (kind of)

Okay I think I found the solution but unfortunately it is not compatible with Spring Data Rest.

By adding optional = false, you can tell hibernate that you will ensure that the child reference will never be null (in my case AccountDetail).

Therefore, it will not need to fetch the child in order to check if it has to create a proxy or assign NULL.

```<code>@OneToOne(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
@LazyToOne(LazyToOneOption.NO_PROXY)
private AccountDetail accountDetail;
</code>```

The issue with this solution is that you cannot create a new Account resource using the POST endpoint provided with the @RepositoryRestResource annotation.
Since, it now expects the AccountDetail to be not null, you need to provide the link of this resource in the JSON (which is not existing yet). And you cannot create the AccountDetail resource because it uses as primary key the foreign key from the Account table.

Body:
I have a simple use case where I created 2 entities Account & AccountDetail.

These entities have a one-to-one relationship as shown below:
table relationship

The Account entity:

@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@EqualsAndHashCode
public class Account {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;

    @OneToOne(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private AccountDetail accountDetail;

}

The AccountDetail entity:

@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@EqualsAndHashCode
public class AccountDetail {
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @MapsId
    private Account account;

    private String firstName;

    private String lastName;
}

I am using Spring Boot (v2.3.0) with following dependencies:
- Spring Data JPA: to persist entities using Hibernate
- Rest Repositories: to expose repositories over REST endpoints

The issue is that Hibernate is fetching the AccountDetail entity even though I specified fetch = FetchType.LAZY.

You can see the 2 sql statements in the log:
hibernate log

What I already tried:

Using Projection:

@Projection(types = {Account.class})
public interface AccountProjection {
    String getUsername();
}

With the following GET request http://localhost:8080/accounts/1?projection=accountProjection, I get:

   {
      "username": "warrior24",
      "_links": {
        "self": {
          "href": "http://localhost:8080/accounts/1"
        },
        "account": {
          "href": "http://localhost:8080/accounts/1{?projection}",
          "templated": true
        },
        "accountDetail": {
          "href": "http://localhost:8080/accounts/1/accountDetail"
        }
      }
    }

Unfortunately, with this solution, it still makes 2 sql requests.

Using Hibernate Bytecode Enhancement with @LazyToOne(LazyToOneOption.NO_PROXY)

@OneToOne(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@LazyToOne(LazyToOneOption.NO_PROXY)
private AccountDetail accountDetail;

Even this solution does not solve the issue.

Conclusion

I am not sure to understand why hibernate is fetching the child. At the moment it is not a big issue, but if the number of database records gets big it could impact on the performance.

Does anybody have a similar issue and maybe know how to solve it?

Update: Including the debug log for a GET request

2020-05-27 15:23:58.414  INFO 2119 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat-3].[localhost].[/]     : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-27 15:23:58.414  INFO 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-05-27 15:23:58.414 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Detected StandardServletMultipartResolver
2020-05-27 15:23:58.415 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-05-27 15:23:58.415  INFO 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
2020-05-27 15:23:58.415 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/accounts/1", parameters={}
2020-05-27 15:23:58.416 DEBUG 2119 --- [nio-8080-exec-1] o.s.d.r.w.RepositoryRestHandlerMapping   : Mapped to org.springframework.data.rest.webmvc.RepositoryEntityController#getItemResource(RootResourceInformation, Serializable, PersistentEntityResourceAssembler, HttpHeaders)
2020-05-27 15:23:58.416 DEBUG 2119 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] stomAnnotationTransactionAttributeSource : Adding transactional method 'findById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Found thread-bound EntityManager [SessionImpl(1137877934<open>)] for JPA transaction
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.jdbc.datasource.DataSourceUtils      : Setting JDBC Connection [HikariProxyConnection@646683728 wrapping conn193: url=jdbc:h2:mem:f0df200a-97ea-4e5b-9f80-050ff9a550f7 user=SA] read-only
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@3a65c273]
2020-05-27 15:23:58.417 DEBUG 2119 --- [nio-8080-exec-1] org.hibernate.SQL                        : select account0_.id as id1_0_0_, account0_.password as password2_0_0_, account0_.username as username3_0_0_ from account account0_ where account0_.id=?
2020-05-27 15:23:58.417 TRACE 2119 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [1]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] org.hibernate.SQL                        : select accountdet0_.account_id as account_3_1_0_, accountdet0_.first_name as first_na1_1_0_, accountdet0_.last_name as last_nam2_1_0_ from account_detail accountdet0_ where accountdet0_.account_id=?
2020-05-27 15:23:58.418 TRACE 2119 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [1]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Initiating transaction commit
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Committing JPA transaction on EntityManager [SessionImpl(1137877934<open>)]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.jdbc.datasource.DataSourceUtils      : Resetting read-only flag of JDBC Connection [HikariProxyConnection@646683728 wrapping conn193: url=jdbc:h2:mem:f0df200a-97ea-4e5b-9f80-050ff9a550f7 user=SA]
2020-05-27 15:23:58.418 DEBUG 2119 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager        : Not closing pre-bound JPA EntityManager after transaction
2020-05-27 15:23:58.421 DEBUG 2119 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/hal+json', given [*/*] and supported [application/hal+json]
2020-05-27 15:23:58.421 DEBUG 2119 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [Resource { content: Account(id=1, username=warrior24, password=1234), links: [<http://localhost:8080 (truncated)...]
2020-05-27 15:23:58.421 DEBUG 2119 --- [nio-8080-exec-1] s.d.r.w.j.PersistentEntityJackson2Module : Serializing PersistentEntity org.springframework.data.jpa.mapping.JpaPersistentEntityImpl@45b7be72.
2020-05-27 15:23:58.423 DEBUG 2119 --- [nio-8080-exec-1] .s.ReloadableResourceBundleMessageSource : No properties file found for [classpath:rest-messages] - neither plain properties nor XML
2020-05-27 15:23:58.424 DEBUG 2119 --- [nio-8080-exec-1] .s.ReloadableResourceBundleMessageSource : No properties file found for [classpath:rest-messages_en] - neither plain properties nor XML
2020-05-27 15:23:58.424 DEBUG 2119 --- [nio-8080-exec-1] .s.ReloadableResourceBundleMessageSource : No properties file found for [classpath:rest-messages_en_GB] - neither plain properties nor XML
2020-05-27 15:23:58.426 DEBUG 2119 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2020-05-27 15:23:58.426 DEBUG 2119 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 200 OK

Body:
SOLUTION (kind of)

Okay I think I found the solution but unfortunately it is not compatible with Spring Data Rest.

By adding optional = false, you can tell hibernate that you will ensure that the child reference will never be null (in my case AccountDetail).

Therefore, it will not need to fetch the child in order to check if it has to create a proxy or assign NULL.

@OneToOne(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
@LazyToOne(LazyToOneOption.NO_PROXY)
private AccountDetail accountDetail;

The issue with this solution is that you cannot create a new Account resource using the POST endpoint provided with the @RepositoryRestResource annotation.
Since, it now expects the AccountDetail to be not null, you need to provide the link of this resource in the JSON (which is not existing yet). And you cannot create the AccountDetail resource because it uses as primary key the foreign key from the Account table.


问:
find the nearest location by latitude and longitude in postgresql
Hi i'm trying find the nearest location by latitude and longitude in postgresql database.But when i run the below query it showing column distance does not exists.</p>

```<code>ERROR:  column "distance" does not exist
LINE 1: ... ) ) ) AS distance FROM station_location   HAVING distance <...
                                                             ^
********** Error **********

ERROR: column "distance" does not exist
SQL state: 42703
Character: 218

CREATE TABLE station_location
(
  id bigint NOT NULL DEFAULT nextval('location_id_seq'::regclass),
  state_name character varying NOT NULL,
  country_name character varying NOT NULL,
  locality character varying NOT NULL,
  created_date timestamp without time zone NOT NULL,
  is_delete boolean NOT NULL DEFAULT false,
  lat double precision,
  lng double precision,
  CONSTRAINT location_pkey PRIMARY KEY (id)
)

SELECT  *,( 3959 * acos( cos( radians(6.414478) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(12.466646) ) + sin( radians(6.414478) ) * sin( radians( lat ) ) ) ) AS distance
FROM station_location
HAVING distance < 5
ORDER BY distance
LIMIT 20;
</code>```

答:
You can use PostgreSQL's cube and earthdistance extensions.

Enable them like this:

```<code>CREATE EXTENSION cube;
CREATE EXTENSION earthdistance;
</code>```

Let's say your current location is 35.697933, 139.707318. Then your query will be something like this:

```<code>SELECT *, point(35.697933, 139.707318) <@>  (point(longitude, latitude)::point) as distance
FROM station_location
-- WHERE (point(35.697933, 139.707318) <@> point(longitude, latitude)) < 3
ORDER BY distance;
</code>```

Please note that the distance is in miles (by default).

Body:
Hi i'm trying find the nearest location by latitude and longitude in postgresql database.But when i run the below query it showing column distance does not exists.

ERROR:  column "distance" does not exist
LINE 1: ... ) ) ) AS distance FROM station_location   HAVING distance <...
                                                             ^
********** Error **********

ERROR: column "distance" does not exist
SQL state: 42703
Character: 218

CREATE TABLE station_location
(
  id bigint NOT NULL DEFAULT nextval('location_id_seq'::regclass),
  state_name character varying NOT NULL,
  country_name character varying NOT NULL,
  locality character varying NOT NULL,
  created_date timestamp without time zone NOT NULL,
  is_delete boolean NOT NULL DEFAULT false,
  lat double precision,
  lng double precision,
  CONSTRAINT location_pkey PRIMARY KEY (id)
)

SELECT  *,( 3959 * acos( cos( radians(6.414478) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(12.466646) ) + sin( radians(6.414478) ) * sin( radians( lat ) ) ) ) AS distance
FROM station_location
HAVING distance < 5
ORDER BY distance
LIMIT 20;

Body:
You can use PostgreSQL's cube and earthdistance extensions.

Enable them like this:

CREATE EXTENSION cube;
CREATE EXTENSION earthdistance;

Let's say your current location is 35.697933, 139.707318. Then your query will be something like this:

SELECT *, point(35.697933, 139.707318) <@>  (point(longitude, latitude)::point) as distance
FROM station_location
-- WHERE (point(35.697933, 139.707318) <@> point(longitude, latitude)) < 3
ORDER BY distance;

Please note that the distance is in miles (by default).


问:
What's the use for converter.build() in TensorRT?
The official documentation on TensorRT lists two ways to convert a TensorFlow SavedModel into a TensorRT SavedModel: the first is

from tensorflow.python.compiler.tensorrt import trt_convert as trt
converter = trt.TrtGraphConverterV2(input_saved_model_dir=input_saved_model_dir)
converter.convert()
converter.save(output_saved_model_dir)
```

<p>and the second is </p>

<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
from tensorflow.python.compiler.tensorrt import trt_convert as trt

conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS
conversion_params = conversion_params._replace(
    max_workspace_size_bytes=(1<<32))
conversion_params = conversion_params._replace(precision_mode="FP16")
conversion_params = conversion_params._replace(
    maximum_cached_engiens=100)

converter = trt.TrtGraphConverterV2(
    input_saved_model_dir=input_saved_model_dir,
    conversion_params=conversion_params)
converter.convert()
def my_input_fn():
  for _ in range(num_runs):
    Inp1 = np.random.normal(size=(8, 16, 16, 3)).astype(np.float32)
    inp2 = np.random.normal(size=(8, 16, 16, 3)).astype(np.float32)
    yield inp1, inp2
converter.build(input_fn=my_input_fn)
converter.save(output_saved_model_dir)

saved_model_loaded = tf.saved_model.load(
    output_saved_model_dir, tags=[tag_constants.SERVING])
graph_func = saved_model_loaded.signatures[
    signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
frozen_func = convert_to_constants.convert_variables_to_constants_v2(
    graph_func)
output = frozen_func(input_data)[0].numpy()
</code>```

Stripping out all of the boilerplate code for imports, inference etc the difference seems to lie in the call to converter.build(). The documentation explains this function as such:

"This method optimizes the converted function (returned by convert()) by building TensorRT engines. This is useful in case the user wants to perform the optimizations before runtime. The optimization is done by running inference on the converted function using the input data received from the argument input_fn. This argument is a generator function that yields input data as a list or tuple. "

What does "before runtime" mean in this context? Will the "optimizations" be performed upon model loading, upon the first inference, or upon every single inference using the converted model? What are those optimizations, even? Isn't converting the model to TensorRT an optimization in itself?

I am asking because if I call converter.build() the conversion seems to fail in unpredictable ways after taking a LOT of time (more than two hours) to run without producing any sensible output, so I was wondering how much am I losing by not calling it and whether there is more comprehensive documentation on using TF2.x SavedModels with TensorRT.

Thanks in advance to whoever can answer!!

答:
From my understanding (after reading TensorFlow's docs) the converter.convert() function converts the graph to tf-trt, replacing whatever nodes it can with TRTEngineOp, but it doesn't create the actual engine files used during inference.

The call to converter.build() however creates the engine files, but for the input sizes of the input provided by input_fn, and for the platform that build is being run on. So, reasons for not calling converter.build() would be that you don't know the input shapes beforehand, or can't do the build on the platform that you're going to run inference on.

I find it hard to imagine that new engine files are created for each forward pass, but definitely for each new input shape. It's unclear from the examples whether the input from input_fn is used in any other way than providing information regarding input shape, but if you return inputs of different shapes, one engine file should be created for each input size.

As an example, providing the following input function would produce one engine for input size (112,112,3) and one for (224,224,3):

```<code>def input_fn():
  input_sizes = [[112, 112], [224, 224]]
  for size in input_sizes:
    inp1 = np.random.normal(size=(1, *size, 3)).astype(np.float32)
    yield [inp1]
</code>```

As for your input_fn, do you have two images as input to your network? What worked for me was returning a single image in a list like in the above sample (tuple didn't work for some reason, even though the docs say it should).

Hope this helped.

Body:
The official documentation on TensorRT lists two ways to convert a TensorFlow SavedModel into a TensorRT SavedModel: the first is

from tensorflow.python.compiler.tensorrt import trt_convert as trt
converter = trt.TrtGraphConverterV2(input_saved_model_dir=input_saved_model_dir)
converter.convert()
converter.save(output_saved_model_dir)

and the second is

import tensorflow as tf
from tensorflow.python.compiler.tensorrt import trt_convert as trt

conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS
conversion_params = conversion_params._replace(
    max_workspace_size_bytes=(1<<32))
conversion_params = conversion_params._replace(precision_mode="FP16")
conversion_params = conversion_params._replace(
    maximum_cached_engiens=100)

converter = trt.TrtGraphConverterV2(
    input_saved_model_dir=input_saved_model_dir,
    conversion_params=conversion_params)
converter.convert()
def my_input_fn():
  for _ in range(num_runs):
    Inp1 = np.random.normal(size=(8, 16, 16, 3)).astype(np.float32)
    inp2 = np.random.normal(size=(8, 16, 16, 3)).astype(np.float32)
    yield inp1, inp2
converter.build(input_fn=my_input_fn)
converter.save(output_saved_model_dir)

saved_model_loaded = tf.saved_model.load(
    output_saved_model_dir, tags=[tag_constants.SERVING])
graph_func = saved_model_loaded.signatures[
    signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]
frozen_func = convert_to_constants.convert_variables_to_constants_v2(
    graph_func)
output = frozen_func(input_data)[0].numpy()

Stripping out all of the boilerplate code for imports, inference etc the difference seems to lie in the call to converter.build(). The documentation explains this function as such:

"This method optimizes the converted function (returned by convert()) by building TensorRT engines. This is useful in case the user wants to perform the optimizations before runtime. The optimization is done by running inference on the converted function using the input data received from the argument input_fn. This argument is a generator function that yields input data as a list or tuple. "

What does "before runtime" mean in this context? Will the "optimizations" be performed upon model loading, upon the first inference, or upon every single inference using the converted model? What are those optimizations, even? Isn't converting the model to TensorRT an optimization in itself?

I am asking because if I call converter.build() the conversion seems to fail in unpredictable ways after taking a LOT of time (more than two hours) to run without producing any sensible output, so I was wondering how much am I losing by not calling it and whether there is more comprehensive documentation on using TF2.x SavedModels with TensorRT.

Thanks in advance to whoever can answer!!

Body:
From my understanding (after reading TensorFlow's docs) the converter.convert() function converts the graph to tf-trt, replacing whatever nodes it can with TRTEngineOp, but it doesn't create the actual engine files used during inference.

The call to converter.build() however creates the engine files, but for the input sizes of the input provided by input_fn, and for the platform that build is being run on. So, reasons for not calling converter.build() would be that you don't know the input shapes beforehand, or can't do the build on the platform that you're going to run inference on.

I find it hard to imagine that new engine files are created for each forward pass, but definitely for each new input shape. It's unclear from the examples whether the input from input_fn is used in any other way than providing information regarding input shape, but if you return inputs of different shapes, one engine file should be created for each input size.

As an example, providing the following input function would produce one engine for input size (112,112,3) and one for (224,224,3):

def input_fn():
  input_sizes = [[112, 112], [224, 224]]
  for size in input_sizes:
    inp1 = np.random.normal(size=(1, *size, 3)).astype(np.float32)
    yield [inp1]

As for your input_fn, do you have two images as input to your network? What worked for me was returning a single image in a list like in the above sample (tuple didn't work for some reason, even though the docs say it should).

Hope this helped.


问:
Extracting data from hyperlink cell in CSV
When I am reading a cell with hyperlink from CSV file I am getting the following:

=HYPERLINK("http://google.com","google") #for example

Is there a way to extract only the "google" without the =hyperlink and the link?

答:
As per @martineau's comment, you have two versions of HYPERLINK.

```<code>>>> s1 = '=HYPERLINK("http://google.com","google")'
</code>```

Or

```<code>>>> s2 = '=HYPERLINK("http://google.com")'
</code>```

You can split, use a regex, but these methods are tricky (what if you have a comma in the url? an escaped quote in the name?).

There is a module called ast that parses Python expressions. We can use it, because Excel function call syntax is close to Python's one. Here's a version that returns the friendly name if there is one, and the url else:

```<code>>>> import ast
>>> ast.parse(s1[1:]).body[0].value.args[-1].s
'google'
</code>```

And:

```<code>>>> ast.parse(s2[1:]).body[0].value.args[-1].s
'http://google.com'
</code>```

This is how it works: s1[1:] removes the = sign. Then we take the value of the expression:

```<code>>>> v = ast.parse(s1[1:]).body[0].value
>>> v
<_ast.Call object at ...>
</code>```

It is easy to extract the function name:

```<code>>>> v.func.id
'HYPERLINK'
</code>```

And the args:

```<code>>>> [arg.s for arg in v.args]
['http://google.com', 'google']
</code>```

Just take the last arg ( ....args[-1].s) to get the friendly name if it exists, and the url else. You can also checklen(args)` to do something if there is one arg, and something else if there are two args.

Body:
As per @martineau's comment, you have two versions of HYPERLINK.

>>> s1 = '=HYPERLINK("http://google.com","google")'

Or

>>> s2 = '=HYPERLINK("http://google.com")'

You can split, use a regex, but these methods are tricky (what if you have a comma in the url? an escaped quote in the name?).

There is a module called ast that parses Python expressions. We can use it, because Excel function call syntax is close to Python's one. Here's a version that returns the friendly name if there is one, and the url else:

>>> import ast
>>> ast.parse(s1[1:]).body[0].value.args[-1].s
'google'

And:

>>> ast.parse(s2[1:]).body[0].value.args[-1].s
'http://google.com'

This is how it works: s1[1:] removes the = sign. Then we take the value of the expression:

>>> v = ast.parse(s1[1:]).body[0].value
>>> v
<_ast.Call object at ...>

It is easy to extract the function name:

>>> v.func.id
'HYPERLINK'

And the args:

>>> [arg.s for arg in v.args]
['http://google.com', 'google']

Just take the last arg ( ....args[-1].s) to get the friendly name if it exists, and the url else. You can also checklen(args)` to do something if there is one arg, and something else if there are two args.


问:
Firebase import export JSON not found
I create a collection in Firebase as shown in the picture:

In the old version, there was a three button in the top, where you can import and export data as JSON and other types, but now I can't find it.

Does the tool change this action (import/export) or I should to do some configuration to solve this?

答:
In the old version, there was a three button in the top, where you can import and export data as JSON and other types, but now I can't find it.

What you're describing is for Firebase Realtime Database.  That import feature is still present for that database product.  However, the database you're working with now is Firestore, which is a completely different database product, and does not have an import feature.  You will have to write code to import data, or find some other way to do so - it's not possible from the console.

Title: Firebase import export JSON not found


问:
In-process communication design with WCF (.NET)
I have an interesting design problem and I was hoping you all could make some suggestions.  I'm using C# and .NET 3.0

I have a very nice, extensible framework built on top of WCF that automates the setup of endpoints and the creation of contracts.  The system I'm working in could be run in different ways - endpoints could be somewhere else on the internet, running in different assemblies on the same box, or even running in the same process.  WCF is great for making all of this transparent, but in the last case, I'd like to improve efficiency:

I'd love to avoid the overhead of serializing objects that aren't really going anywhere.  There's really no point in doing that to communicate between two threads in the same assembly.  At the same time, I'd like to utilize the WCF-based framework that's already in place, because it will be a lot easier to maintain if we don't have two separate communications pathways depending on the setup of the system.

My first thought was to use object pointers in an unsafe context - to not fight the serialization, but to only serialize the minimum amount.  My concern with this is that on asynchronous messages in environments where the GC is being aggressive, the message might and probably will be gone before we have a chance to dereference the pointer contained in it, which would lead to plenty of issues.

My next thought was to use GCHandles, but I'm unsure about their behavior - if a GCHandle isn't referenced anymore, but contains a reference to a managed object, are both cleaned up by the GC, or neither?  I'm worried about introducing a huge memory leak by using these, because the chance that a message will get lost is great, and we won't be able to call Free(), and the documentation I can find is... lacking.

Another thought is to use reflection to look at all managed objects, but it seems like the overhead for this would be huge, and this system must be as efficient as possible.

So, in summary, I'm trying to send an object across a process with WCF without serializing it, which as far as I can tell means keeping it alive even if it temporarily has no references.  It seems like it should be possible, but I wonder if I'm trying to have my cake and eat it too.

Thank you so much for your input!

答:
I would investigate the "NetNamedPipes" transport protocol in WCF which is specifically designed for same-machine, inter-process communication and which has the least overhead possible (including fast binary serialization).

Marc

ContentLicense: CC BY-SA 2.5


问:
error: "fatal: I don't handle protocol ``git` when using bundle install
I have the following line in my GemFile :

gem 'rails', :git => 'git://github.com/rails/rails.git'

I get the following error:

```<code>Fetching git://github.com/rails/rails.git
fatal: I don't handle protocol ''git'
Git error: command `git clone 'git://github.com/rails/rails.git'...
</code>```

but when I run gem install 'rails' it works fine.

basically when running the clone command, bundler adds the single quotes around the git:// address which throws the error.

I am working on windows. Any ideas why I am getting this error?

Cheers

答:
It's the issue with the newer version of the Bundler 1.0.14.

I needed to revert to 1.0.13 to make it work. They apparently had some issues dealing with escape characters in Windows.

See here > https://github.com/carlhuda/bundler/issues/1212

Body:
I have the following line in my GemFile :

gem 'rails', :git => 'git://github.com/rails/rails.git'

I get the following error:

Fetching git://github.com/rails/rails.git
fatal: I don't handle protocol ''git'
Git error: command `git clone 'git://github.com/rails/rails.git'...

but when I run gem install 'rails' it works fine.

basically when running the clone command, bundler adds the single quotes around the git:// address which throws the error.

I am working on windows. Any ideas why I am getting this error?

Cheers


问:
How to hide zero values in a pie chart with the EPPLUS library
I'm developing with c# and use the EPPLUS library to create excel sheets, specifically
I've created pie charts where I also show zero values but I would like to remove them. I have not been able to find any workaround. below the code I use:

```<code>```    int chart_RegionHeaderRow = 1;
int chart_RegionHeaderColumn = 13;
firstRowCategory = 2;
lastRowCategory = 2;
firstColCategory = 3;
lastColCategory = firstColCategory + pDeployVersionSet.Length - 1;

int firstColValue = 3;
int lastColValue = firstColValue + pDeployVersionSet.Length - 1;
int firstRowSerie = 3;

int rowCR = chart_RegionHeaderRow;
int colCR = chart_RegionHeaderColumn;

int chart_RegionColStep = 6;
int chart_RegionRowStep = 16;

//Create the Region chart WW
var chartWW = (ExcelPieChart)worksheet.Drawings.AddChart("pieChartDeployWW", eChartType.Pie);
chartWW.SetSize(300, 300);
chartWW.SetPosition(rowCR, 0, colCR, 0);
chartWW.Title.Text = "WW";

chartWW.DataLabel.ShowValue = true;
chartWW.DataLabel.ShowPercent = true;
chartWW.DataLabel.ShowLeaderLines = true;
indexSerie = firstRowSerie;
chartWW.Series.Add(ExcelRange.GetAddress(indexSerie + _RegionsSet.Length,
     firstColValue,
     indexSerie + _RegionsSet.Length,
     lastColValue),
       ExcelRange.GetAddress(firstRowCategory, firstColCategory, lastRowCategory, lastColCategory
```

and also the resulting excel file:

enter image description here

I hope somebody can give me directions.
Thank you

答:
Simply took the size to 0.
Not very elegant but it works. </p>

```<code>var deletePieChart = ws.Drawings["Chart 6"] as ExcelPieChart;
deletePieChart.SetSize(0, 0);
</code>```

Body:
I'm developing with c# and use the EPPLUS library to create excel sheets, specifically
I've created pie charts where I also show zero values but I would like to remove them. I have not been able to find any workaround. below the code I use:

    int chart_RegionHeaderRow = 1;
int chart_RegionHeaderColumn = 13;
firstRowCategory = 2;
lastRowCategory = 2;
firstColCategory = 3;
lastColCategory = firstColCategory + pDeployVersionSet.Length - 1;

int firstColValue = 3;
int lastColValue = firstColValue + pDeployVersionSet.Length - 1;
int firstRowSerie = 3;

int rowCR = chart_RegionHeaderRow;
int colCR = chart_RegionHeaderColumn;

int chart_RegionColStep = 6;
int chart_RegionRowStep = 16;

//Create the Region chart WW
var chartWW = (ExcelPieChart)worksheet.Drawings.AddChart("pieChartDeployWW", eChartType.Pie);
chartWW.SetSize(300, 300);
chartWW.SetPosition(rowCR, 0, colCR, 0);
chartWW.Title.Text = "WW";

chartWW.DataLabel.ShowValue = true;
chartWW.DataLabel.ShowPercent = true;
chartWW.DataLabel.ShowLeaderLines = true;
indexSerie = firstRowSerie;
chartWW.Series.Add(ExcelRange.GetAddress(indexSerie + _RegionsSet.Length,
     firstColValue,
     indexSerie + _RegionsSet.Length,
     lastColValue),
       ExcelRange.GetAddress(firstRowCategory, firstColCategory, lastRowCategory, lastColCategory

and also the resulting excel file:

enter image description here

I hope somebody can give me directions.
Thank you

Body:
Simply took the size to 0.
Not very elegant but it works.

var deletePieChart = ws.Drawings["Chart 6"] as ExcelPieChart;
deletePieChart.SetSize(0, 0);


问:
Why am I getting an error fetching messages?
there is an error calling the script. Can you ask for help?

Below I paste the code and the error.

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg = chn.fetchMessage('717369584801546273');
msg.edit(embedit);
```

<pre class="lang-js prettyprint-override"><code>TypeError: msg.edit is not a function
</code>```

答:
Is this v11?

Regardless fetching something is async, so you need to wait for msg to resolve.

https://discord.js.org/#/docs/main/11.1.0/class/TextChannel?scrollTo=fetchMessage

Here's how you can go about it:

First one is using await which needs to be inside of an async function

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg = await chn.fetchMessage('717369584801546273');
msg.edit(embedit);
```

<p>Second is <code>.then</code></p>

<pre class="lang-js prettyprint-override"><code>let chn = client.channels.find(channel => channel.id === '717019301357420554');
chn.fetchMessage('717369584801546273').then(msg => msg.edit(embedit));
</code>```

If you want to save it in a variable

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg;
chn.fetchMessage('717369584801546273').then(m => msg = m);
//note you will have to wait for the promise to resolve to use
//the variable msg correctly
//any code beyond this isn't guranteed to have access to
```

These are some bad variable names btw, you shouldn't use abbreviations like chn rather channel, and embedit => embEdit. But up to you

Body:
there is an error calling the script. Can you ask for help?

Below I paste the code and the error.

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg = chn.fetchMessage('717369584801546273');
msg.edit(embedit);

TypeError: msg.edit is not a function

Body:
Is this v11?

Regardless fetching something is async, so you need to wait for msg to resolve.

https://discord.js.org/#/docs/main/11.1.0/class/TextChannel?scrollTo=fetchMessage

Here's how you can go about it:

First one is using await which needs to be inside of an async function

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg = await chn.fetchMessage('717369584801546273');
msg.edit(embedit);

Second is .then

let chn = client.channels.find(channel => channel.id === '717019301357420554');
chn.fetchMessage('717369584801546273').then(msg => msg.edit(embedit));

If you want to save it in a variable

let chn = client.channels.find(channel => channel.id === '717019301357420554');
let msg;
chn.fetchMessage('717369584801546273').then(m => msg = m);
//note you will have to wait for the promise to resolve to use
//the variable msg correctly
//any code beyond this isn't guranteed to have access to

These are some bad variable names btw, you shouldn't use abbreviations like chn rather channel, and embedit => embEdit. But up to you


问:
Typescript - type of output to depend on type of input
I have a function that checks validity of input fields.

```<code>export const getInputValidity = (inputData:DeepReadonly<InputData> , val:string) => {
    const {length} = val
    if (inputData.type==="select"){
        return val.length<5
    }
    if (inputData.type==="email"){
        return {
            validEdit: !length || isExp(val, /^[a-zA-Z0-9!#$%&'*+-/=?^_`{|}~."(),:;<>@[\]]+$/),
            validFinal: length && isExp(val, COMMON_REGEX.email)
        }
    }
}
</code>```

I want the output to depend on the input

```<code>const validity = getInputValidity(EMAIL_INPUT_DATA, emailVal )
</code>```

So if EMAIL_INPUT_DATA.type==="email" I'd like the type of validity will be

```<code>{
   validEdit: boolean
   validFinal: boolean
}
</code>```

Is it possible? Currently validity is typed as

```<code>const validity: true | {
    readonly validEdit: boolean;
    readonly validFinal: boolean | 0;
    readonly validLength?: undefined;
    readonly validChars?: undefined;
} | {
    readonly validLength: boolean;
    readonly validChars: boolean;
    readonly validEdit?: undefined;
    readonly validFinal?: undefined;
}
</code>```

I understand that this could be done by typing getInputValidity as a function, but could it be inferred from implementation?

答:
You can use function overloads to do this:

const isExp = (s: String, r: RegExp) => true;

interface IValidityReturn {
  validEdit: boolean;
  validFinal: boolean;
}

function getInputValidity(inputData: { type: 'select' }, val: string): boolean;
function getInputValidity(inputData: { type: 'select' }, val: string): boolean;
function getInputValidity(inputData: { type: 'select' | 'email' }, val: string): boolean | IValidityReturn {
    const { length } = val

    if (inputData.type==="select"){
        return val.length<5
    }

    if (inputData.type==="email"){
        return {
            validEdit: !length || isExp(val, /^[a-zA-Z0-9!#$%&'*+-/=?^_`{|}~."(),:;<>@[\]]+$/),
            validFinal: !!length && isExp(val, /a/g),
        }
    }

    // only to make example work:
    return {
      validEdit: false,
      validFinal: false,
    }
}
```

Some of these parts are pieced together for the purpose of the example, but it seems as though this should solve the problem.

Body:
I have a function that checks validity of input fields.

export const getInputValidity = (inputData:DeepReadonly<InputData> , val:string) => {
    const {length} = val
    if (inputData.type==="select"){
        return val.length<5
    }
    if (inputData.type==="email"){
        return {
            validEdit: !length || isExp(val, /^[a-zA-Z0-9!#$%&'*+-/=?^_`{|}~."(),:;<>@[\]]+$/),
            validFinal: length && isExp(val, COMMON_REGEX.email)
        }
    }
}

I want the output to depend on the input

const validity = getInputValidity(EMAIL_INPUT_DATA, emailVal )

So if EMAIL_INPUT_DATA.type==="email" I'd like the type of validity will be

{
   validEdit: boolean
   validFinal: boolean
}

Is it possible? Currently validity is typed as

const validity: true | {
    readonly validEdit: boolean;
    readonly validFinal: boolean | 0;
    readonly validLength?: undefined;
    readonly validChars?: undefined;
} | {
    readonly validLength: boolean;
    readonly validChars: boolean;
    readonly validEdit?: undefined;
    readonly validFinal?: undefined;
}

I understand that this could be done by typing getInputValidity as a function, but could it be inferred from implementation?

Body:
You can use function overloads to do this:

const isExp = (s: String, r: RegExp) => true;

interface IValidityReturn {
  validEdit: boolean;
  validFinal: boolean;
}

function getInputValidity(inputData: { type: 'select' }, val: string): boolean;
function getInputValidity(inputData: { type: 'select' }, val: string): boolean;
function getInputValidity(inputData: { type: 'select' | 'email' }, val: string): boolean | IValidityReturn {
    const { length } = val

    if (inputData.type==="select"){
        return val.length<5
    }

    if (inputData.type==="email"){
        return {
            validEdit: !length || isExp(val, /^[a-zA-Z0-9!#$%&'*+-/=?^_`{|}~."(),:;<>@[\]]+$/),
            validFinal: !!length && isExp(val, /a/g),
        }
    }

    // only to make example work:
    return {
      validEdit: false,
      validFinal: false,
    }
}

Some of these parts are pieced together for the purpose of the example, but it seems as though this should solve the problem.


问:
ValueError: Cannot use 'filtered_detections/map/while/strided_slice_1' as input to 'filtered_detections/map/while/ones/packed'
Training on custom dataset by using Keras retinanet (https://github.com/fizyr/keras-retinanet). while running the retinanet-train command , i got the following error

```<code> File "c:\users\samjith.cp\anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_util.py", line 350, in CheckInputFromValidContext
raise ValueError(error_msg + " See info log for more details.")
ValueError: Cannot use 'filtered_detections/map/while/strided_slice_1' as
input to 'filtered_detections/map/while/ones/packed'
because 'filtered_detections/map/while/strided_slice_1' is in a while loop.
See info log for more details.
</code>```

how to solve this error?

答:
According to here:

you can use tensorflow 1.14, keras 2.2.5 and keras-retinanet 0.5.1..

I can confirm that it fixes the problem.

Body:
Training on custom dataset by using Keras retinanet (https://github.com/fizyr/keras-retinanet). while running the retinanet-train command , i got the following error

 File "c:\users\samjith.cp\anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_util.py", line 350, in CheckInputFromValidContext
raise ValueError(error_msg + " See info log for more details.")
ValueError: Cannot use 'filtered_detections/map/while/strided_slice_1' as
input to 'filtered_detections/map/while/ones/packed'
because 'filtered_detections/map/while/strided_slice_1' is in a while loop.
See info log for more details.

how to solve this error?


问:
Changing an AWS RDS MySQL instance to Postgres
What is the best way to go about this? I have a mobile app a project team developed whereby they setup the database as a MySQL instance. However, with this new project I have with my own developers, we believe Postgres would better suit or needs - but I want everything on one DB instance (data between the mobile app and the new project will be shared). What is the best way to accomplish this?</p>

答:
You will need to create a new RDS instance to switch the engine type to Postgres.

Whilst transitioning you will need to have both running, to migrate the DB across you will want to keep the data synchronised between both. Luckily AWS has the database migration service.

You should try to migrate your existing application to use this first, then remove the DMS setup and shutdown the MySQL database.


问:
Python 3 memory error for large loop with large sparse matrix
I am working with a code that involves the creating of a large relatively sparse matrix and the solution of a least squares minimization problem using it. However, I have been getting memory errors when I run my code, despite the fact that it seems that the matrix should not be large enough to strain my system (27000 by 2100 roughly, in my test cases)

I have created a simplified code that has the same storage requirements as my test case and also generates a memory error (note that the "sparse" matrix is not actually very sparse as I am testing with a smaller scale problem than what the actual intended dataset will entail):

```<code>import numpy as np
from scipy import sparse

BM = sparse.lil_matrix((27000, 3000))
for i in range(0, 3000):
    local_mat = np.random.rand(30,30,30)
    local_mat[local_mat<0.1] = 0
    vals = local_mat.ravel()
    nonzero = vals.nonzero()
    BM[nonzero, i] = vals[nonzero]
</code>```

If I change the parameters such that there are more zero entries in the sparse matrix, I will still get a memory error from scipy.sparse.linalg.lsq_linear after filling the rows of the matrix and performing a minimization problem with it

It goes without saying that I get a memory error if I use a dense matrix as well.

I have tried to increase the size of my paging file to 2-4 gigabytes but that hasn't helped, though it seems like this should not be that memory intensive regardless

答:
You've created a memory bonfire. Let's recall how a lil_matrix works:

Each row of the matrix is kept as a python list. There is one list for data and another list for index. Each non-zero element has one entry on each list.

Taking your example 27000, 3000 matrix, let's add this up. Each entry in a python list is an object which burns 16 bytes for overhead. For the data list, the float data itself is another 8 bytes. So just the non-zero values eats up 2GB. Now let's look at the indices - another set of lists each entry of which burns 16 bytes for overhead. Poof - there's another 1.5 GB gone. Bit more memory for the lists and the array that holds them, but that's not much compared to what's already gone down.

Compared to a 27000, 3000 dense array, which eats up 650MB of memory, you've managed to use an extra 5x as much memory, while also acquiring several major disadvantages compared to a numpy array. A standard sparse format like CSR would be a much better choice - that would use just about 900MB of memory for your 90% dense example.

EDIT: Also you're trying to call a function which absolutely requires a CSR matrix, so that function is casting the horrible lil_matrix you've created into a csr_matrix, forcing you to keep two full copies of this data in-memory.

Body:
I am working with a code that involves the creating of a large relatively sparse matrix and the solution of a least squares minimization problem using it. However, I have been getting memory errors when I run my code, despite the fact that it seems that the matrix should not be large enough to strain my system (27000 by 2100 roughly, in my test cases)

I have created a simplified code that has the same storage requirements as my test case and also generates a memory error (note that the "sparse" matrix is not actually very sparse as I am testing with a smaller scale problem than what the actual intended dataset will entail):

import numpy as np
from scipy import sparse

BM = sparse.lil_matrix((27000, 3000))
for i in range(0, 3000):
    local_mat = np.random.rand(30,30,30)
    local_mat[local_mat<0.1] = 0
    vals = local_mat.ravel()
    nonzero = vals.nonzero()
    BM[nonzero, i] = vals[nonzero]

If I change the parameters such that there are more zero entries in the sparse matrix, I will still get a memory error from scipy.sparse.linalg.lsq_linear after filling the rows of the matrix and performing a minimization problem with it

It goes without saying that I get a memory error if I use a dense matrix as well.

I have tried to increase the size of my paging file to 2-4 gigabytes but that hasn't helped, though it seems like this should not be that memory intensive regardless


问:
ImportError no module named 'playsound'
I did

```<code>pip install playsound
Downloading/unpacking playsound
  Downloading playsound-1.2.2-py2.py3-none-any.whl
Installing collected packages: playsound
Successfully installed playsound
Cleaning up...
</code>```

and it installed playsound (at least is said so), but when i type

```<code>python3
Python 3.4.2 (default, Sep 16 2019, 19:58:00)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import playsound
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'playsound'

</code>```

there is no module?
Why does this happen?
Oh, I just found out there is no problem when i try to import this when i use python2. There must be a problem with python3 and playsound? How do i import it with python3?

答:
most probably you have both python2 and python3 installed with their package managers, so pip refers to the package manager for python2
instead use

```<code>pip3 install playsound
</code>```

and it should work fine.

Title: ImportError no module named 'playsound'

Body:
I did

pip install playsound
Downloading/unpacking playsound
  Downloading playsound-1.2.2-py2.py3-none-any.whl
Installing collected packages: playsound
Successfully installed playsound
Cleaning up...

and it installed playsound (at least is said so), but when i type

python3
Python 3.4.2 (default, Sep 16 2019, 19:58:00)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import playsound
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'playsound'

there is no module?
Why does this happen?
Oh, I just found out there is no problem when i try to import this when i use python2. There must be a problem with python3 and playsound? How do i import it with python3?

Body:
most probably you have both python2 and python3 installed with their package managers, so pip refers to the package manager for python2
instead use

pip3 install playsound

and it should work fine.


问:
how to catch a return value from a ssh task ant
I have defined a macro in ANT that checks if a dir exists on a remote linux box:

```<code><macrodef name="checkIfDirExists">
    <attribute name="host" />
    <attribute name="username" />
    <attribute name="password" />
    <attribute name="dir" />
    <sequential>
        <runcommand executable="[ -d @{dir} ]" host="@{host}" username="@{username}" password="@{password}"/>
    </sequential>
</macrodef>
</code>```

runcommand is just a wrapper macro for sshexec task that validates some additional stuff, but basically it's just an sshexec.

Right now, if i run this, it works in a way that if the directory exists the build go on but if it doesn't exist the build fails since [ -d @{dir} ] return value is 1.

I want to be able to check the return value so i can put it in a conditional tag, for example if the dir exists, skip, and if it doesn't create it with mkdir.

Is this possible ?

答:
This is a total stab in the dark, I don't know if ant will let you do this. However if it's invoking bash on the remote host, it should work.

```<code><macrodef name="checkIfDirExists">
    <attribute name="host" />
    <attribute name="username" />
    <attribute name="password" />
    <attribute name="dir" />
    <sequential>
        <runcommand executable="[ -d @{dir} ] || mkdir @{dir}" host="@{host}" username="@{username}" password="@{password}"/>
    </sequential>
</macrodef>
</code>```

This way if the directory exists it will short circuit and return success. If it doesn't exist, it will call mkdir. If mkdir fails, then ant will fail.

Body:
I have defined a macro in ANT that checks if a dir exists on a remote linux box:

<macrodef name="checkIfDirExists">
    <attribute name="host" />
    <attribute name="username" />
    <attribute name="password" />
    <attribute name="dir" />
    <sequential>
        <runcommand executable="[ -d @{dir} ]" host="@{host}" username="@{username}" password="@{password}"/>
    </sequential>
</macrodef>

runcommand is just a wrapper macro for sshexec task that validates some additional stuff, but basically it's just an sshexec.

Right now, if i run this, it works in a way that if the directory exists the build go on but if it doesn't exist the build fails since [ -d @{dir} ] return value is 1.

I want to be able to check the return value so i can put it in a conditional tag, for example if the dir exists, skip, and if it doesn't create it with mkdir.

Is this possible ?

Body:
This is a total stab in the dark, I don't know if ant will let you do this. However if it's invoking bash on the remote host, it should work.

<macrodef name="checkIfDirExists">
    <attribute name="host" />
    <attribute name="username" />
    <attribute name="password" />
    <attribute name="dir" />
    <sequential>
        <runcommand executable="[ -d @{dir} ] || mkdir @{dir}" host="@{host}" username="@{username}" password="@{password}"/>
    </sequential>
</macrodef>

This way if the directory exists it will short circuit and return success. If it doesn't exist, it will call mkdir. If mkdir fails, then ant will fail.


问:
Can I schedule a mail delivery without using GAS trigger?
Gmail has the option to schedule mailings from the application.

Is this option implemented in GmailApp.sendEmail()?

I don't want to use Google Apps Script triggers, I want to use the option given by the GmailApp

答:
Is this option implemented in GmailApp.sendEmail()?

ATTOW, no, please see the official documentation

Bonus: can I schedule this using Gmail API?

ATTOW, also no, see the documentation

Workaround

I understand that you don't want to use triggers, but until the feature is implemented, you can emulate scheduling logic using a trigger and PropertiesService (or a database of your choosing if you need to store larger emails). Here is a working sample of how you may achieve this (I opted to use a 1 minute trigger, but in real world it might be more pragmatic to use a higher delay between checks):

```<code>
const sendScheduledEmail = () => {
    const propertyName = "emailSchedule";

    const store = PropertiesService.getUserProperties();

    const savedSchedule = store.getProperty(propertyName) || "[]";

    /** @type {emailConfig[]} */
    const parsed = JSON.parse(savedSchedule);

    if(!parsed.length) {
        console.log("Nothing to send");
        return;
    }

    const currentDT = Date.now();

    const leftToSend = parsed.filter(emailConfig => {

        const {
            delay,
            subject,
            recipient,
            body,
            options
        } = emailConfig;

        if (currentDT > delay) {
            GmailApp.sendEmail(recipient, subject, body, options);
            return false;
        }

        return true;
    });

    store.setProperty(propertyName, JSON.stringify(leftToSend));
};

/**
 * @typedef {object} delayedConfig
 * @property {number} delay
 *
 * @typedef {object} commonEmailConfig
 * @property {string} body
 * @property {string} recipient
 * @property {string} subject
 * @property {GoogleAppsScript.Gmail.GmailAdvancedOptions} options
 *
 * @typedef {commonEmailConfig & delayedConfig} emailConfig
 *
 * @param {...emailConfig} configs
 * @returns {boolean}
 */
const scheduleEmailSend = (...configs) => {

    try {

        const now = Date.now();

        const normalizedDelayConfigs = configs.map(config => {
            const { delay } = config;
            config.delay = now + delay;
            return config;
        });

        const checkTriggerName = "sendScheduledEmail", propertyName = "emailSchedule";

        const triggers = ScriptApp.getProjectTriggers();

        const [trigger] = triggers.filter(trig => trig.getHandlerFunction() === checkTriggerName);

        !trigger && ScriptApp.newTrigger(checkTriggerName).timeBased().everyMinutes(1).create();

        const store = PropertiesService.getUserProperties();

        const savedSchedule = store.getProperty(propertyName) || "[]";

        /** @type {emailConfig[]} */
        const parsed = JSON.parse(savedSchedule);

        parsed.push(...normalizedDelayConfigs);

        store.setProperty(propertyName, JSON.stringify(parsed));

    } catch (error) {
        console.warn(error);
        return false;
    }

    return true;
};
</code>```

Google is already aware of the feature, please join others on the already opened request - it will have a better chance of being introduced.

Body:
Is this option implemented in GmailApp.sendEmail()?

ATTOW, no, please see the official documentation

Bonus: can I schedule this using Gmail API?

ATTOW, also no, see the documentation

Workaround

I understand that you don't want to use triggers, but until the feature is implemented, you can emulate scheduling logic using a trigger and PropertiesService (or a database of your choosing if you need to store larger emails). Here is a working sample of how you may achieve this (I opted to use a 1 minute trigger, but in real world it might be more pragmatic to use a higher delay between checks):

const sendScheduledEmail = () => {
    const propertyName = "emailSchedule";

    const store = PropertiesService.getUserProperties();

    const savedSchedule = store.getProperty(propertyName) || "[]";

    /** @type {emailConfig[]} */
    const parsed = JSON.parse(savedSchedule);

    if(!parsed.length) {
        console.log("Nothing to send");
        return;
    }

    const currentDT = Date.now();

    const leftToSend = parsed.filter(emailConfig => {

        const {
            delay,
            subject,
            recipient,
            body,
            options
        } = emailConfig;

        if (currentDT > delay) {
            GmailApp.sendEmail(recipient, subject, body, options);
            return false;
        }

        return true;
    });

    store.setProperty(propertyName, JSON.stringify(leftToSend));
};

/**
 * @typedef {object} delayedConfig
 * @property {number} delay
 *
 * @typedef {object} commonEmailConfig
 * @property {string} body
 * @property {string} recipient
 * @property {string} subject
 * @property {GoogleAppsScript.Gmail.GmailAdvancedOptions} options
 *
 * @typedef {commonEmailConfig & delayedConfig} emailConfig
 *
 * @param {...emailConfig} configs
 * @returns {boolean}
 */
const scheduleEmailSend = (...configs) => {

    try {

        const now = Date.now();

        const normalizedDelayConfigs = configs.map(config => {
            const { delay } = config;
            config.delay = now + delay;
            return config;
        });

        const checkTriggerName = "sendScheduledEmail", propertyName = "emailSchedule";

        const triggers = ScriptApp.getProjectTriggers();

        const [trigger] = triggers.filter(trig => trig.getHandlerFunction() === checkTriggerName);

        !trigger && ScriptApp.newTrigger(checkTriggerName).timeBased().everyMinutes(1).create();

        const store = PropertiesService.getUserProperties();

        const savedSchedule = store.getProperty(propertyName) || "[]";

        /** @type {emailConfig[]} */
        const parsed = JSON.parse(savedSchedule);

        parsed.push(...normalizedDelayConfigs);

        store.setProperty(propertyName, JSON.stringify(parsed));

    } catch (error) {
        console.warn(error);
        return false;
    }

    return true;
};

Google is already aware of the feature, please join others on the already opened request - it will have a better chance of being introduced.


问:
How to get names of enum entries?
I would like to iterate a TypeScript enum object and get each enumerated symbol name, for example:
enum myEnum { entry1, entry2 }</p>
```<code>for (var entry in myEnum) {
    // use entry's name here, e.g., "entry1"
}
</code>```

答:
There are already a lot of answers here but I figure I'll throw my solution onto the stack anyway.

TypeScript Playground

```<code>enum AccountType {
  Google = 'goo',
  Facebook = 'boo',
  Twitter = 'wit',
}

type Key = keyof typeof AccountType // "Google" | "Facebook" | "Twitter"

// this creates a POJO of the enum "reversed" using TypeScript's Record utility
const reversed = (Object.keys(AccountType) as Key[]).reduce((acc, key) => {
  acc[AccountType[key]] = key
  return acc
}, {} as Record<AccountType, string>)
</code>```

For Clarity:

```<code>/*
 * reversed == {
 *   "goo": "Google",
 *   "boo": "Facebook",
 *   "wit": "Twitter",
 * }
 * reversed[AccountType.Google] === "Google"
 */
</code>```

Reference for TypeScript Record

To iterate:

```<code>for (const [key, value] of Object.entries(reversed)) {
  console.log(`${key}: ${value}`);
}
</code>```

A nice helper function:

```<code>const getAccountTypeName = (type: AccountType) => {
  return reversed[type]
};

// getAccountTypeName(AccountType.Twitter) === 'Twitter'
</code>```

Title: How to get names of enum entries?

Body:
I would like to iterate a TypeScript enum object and get each enumerated symbol name, for example:
enum myEnum { entry1, entry2 }

for (var entry in myEnum) {
    // use entry's name here, e.g., "entry1"
}

Body:
There are already a lot of answers here but I figure I'll throw my solution onto the stack anyway.

<a href="https://www.typescriptlang.org/play/#code/KYOwrgtgBAggxnA9mEAXAKgTwA7CgbwFgAoKKAcUUQHMAbPAXigHJqrmAaEsgGUTgCGtKE2aDanblABiAuMABGVANYiWSxJNJR0AdwCWqVMABOa5gdRbe+kMuAATAJIhzt5cxIBfEqhx4AaWBMNXtMRAAzKD9cSNgEZDQsXCgAelSoIJCmACJKGnocqAAfKBy+cSLSnNl5DWUqsr1DYxNG8vdHFxySJBAAZ1QobAF9E0c1AAoAeQUAK2A4VAA6MP7J+CQUDH8ASigBfszggG0AXV3l8YcweUnJuTgOKDD9hgA+AilHk83EndwJzCZzOoWCUnGqDAJlcj28z3wXgORwASotECYHAAeP7bZLAZ6DEy2ajvXYkCnEPqDKDUYCoXFJfwAOQEEEYUEmMWAAC54lsmbg3p8iNpIdDXCMxo4Ttyzt4ANyU3qIAaIejLWg0SZ0hkJPEstnADb6wXAZa1RQqXa7IA" rel="noreferrer">TypeScript Playground

enum AccountType {
  Google = 'goo',
  Facebook = 'boo',
  Twitter = 'wit',
}

type Key = keyof typeof AccountType // "Google" | "Facebook" | "Twitter"

// this creates a POJO of the enum "reversed" using TypeScript's Record utility
const reversed = (Object.keys(AccountType) as Key[]).reduce((acc, key) => {
  acc[AccountType[key]] = key
  return acc
}, {} as Record<AccountType, string>)

For Clarity:

/*
 * reversed == {
 *   "goo": "Google",
 *   "boo": "Facebook",
 *   "wit": "Twitter",
 * }
 * reversed[AccountType.Google] === "Google"
 */

Reference for TypeScript Record

To iterate:

for (const [key, value] of Object.entries(reversed)) {
  console.log(`${key}: ${value}`);
}

A nice helper function:

const getAccountTypeName = (type: AccountType) => {
  return reversed[type]
};

// getAccountTypeName(AccountType.Twitter) === 'Twitter'


问:
Installing OSMnx with Anaconda
I am trying to install the osmnx package in Python 3 on my computer, following the steps outlined here https://geoffboeing.com/2017/02/python-getting-started/. The steps are:

Download miniconda, with the path C:\Anaconda. I am unable to do this as I am using university computers. However, Anaconda is already installed on those computers, with the path C:\Program Files \Anaconda3.

Within the Anaconda Prompt, I tried conda update -n base conda. However, this does not go through because I do not 'have write permission to the target environment' (C:\Program Files \Anaconda3).

I ignored this error, assuming conda was up to date. conda config --prepend channels conda-forge ran fine.

conda create -n ox -c conda-forge osmnx jupyterlab and conda activate ox ran fine. OSMnx and jupyterlab are listed in Anaconda Navigator>Environments>ox>installed.

In the ox environment, I ran jupyter lab, but this gave the following error. I'm sorry for this huge quote, but I don't know how to interpret any of this:

```<code>(ox) C:\Users\bm17652>jupyter lab
[I 15:47:48.265 LabApp] Writing notebook server cookie secret to C:\Users\bm17652\AppData\Roaming\jupyter\runtime\notebook_cookie_secret
Traceback (most recent call last):
  File "C:\Users\bm17652\.conda\envs\ox\Scripts\jupyter-lab-script.py", line 9, in <module>
    sys.exit(main())
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\jupyter_core\application.py", line 268, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\traitlets\config\application.py", line 663, in launch_instance
    app.initialize(argv)
  File "<C:\Users\bm17652\.conda\envs\ox\lib\site-packages\decorator.py:decorator-gen-7>", line 2, in initialize
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\traitlets\config\application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\notebook\notebookapp.py", line 1679, in initialize
    self.init_webapp()
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\jupyterlab\labapp.py", line 404, in init_webapp
    super().init_webapp(*args, **kwargs)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\notebook\notebookapp.py", line 1442, in init_webapp
    self.http_server.listen(port, self.ip)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\tcpserver.py", line 152, in listen
    self.add_sockets(sockets)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
    self._handlers[sock.fileno()] = add_accept_handler(
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\platform\asyncio.py", line 99, in add_handler
    self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
  File "C:\Users\bm17652\.conda\envs\ox\lib\asyncio\events.py", line 501, in add_reader
    raise NotImplementedError
NotImplementedError
</code>```

When I try to open Jupyter Lab from Anaconda Navigator and run import osmnx as ox, I get the error "No module named 'osmnx'".

To me, it seems like Jupyter Lab is not installed properly, or does not have the proper connections with osmnx.
Are these errors occurring because:

I haven't updated conda?

I am running the code from a different directory (C:\Users\bm17652) than where Anaconda is (C:\Program Files \Anaconda3)?

Should I download Anaconda to another path?

答:
I ran into a similar problem. The solution is to create a new full environment specified for OSMnx. This can be done using

```<code>conda config --prepend channels conda-forge
conda create -n ox --strict-channel-priority osmnx
</code>```

you then have to activate that environment using:

```<code>(base) C:\Users\User>conda activate ox
</code>```

after which you can run:

```<code>(ox) C:\Users\User>python
>>> import osmnx as ox
>>>
</code>```

to test for successful installation

Title: Installing OSMnx with Anaconda

Body:
I am trying to install the osmnx package in Python 3 on my computer, following the steps outlined here https://geoffboeing.com/2017/02/python-getting-started/. The steps are:

Download miniconda, with the path C:\Anaconda. I am unable to do this as I am using university computers. However, Anaconda is already installed on those computers, with the path C:\Program Files \Anaconda3.

Within the Anaconda Prompt, I tried conda update -n base conda. However, this does not go through because I do not 'have write permission to the target environment' (C:\Program Files \Anaconda3).

I ignored this error, assuming conda was up to date. conda config --prepend channels conda-forge ran fine.

conda create -n ox -c conda-forge osmnx jupyterlab and conda activate ox ran fine. OSMnx and jupyterlab are listed in Anaconda Navigator>Environments>ox>installed.

In the ox environment, I ran jupyter lab, but this gave the following error. I'm sorry for this huge quote, but I don't know how to interpret any of this:

(ox) C:\Users\bm17652>jupyter lab
[I 15:47:48.265 LabApp] Writing notebook server cookie secret to C:\Users\bm17652\AppData\Roaming\jupyter\runtime\notebook_cookie_secret
Traceback (most recent call last):
  File "C:\Users\bm17652\.conda\envs\ox\Scripts\jupyter-lab-script.py", line 9, in <module>
    sys.exit(main())
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\jupyter_core\application.py", line 268, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\traitlets\config\application.py", line 663, in launch_instance
    app.initialize(argv)
  File "<C:\Users\bm17652\.conda\envs\ox\lib\site-packages\decorator.py:decorator-gen-7>", line 2, in initialize
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\traitlets\config\application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\notebook\notebookapp.py", line 1679, in initialize
    self.init_webapp()
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\jupyterlab\labapp.py", line 404, in init_webapp
    super().init_webapp(*args, **kwargs)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\notebook\notebookapp.py", line 1442, in init_webapp
    self.http_server.listen(port, self.ip)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\tcpserver.py", line 152, in listen
    self.add_sockets(sockets)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
    self._handlers[sock.fileno()] = add_accept_handler(
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
  File "C:\Users\bm17652\.conda\envs\ox\lib\site-packages\tornado\platform\asyncio.py", line 99, in add_handler
    self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
  File "C:\Users\bm17652\.conda\envs\ox\lib\asyncio\events.py", line 501, in add_reader
    raise NotImplementedError
NotImplementedError

When I try to open Jupyter Lab from Anaconda Navigator and run import osmnx as ox, I get the error "No module named 'osmnx'".

To me, it seems like Jupyter Lab is not installed properly, or does not have the proper connections with osmnx.
Are these errors occurring because:

I haven't updated conda?

I am running the code from a different directory (C:\Users\bm17652) than where Anaconda is (C:\Program Files \Anaconda3)?

Should I download Anaconda to another path?

Body:
I ran into a similar problem. The solution is to create a new full environment specified for OSMnx. This can be done using

conda config --prepend channels conda-forge
conda create -n ox --strict-channel-priority osmnx

you then have to activate that environment using:

(base) C:\Users\User>conda activate ox

after which you can run:

(ox) C:\Users\User>python
>>> import osmnx as ox
>>>

to test for successful installation


问:
Ionic 4, Android Studio, Gradle, Java jdk or Cordova error
I am trying to test if the qr-scanner for my Ionic 4 app is working so I need to test my application on an android device (tablet).
I used the command: ionic cordova run android in my Visual Studio Code command prompt but I keep getting errors. My latest error is:

cordova.cmd run android
  Checking Java JDK and Android SDK versions
  ANDROID_SDK_ROOT=undefined (recommended setting)
  ANDROID_HOME=C:\Users\Me\AppData\Local\Android\Sdk (DEPRECATED)
  Could not find an installed version of Gradle either in Android Studio,
  or on your system to install the gradle wrapper. Please include gradle
  in your path, or install Android Studio
  [ERROR] An error occurred while running subprocess cordova.
  cordova.cmd run android exited with exit code 1.
  Re-running this command with the --verbose flag may provide more information.

I have downloaded/installed and configured Android Studio, Java jdk, Gradle and Cordova as all the solutions I have tried suggests but I keep getting more errors as I progress. Even after setting the user environmental variable ANDROID_HOME and system environmental variable PATH and restarting my computer.

答:
Your problem is most likely that you are not running your Visual Studio Code as Admin.
So it cannot access the displayed paths.

Regards,
Markus


问:
Retaining control after telling Preview to close a window
I have hundreds of images in a directory structure, and sometimes I want to look at them one by one in order to find the one I'm thinking of.

I'd like to bring each one up, and then if it's not the one I want, close it and look at the next one, with either a single mouse click or  a one-letter command in a terminal window.  Is it possible to open a file and retain control after doing an applescript tell to Preview to close the frontmost window.  When I try this,  Preview stays active, my script pauses, and I need to cmd-tab back to the iTerm window to have it continue. I've tried setting a timeout in applescript before I do the 'tell' to Preview, but that didn't work.   Is there a way around this?  Here's my current ruby script:

```<code>#!/usr/bin/env ruby

require 'find'

def osascript(script)
  system 'osascript', *script.split(/\n/).map { |line| ['-e', line] }.flatten
end

file_paths = []

Find.find('.') do |path|
  file_paths << path if path =~ /.*\.png$/
end

file_paths.each do |f|

  system "open '#{f}'"

  decision = gets.chomp

  if decision.eql? "s" then
    exit
  end

  osascript <<-END
  tell application "Preview"
  close window 1
  end tell
  END

end
</code>```

答:
Why are you not just using standard Finder feature? Open the folder with the Finder, select the 1st file and type space bar to have a quick view. then just use up and down arrow keys to display next/previous images from that folder. Quicker and built-in.

An other way is to select, in the Finder window, a view per thumbnail. You can adjust the  size at bottom right of the window. Images are smaller, but you can see more of them at same time on your screen.

Body:
I have hundreds of images in a directory structure, and sometimes I want to look at them one by one in order to find the one I'm thinking of.

I'd like to bring each one up, and then if it's not the one I want, close it and look at the next one, with either a single mouse click or  a one-letter command in a terminal window.  Is it possible to open a file and retain control after doing an applescript tell to Preview to close the frontmost window.  When I try this,  Preview stays active, my script pauses, and I need to cmd-tab back to the iTerm window to have it continue. I've tried setting a timeout in applescript before I do the 'tell' to Preview, but that didn't work.   Is there a way around this?  Here's my current ruby script:

#!/usr/bin/env ruby

require 'find'

def osascript(script)
  system 'osascript', *script.split(/\n/).map { |line| ['-e', line] }.flatten
end

file_paths = []

Find.find('.') do |path|
  file_paths << path if path =~ /.*\.png$/
end

file_paths.each do |f|

  system "open '#{f}'"

  decision = gets.chomp

  if decision.eql? "s" then
    exit
  end

  osascript <<-END
  tell application "Preview"
  close window 1
  end tell
  END

end