问:
Font-awesome icons not loading on Angular4 project
I'm working on an angular 4 project using font-awesome, i followed this guide to install the library with npm:
How to add font-awesome to Angular 2 + CLI project

i've configured the project to compile the scss stylesheets with the ng-serve command, my styles paths of the angular-cli.json looks like this:

```<code>"styles": [
        "../node_modules/bootstrap/scss/bootstrap.scss",
        "../node_modules/bootstrap/scss/main.scss",
        "../node_modules/font-awesome/scss/font-awesome.scss"

      ],
</code>```

i want to make a button with an address card icon on it, i'm also working with Bootstrap 4, so it looks like this:

```<code><button class="btn btn-sm btn-primary"><span class="fas fa-address-card"></span></button>
</code>```

but when it loads, it looks like this:

答:
You should be using the class fa instead of fas. The fa class sets the font-face. (hat tip to @mike-hill)

View source on
http://fontawesome.io/icon/address-card/

Body:
I'm working on an angular 4 project using font-awesome, i followed this guide to install the library with npm:
How to add font-awesome to Angular 2 + CLI project

i've configured the project to compile the scss stylesheets with the ng-serve command, my styles paths of the angular-cli.json looks like this:

"styles": [
        "../node_modules/bootstrap/scss/bootstrap.scss",
        "../node_modules/bootstrap/scss/main.scss",
        "../node_modules/font-awesome/scss/font-awesome.scss"

      ],

i want to make a button with an address card icon on it, i'm also working with Bootstrap 4, so it looks like this:

<button class="btn btn-sm btn-primary"></button>

but when it loads, it looks like this:


来源: stackexchange

问:
How to run Kotlin Koans in IntelliJ? What is the "Main class"?
I have downloaded Kotlin Koans from Github, installed IntelliJ IDEA 2016.1.3 and opened the Koans project. As I understand I need a Configuration to run the examples. This Configuration needs a Main class. I cannot figure out where I find the main class in the Kotlin Koans. I have searched for one but found none (except for a special one in htmlDemo.kt).

I see that some kind of unit test framework is used. It probably somehow calls task0 but the IDE shows no references to task0 except one from todoTask0. The only reference to todoTask0 is in task0. So we have circular references but nowhere do I find an external reference to call up one of these functions.

Can someone explain to me how to get the Kotlin Koans running in the IntelliJ IDE?

答:
In my case, it is the zsh's bug, can be solved in following:

add setopt no_nomatch in the end of file  ~/.zshrc;

then run source /.zshrc

ContentLicense: CC BY-SA 3.0


问:
How to overwrite files added using SparkContext.addFile?
I am trying to use sc.addFile to add a file to all worker nodes. However, I found it could not overwrite the same file. Is there any way to overwrite a file through sc.addFile?</p>

答:
It is configured with spark.files.overwrite:

Whether to overwrite files added through SparkContext.addFile() when the target file exists and its contents do not match those of the source.

So just set it to true in your config

```<code>spark.files.overwrite   true
</code>```

or session

```<code>spark = SparkSession.builder.conf("spark.files.overwrite", "true").getOrCreate()
sc  = spark.sparkContext
</code>```

or SparkConf

```<code>conf = SparkConf().set("spark.files.overwrite", "true")
sc = SparkContext(conf=conf)
</code>```

Body:
It is configured with spark.files.overwrite:

Whether to overwrite files added through SparkContext.addFile() when the target file exists and its contents do not match those of the source.

So just set it to true in your config

spark.files.overwrite   true

or session

spark = SparkSession.builder.conf("spark.files.overwrite", "true").getOrCreate()
sc  = spark.sparkContext

or SparkConf

conf = SparkConf().set("spark.files.overwrite", "true")
sc = SparkContext(conf=conf)


问:
Facebook API - Batch upload photos
I'm trying to batch upload photos and I keep getting a response back from Postman saying "Batch parameter must be a JSON Array"  Does anyone see what is wrong with this because it looks like valid json to me.  I've been rattling with this for a few hours making minor tweaks trying to get it to upload to no avail.  I also have tried encoding the url.</p>

```<code>https://graph.facebook.com/v2.11?batch=[{"method":"POST", "relative_url":"https://graph.facebook.com/v2.11/{pageid}/photos?access_token={access-token}", "body":"link_url":"https://{link-to-image}/wmphotos/999995/6d5cc4169bbf4e7dbe31f3739e025412/a572c29dff_640.jpg"}]&access_token={access-token}
</code>```

答:
Looking at your code, it seems that the JSON object in your batch array is actually malformed. body:link_url:link should be body: {link_url:link}

Bad:

```<code>[
    {
        "method":"POST",
        "relative_url":"foo",
        "body":"link_url":"link"
    }
]
</code>```

Good:

```<code>[
    {
        "method":"POST",
        "relative_url":"foo",
        "body":{"link_url":"link"}
   }
]
</code>```

Title: Facebook API - Batch upload photos

Body:
I'm trying to batch upload photos and I keep getting a response back from Postman saying "Batch parameter must be a JSON Array"  Does anyone see what is wrong with this because it looks like valid json to me.  I've been rattling with this for a few hours making minor tweaks trying to get it to upload to no avail.  I also have tried encoding the url.

https://graph.facebook.com/v2.11?batch=[{"method":"POST", "relative_url":"https://graph.facebook.com/v2.11/{pageid}/photos?access_token={access-token}", "body":"link_url":"https://{link-to-image}/wmphotos/999995/6d5cc4169bbf4e7dbe31f3739e025412/a572c29dff_640.jpg"}]&access_token={access-token}

Body:
Looking at your code, it seems that the JSON object in your batch array is actually malformed. body:link_url:link should be body: {link_url:link}

Bad:

[
    {
        "method":"POST",
        "relative_url":"foo",
        "body":"link_url":"link"
    }
]

Good:

[
    {
        "method":"POST",
        "relative_url":"foo",
        "body":{"link_url":"link"}
   }
]


问:
users does not define no argument constructor
i kept getting this error
"users does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped." Tried everything, no idea why it happen.

```<code>public void retrievingUserInfo(){

    databaseUserID.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous userinfo list
            Users_Info.clear();

            //iterating through all the nodes
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //getting userinfo
                users userinfo = postSnapshot.getValue(users.class);
                //adding userinfo to the list
                Users_Info.add(userinfo);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

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

users.class

```<code>@Keep
public class users {

    public String user_id, address, contact, name;

    public users(String user_id, String address, String contact,String name)
    {}

}
</code>```

答:
JavaBeans require a no-argument constructor to be present.

When a Java class has no constructors at all, there is a default no-arg constructor automatically added to it by the compiler.  The moment you define any constructor in the class, the default no-arg constructor goes away.

In your code, your users class defines such a constructor that contains arguments:

```<code>public users(String user_id, String address, String contact,String name)
{}
</code>```

As long as that constructor is present, and you don't define a no-arg constructor, that class will not have one.

To resolve this, you either need to remove that constructor from the class, or manually add a no-arg constructor to it:

```<code>public users() {}
</code>```

Body:
i kept getting this error
"users does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped." Tried everything, no idea why it happen.

public void retrievingUserInfo(){

    databaseUserID.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //clearing the previous userinfo list
            Users_Info.clear();

            //iterating through all the nodes
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                //getting userinfo
                users userinfo = postSnapshot.getValue(users.class);
                //adding userinfo to the list
                Users_Info.add(userinfo);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

users.class

@Keep
public class users {

    public String user_id, address, contact, name;

    public users(String user_id, String address, String contact,String name)
    {}

}

Body:
JavaBeans require a no-argument constructor to be present.

When a Java class has no constructors at all, there is a default no-arg constructor automatically added to it by the compiler.  The moment you define any constructor in the class, the default no-arg constructor goes away.

In your code, your users class defines such a constructor that contains arguments:

public users(String user_id, String address, String contact,String name)
{}

As long as that constructor is present, and you don't define a no-arg constructor, that class will not have one.

To resolve this, you either need to remove that constructor from the class, or manually add a no-arg constructor to it:

public users() {}


问:
Find first character of string, then compare it with a symbol c++
Attempting to check the first character of a string to see if it contains a "/".

```<code>string pathname = "/test";
if(pathname.at(0) == "/")
{
    // if first character is a slash then delete the slash
    // but only delete the slash if it's the first character
    pathname.erase(pathname.begin()+0);
}
</code>```

I understand that the above code will not work because pathname.at(0) is considered an int.

I'm sure this has been asked before. But I have looked around a lot. I've seen the substr method the find method and many others. I can't seem to get them working right though.

Suggestions? Thanks in advance.

答:
You compare the first symbol code with a pointer to string. Try to compare the first symbol with the char.</p>

```<code>if(pathname.at(0) == '/')
</code>```

Body:
Attempting to check the first character of a string to see if it contains a "/".

string pathname = "/test";
if(pathname.at(0) == "/")
{
    // if first character is a slash then delete the slash
    // but only delete the slash if it's the first character
    pathname.erase(pathname.begin()+0);
}

I understand that the above code will not work because pathname.at(0) is considered an int.

I'm sure this has been asked before. But I have looked around a lot. I've seen the substr method the find method and many others. I can't seem to get them working right though.

Suggestions? Thanks in advance.

Body:
You compare the first symbol code with a pointer to string. Try to compare the first symbol with the char.

if(pathname.at(0) == '/')


问:
Algorithm - Lexicographically largest possible magical substring
I am working on this magical sub-string problem.

Magical binary strings are non-empty binary strings if the following two conditions are true:

The number of 0's is equal to the number of 1's.

For every prefix of the binary string, the number of 1's should not be less than the number of 0's.

I got stuck on how to proceed further in my Java program.

Here is my program:

```<code>static String findLargest(String str) {
        String[] splits = str.split("");
        Set<String> set = new LinkedHashSet<String>();
        for (int i = 0; i < splits.length; i++) {
            if (splits[i].equals("0")) {
                continue;
            }
            int zeros = 0;
            int ones = 0;
            StringBuilder sb = new StringBuilder("");
            for (int j = i; j < splits.length; j++) {
                if (splits[j].equals("0")) {
                    zeros++;
                } else {
                    ones++;
                }
                sb.append(splits[j]);
                if (zeros == ones && ones >= zeros) {
                    set.add(sb.toString());
                }
            }
        }
        set.remove(str);

        List<String> list = new ArrayList<String>(set);
        System.out.println(list);

        return null;
    }
</code>```

Using this program I am able to get the magical sub-strings for the given input String 11011000 as [10, 101100, 1100] in my list variable.

Now from here I am struggling how to remove the invalid entry of 101100 from my list and then use the elements 10, 1100 to swap from my input 11011000 to get the final result as 11100100

Also please guide me if there is any other alternate approach.

答:
I can provide some points.
First, get all the magical substrings and store them as a pair of start and end index(l, r) in a list;
Second, sort the list based on index l;
Those who can be potentially swapped substring can get from the same index l. look at the example given "11011000"
the list will have (0,7),(1,2),(1,6),(3,6),(4,5)
obviously only potential swap is among (1,2)(1,6)

deal these substrings have same index l will help find potential swapping substrings, sort them to find the maximum order.

ContentLicense: CC BY-SA 4.0

Body:
I am working on this magical sub-string problem.

Magical binary strings are non-empty binary strings if the following two conditions are true:

The number of 0's is equal to the number of 1's.

For every prefix of the binary string, the number of 1's should not be less than the number of 0's.

I got stuck on how to proceed further in my Java program.

Here is my program:

static String findLargest(String str) {
        String[] splits = str.split("");
        Set<String> set = new LinkedHashSet<String>();
        for (int i = 0; i < splits.length; i++) {
            if (splits[i].equals("0")) {
                continue;
            }
            int zeros = 0;
            int ones = 0;
            StringBuilder sb = new StringBuilder("");
            for (int j = i; j < splits.length; j++) {
                if (splits[j].equals("0")) {
                    zeros++;
                } else {
                    ones++;
                }
                sb.append(splits[j]);
                if (zeros == ones && ones >= zeros) {
                    set.add(sb.toString());
                }
            }
        }
        set.remove(str);

        List<String> list = new ArrayList<String>(set);
        System.out.println(list);

        return null;
    }

Using this program I am able to get the magical sub-strings for the given input String 11011000 as [10, 101100, 1100] in my list variable.

Now from here I am struggling how to remove the invalid entry of 101100 from my list and then use the elements 10, 1100 to swap from my input 11011000 to get the final result as 11100100

Also please guide me if there is any other alternate approach.


问:
fullcalendar viewRender - can't call service angular 5
I am trying to get events based on the current view. To track 'prev', 'next' clicks and initial display views, I'm using the CalendarOption viewRender which returns the full view, and invokes itself every click - which gives a new full view.

Problem is - I cannot call the service from which I'm getting my events from, based on the extracted parameter of the viewRender view output.

```<code>constructor (public eventService: EventService)

calendarOptions = {
  ...
  ...
  eventLimit: true,
  viewRender: function(view) {
    this.eventService.getEvents(view)   // <--- code stops here, error printed at bottom
      .subscribe(
        response => {
          this.events = response.events;
        },
        error => {
          console.log(error)
        }
      );
    console.log(this.events);
  },
  events: this.events,
  ...
  ...
}
</code>```

I'm expecting my service to work and be triggered from within that scenario - on calendar first initializing and each time the 'prev' / 'next' buttons are clicked

currently, the output is

ERROR TypeError: Cannot read property 'getEvents' of undefined

Is there any other way I can invoke this external command?
I also tried using httpClient directly, but HTTP is also a service which can't be accessed as it seems

答:
It is now solved

Managed to get access to my service by appending:

const eventService = this.eventService;

here:

```<code>initCalendar() {
  const eventService = this.eventService;
  var events = []
  this.calendarOptions = {
    ...
    ...
    viewRender: function(view) {
    eventService.getEvents(view) // <----- Not accessing with 'this' anymore
      .subscribe(
        response => {
          events = response.events;
        },
        error => {
          console.log(error)
        }
      );
    },
    events: events;
    ...
    ...
  }
}
</code>```

Body:
I am trying to get events based on the current view. To track 'prev', 'next' clicks and initial display views, I'm using the CalendarOption viewRender which returns the full view, and invokes itself every click - which gives a new full view.

Problem is - I cannot call the service from which I'm getting my events from, based on the extracted parameter of the viewRender view output.

constructor (public eventService: EventService)

calendarOptions = {
  ...
  ...
  eventLimit: true,
  viewRender: function(view) {
    this.eventService.getEvents(view)   // <--- code stops here, error printed at bottom
      .subscribe(
        response => {
          this.events = response.events;
        },
        error => {
          console.log(error)
        }
      );
    console.log(this.events);
  },
  events: this.events,
  ...
  ...
}

I'm expecting my service to work and be triggered from within that scenario - on calendar first initializing and each time the 'prev' / 'next' buttons are clicked

currently, the output is

ERROR TypeError: Cannot read property 'getEvents' of undefined

Is there any other way I can invoke this external command?
I also tried using httpClient directly, but HTTP is also a service which can't be accessed as it seems

Body:
It is now solved

Managed to get access to my service by appending:

const eventService = this.eventService;

here:

initCalendar() {
  const eventService = this.eventService;
  var events = []
  this.calendarOptions = {
    ...
    ...
    viewRender: function(view) {
    eventService.getEvents(view) // <----- Not accessing with 'this' anymore
      .subscribe(
        response => {
          events = response.events;
        },
        error => {
          console.log(error)
        }
      );
    },
    events: events;
    ...
    ...
  }
}


问:
a-videosphere control mute
I want to create a landing page with a-videosphere 360 video but I want to load it muted ... or with the volume at 0 because it's annoying to get surprised by sound when you land on a site. But I don't know the command to "mute" and "unmute" the video. ( and or control the volume )</p>

```<code><video muted id="video" style="display:none" autoplay loop crossorigin="anonymous" playsinline webkit-playsinline>
<source type="video/mp4" src="<?php echo $src; ?>" />
</video>

document.querySelector("#video").???();
</code>```

答:
Your example code already contains the correct attribute to load the video - 'muted'.

You can mute a video by getting a reference to it and then set it to muted or not muted in Javascript:

vid = document.getElementById("myPath/myvideo.mp4");

//Mute video
vid.muted = true;

//Turn sound on
vid.muted = false;
```

Title: a-videosphere control mute

Body:
I want to create a landing page with a-videosphere 360 video but I want to load it muted ... or with the volume at 0 because it's annoying to get surprised by sound when you land on a site. But I don't know the command to "mute" and "unmute" the video. ( and or control the volume )

<video muted id="video" style="display:none" autoplay loop crossorigin="anonymous" playsinline webkit-playsinline>
<source type="video/mp4" src="<?php echo $src; ?>" />
</video>

document.querySelector("#video").???();


问:
Why does H2 database tells me my table does not exist for some tests only
I have a Spring JPA Repository which I'm trying to test using a H2 in-memory database. Some of the tests pass while others are not. The problem is that H2 is telling me my table doesn't exist (which is weird because the tests that pass also use that very same table).

Here is my database configuration:

```<code>@Configuration
@Import({BaseConfiguration.class, DatabaseProperties.class})
@EnableJpaRepositories(basePackages = DatabaseConfiguration.REPOSITORIES_PACKAGE)
public class DatabaseConfiguration {

    /*
     * Constants
     */
    public static final String MODEL_PACKAGE = "be.dupirefr.examples.spring.batch.simple.model";
    public static final String REPOSITORIES_PACKAGE = "be.dupirefr.examples.spring.batch.simple.repositories";

    /*
     * Beans
     */
    @Bean
    public DataSource dataSource(DatabaseProperties properties) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(properties.url);
        dataSource.setUsername(properties.username);
        dataSource.setPassword(properties.password);
        dataSource.setDriverClassName(properties.driverClassName);

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPackagesToScan(MODEL_PACKAGE);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        return entityManagerFactoryBean;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
</code>```

The properties used in the previous configuration class are stored in a database.properties file mapped to the following configuration class:

```<code>@Configuration
@PropertySource("classpath:be/dupirefr/examples/spring/batch/simple/config/database/database.properties")
public class DatabaseProperties {

    /*
     * Fields
     */
    @Value("${spring.datasource.url}")
    public String url;

    @Value("${spring.datasource.username}")
    public String username;

    @Value("${spring.datasource.password}")
    public String password;

    @Value("${spring.datasource.driver-class-name}")
    public String driverClassName;

}
</code>```

This file uses the properties found in the database.properties file:

```<code>spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=admin
spring.datasource.password=admin
spring.datasource.driver-class-name=org.h2.Driver
</code>```

And here are the Employer class and its repository test class:

Employer:

```<code>@Entity
public class Employer {

    /*
     * Fields
     */
    @Id
    private Long id;

    @Column(nullable = false)
    private String name;

    @OneToMany(mappedBy = "employer")
    private List<Employee> employees;

    /*
     * Constructors
     */
    private Employer() {}

    public Employer(Long id, String name) {
        this.id = id;
        this.name = name;

        this.employees = new ArrayList<>();
    }

    /*
     * Getters
     */
    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    /*
     * Methods
     */
    //...

}
</code>```

EmployerRepositoryIT:

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DatabaseConfiguration.class)
@Transactional
public class EmployerRepositoryIT {

    /*
     * Constants
     */
    public static final Employer GOOGLE = new Employer(1L, "Google");
    public static final Employer MICROSOFT = new Employer(2L, "Microsoft");
    public static final Employer APPLE = new Employer(3L, "Apple");

    /*
     * Fields
     */
    @Autowired
    private EmployerRepository repository;

    @Autowired
    private EntityManager entityManager;

    /*
     * Setups
     */
    @Before
    public void setUp() {
        entityManager.persist(GOOGLE);
        entityManager.persist(MICROSOFT);
    }

    /*
     * Tests
     */
    @Test
    public void findById_Exists() {
        assertEquals(GOOGLE, repository.findById(GOOGLE.getId()).get());
        assertEquals(MICROSOFT, repository.findById(MICROSOFT.getId()).get());
    }

    @Test
    public void findById_NotExists() {
        assertFalse(repository.findById(Long.MAX_VALUE).isPresent());
    }

    @Test
    public void findAll() {
        assertEquals(Arrays.asList(GOOGLE, MICROSOFT), repository.findAll());
    }

    @Test
    public void save() {
        repository.save(APPLE);
        assertEquals(APPLE, entityManager.find(Employer.class, APPLE.getId()));
    }

    @Test
    public void delete() {
        repository.delete(MICROSOFT);
        assertNull(entityManager.find(Employer.class, MICROSOFT.getId()));
    }

}
</code>```

As I'm only testing JpaRepository methods I spare you the EmployerRepository interface which has no added value here.

Of the tests shown above, only findById_Exists and delete are working. For the others I got the following error:

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select employer0_.id as id1_2_0_, employer0_.name as name2_2_0_ from Employer employer0_ where employer0_.id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
</code>```

Which seemed to be caused by:

```<code>org.h2.jdbc.JdbcSQLException: Table "EMPLOYER" not found; SQL statement:
</code>```

select employer0_.id as id1_2_0_, employer0_.name as name2_2_0_ from Employer employer0_ where employer0_.id=? [42102-187]

I also tried the followings for my database url:

Do you have any idea what the problem could be?

```<code>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE
</code>```

But none of them worked.

EDIT :
I figured out something. The tests that are failing are those that are actually reaching the database. The others are just performing in the EntityManager's cache. So it seems that my problem lies in the H2 database configuration or something like that. I'll check that out but if somebody have an idea it'll be welcomed.

EDIT 2:
In fine, adding DB_CLOSE_DELAY=-1 did the trick. I just forgot to tell Hibernate to generate the DDL.

答:
This appears to be due to the close of connect when the database
  is initialized,which results in the shutdown of database.

So when you execute a separate query SQL, because of the database has been closed, you will not be able to find the Table: Table "EMPLOYER" not found

If you want to keep the database open for use, you can try to add
  parameters to the database URL @Value("${spring.datasource.url}")

```<code>DB_CLOSE_DELAY=-1
</code>```

which like:

```<code>jdbc:h2:tcp://localhost/xxxxx:xxxxxx;DB_CLOSE_DELAY=-1
</code>```

Body:
I have a Spring JPA Repository which I'm trying to test using a H2 in-memory database. Some of the tests pass while others are not. The problem is that H2 is telling me my table doesn't exist (which is weird because the tests that pass also use that very same table).

Here is my database configuration:

@Configuration
@Import({BaseConfiguration.class, DatabaseProperties.class})
@EnableJpaRepositories(basePackages = DatabaseConfiguration.REPOSITORIES_PACKAGE)
public class DatabaseConfiguration {

    /*
     * Constants
     */
    public static final String MODEL_PACKAGE = "be.dupirefr.examples.spring.batch.simple.model";
    public static final String REPOSITORIES_PACKAGE = "be.dupirefr.examples.spring.batch.simple.repositories";

    /*
     * Beans
     */
    @Bean
    public DataSource dataSource(DatabaseProperties properties) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(properties.url);
        dataSource.setUsername(properties.username);
        dataSource.setPassword(properties.password);
        dataSource.setDriverClassName(properties.driverClassName);

        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPackagesToScan(MODEL_PACKAGE);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        return entityManagerFactoryBean;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

The properties used in the previous configuration class are stored in a database.properties file mapped to the following configuration class:

@Configuration
@PropertySource("classpath:be/dupirefr/examples/spring/batch/simple/config/database/database.properties")
public class DatabaseProperties {

    /*
     * Fields
     */
    @Value("${spring.datasource.url}")
    public String url;

    @Value("${spring.datasource.username}")
    public String username;

    @Value("${spring.datasource.password}")
    public String password;

    @Value("${spring.datasource.driver-class-name}")
    public String driverClassName;

}

This file uses the properties found in the database.properties file:

spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=admin
spring.datasource.password=admin
spring.datasource.driver-class-name=org.h2.Driver

And here are the Employer class and its repository test class:

Employer:

@Entity
public class Employer {

    /*
     * Fields
     */
    @Id
    private Long id;

    @Column(nullable = false)
    private String name;

    @OneToMany(mappedBy = "employer")
    private List<Employee> employees;

    /*
     * Constructors
     */
    private Employer() {}

    public Employer(Long id, String name) {
        this.id = id;
        this.name = name;

        this.employees = new ArrayList<>();
    }

    /*
     * Getters
     */
    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    /*
     * Methods
     */
    //...

}

EmployerRepositoryIT:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = DatabaseConfiguration.class)
@Transactional
public class EmployerRepositoryIT {

    /*
     * Constants
     */
    public static final Employer GOOGLE = new Employer(1L, "Google");
    public static final Employer MICROSOFT = new Employer(2L, "Microsoft");
    public static final Employer APPLE = new Employer(3L, "Apple");

    /*
     * Fields
     */
    @Autowired
    private EmployerRepository repository;

    @Autowired
    private EntityManager entityManager;

    /*
     * Setups
     */
    @Before
    public void setUp() {
        entityManager.persist(GOOGLE);
        entityManager.persist(MICROSOFT);
    }

    /*
     * Tests
     */
    @Test
    public void findById_Exists() {
        assertEquals(GOOGLE, repository.findById(GOOGLE.getId()).get());
        assertEquals(MICROSOFT, repository.findById(MICROSOFT.getId()).get());
    }

    @Test
    public void findById_NotExists() {
        assertFalse(repository.findById(Long.MAX_VALUE).isPresent());
    }

    @Test
    public void findAll() {
        assertEquals(Arrays.asList(GOOGLE, MICROSOFT), repository.findAll());
    }

    @Test
    public void save() {
        repository.save(APPLE);
        assertEquals(APPLE, entityManager.find(Employer.class, APPLE.getId()));
    }

    @Test
    public void delete() {
        repository.delete(MICROSOFT);
        assertNull(entityManager.find(Employer.class, MICROSOFT.getId()));
    }

}

As I'm only testing JpaRepository methods I spare you the EmployerRepository interface which has no added value here.

Of the tests shown above, only findById_Exists and delete are working. For the others I got the following error:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select employer0_.id as id1_2_0_, employer0_.name as name2_2_0_ from Employer employer0_ where employer0_.id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement

Which seemed to be caused by:

org.h2.jdbc.JdbcSQLException: Table "EMPLOYER" not found; SQL statement:

select employer0_.id as id1_2_0_, employer0_.name as name2_2_0_ from Employer employer0_ where employer0_.id=? [42102-187]

I also tried the followings for my database url:

Do you have any idea what the problem could be?

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE

But none of them worked.

EDIT :
I figured out something. The tests that are failing are those that are actually reaching the database. The others are just performing in the EntityManager's cache. So it seems that my problem lies in the H2 database configuration or something like that. I'll check that out but if somebody have an idea it'll be welcomed.

EDIT 2:
In fine, adding DB_CLOSE_DELAY=-1 did the trick. I just forgot to tell Hibernate to generate the DDL.

Body:
This appears to be due to the close of connect when the database
  is initialized,which results in the shutdown of database.

So when you execute a separate query SQL, because of the database has been closed, you will not be able to find the Table: Table "EMPLOYER" not found

If you want to keep the database open for use, you can try to add
  parameters to the database URL @Value("${spring.datasource.url}")

DB_CLOSE_DELAY=-1

which like:

jdbc:h2:tcp://localhost/xxxxx:xxxxxx;DB_CLOSE_DELAY=-1


问:
Can a Spring Bean class contain static methods?
I hope this isn't too noob of a question, I'm still quite new to Spring. Can a bean class contain static methods? My initial thoughts is no because a static method is global, there's one instance per the entire application and threads to share but a bean might not be defined as such.

I tried searching for this question but couldn't find a clear answer.

答:
It can be contained.</p>
```<code>@Service
public class TestService {

    @Autowired
    private TestDao testDao;

    public static void test(){
        System.out.println("test");
    }
}

@RestController
@RequestMapping("/api/")
public class TestController {

    @Autowired
    private TestService testService;

    @PostMapping("test")
    public String test(){
       TestService.test();
       return "ok";
    }
}
</code>```

Body:
It can be contained.

@Service
public class TestService {

    @Autowired
    private TestDao testDao;

    public static void test(){
        System.out.println("test");
    }
}

@RestController
@RequestMapping("/api/")
public class TestController {

    @Autowired
    private TestService testService;

    @PostMapping("test")
    public String test(){
       TestService.test();
       return "ok";
    }
}


问:
Error Code: 1109. Unknown table 'new' in field list
I'm creating a database, where I validate input data with triggers. I added them successfully, but there is an error when I try to input fine data.

creating db, tables and triggers

```<code>CREATE DATABASE IF NOT EXISTS DBWorkers;

CREATE TABLE IF NOT EXISTS Ludzie(
PESEL char(11) NOT NULL,
imie varchar(30) NOT NULL,
nazwisko varchar(30) NOT NULL,
data_urodzenia date NOT NULL,
wzrost float NOT NULL,
waga float NOT NULL,
rozmiar_buta int NOT NULL,

PRIMARY KEY(PESEL));

DELIMITER $$
CREATE FUNCTION check_pesel(PESEL char(11)) RETURNS bool
BEGIN
IF(
    CHAR_LENGTH(NEW.PESEL) <> 11 AND
    CONVERT(PESEL, SIGNED INT) > 0 AND
    CONVERT(LEFT(PESEL,2), SIGNED INT) BETWEEN 0 AND 99 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND 12 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND     DAY(LAST_DAY(CONCAT('19',LEFT(PESEL,2),'-',SUBSTRING(PESEL,3,2),'-01')))
    )
    THEN
        RETURN TRUE;
    ELSE
        RETURN FALSE;
END IF;
END $$

CREATE TRIGGER `ludzie_data_check_before_insert` BEFORE INSERT ON `Ludzie`
FOR EACH ROW
BEGIN
IF NOT(
        check_pesel(NEW.PESEL) AND
        NEW.WZROST > 0.0 AND
        NEW.WAGA > 0.0 AND
        NEW.ROZMIAR_BUTA > 0
    )
THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'check on Ludzie failed during insert';
END IF;
END $$
DELIMITER ;
</code>```

When I try to input data by

```<code>INSERT INTO Ludzie VALUES ('7810396705', 'Anders', 'Kennedy','1958-08-20', 1.70, 88.6, 43)
</code>```

I get

```<code>Error Code: 1109. Unknown table 'new' in field list
</code>```

I already tried turning mysql server on and off, checked if I'm doing it to the right database. Everything seems to look fine, but it isn't :/

答:
I think I found your problem:

```<code>CHAR_LENGTH(NEW.PESEL) <> 11 AND
CONVERT(PESEL, SIGNED INT) > 0 AND
</code>```

That is inconsistent usage of NEW.PESEL and PESEL, you should not use the keyword new in a function that does not add anything to the database.  In this context, the error recognized NEW as a table instead of a keyword.

Body:
I'm creating a database, where I validate input data with triggers. I added them successfully, but there is an error when I try to input fine data.

creating db, tables and triggers

CREATE DATABASE IF NOT EXISTS DBWorkers;

CREATE TABLE IF NOT EXISTS Ludzie(
PESEL char(11) NOT NULL,
imie varchar(30) NOT NULL,
nazwisko varchar(30) NOT NULL,
data_urodzenia date NOT NULL,
wzrost float NOT NULL,
waga float NOT NULL,
rozmiar_buta int NOT NULL,

PRIMARY KEY(PESEL));

DELIMITER $$
CREATE FUNCTION check_pesel(PESEL char(11)) RETURNS bool
BEGIN
IF(
    CHAR_LENGTH(NEW.PESEL) <> 11 AND
    CONVERT(PESEL, SIGNED INT) > 0 AND
    CONVERT(LEFT(PESEL,2), SIGNED INT) BETWEEN 0 AND 99 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND 12 AND
    CONVERT(SUBSTRING(PESEL,3,2), SIGNED INT) BETWEEN 1 AND     DAY(LAST_DAY(CONCAT('19',LEFT(PESEL,2),'-',SUBSTRING(PESEL,3,2),'-01')))
    )
    THEN
        RETURN TRUE;
    ELSE
        RETURN FALSE;
END IF;
END $$

CREATE TRIGGER `ludzie_data_check_before_insert` BEFORE INSERT ON `Ludzie`
FOR EACH ROW
BEGIN
IF NOT(
        check_pesel(NEW.PESEL) AND
        NEW.WZROST > 0.0 AND
        NEW.WAGA > 0.0 AND
        NEW.ROZMIAR_BUTA > 0
    )
THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'check on Ludzie failed during insert';
END IF;
END $$
DELIMITER ;

When I try to input data by

INSERT INTO Ludzie VALUES ('7810396705', 'Anders', 'Kennedy','1958-08-20', 1.70, 88.6, 43)

I get

Error Code: 1109. Unknown table 'new' in field list

I already tried turning mysql server on and off, checked if I'm doing it to the right database. Everything seems to look fine, but it isn't :/

Body:
I think I found your problem:

CHAR_LENGTH(NEW.PESEL) <> 11 AND
CONVERT(PESEL, SIGNED INT) > 0 AND

That is inconsistent usage of NEW.PESEL and PESEL, you should not use the keyword new in a function that does not add anything to the database.  In this context, the error recognized NEW as a table instead of a keyword.


问:
What does double brackets mean in this condition?
This below is my for-loop and im a beginner so i need help to understand what [i] means where it says ".checked" and ".value".  Also, does "var i" stand for "variable i"? Side note: this loop is for a list of checkboxes.</p>

```<code>for (var i=0; i<flightprices.length; i++) {

if (flightprices.length[i].checked) {

flightPrice = +flightprices[i].value;
}}
</code>```

答:
Ignoring the fact that this code results in an error, I can tell you the following.

var i=0; is defining a variable named i to the value 0.

flightprices[i] means the i+1th element of the array flightprices. [] notation is an array selector. Because JavaScript is 0-indexed, flightprices[0] means the first element, flightprices[1] is the second element, and so on.

Why there is an error

This line:

```<code>if (flightprices.length[i].checked) {
</code>```

tries to find element i of flightprices.length, however the length of something is always an integer, and integers aren't arrays.

Body:
This below is my for-loop and im a beginner so i need help to understand what [i] means where it says ".checked" and ".value".  Also, does "var i" stand for "variable i"? Side note: this loop is for a list of checkboxes.

for (var i=0; i<flightprices.length; i++) {

if (flightprices.length[i].checked) {

flightPrice = +flightprices[i].value;
}}

Body:
Ignoring the fact that this code results in an error, I can tell you the following.

var i=0; is defining a variable named i to the value 0.

flightprices[i] means the i+1th element of the array flightprices. [] notation is an array selector. Because JavaScript is 0-indexed, flightprices[0] means the first element, flightprices[1] is the second element, and so on.

Why there is an error

This line:

if (flightprices.length[i].checked) {

tries to find element i of flightprices.length, however the length of something is always an integer, and integers aren't arrays.


问:
How do I write to multiple files in Apache Beam?
Let me simplify my case. I'm using Apache Beam 0.6.0. My final processed result is PCollection<KV<String, String>>. And I want to write values to different files corresponding to their keys.

For example, let's say the result consists of

```<code>(key1, value1)
(key2, value2)
(key1, value3)
(key1, value4)
</code>```

Then I want to write value1, value3 and value4 to key1.txt, and write value4 to key2.txt.

And in my case:

Key set is determined when the pipeline is running, not when constructing the pipeline.

Key set may be quite small, but the number of values corresponding to each key may be very very large.

Any ideas?

答:
In Apache Beam 2.2 Java SDK, this is natively supported in TextIO and AvroIO using respectively TextIO and AvroIO.write().to(DynamicDestinations). See e.g. this method.

Update (2018): Prefer to use FileIO.writeDynamic() together with TextIO.sink() and AvroIO.sink() instead.

Body:
Let me simplify my case. I'm using Apache Beam 0.6.0. My final processed result is PCollection<KV<String, String>>. And I want to write values to different files corresponding to their keys.

For example, let's say the result consists of

(key1, value1)
(key2, value2)
(key1, value3)
(key1, value4)

Then I want to write value1, value3 and value4 to key1.txt, and write value4 to key2.txt.

And in my case:

Key set is determined when the pipeline is running, not when constructing the pipeline.

Key set may be quite small, but the number of values corresponding to each key may be very very large.

Any ideas?


问:
The variable is being used without being initialized (C++, other solutions don't work)
My problem is that when I enter a value in my C++ program (via cin) it gives me a debug error and says "Run-time Check Failure #3 - the variable 'result' is being used without being initialized." 'result' is an int, and is initialized with a 1, but still gives me this, unlike other peoples' questions. </p>

```<code>int multiplication(int x, int y, int result)
{
    result = 1;
    result = x * y;
    return result;
}

int main() //Declares the "main" function, which is mandatory.
{
    int result = 0;
    char operation;
    int x;
    int y;
    std::cout << "Enter your first number: ";
    std::cin >> x;
    std::cout << "Enter your second number: ";
    std::cin >> y;
    std::cout << "Enter your operation (+, -, *, /): ";
    std::cin >> operation;
    if (operation == '*');
    {
        int result = multiplication(x, y, result);
    }

    std::cout << "The answer is: " << result << std::endl;
    return 0; //Ends the process with 0x0.
}
</code>```

答:
Two things.

You are using two different results.

```<code>int result = 0;
int result = multiplication(x, y, result);
</code>```

You need to change to:

```<code>result = multiplication(x, y, result);
</code>```

Why do you need to pass result by parameter? You can simply do this:

```<code>int multiplication(int x, int y) { return x * y; }
</code>```

In this case, inside the main, change by this:

```<code>result = multiplication(x, y);
</code>```

Body:
My problem is that when I enter a value in my C++ program (via cin) it gives me a debug error and says "Run-time Check Failure #3 - the variable 'result' is being used without being initialized." 'result' is an int, and is initialized with a 1, but still gives me this, unlike other peoples' questions.

int multiplication(int x, int y, int result)
{
    result = 1;
    result = x * y;
    return result;
}

int main() //Declares the "main" function, which is mandatory.
{
    int result = 0;
    char operation;
    int x;
    int y;
    std::cout << "Enter your first number: ";
    std::cin >> x;
    std::cout << "Enter your second number: ";
    std::cin >> y;
    std::cout << "Enter your operation (+, -, *, /): ";
    std::cin >> operation;
    if (operation == '*');
    {
        int result = multiplication(x, y, result);
    }

    std::cout << "The answer is: " << result << std::endl;
    return 0; //Ends the process with 0x0.
}

Body:
Two things.

You are using two different results.

int result = 0;
int result = multiplication(x, y, result);

You need to change to:

result = multiplication(x, y, result);

Why do you need to pass result by parameter? You can simply do this:

int multiplication(int x, int y) { return x * y; }

In this case, inside the main, change by this:

result = multiplication(x, y);


问:
Align HTML elements horizontally in a div
I have three HTML objects and want to arrange Previous button at the left side, Next button at right side and span in the middle inside a container div.

```<code><PREVIOUS> |SPAN| <NEXT>
</code>```

    #btnPrevious
    {
        float:left;
    }
    #spanStage
    {
        font-weight:bold;
        vertical-align:middle;
    }
    #btnNext
    {
        float:right;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div>
        <input type="button" value="Previous" id="btnPrevious"/>
        <span id="spanStage">Stage 5</span>
        <input type="button" value="Next" id="btnNext"/>
    </div></code>```

答:
The "display:flex" style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.

Example:

```<code><div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
     <input type="button" value="Previous" id="btnPrevious"/>
     <span id="spanStage">Stage 5</span>
     <input type="button" value="Next" id="btnNext"/>
</div>
</code>```

More detail about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

flex-direction: row, column

justify-content: flex-end, center, space-between, space-around

align-items: stretch, flex-start, flex-end, center

Body:
I have three HTML objects and want to arrange Previous button at the left side, Next button at right side and span in the middle inside a container div.

<PREVIOUS> |SPAN| <NEXT>

    #btnPrevious
    {
        float:left;
    }
    #spanStage
    {
        font-weight:bold;
        vertical-align:middle;
    }
    #btnNext
    {
        float:right;
    }

        <input type="button" value="Previous" id="btnPrevious"/>
        Stage 5
        <input type="button" value="Next" id="btnNext"/>

Body:
The "display:flex" style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.

Example:

<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
     <input type="button" value="Previous" id="btnPrevious"/>
     <span id="spanStage">Stage 5</span>
     <input type="button" value="Next" id="btnNext"/>
</div>

More detail about flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

flex-direction: row, column

justify-content: flex-end, center, space-between, space-around

align-items: stretch, flex-start, flex-end, center


问:
How do I add
 tags using PHP code?
In PHP I would like add a field of type paragraph (
) to some content. Using site-building I have no problem but I can not find the way to do it correctly using PHP code.

答:
```<code><?php
  //Suposse that in $content it is the content html of the page
  $content .= "<p>Lorem ipsum</p>";
  echo $content;
?>
</code>```

Title: How do I add <p> tags using PHP code?


问:
integrating paypal check without leaving your site
I want to integrate paypal in my website. But my requirement is, I dont want my customers to go into paypal site for payment. (I know it is not a secure way, but it is my requirements) Is there a way such that I can do credit card checks in backend using paypal APIs ?  If so, which method to be used? I want it for "singapore" country and SGD as currency.

Waiting for your suggestions!!!

Thanks in advance. :)

答: Maybe you are looking for this Paypal product </p>

ContentLicense: CC BY-SA 2.5


问:
how to calculate PDF in tensorflow
In Matlab, I can calculate the probability density function(PDF) of Gaussian distribution by using

```<code>x = [0.8147,0.9058,0.1270,0.9134,0.6324,0.0975,0.2785,0.5469,0.9575,0.9649]
y = normpdf(x,1.0,2.5)
</code>```

output:

```<code>y = 0.1591    0.1595    0.1501    0.1595    0.1579    0.1495    0.1531    0.1570    0.1596    0.1596
</code>```

Using tensorflow, I have tried with this

```<code>x = tf.variable([0.8147,0.9058,0.1270,0.9134,0.6324,0.0975,0.2785,0.5469,0.9575,0.9649],tf.float32)
y = tf.contrib.distributions.NormalWithSoftplusSigma.pdf(x)
</code>```

I get an error TypeError: pdf missing 1 required positional argument

how to input the mu and sigma values to this distribution ? to get the similar output.

答:
This function pdf is updated as prob:

```<code>dist = tf.contrib.distributions.Normal(1.0, 2.5)
y = dist.prob(x)
</code>```

Title: how to calculate PDF in tensorflow

Body:
In Matlab, I can calculate the probability density function(PDF) of Gaussian distribution by using

x = [0.8147,0.9058,0.1270,0.9134,0.6324,0.0975,0.2785,0.5469,0.9575,0.9649]
y = normpdf(x,1.0,2.5)

output:

y = 0.1591    0.1595    0.1501    0.1595    0.1579    0.1495    0.1531    0.1570    0.1596    0.1596

Using tensorflow, I have tried with this

x = tf.variable([0.8147,0.9058,0.1270,0.9134,0.6324,0.0975,0.2785,0.5469,0.9575,0.9649],tf.float32)
y = tf.contrib.distributions.NormalWithSoftplusSigma.pdf(x)

I get an error TypeError: pdf missing 1 required positional argument

how to input the mu and sigma values to this distribution ? to get the similar output.

Body:
This function pdf is updated as prob:

dist = tf.contrib.distributions.Normal(1.0, 2.5)
y = dist.prob(x)


问:
Conversion between latitude, longitude to UTM notation
I have locations coordinates in the form of latitude, longitude such as: 23⁰ 39' 24.8" N & 58⁰ 11' 36.5" E , see the pic below. But in my work place I use ArcGIS and it seems that doesn't support degree (latitude, longitude) form coordinates. I am planning now to write a C++  code to convert degree form to UTM notation, for example 23⁰ 39' 24.8" N & 58⁰ 11' 36.5E"  to 2616726 N & 621702 E. I would like to know how can do such conversion?'

PS:  E = East, N= North.

答:
Adding to rve's answer, you can implement the lat/long -> UTM conversion by following the equations on Wikipedia.

Alternatively, you could download and install an open-source geodesy package such as GeographicLib to do the conversion for you.

A third option is to borrow code directly from GeographicLib or another open-source package, such as this navsat_conversions file. Be sure to give credit to the original author(s) if you do this.


问:
Save newly scaled image to PhotoLibrary
I would like the user to be able to scale an image using UIPinchGesture. When the image is scaled to the size they would like, I want the ability to save that newly scaled and background UIView as a high resolution .png to the PhotoLibrary.

Here is my scale image code and my save code:

//touch scale image action

```<code>@IBAction func scaleImage(_ sender: UIPinchGestureRecognizer) {

    myImageView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale)
}
</code>```

//save image function

```<code>@IBAction func saveArtwork(_ sender: AnyObject) {

    UIGraphicsBeginImageContext(self.myImageView.bounds.size)

    // The code below may solve your problem
    myImageView.layer.render(in: UIGraphicsGetCurrentContext()!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
    present(activity, animated: true, completion: nil)

}
</code>```

I am making an app where you can scale an image and save the new scale, it can be as large or as small as you would like if it goes out of bounds i want it to crop what is out of view. if it is a scaled small, i would like the background to be saved so you can see the tiny image against the editing backdrop. the original image is an instagram square photo.
this is the app where i scale the image to be very small. i would like it to appear just this way with the black background as a new photo that is the same resolution and aspect ratio as the screen. so it will appear to be a black portrait rectangle with the new scaled image.my app saves this image to the library it is low resolution, unscaled and the background it looks to be transparent and appears white. not what i want.

The result I am getting now is that the image appears to scale, then when I save it is centered and cropped to image view bounds on the left and right.

答:
AHA! I got it, I created another Subview, and made my imageView a child of that view and then gave that newly created view an outlet and changed the code to this:

@IBAction func saveArtwork(_ sender: AnyObject) {

```<code>    UIGraphicsBeginImageContext(self.captureView.bounds.size)

    // The code below may solve your problem
    captureView.layer.render(in: UIGraphicsGetCurrentContext()!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
    present(activity, animated: true, completion: nil)
}
</code>```

new view is captureView.

Now it works but it looks like crap. It's very low res. I have to figure out how to take this snapshot and have it be the resolution of the device.

Title: Save newly scaled image to PhotoLibrary

Body:
I would like the user to be able to scale an image using UIPinchGesture. When the image is scaled to the size they would like, I want the ability to save that newly scaled and background UIView as a high resolution .png to the PhotoLibrary.

Here is my scale image code and my save code:

//touch scale image action

@IBAction func scaleImage(_ sender: UIPinchGestureRecognizer) {

    myImageView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale)
}

//save image function

@IBAction func saveArtwork(_ sender: AnyObject) {

    UIGraphicsBeginImageContext(self.myImageView.bounds.size)

    // The code below may solve your problem
    myImageView.layer.render(in: UIGraphicsGetCurrentContext()!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
    present(activity, animated: true, completion: nil)

}

I am making an app where you can scale an image and save the new scale, it can be as large or as small as you would like if it goes out of bounds i want it to crop what is out of view. if it is a scaled small, i would like the background to be saved so you can see the tiny image against the editing backdrop. the original image is an instagram square photo.
this is the app where i scale the image to be very small. i would like it to appear just this way with the black background as a new photo that is the same resolution and aspect ratio as the screen. so it will appear to be a black portrait rectangle with the new scaled image.my app saves this image to the library it is low resolution, unscaled and the background it looks to be transparent and appears white. not what i want.

The result I am getting now is that the image appears to scale, then when I save it is centered and cropped to image view bounds on the left and right.

Body:
AHA! I got it, I created another Subview, and made my imageView a child of that view and then gave that newly created view an outlet and changed the code to this:

@IBAction func saveArtwork(_ sender: AnyObject) {

    UIGraphicsBeginImageContext(self.captureView.bounds.size)

    // The code below may solve your problem
    captureView.layer.render(in: UIGraphicsGetCurrentContext()!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
    present(activity, animated: true, completion: nil)
}

new view is captureView.

Now it works but it looks like crap. It's very low res. I have to figure out how to take this snapshot and have it be the resolution of the device.


问:
Flask app can't find google module

I'm using a virtual environment to run a flask app. When I run pip freeze, I get the following:

```<code>google-api-core==0.1.1
google-auth==1.2.1
google-cloud-core==0.28.0
google-cloud-speech==0.30.0
google-gax==0.15.16
googleapis-common-protos==1.5.3
</code>```

However, during run time, I get the following error:

```<code>    from google.cloud import speech
ModuleNotFoundError: No module named 'google'
</code>```

I'm using the google speech APIs. They work just fine when I run them locally. I don't understand why the app can't find the modules even though they're listed as installed. Can someone suggest a fix? I've tried doing pip install google, and it downloaded a bunch of other stuff, but still no fix.

答:
So there are a lot of places where the error could be coming from. Could you please provide more details?

For example, which python version are you using? Python 2 or 3? If you are calling the wrong interpreter you need to type

```<code>python3 -m pip install
</code>```

or

```<code>python3 -m pip install
</code>```

accordingly.

Secondly are you using conda? If so, you need to use

```<code>conda install
</code>```

instead of pip install. You can find out by typing which python in your terminal.

Third, are you sure you installed the google module correctly? If not try using

```<code>pip install google --user
</code>```

and see if that works.

Lastly, are you installing the correct package? Because I believe for the speech api you need to do:

```<code>pip install --upgrade google-api-python-client
</code>```

Title: Flask app can't find google module

Body:
I'm using a virtual environment to run a flask app. When I run pip freeze, I get the following:

google-api-core==0.1.1
google-auth==1.2.1
google-cloud-core==0.28.0
google-cloud-speech==0.30.0
google-gax==0.15.16
googleapis-common-protos==1.5.3

However, during run time, I get the following error:

    from google.cloud import speech
ModuleNotFoundError: No module named 'google'

I'm using the google speech APIs. They work just fine when I run them locally. I don't understand why the app can't find the modules even though they're listed as installed. Can someone suggest a fix? I've tried doing pip install google, and it downloaded a bunch of other stuff, but still no fix.

Body:
So there are a lot of places where the error could be coming from. Could you please provide more details?

For example, which python version are you using? Python 2 or 3? If you are calling the wrong interpreter you need to type

python3 -m pip install

or

python3 -m pip install

accordingly.

Secondly are you using conda? If so, you need to use

conda install

instead of pip install. You can find out by typing which python in your terminal.

Third, are you sure you installed the google module correctly? If not try using

pip install google --user

and see if that works.

Lastly, are you installing the correct package? Because I believe for the speech api you need to do:

pip install --upgrade google-api-python-client


问:
How to get the compiled raw sql from graphQL with SQLAlchemy?
How to get the compiled raw sql command from the graphQL with SQLAlchemy? I did the search but no luck :(

schema.py

```<code>class RecordType(SQLAlchemyObjectType):

    class Meta:
        model = Record
        interfaces = (graphene.relay.Node, )

class Query(graphene.ObjectType):

    node = graphene.relay.Node.Field()
    record = graphene.Field(RecordType, id=graphene.Int())

    def resolve_record(self, info, **args):
        id = args.get('id')
        return RecordType.get_query(info).get(id)

schema = graphene.Schema(query=Query, types=[RecordType])
</code>```

答:
Well, I just found the way, reference from https://stackoverflow.com/a/36141722/9041712</p>

```<code>query = RecordType.get_query(info)
print(query.statement.compile(compile_kwargs={"literal_binds": True}))
</code>```

Body:
How to get the compiled raw sql command from the graphQL with SQLAlchemy? I did the search but no luck :(

schema.py

class RecordType(SQLAlchemyObjectType):

    class Meta:
        model = Record
        interfaces = (graphene.relay.Node, )

class Query(graphene.ObjectType):

    node = graphene.relay.Node.Field()
    record = graphene.Field(RecordType, id=graphene.Int())

    def resolve_record(self, info, **args):
        id = args.get('id')
        return RecordType.get_query(info).get(id)

schema = graphene.Schema(query=Query, types=[RecordType])

Body:
Well, I just found the way, reference from https://stackoverflow.com/a/36141722/9041712

query = RecordType.get_query(info)
print(query.statement.compile(compile_kwargs={"literal_binds": True}))


问:
excel file read on eclipse
I have an error "the method Getworkbook(file) in the type workbook is not applicable for the arguments (string)" in the following code. I precise that there is another class before ReadExcel which opens an internet browser and go till a form. My objective is to fill a form with excel. ANy advices would help, I am at the very beginning of my Java learning.

Thanks,

```<code>class ReadExcel {

private String inputFile;

public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
}

public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
        w = Workbook.getWorkbook("C:\\Users\\mahfo\\eclipse-workspace\\Download\\uketsukebango_list.xlsx");
        // Get the first sheet
        Sheet sheet = w.getSheet("Sheet1");
        // Loop over first 10 column and lines

        for (int j = 0; j < sheet.getColumns(); j++) {
            for (int i = 0; i < sheet.getRows(); i++) {
                Cell cell = sheet.getCell(1, 1);
                CellType type = cell.getType();
                if (type == CellType.LABEL) {
                    System.out.println("I got a label "
                            + cell.getContents());
                }

                if (type == CellType.NUMBER) {
                    System.out.println("I got a number "
                            + cell.getContents());
                }

            }
        }
    } catch (BiffException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws IOException {
    ReadExcel test = new ReadExcel();
    test.setInputFile("C:\\Users\\mahfo\\eclipse-workspace\\Download\\uketsukebango_list.xlsx");
    test.read();
}
</code>```

}

答:
Change your code as below

w = Workbook.getWorkbook(inputWorkbook);

Check out this javadoc

Beaware of IOException. Catch & handle it.

Title: excel file read on eclipse

Body:
I have an error "the method Getworkbook(file) in the type workbook is not applicable for the arguments (string)" in the following code. I precise that there is another class before ReadExcel which opens an internet browser and go till a form. My objective is to fill a form with excel. ANy advices would help, I am at the very beginning of my Java learning.

Thanks,

class ReadExcel {

private String inputFile;

public void setInputFile(String inputFile) {
    this.inputFile = inputFile;
}

public void read() throws IOException  {
    File inputWorkbook = new File(inputFile);
    Workbook w;
    try {
        w = Workbook.getWorkbook("C:\\Users\\mahfo\\eclipse-workspace\\Download\\uketsukebango_list.xlsx");
        // Get the first sheet
        Sheet sheet = w.getSheet("Sheet1");
        // Loop over first 10 column and lines

        for (int j = 0; j < sheet.getColumns(); j++) {
            for (int i = 0; i < sheet.getRows(); i++) {
                Cell cell = sheet.getCell(1, 1);
                CellType type = cell.getType();
                if (type == CellType.LABEL) {
                    System.out.println("I got a label "
                            + cell.getContents());
                }

                if (type == CellType.NUMBER) {
                    System.out.println("I got a number "
                            + cell.getContents());
                }

            }
        }
    } catch (BiffException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws IOException {
    ReadExcel test = new ReadExcel();
    test.setInputFile("C:\\Users\\mahfo\\eclipse-workspace\\Download\\uketsukebango_list.xlsx");
    test.read();
}

}


问:
What are "named tuples" in Python?

What are named tuples and how do I use them?

When should I use named tuples instead of normal tuples, or vice versa?

Are there "named lists" too? (i.e. mutable named tuples)

For the last question specifically, see also Existence of mutable named tuple in Python?.

答:
Everyone else has already answered it, but I think I still have something else to add.

Namedtuple could be intuitively deemed as a shortcut to define a class.

See a cumbersome and conventional  way to define a class .

```<code>class Duck:
    def __init__(self, color, weight):
        self.color = color
        self.weight = weight
red_duck = Duck('red', '10')

    In [50]: red_duck
    Out[50]: <__main__.Duck at 0x1068e4e10>
    In [51]: red_duck.color
    Out[51]: 'red'
</code>```

As for namedtuple

```<code>from collections import namedtuple
Duck = namedtuple('Duck', ['color', 'weight'])
red_duck = Duck('red', '10')

In [54]: red_duck
Out[54]: Duck(color='red', weight='10')
In [55]: red_duck.color
Out[55]: 'red'
</code>```

Title: What are "named tuples" in Python?

Body:
Everyone else has already answered it, but I think I still have something else to add.

Namedtuple could be intuitively deemed as a shortcut to define a class.

See a cumbersome and conventional  way to define a class .

class Duck:
    def __init__(self, color, weight):
        self.color = color
        self.weight = weight
red_duck = Duck('red', '10')

    In [50]: red_duck
    Out[50]: <__main__.Duck at 0x1068e4e10>
    In [51]: red_duck.color
    Out[51]: 'red'

As for namedtuple

from collections import namedtuple
Duck = namedtuple('Duck', ['color', 'weight'])
red_duck = Duck('red', '10')

In [54]: red_duck
Out[54]: Duck(color='red', weight='10')
In [55]: red_duck.color
Out[55]: 'red'


问:
How to include \n, \t, \r and similar items to json.loads?
I want to include \n not as newline but as a string literal in json.loads

for example, json.loads('"hello\n"')

how do i handle the \?

答:
\n is the escape sequence for line feed. Use the \\ escape sequence: json.loads('"hello\\n"')

Alternatively, use a raw string, which treats a backslash as a literal character: json.loads(r'"hello\n"')


问:
Can I break an SQL statement with JOINs into smaller queries or optimize query?
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.</p>

```<code>SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`
</code>```

答:
I think you just want conditional aggregation:</p>

```<code>SELECT qu.*,
       SUM(CASE WHEN qq.Category = 1 THEN qa.AnswerValue END) as SectionOne,
       SUM(CASE WHEN qq.Category = 2 THEN qa.AnswerValue END) as SectionTwo,
       SUM(CASE WHEN qq.Category = 3 THEN qa.AnswerValue END) as SectionThree,
       SUM(CASE WHEN qq.Category = 4 THEN qa.AnswerValue END) as SectionFour,
       SUM(CASE WHEN qq.Category = 5 THEN qa.AnswerValue END) as SectionFive
FROM wp_quiz_users qu LEFT JOIN
     wp_quiz_users_answers qa
     ON qa.UserId = q.id  LEFT JOIN
     wp_quiz_questions qq
     ON qa.QuestionId = qq.id
GROUP BY qu.UserId;
</code>```

Body:
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.

SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`

Body:
I think you just want conditional aggregation:

SELECT qu.*,
       SUM(CASE WHEN qq.Category = 1 THEN qa.AnswerValue END) as SectionOne,
       SUM(CASE WHEN qq.Category = 2 THEN qa.AnswerValue END) as SectionTwo,
       SUM(CASE WHEN qq.Category = 3 THEN qa.AnswerValue END) as SectionThree,
       SUM(CASE WHEN qq.Category = 4 THEN qa.AnswerValue END) as SectionFour,
       SUM(CASE WHEN qq.Category = 5 THEN qa.AnswerValue END) as SectionFive
FROM wp_quiz_users qu LEFT JOIN
     wp_quiz_users_answers qa
     ON qa.UserId = q.id  LEFT JOIN
     wp_quiz_questions qq
     ON qa.QuestionId = qq.id
GROUP BY qu.UserId;


问:
Doesn't Linq to SQL miss the point? Aren't ORM-mappers (SubSonic, etc.) sub-optimal solutions?
I'd like the community's take on some thoughts I've had about Linq to Sql and other ORM mappers.

I like Linq to Sql and the idea of expressing data access logic (or CRUD operations in general) in your native development tongue rather than having to deal with the "impedance mismatch" between C# and SQL.  For example, to return an ObjectDataSource-compatible list of Event instances for a business layer, we use:

```<code>return db.Events.Select(c => new EventData() { EventID = c.EventID, Title = c.Title })
</code>```

If I were to implement this using old SQL-to-C# constructs, I'd have to create a Command class, add the EventID parameter (using a string to describe the "@EventID" argument), add the SQL query string to the Command class, execute the command, and then use (cast-type)nwReader["FieldName"] to pull each returned field value and assign it to a member of a newly created instance of my EventData class (yuck).

So, that is why people like Linq/SubSonic/etc. and I agree.

However, in the bigger picture I see a number of things that are wrong.  My sense is that Microsoft also sees something wrong and that is why they are killing Linq to SQL and trying to move people to Linq to Entities.  Only, I think that Microsoft is doubling-down on a bad bet.

So, what is wrong?

The problem is that there are architecture astronauts, especially at Microsoft, who look at Linq to Sql and realize that it is not a true data management tool: there are still many things you cannot do easily of comfortably in C# and they aim to fix it.  You see this manifested in the ambitions behind Linq to Entities, blog posts about the revolutionary nature of Linq and even the LinqPad challenge.

And the problem with that is that it assumes that SQL is the problem.  That is, in order to reduce a mild discomfort (impedance mismatch between SQL and C#), Microsoft has proposed the equivalent of a space suit (full isolation) when a band-aid (Linq to SQL or something similar) would do just fine.

As far as I can see, developers are quite smart enough to master the relational model and then apply it intelligently in their development efforts.  In fact, I would go one further and say that Linq to SQL, SubSonic, etc. are already too complex: the learning curve isn't that much different from mastering SQL itself.  Since, for the foreseeable future, developers must master SQL and the relational model, we're now faced with learning two query / CRUD languages.  Worse yet, Linq is often difficult to test (you don't have a query window), removes us one layer from the real work we are doing (it generates SQL), and has very clumsy support (at best) for SQL constructs like Date handling (e.g. DateDiff), "Having" and even "Group By".

What is the alternative? Personally, I don't need a different model for data access like Linq to Entities.  I'd prefer to simply pop up a window in Visual Studio, enter and validate my SQL, and then press a button to generate or supplement a C# class to encapsulate the call.   Since you already know SQL, wouldn't you prefer to just enter something like this:

```<code>Select EventID, Title From Events Where Location=@Location
</code>```

and end up with an EventData class that A) contains the EventID and Title fields as properties and B) has a factory method that takes a 'Location' string as an argument and that generates a List<EventData>?  You'd have to think carefully about the object model (the above example obviously doesn't deal with that) but the fundamental approach of still using SQL while eliminating the impedance mismatch appeals to me a great deal.

The question is: am I wrong?  Should Microsoft rewrite the SQL infrastructure so that you don't have to learn SQL / relational data management any more?  Can they rewrite the SQL infrastructure in this way? Or do you think that a very thin layer on top of SQL to eliminate the pain of setting up parameters and accessing data fields is quite sufficient?

Update I wanted to promote two links to the top because I think that they capture important aspects of what I am after.  First, CodeMonkey points out an article entitled "The Vietnam of Computer Science."  It takes a while to get started but is a very interesting read.  Second, AnSGri points to one of Joel Spolsky's more prominent pieces: The Law of Leaky Abstractions. It isn't exactly on topic but it is close and is a great read.

Update 2: I've given the "answer" to ocdecio although there are many great answers here and the choice of the "right" answer is purely subjective. In this case, his answer squared with what I think is truly the best practice given the current state of technology.  This is an area that I fully expect to evolve, however, so things may well change.  I'd like to thank everyone who contributed, I've upvoted everyone who I think gave a thoughtful answer.

答:
Dmitry's statement that Developer's don't like SQL may have lot of truth but the solution isn't only ORM. The solution is to hire as part of the development team a Development DBA. In my company my .net development team has an excellent Oracle DBA who does absolutely no production dba work. His role in our team is data modelling, physical db design, creating stored procs, data analysis etc. He is the reason our db side is so clean and performing. All our DB access is via stored procs.

What is a development DBA ?
http://www.simple-talk.com/sql/database-administration/what-use-is-a-development-dba/

OwnerDisplayName: Mark Brittingham

Body:
I'd like the community's take on some thoughts I've had about Linq to Sql and other ORM mappers.

I like Linq to Sql and the idea of expressing data access logic (or CRUD operations in general) in your native development tongue rather than having to deal with the "impedance mismatch" between C# and SQL.  For example, to return an ObjectDataSource-compatible list of Event instances for a business layer, we use:

return db.Events.Select(c => new EventData() { EventID = c.EventID, Title = c.Title })

If I were to implement this using old SQL-to-C# constructs, I'd have to create a Command class, add the EventID parameter (using a string to describe the "@EventID" argument), add the SQL query string to the Command class, execute the command, and then use (cast-type)nwReader["FieldName"] to pull each returned field value and assign it to a member of a newly created instance of my EventData class (yuck).

So, that is why people like Linq/SubSonic/etc. and I agree.

However, in the bigger picture I see a number of things that are wrong.  My sense is that Microsoft also sees something wrong and that is why they are killing Linq to SQL and trying to move people to Linq to Entities.  Only, I think that Microsoft is doubling-down on a bad bet.

So, what is wrong?

The problem is that there are architecture astronauts, especially at Microsoft, who look at Linq to Sql and realize that it is not a true data management tool: there are still many things you cannot do easily of comfortably in C# and they aim to fix it.  You see this manifested in the ambitions behind Linq to Entities, blog posts about the revolutionary nature of Linq and even the LinqPad challenge.

And the problem with that is that it assumes that SQL is the problem.  That is, in order to reduce a mild discomfort (impedance mismatch between SQL and C#), Microsoft has proposed the equivalent of a space suit (full isolation) when a band-aid (Linq to SQL or something similar) would do just fine.

As far as I can see, developers are quite smart enough to master the relational model and then apply it intelligently in their development efforts.  In fact, I would go one further and say that Linq to SQL, SubSonic, etc. are already too complex: the learning curve isn't that much different from mastering SQL itself.  Since, for the foreseeable future, developers must master SQL and the relational model, we're now faced with learning two query / CRUD languages.  Worse yet, Linq is often difficult to test (you don't have a query window), removes us one layer from the real work we are doing (it generates SQL), and has very clumsy support (at best) for SQL constructs like Date handling (e.g. DateDiff), "Having" and even "Group By".

What is the alternative? Personally, I don't need a different model for data access like Linq to Entities.  I'd prefer to simply pop up a window in Visual Studio, enter and validate my SQL, and then press a button to generate or supplement a C# class to encapsulate the call.   Since you already know SQL, wouldn't you prefer to just enter something like this:

Select EventID, Title From Events Where Location=@Location

and end up with an EventData class that A) contains the EventID and Title fields as properties and B) has a factory method that takes a 'Location' string as an argument and that generates a List<EventData>?  You'd have to think carefully about the object model (the above example obviously doesn't deal with that) but the fundamental approach of still using SQL while eliminating the impedance mismatch appeals to me a great deal.

The question is: am I wrong?  Should Microsoft rewrite the SQL infrastructure so that you don't have to learn SQL / relational data management any more?  Can they rewrite the SQL infrastructure in this way? Or do you think that a very thin layer on top of SQL to eliminate the pain of setting up parameters and accessing data fields is quite sufficient?

Update I wanted to promote two links to the top because I think that they capture important aspects of what I am after.  First, CodeMonkey points out an article entitled "The Vietnam of Computer Science."  It takes a while to get started but is a very interesting read.  Second, AnSGri points to one of Joel Spolsky's more prominent pieces: The Law of Leaky Abstractions. It isn't exactly on topic but it is close and is a great read.

Update 2: I've given the "answer" to ocdecio although there are many great answers here and the choice of the "right" answer is purely subjective. In this case, his answer squared with what I think is truly the best practice given the current state of technology.  This is an area that I fully expect to evolve, however, so things may well change.  I'd like to thank everyone who contributed, I've upvoted everyone who I think gave a thoughtful answer.

LastEditorDisplayName: Mark Brittingham

OwnerDisplayName: kanad


问:
Can we set type from interface for a variable in typescript?
Below is my code

```<code>interface apiResult {
    Token: string;
    Result: any;
}

const result: apiResult = payload.Result;
</code>```

What is this code mean?
Can we set type from interface to a variable?

答:
The interface is used to define what your TS class can receive so here the interface is defined as apiResult can accept a token which is a string and a Result of any type (dynamic).
If you need to strongly type a variable from the interface it should be done with a model

```<code>Result: ResultModel;
</code>```

then define your ResultModel

example:

```<code>export class ResultModel {

//Fields
id: number
documentId: number
someProperty?: string

constructor (id: number, documentId: number){
   this.id = id
   this.documentId = documentId
}}
</code>```

Here you build a model that states id and documentId must be populated where someProperty is nullable/optional

Body:
Below is my code

interface apiResult {
    Token: string;
    Result: any;
}

const result: apiResult = payload.Result;

What is this code mean?
Can we set type from interface to a variable?

Body:
The interface is used to define what your TS class can receive so here the interface is defined as apiResult can accept a token which is a string and a Result of any type (dynamic).
If you need to strongly type a variable from the interface it should be done with a model

Result: ResultModel;

then define your ResultModel

example:

export class ResultModel {

//Fields
id: number
documentId: number
someProperty?: string

constructor (id: number, documentId: number){
   this.id = id
   this.documentId = documentId
}}

Here you build a model that states id and documentId must be populated where someProperty is nullable/optional


问:
I have an If statement that isn't behaving like I expect it too, maybe I'm stacking it wrong?
I have an if/then statement that is not behaving as such. My level of expertise is about 1/10.

I'm trying to take a user input value and give a variable output
depending on the value.

My script gives me 10, which is each function returning 5, which is wrong

```<code> def abs_func():
    plank_input = raw_input("How long can you hold a plank?:")
    situps_input = raw_input("How many situps can you do?:")

#checking the input we just recieved
    print "Plank Input:",plank_input
    print "Situps Input:",situps_input

#This Checks the plank time against my values.
    def abs_char1(plank):
        global abs_rate1
        if plank >= 120:
            abs_rate1 =+ 5
        else:
            if plank >= 90:
                abs_rate1 =+ 4
            else:
                if plank >= 60:
                    abs_rate1 =+ 3
                else:
                    abs_rate1 =+ 2
        print "Abs 1:",abs_rate1
        return abs_rate1

#This Checks the plank time against my values.
    def abs_char2(situps):
        global abs_rate2

        if situps >= 120:
            abs_rate2 =+ 5
        else:
            if situps >= 100:
                abs_rate2 =+ 4
            else:
                if situps >= 80:
                    abs_rate2 =+ 3
                else:
                    abs_rate2 =+ 2
        print "Abs 2:", abs_rate2
        return abs_rate2

    a1 = abs_char1(plank_input)
    a2 = abs_char2(situps_input)

    print "a1:",a1,"a2:",a2
    abs_rate = a1 + a2
    print abs_rate

abs_func()
</code>```

I want it to spit out the correct values, like 3 and 4, totaling 7.

But, it always prints out 5 and 5, totaling 10 and I don't know why...

答:
I guess you are not using Python 3, cause raw_input is just renamed input() in Python 3. When I tried running your code with input(), it had a bunch of problems because you are comparing a string value (input() returns a string) to an integer value (120 for example).

Try fixing this for the time being and keep us posted with your new results. :)

Body:
I have an if/then statement that is not behaving as such. My level of expertise is about 1/10.

I'm trying to take a user input value and give a variable output
depending on the value.

My script gives me 10, which is each function returning 5, which is wrong

 def abs_func():
    plank_input = raw_input("How long can you hold a plank?:")
    situps_input = raw_input("How many situps can you do?:")

#checking the input we just recieved
    print "Plank Input:",plank_input
    print "Situps Input:",situps_input

#This Checks the plank time against my values.
    def abs_char1(plank):
        global abs_rate1
        if plank >= 120:
            abs_rate1 =+ 5
        else:
            if plank >= 90:
                abs_rate1 =+ 4
            else:
                if plank >= 60:
                    abs_rate1 =+ 3
                else:
                    abs_rate1 =+ 2
        print "Abs 1:",abs_rate1
        return abs_rate1

#This Checks the plank time against my values.
    def abs_char2(situps):
        global abs_rate2

        if situps >= 120:
            abs_rate2 =+ 5
        else:
            if situps >= 100:
                abs_rate2 =+ 4
            else:
                if situps >= 80:
                    abs_rate2 =+ 3
                else:
                    abs_rate2 =+ 2
        print "Abs 2:", abs_rate2
        return abs_rate2

    a1 = abs_char1(plank_input)
    a2 = abs_char2(situps_input)

    print "a1:",a1,"a2:",a2
    abs_rate = a1 + a2
    print abs_rate

abs_func()

I want it to spit out the correct values, like 3 and 4, totaling 7.

But, it always prints out 5 and 5, totaling 10 and I don't know why...


问:
r googlesheets package Waiting for authentication in browser
I installed the googlesheets package and

```<code>code:
gs_auth()
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
</code>```

The browser pop up in a blank website, it is not go to the google auth page.

Below is my session_info():

```<code>R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS:
</code>```

/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

```<code>locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] googlesheets_0.2.2       Rcpp_0.12.14             ggplot2_2.2.1
quantmod_0.4-11
 [5] TTR_0.23-2               xts_0.10-0               zoo_1.8-0
dplyr_0.7.4
 [9] data.table_1.10.4-3      bindrcpp_0.2
alphavantager_0.1.0.9000 devtools_1.13.4

loaded via a namespace (and not attached):
 [1] cellranger_1.1.0 compiler_3.4.2   git2r_0.19.0     plyr_1.8.4
bindr_0.1
 [6] tools_3.4.2      digest_0.6.12    jsonlite_1.5     memoise_1.1.0
tibble_1.3.4
[11] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.4
curl_3.0
[16] xml2_1.1.1       withr_2.1.0      httr_1.3.1       stringr_1.2.0
knitr_1.17
[21] hms_0.4.0        grid_3.4.2       glue_1.2.0       R6_2.2.2
purrr_0.2.4
[26] readr_1.1.1      magrittr_1.5     scales_0.5.0
assertthat_0.2.0 colorspace_1.3-2
[31] httpuv_1.3.5     stringi_1.1.6    openssl_0.9.9    lazyeval_0.2.1
munsell_0.4.3
</code>```

I have checked my httr package is updated, so I have not idea where the problem is. please advice.

Thanks.

答: It is the chrome browser issue rather than any R packages, I have tested in Firefox and safari in Mac which can successfully connected the google sheets.</p>

Body:
I installed the googlesheets package and

code:
gs_auth()
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort

The browser pop up in a blank website, it is not go to the google auth page.

Below is my session_info():

R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.1

Matrix products: default
BLAS:

/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] googlesheets_0.2.2       Rcpp_0.12.14             ggplot2_2.2.1
quantmod_0.4-11
 [5] TTR_0.23-2               xts_0.10-0               zoo_1.8-0
dplyr_0.7.4
 [9] data.table_1.10.4-3      bindrcpp_0.2
alphavantager_0.1.0.9000 devtools_1.13.4

loaded via a namespace (and not attached):
 [1] cellranger_1.1.0 compiler_3.4.2   git2r_0.19.0     plyr_1.8.4
bindr_0.1
 [6] tools_3.4.2      digest_0.6.12    jsonlite_1.5     memoise_1.1.0
tibble_1.3.4
[11] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.1  rlang_0.1.4
curl_3.0
[16] xml2_1.1.1       withr_2.1.0      httr_1.3.1       stringr_1.2.0
knitr_1.17
[21] hms_0.4.0        grid_3.4.2       glue_1.2.0       R6_2.2.2
purrr_0.2.4
[26] readr_1.1.1      magrittr_1.5     scales_0.5.0
assertthat_0.2.0 colorspace_1.3-2
[31] httpuv_1.3.5     stringi_1.1.6    openssl_0.9.9    lazyeval_0.2.1
munsell_0.4.3

I have checked my httr package is updated, so I have not idea where the problem is. please advice.

Thanks.