问:
Select element with selenium python
Consider the following HTML:

```<code> <div class="nav-category__col" id="category_nav_level_3" style="display: block;">
   <input type="hidden" value="1" name="videogame_type" id="videogame_type">
   <ul class="nav-category__list" adparam_name="videogame_type" role="radiogroup">
      <li class="nav-category__list-item  nav-category__list-item--selected" id="1" tabindex="-1" role="radio" aria-checked="true">
         <p class="nav-category__name">Consoles</p>
      </li>
      <li class="nav-category__list-item " id="2" tabindex="-1" role="radio" aria-checked="false">
         <p class="nav-category__name">Jogos</p>
      </li>
      <li class="nav-category__list-item " id="3" tabindex="-1" role="radio" aria-checked="false">
         <p class="nav-category__name">Acessórios</p>
      </li>
   </ul>
</div>
</code>```

I want to click on
Consoles
 so I tried doing this:

```<code>    elem = driver.find_element_by_xpath("//*[@id="1"]/p")
    elem.click()
</code>```

I found this xpath by inspecting the element and copying the xpath from it, but it says "Unable to locate element" anyway. How could I do it right?

I don't know very much of HTML, but I am capable of finding other elements by id or by name.

答:
I would recommend not to use time.sleep() in your script
Because it pause your script for fix  time duration even if your element is available to use in less then given time.

Lets say you have put time.sleep(5) So here it exactly pause your script for 5 seconds even if your element is available within 2 seconds.

Better way to overcome this situation use either Implicit Wait or Explicit Wait

Implicit Wait -

An implicit wait tells WebDriver to poll the DOM for a certain amount
  of time when trying to find any element (or elements) not immediately
  available.

```<code>driver.implicitly_wait(10) # seconds
</code>```

Explicit Wait -

An explicit wait is code you define to wait for a certain condition to
  occur before proceeding further in the code.

```<code>element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "id"))
</code>```

Please refer this for further.

Title: Select element with selenium python

Body:
Consider the following HTML:

   <input type="hidden" value="1" name="videogame_type" id="videogame_type">

Consoles

Jogos

Acessórios

I want to click on
Consoles
 so I tried doing this:

    elem = driver.find_element_by_xpath("//*[@id="1"]/p")
    elem.click()

I found this xpath by inspecting the element and copying the xpath from it, but it says "Unable to locate element" anyway. How could I do it right?

I don't know very much of HTML, but I am capable of finding other elements by id or by name.

Body:
I would recommend not to use time.sleep() in your script
Because it pause your script for fix  time duration even if your element is available to use in less then given time.

Lets say you have put time.sleep(5) So here it exactly pause your script for 5 seconds even if your element is available within 2 seconds.

Better way to overcome this situation use either Implicit Wait or Explicit Wait

Implicit Wait -

An implicit wait tells WebDriver to poll the DOM for a certain amount
  of time when trying to find any element (or elements) not immediately
  available.

driver.implicitly_wait(10) # seconds

Explicit Wait -

An explicit wait is code you define to wait for a certain condition to
  occur before proceeding further in the code.

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "id"))

Please refer this for further.


来源: stackexchange

问:
SQL Server query update child node based on parent records
I am trying to query data with the following structure in a SQL Server table
'tableA' with column 'node' (varchar) and 'destination' (bit). The data in the node column is based on parent/child relationship. Row child: 1001111001 has all these rows/nodes as parents (100111100, 10011110, 1001111, 100111, 10011, 1001, 100, 10, 1). I would like to accomplish the following in a store procedure on sql server

1- Retrieve all parents of a child node.

2- Update destination of child row if all parent destination are equal to 0

答:
try this:::</p>

```<code>CREATE PROCEDURE UP_PROCEURENAME
@tablename varchar(30)
AS
BEGIN
 DECLARE @cnt INT = 1
 WHILE @cnt < len(destination)
 (select left(destination, len(destination)-@cnt) AS Parents from @tablename
 set @cnt = @cnt + 1)
 END LOOP
 GO
 IF(LEFT(destination,LEN(destination)-1) = 0)
   UPDATE @tablename
   SET destination =   ------YOUR UPDATE STATEMENT
END

EXEC UP_PROCEURENAME TableA
</code>```

ContentLicense: CC BY-SA 3.0

Body:
try this:::

CREATE PROCEDURE UP_PROCEURENAME
@tablename varchar(30)
AS
BEGIN
 DECLARE @cnt INT = 1
 WHILE @cnt < len(destination)
 (select left(destination, len(destination)-@cnt) AS Parents from @tablename
 set @cnt = @cnt + 1)
 END LOOP
 GO
 IF(LEFT(destination,LEN(destination)-1) = 0)
   UPDATE @tablename
   SET destination =   ------YOUR UPDATE STATEMENT
END

EXEC UP_PROCEURENAME TableA


问:
How to get the process ID to kill a nohup process?
I'm running a nohup process on the server. When I try to kill it my putty console closes instead.

this is how I try to find the process ID:

```<code>ps -ef |grep nohup
</code>```

this is the command to kill

```<code> kill -9 1787 787
</code>```

答:
I started django server with the following command.

```<code>nohup manage.py runserver <localhost:port>
</code>```

This works on CentOS:

```<code>:~ ns$netstat -ntlp
:~ ns$kill -9 PID
</code>```

Body:
I'm running a nohup process on the server. When I try to kill it my putty console closes instead.

this is how I try to find the process ID:

ps -ef |grep nohup

this is the command to kill

 kill -9 1787 787

Body:
I started django server with the following command.

nohup manage.py runserver <localhost:port>

This works on CentOS:

:~ ns$netstat -ntlp
:~ ns$kill -9 PID


问:
Group html between heading tags in javascript
I have an html page with headings. I want to group the content (html) which is under the heading using javascript or any native library. How can I do that?
Example is below </p>

```<code><div>
  <h2>Main</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main2</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main3</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
</div>
</code>```

<p>Output should be </p>

```<code><div>
  <div>
    <h2>Main</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
  <div>
    <h2>Main2</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
  <div>
    <h2>Main3</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
</div>
</code>```

答:
This should do what you need

Main

 Content goes here

Main2

 Content goes here

Main3

 Content goes here

```

Body:
I have an html page with headings. I want to group the content (html) which is under the heading using javascript or any native library. How can I do that?
Example is below

Main

 Content goes here

Main2

 Content goes here

Main3

 Content goes here

Output should be

Main

 Content goes here

Main2

 Content goes here

Main3

 Content goes here

Body:
This should do what you need

<div>
  <h2 style="margin-bottom: 0;">Main</h2>
  <p style="margin-top: 0;"> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2 style="margin-bottom: 0;">Main2</h2>
  <p style="margin-top: 0;"> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2 style="margin-bottom: 0;">Main3</h2>
  <p style="margin-top: 0;"> Content goes here</p>
  <img src="someimg.jpg"/>
</div>


问:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined
I'm using spring boot version 1.3.5.RELEASE for my app. When I configure the data source it will throw some exceptions. It is showing org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined.

application.properties

```<code>library.datasource.driver-class-name = com.mysql.jdbc.Driver
library.datasource.url = jdbc:mysql://192.168.0.188:3306/library_keycloak?autoReconnect=true
library.datasource.username = jijesh
library.datasource.password = jijesh

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.validationQuery = SELECT 1

# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.max-active=50

# Validate the connection before borrowing it from the pool.
spring.datasource.test-on-borrow=true

# Show or not log for each sql query
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
spring.jpa.hibernate.hikari.minimumIdle=5
spring.jpa.hibernate.hikari.maximumPoolSize=10

# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
hibernate.temp.use_jdbc_metadata_defaults = false
#Hibernate ddl auto (create, create-drop, update)
 #spring.jpa.hibernate.ddl-auto = update
#spring.jpa.hibernate.ddl-auto = create-drop
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
</code>```

DB Config

```<code>@Configuration
@ComponentScan("com.appscook.library.service")
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "libraryEntityManagerFactory",
        transactionManagerRef = "libraryTransactionManager",
        basePackages = "com.appscook.library.*")
public class LibraryDBConfig {
      @Bean
      @Primary
      @ConfigurationProperties(prefix = "library.datasource")
      public DataSource hrmsDataSource()
      {
        return DataSourceBuilder.create().build();
      }

      @Bean
      public LocalContainerEntityManagerFactoryBean hrmsEntityManagerFactory(final EntityManagerFactoryBuilder builder)
      {
        return builder
            .dataSource(hrmsDataSource())
            .packages("com.appscook.library.domain")
            .persistenceUnit("libraryPersistenceUnit")
            .build();
      }

      @Bean
      public JpaTransactionManager hrmsTransactionManager(@Qualifier("libraryEntityManagerFactory") final EntityManagerFactory factory)
      {
        return new JpaTransactionManager(factory);
      }
}
</code>```

stacktrace

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2424cb9d': Cannot resolve reference to bean 'libraryEntityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:444) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    ... 45 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
</code>```

答:
Found answer </p>

```<code> @Bean
      public LocalContainerEntityManagerFactoryBean hrmsEntityManagerFactory(final EntityManagerFactoryBuilder builder)
      {
        return builder
            .dataSource(hrmsDataSource())
            .packages("com.appscook.library.domain")
            .persistenceUnit("libraryPersistenceUnit")
            .build();
      }
</code>```

<p>to </p>

```<code> @Bean
      public LocalContainerEntityManagerFactoryBean  libraryEntityManagerFactory(final EntityManagerFactoryBuilder builder)
      {
        return builder
            .dataSource(hrmsDataSource())
            .packages("com.appscook.library.domain")
            .persistenceUnit("libraryPersistenceUnit")
            .build();
      }
</code>```

Body:
I'm using spring boot version 1.3.5.RELEASE for my app. When I configure the data source it will throw some exceptions. It is showing org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined.

application.properties

library.datasource.driver-class-name = com.mysql.jdbc.Driver
library.datasource.url = jdbc:mysql://192.168.0.188:3306/library_keycloak?autoReconnect=true
library.datasource.username = jijesh
library.datasource.password = jijesh

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 60000
spring.datasource.validationQuery = SELECT 1

# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.max-active=50

# Validate the connection before borrowing it from the pool.
spring.datasource.test-on-borrow=true

# Show or not log for each sql query
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
spring.jpa.hibernate.hikari.minimumIdle=5
spring.jpa.hibernate.hikari.maximumPoolSize=10

# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
hibernate.temp.use_jdbc_metadata_defaults = false
#Hibernate ddl auto (create, create-drop, update)
 #spring.jpa.hibernate.ddl-auto = update
#spring.jpa.hibernate.ddl-auto = create-drop
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

DB Config

@Configuration
@ComponentScan("com.appscook.library.service")
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "libraryEntityManagerFactory",
        transactionManagerRef = "libraryTransactionManager",
        basePackages = "com.appscook.library.*")
public class LibraryDBConfig {
      @Bean
      @Primary
      @ConfigurationProperties(prefix = "library.datasource")
      public DataSource hrmsDataSource()
      {
        return DataSourceBuilder.create().build();
      }

      @Bean
      public LocalContainerEntityManagerFactoryBean hrmsEntityManagerFactory(final EntityManagerFactoryBuilder builder)
      {
        return builder
            .dataSource(hrmsDataSource())
            .packages("com.appscook.library.domain")
            .persistenceUnit("libraryPersistenceUnit")
            .build();
      }

      @Bean
      public JpaTransactionManager hrmsTransactionManager(@Qualifier("libraryEntityManagerFactory") final EntityManagerFactory factory)
      {
        return new JpaTransactionManager(factory);
      }
}

stacktrace

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2424cb9d': Cannot resolve reference to bean 'libraryEntityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:634) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:444) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    ... 45 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'libraryEntityManagerFactory' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]

Body:
Found answer

 @Bean
      public LocalContainerEntityManagerFactoryBean hrmsEntityManagerFactory(final EntityManagerFactoryBuilder builder)
      {
        return builder
            .dataSource(hrmsDataSource())
            .packages("com.appscook.library.domain")
            .persistenceUnit("libraryPersistenceUnit")
            .build();
      }

to

 @Bean
      public LocalContainerEntityManagerFactoryBean  libraryEntityManagerFactory(final EntityManagerFactoryBuilder builder)
      {
        return builder
            .dataSource(hrmsDataSource())
            .packages("com.appscook.library.domain")
            .persistenceUnit("libraryPersistenceUnit")
            .build();
      }


问:
Count level within group_by hierarchy in dplyr
I have a large data set in R that is organised with multiple records from individual cases, nested within groups. A toy example is here:

```<code>d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))
</code>```

If in a dplyr chain, group_by(group, case) is applied, how can a column be created that numbers each row with the order of its case within the group? e.g. in the example below, in the third column, case 'a' is the first case in the control group, and case 'c' the third, but the numbering resets to 1 for case 'd', the first case in the patient group.

```<code>  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2
</code>```

I can see how this would be done by counting cases using a 'for' loop, but am wondering if there is a way to achieve this within a standard dplyr-style chain of operations?

答:
```<code>group_by(d, group) %>%
   mutate(number= droplevels(case) %>% as.numeric)
</code>```

Body:
I have a large data set in R that is organised with multiple records from individual cases, nested within groups. A toy example is here:

d = data.frame(group = rep(c('control','patient'), each = 5), case = c('a', 'a', 'b', 'c', 'c', 'd','d','d','e','e'))

If in a dplyr chain, group_by(group, case) is applied, how can a column be created that numbers each row with the order of its case within the group? e.g. in the example below, in the third column, case 'a' is the first case in the control group, and case 'c' the third, but the numbering resets to 1 for case 'd', the first case in the patient group.

  group case  number
control  a    1
control  a    1
control  b    2
control  c    3
control  c    3
patient  d    1
patient  d    1
patient  d    1
patient  e    2
patient  e    2

I can see how this would be done by counting cases using a 'for' loop, but am wondering if there is a way to achieve this within a standard dplyr-style chain of operations?


问:
ActionCable, Heroku Custom Domain, & Cookies
Here's the scenario. I'm using ActionCable for a site (let's call it www.example.com). It's works perfect in dev, but once I push it to Heroku, I'm getting 302 errors for the WebSocket connection.

The problem seems to stem from the fact that I have Heroku using a custom domain. Because of this, if I point the WebSocket to wss://example.com, it gives me a 302, I'm assuming because it's being redirected to the example.herokuapp.com url?

So in light of this issue, I was forced to instead point the WebSocket connection to wss://example.herokuapp.com. The problem that I'm running into now is that because it's essentially a new domain I'm pointing at, the cookies from example.com are not shared with example.herokuapp.com. This means that example.herokuapp.com is passing a blank cookie that is actually being set on example.com that I use for authentication.

I verified this is the issue by logging the unsigned cookie (just temporarily unsigned for testing, don't freak out about security), and also setting that cookie on the example.herokuapp.com server. After that it worked beautifully.

Obviously I can't have someone go to both sites just to set a damn cookie...

What I would love is to find a way to fix the original issue and be able to point the WebSocket at my custom domain of wss://example.com and not have to worry about cookie signing issues. Is this possible?

If not, what would be the best way to set the cookie on the example.herokuapp.com domain?

P.S. yes I have looked at other SO questions about ActionCable & Heroku, but none seem to deal with Custom domains. This one talks about a cookie workaround, but I don't feel like it would work with this scenario since they aren't the same subdomains: Deploying Ruby on Rails app to Heroku while using Action Cable (Puma port listening)

Thanks for taking the time to help me out guys :)

[EDIT] It seems very similar to this question here, but I'm getting a 302 not a 503. Heroku error 503, webSockets on multiple domains

答:
I have been struggling with the exact same setup. If you are using devise you can get the user id from env['warden'].user.id (which is only set once you are successfully logged in) rather than from a signed cookie.

i.e. in your connection do something like:

```<code>module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
      def find_verified_user
        # if verified_user = User.find_by(id: cookies.signed[:user_channel_key])
        if verified_user = User.find_by(id: env['warden'].user.id)
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end
</code>```

Body:
I have been struggling with the exact same setup. If you are using devise you can get the user id from env['warden'].user.id (which is only set once you are successfully logged in) rather than from a signed cookie.

i.e. in your connection do something like:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
      def find_verified_user
        # if verified_user = User.find_by(id: cookies.signed[:user_channel_key])
        if verified_user = User.find_by(id: env['warden'].user.id)
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end


问:
Crud API post, put and delete
I am trying this PHP-CRUD api, but how do I use it to post? Is it via URL like:

```<code>localhost/hris/api.php/employee_details/create?id=2&name=john
</code>```

or I'm using it the wrong way?

Or the long way?

```<code>$url = 'http://localhost/hris/api.php/login';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'emp_id' => '2017-0007',
    'username' => 'jabril',
    'password' => 'Donor2017',
    'type' => 'admin'
);

$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);
</code>```

I've also tried this

```<code>require('crud.php');

function call($method, $url, $data = false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $url);
if ($data) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Content-Length: ' . strlen($data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return curl_exec($ch);
}

$object = array('emp_id'=>'2017-0007','username'=>'jabril','password'=>'Donor2017','type'=>'');
$posting = call('POST', 'http://localhost/api.php/login',json_encode($object));
</code>```

答: json_encode looks correct, are you facing some issues if any please share..</p>

Title: Crud API post, put and delete

Body:
I am trying this PHP-CRUD api, but how do I use it to post? Is it via URL like:

localhost/hris/api.php/employee_details/create?id=2&name=john

or I'm using it the wrong way?

Or the long way?

$url = 'http://localhost/hris/api.php/login';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'emp_id' => '2017-0007',
    'username' => 'jabril',
    'password' => 'Donor2017',
    'type' => 'admin'
);

$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);

I've also tried this

require('crud.php');

function call($method, $url, $data = false) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $url);
if ($data) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Content-Length: ' . strlen($data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return curl_exec($ch);
}

$object = array('emp_id'=>'2017-0007','username'=>'jabril','password'=>'Donor2017','type'=>'');
$posting = call('POST', 'http://localhost/api.php/login',json_encode($object));


问:
FFMPEG set -ss and -to with string
I know I can set the start with -ss and end with -to but can someone please help me to format the following so that I can enter the -ss and -to with a string?

I want -ss to come from

```<code>String start = editStart.getText().toString();
</code>```

and -to to come from

```<code>String end = editEnd.getText().toString();
</code>```

Here is my ffmpeg string I want to edit, I have entered -ss and -to to show where I want the above strings to be.

```<code>String s = "-i" + " " + mVideoUri.toString().replace("file:///", "") + " -filter_complex [1:v][0:v]scale2ref=iw:ih[ovr][base];[ovr]colorchannelmixer=aa=0.7[ovrl];[base][ovrl]overlay[v] -ss -to -map [v]" + directoryToStore + "/" + FileName + mp4;

String[] arguments = s.split(" ");

ExecuteFFMPEG(arguments);
</code>```

答:
Ok so you get your start and end point from:

```<code>String start = editStart.getText().toString();
String end = editEnd.getText().toString();
</code>```

So instead of splitting the argument do this instead:

```<code>String[] s = {"-i" ,mVideoUri.toString(),"-filter_complex","[1:v][0:v]scale2ref=iw:ih[ovr][base];[ovr]colorchannelmixer=aa=0.7[ovrl];[base][ovrl]overlay[v]","-ss","start","-to","end","-map","[v]",directoryToStore+"/"+"output.mp4"};
ExecuteFFMPEG(s);
</code>```

Title: FFMPEG set -ss and -to with string

Body:
I know I can set the start with -ss and end with -to but can someone please help me to format the following so that I can enter the -ss and -to with a string?

I want -ss to come from

String start = editStart.getText().toString();

and -to to come from

String end = editEnd.getText().toString();

Here is my ffmpeg string I want to edit, I have entered -ss and -to to show where I want the above strings to be.

String s = "-i" + " " + mVideoUri.toString().replace("file:///", "") + " -filter_complex [1:v][0:v]scale2ref=iw:ih[ovr][base];[ovr]colorchannelmixer=aa=0.7[ovrl];[base][ovrl]overlay[v] -ss -to -map [v]" + directoryToStore + "/" + FileName + mp4;

String[] arguments = s.split(" ");

ExecuteFFMPEG(arguments);

Body:
Ok so you get your start and end point from:

String start = editStart.getText().toString();
String end = editEnd.getText().toString();

So instead of splitting the argument do this instead:

String[] s = {"-i" ,mVideoUri.toString(),"-filter_complex","[1:v][0:v]scale2ref=iw:ih[ovr][base];[ovr]colorchannelmixer=aa=0.7[ovrl];[base][ovrl]overlay[v]","-ss","start","-to","end","-map","[v]",directoryToStore+"/"+"output.mp4"};
ExecuteFFMPEG(s);


问:
PHP - Read text from captcha image
How I Can in php read text from image file?
Example images: http://imgur.com/a/tv1Bg

Technology? Library?

Thanks

答: Damn, It's a security check that is not machine readable easily, just to prevent from some bad robots and malicious hackers from wreaking havoc on a site's infrastructure. But there are plenty of scripts for generating those captcha images with PHP, I didn't find any for reading them yet</p>

Title: PHP - Read text from captcha image


问:
SHA1 signature could not be verified: broken signature (Composer Error)
my composer gives that error. I searched but i could not find anything.

Here is an image from error.

composer_error_screenshot

Fatal error: Uncaught exception 'PharException' with message 'phar "C:\ProgramData\ComposerSetup\bin\composer.phar" SHA1 signature could not be verified: broken signature' in C:\ProgramData\Co
  mposerSetup\bin\composer.phar on line 24
  PharException: phar "C:\ProgramData\ComposerSetup\bin\composer.phar" SHA1 signature could not be verified: broken signature in C:\ProgramData\ComposerSetup\bin\composer.phar on line 24
  Call Stack:
      0.0082     233920   1. {main}() C:\ProgramData\ComposerSetup\bin\composer.phar:0
      0.0084     234080   2. Phar::mapPhar() C:\ProgramData\ComposerSetup\bin\composer.phar:24

Waiting for your suggestions..

Thanks.

答: Uninstall composer from control panel and install it again.</p>


问:
Laravel : Call to a member function where() on float
I was trying to find sum of different column using Query Builder.
Here is Query :

```<code>   DB::table('carts')
           ->sum(\DB::raw('carts.price+COALESCE(carts.support,0)+COALESCE(carts.installation,0)' ))
           ->where('status','=',1)
           ->where('user_id','=',$id);
</code>```

But when i dd() the output i got the above Error.ie,

Call to a member function where() on float

How do i avoid that?

答:
You should call sum at the end of the query:

```<code>DB::table('carts')
   ->where('status', 1)
   ->where('user_id', $id)
   ->sum(\DB::raw(
       'carts.price
       + COALESCE(carts.support, 0)
       + COALESCE(carts.installation, 0)'
   ));
</code>```

Body:
I was trying to find sum of different column using Query Builder.
Here is Query :

   DB::table('carts')
           ->sum(\DB::raw('carts.price+COALESCE(carts.support,0)+COALESCE(carts.installation,0)' ))
           ->where('status','=',1)
           ->where('user_id','=',$id);

But when i dd() the output i got the above Error.ie,

Call to a member function where() on float

How do i avoid that?

Body:
You should call sum at the end of the query:

DB::table('carts')
   ->where('status', 1)
   ->where('user_id', $id)
   ->sum(\DB::raw(
       'carts.price
       + COALESCE(carts.support, 0)
       + COALESCE(carts.installation, 0)'
   ));


问:
How to add scrollbars in c# form
For some reason only adding a vertical scroll bar works with my code.

I can't seem to add BOTH a vertical and horizontal scroll bar.

```<code>private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox1.ScrollBars = ScrollBars.Vertical;
}
</code>```

答: you don't need to write a code for this. Just change the properties of textBox. For both scroll bars, if Multiline set to True, then  set ScrollBars to Both and set WordWrap to False in properties. No need for writing code at all since this is for WinForms.</p>

Title: How to add scrollbars in c# form

Body:
For some reason only adding a vertical scroll bar works with my code.

I can't seem to add BOTH a vertical and horizontal scroll bar.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox1.ScrollBars = ScrollBars.Vertical;
}


问:
jQuery plus minus toggle
I am trying to implement plus/minus icons in a the datagrid using jQuery. On expand, minus icon is coming but on collapse the plus icon is not coming back.

Here is the implementation: http://jsfiddle.net/pixelfx/3fwyf/10/

Can anyone please look into the code.

ContentLicense: CC BY-SA 2.5

Title: jQuery plus minus toggle

Body:
Replace

$('.minus').show();
$('.add').hide();

with

$('.minus').toggle();
$('.add').toggle();


问:
Lost connection to MySQL server at 'reading initial communication packet', system error: 0
I am getting error:

"Lost connection to MySQL server at 'reading initial communication packet, system error: 0"

while I am going to connect my db.

If I am using localhost everything is working fine.
But when I am using my live IP address like below, it's getting error:

```<code>mysql_connect("202.131.xxx.106:xxxx", "xxxx", "xxxxx") or die(mysql_error());
</code>```

答:
Database directory read-write permission also a problem i found.
Just make sure your application is able to rw files on db location. Try chmod 777 for testing.</p>

Body:
I am getting error:

"Lost connection to MySQL server at 'reading initial communication packet, system error: 0"

while I am going to connect my db.

If I am using localhost everything is working fine.
But when I am using my live IP address like below, it's getting error:

mysql_connect("202.131.xxx.106:xxxx", "xxxx", "xxxxx") or die(mysql_error());


问:
ppt paste from excel clipboard to slide
I have a chart range copied from excel. Now I want to paste it as picture in slide 5 of active presentation, but it is giving me below error.

"Shapes(unknown member):Invalid request.Clipboard is empty or contains data which may not be pasted here."

Please help, code below.

```<code>Sub UpdateCharts()
Dim oPP As PowerPoint.Slide
Dim shp As PowerPoint.shape
ActivePresentation.Slides(5).Shapes.Paste
End Sub
</code>```

答:
Try the code below (explanation inside the code comments):</p>

```<code>Option Explicit

'=====================================================================
' This sub exports a range from Excel to PowerPoint,
' pastes it, and later on modifies it's position and size (if needed)
' The code works using Late-Binding, so there's no need
' to add References to the VB Project
'=====================================================================

Sub UpdateCharts()

Dim ppApp                               As Object
Dim ppPres                              As Object
Dim ppSlide                             As Object
Dim ppShape                             As Object

' check if PowerPoint application is Open
On Error Resume Next
Set ppApp = GetObject(, "PowerPoint.Application")
On Error GoTo 0

If ppApp Is Nothing Then
    MsgBox "PowerPoint Application is not open", vbCritical
    Exit Sub
End If

' set the Active Presentation
Set ppPres = ppApp.ActivePresentation

' set the Slide
Set ppSlide = ppPres.Slides(5)

' --- copy the Chart's Range (from Excel) ---
' <-- put your copy section here, right before the Paste
'With Worksheets("toPPT")
'    .Range("F6:J7").Copy
'End With

' --- Paste to PowerPoint and modify properties (if needed) ---
Set ppShape = ppSlide.Shapes.PasteSpecial(3, msoFalse) ' 3 = ppPasteMetafilePicture
' modify properties of the pasted Chart (if needed)
With ppShape
    .Left = 535
    .Top = 86
End With
Application.CutCopyMode = False

ppPres.Save

Set ppSlide = Nothing
Set ppPres = Nothing
Set ppApp = Nothing

End Sub
</code>```

Title: ppt paste from excel clipboard to slide

Body:
I have a chart range copied from excel. Now I want to paste it as picture in slide 5 of active presentation, but it is giving me below error.

"Shapes(unknown member):Invalid request.Clipboard is empty or contains data which may not be pasted here."

Please help, code below.

Sub UpdateCharts()
Dim oPP As PowerPoint.Slide
Dim shp As PowerPoint.shape
ActivePresentation.Slides(5).Shapes.Paste
End Sub

Body:
Try the code below (explanation inside the code comments):

Option Explicit

'=====================================================================
' This sub exports a range from Excel to PowerPoint,
' pastes it, and later on modifies it's position and size (if needed)
' The code works using Late-Binding, so there's no need
' to add References to the VB Project
'=====================================================================

Sub UpdateCharts()

Dim ppApp                               As Object
Dim ppPres                              As Object
Dim ppSlide                             As Object
Dim ppShape                             As Object

' check if PowerPoint application is Open
On Error Resume Next
Set ppApp = GetObject(, "PowerPoint.Application")
On Error GoTo 0

If ppApp Is Nothing Then
    MsgBox "PowerPoint Application is not open", vbCritical
    Exit Sub
End If

' set the Active Presentation
Set ppPres = ppApp.ActivePresentation

' set the Slide
Set ppSlide = ppPres.Slides(5)

' --- copy the Chart's Range (from Excel) ---
' <-- put your copy section here, right before the Paste
'With Worksheets("toPPT")
'    .Range("F6:J7").Copy
'End With

' --- Paste to PowerPoint and modify properties (if needed) ---
Set ppShape = ppSlide.Shapes.PasteSpecial(3, msoFalse) ' 3 = ppPasteMetafilePicture
' modify properties of the pasted Chart (if needed)
With ppShape
    .Left = 535
    .Top = 86
End With
Application.CutCopyMode = False

ppPres.Save

Set ppSlide = Nothing
Set ppPres = Nothing
Set ppApp = Nothing

End Sub


问:
How to run UWP background tasks in seperate processes?
In an app that declares multiple different background task extensions, how can I control which tasks can share a hosting process and which ones can not - for the purpose of resource separation and stability?</p>

答:
Use the ResourceGroup property on the Extension node to specify which tasks can run together vs need to be run in a separate process:

```<code>  <Extensions>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.SessionConnectedTriggerTask"
               ResourceGroup="foo">
      <BackgroundTasks>
        <Task Type="systemEvent" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.TimeZoneTriggerTask"
               ResourceGroup="foo">
      <BackgroundTasks>
        <Task Type="systemEvent" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.TimerTriggerTask"
               ResourceGroup="bar">
      <BackgroundTasks>
        <Task Type="timer" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.ApplicationTriggerTask"
               ResourceGroup="bar">
      <BackgroundTasks>
        <Task Type="general" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.MaintenanceTriggerTask"
               ResourceGroup="foobar">
      <BackgroundTasks>
        <Task Type="general" />
      </BackgroundTasks>
    </Extension>
  </Extensions>
</code>```

Body:
Use the ResourceGroup property on the Extension node to specify which tasks can run together vs need to be run in a separate process:

  <Extensions>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.SessionConnectedTriggerTask"
               ResourceGroup="foo">
      <BackgroundTasks>
        <Task Type="systemEvent" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.TimeZoneTriggerTask"
               ResourceGroup="foo">
      <BackgroundTasks>
        <Task Type="systemEvent" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.TimerTriggerTask"
               ResourceGroup="bar">
      <BackgroundTasks>
        <Task Type="timer" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.ApplicationTriggerTask"
               ResourceGroup="bar">
      <BackgroundTasks>
        <Task Type="general" />
      </BackgroundTasks>
    </Extension>
    <Extension Category="windows.backgroundTasks"
               EntryPoint="BackgroundTasks.MaintenanceTriggerTask"
               ResourceGroup="foobar">
      <BackgroundTasks>
        <Task Type="general" />
      </BackgroundTasks>
    </Extension>
  </Extensions>


问:
UILabel get Frame width or height
```<code>`lblAddress.frame.width`
`lblAddress.frame.size.width`
</code>```

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

答:
you want to find origin point use this code
here ViewSend is outlet of view

```<code>self.ViewSend.frame.origin.y
</code>```

you want to find hight so use this code

```<code>self.ViewSend.frame.size.height
</code>```

you want to find width so use this code

```<code>self.ViewSend.frame.size.width
</code>```

Title: UILabel get Frame width or height

Body:
`lblAddress.frame.width`
`lblAddress.frame.size.width`

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

Body:
you want to find origin point use this code
here ViewSend is outlet of view

self.ViewSend.frame.origin.y

you want to find hight so use this code

self.ViewSend.frame.size.height

you want to find width so use this code

self.ViewSend.frame.size.width


问:
0 - Input_0:112: ERROR - "arguments.callee" cannot be used in strict mode
I am stumped!

Getting the error, then refresh page it disappears. I really hope someone can point me  in the right directions. NO IDEA what is causing it... Using apache, nginx, Joomla,...

0 - Input_0:112: ERROR - "arguments.callee" cannot be used in strict mode

0 - Input_0:112: ERROR - "arguments.callee" cannot be used in strict mode if(arguments.callee && ^^^^^^^^^^^^^^^^ Input_0:113: ERROR - "arguments.callee" cannot be used in strict mode arguments.callee.caller && ^^^^^^^^^^^^^^^^ Input_0:114: ERROR - "arguments.callee" cannot be used in strict mode arguments.callee.caller.toString().indexOf('isPropagationStopped') !== -1){  //jquery mark ^^^^^^^^^^^^^^^^ Input_0:122: ERROR - "arguments.callee" cannot be used in strict mode if(arguments.callee && ^^^^^^^^^^^^^^^^ Input_0:123: ERROR - "arguments.callee" cannot be used in strict mode arguments.callee.caller && ^^^^^^^^^^^^^^^^ Input_0:124: ERROR - "arguments.callee" cannot be used in strict mode arguments.callee.caller.toString().indexOf('isPropagationStopped') !== -1){    //jquery mark ^^^^^^^^^^^^^^^^ Input_0:132: ERROR - "arguments.callee" cannot be used in strict mode if(arguments.callee && ^^^^^^^^^^^^^^^^ Input_0:133: ERROR - "arguments.callee" cannot be used in strict mode arguments.callee.caller && ^^^^^^^^^^^^^^^^ Input_0:134: ERROR - "arguments.callee" cannot be used in strict mode arguments.callee.caller.toString().indexOf('isPropagationStopped') !== -1){    //jquery mark ^^^^^^^^^^^^^^^^

答:
File: \plugins\system\t3\base-bs3\js\menu.js

Line: 15

Remove char ";" (alone char before main code)


问:
debugging deobfuscated javascript
I am trying to reverse-engineer a website I don't own, figuring out how some dumb "encryption" works, in order to be able to carry out some operations automatically, by taking the functionality outside the browser.

One of the files is of particular interest, let's call it javascript.js. It is linked in the HTML document like this

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

I have

deobfuscated javascript.js

pretty-printed its code

My question is now, considering that I'm using venkman and firefox, how to replace the on-site obfuscated javascript.js with my own pretty-printed code, in order to learn how it works.

Any other tool beside venkman should do, as long as I can still step through the deobfuscated code.

Additional question (just in case I may come cross this related situation):

How to do the same if the javascript.js would be emdedded inline in the html code like ?

For those of you wondering about how legal this is, my question is not the first about reverse-engineering on SO: https://stackoverflow.com/questions/tagged/reverse-engineering

Apparently there's no problem with those questions, why should there be one with mine?

My objective is to understand the code AND my question is about the TOOLS, as in "where to point and click" or which tool could help me (if venkman cannot).

答:
Way 1:
Export the web page that uses the code to your drive (I know for sure Opera, Firefox and Chrome supports this - ctrl+s - make sure to save all content). They download all linked content (css, scripts, images), and fix the url's so the downloaded ones are loaded instead. Then replace the javascript file you want to debug and open the downloaded html in a browser, say firefox with firebug, and start debugging. This should work unless the page is heavily ajaxified.

Way 2:
I've managed to get this working in Google Chrome (v8.0.552.215 - I need to update BTW) on a page that has no jQuery (for example w3c.org) - try it yourself, just copy paste it in the address bar and wait for the page to disappear :)

```<code>javascript:(eval("var script=document.createElement('script');script.src='http://code.jquery.com/jquery-1.4.4.min.js'; document.getElementsByTagName('head')[0].appendChild(script);window.setTimeout(\"$('body').fadeOut(5000);\", 2000)"));
</code>```

The script shows up in the scripts section of the console (CTRL+SHIFT+J) and you can set breakpoints. So something like this should work (feel free to modify):

```<code>javascript:(eval("for (var allsuspects=document.getElementsByTagName('script'), i=allsuspects.length, oldfile=prompt('Remove script src:'); oldfile && i>=0; i--)   if (allsuspects[i] && allsuspects[i].getAttribute('src')!=null && allsuspects[i].getAttribute('src').indexOf(oldfile)!=-1)      allsuspects[i].parentNode.removeChild(allsuspects[i]);var script=document.createElement('script');script.src = prompt('Inject script src:');document.getElementsByTagName('head')[0].appendChild(script);"));
</code>```

The script expanded and explained:

```<code>for (var allsuspects=document.getElementsByTagName('script'), i=allsuspects.length, oldfile=prompt('Remove script src:'); oldfile && i>=0; i--)
  if (allsuspects[i] && allsuspects[i].getAttribute('src')!=null && allsuspects[i].getAttribute('src').indexOf(oldfile)!=-1)
    allsuspects[i].parentNode.removeChild(allsuspects[i]); // remove old script
var script=document.createElement('script'); // inject new script
script.src = prompt('Inject script src:');
document.getElementsByTagName('head')[0].appendChild(script);
</code>```

The script works only in Chrome (maybe in Safari too?). I've tried Firefox, IE and Opera, but none of them worked. I would guess that there might also be an issue if the file is not available online (if you use you use the 'file://').

UPDATE: also works in Chrome v8.0.552.224

Title: debugging deobfuscated javascript

Body:
I am trying to reverse-engineer a website I don't own, figuring out how some dumb "encryption" works, in order to be able to carry out some operations automatically, by taking the functionality outside the browser.

One of the files is of particular interest, let's call it javascript.js. It is linked in the HTML document like this

I have

deobfuscated javascript.js

pretty-printed its code

My question is now, considering that I'm using venkman and firefox, how to replace the on-site obfuscated javascript.js with my own pretty-printed code, in order to learn how it works.

Any other tool beside venkman should do, as long as I can still step through the deobfuscated code.

Additional question (just in case I may come cross this related situation):

How to do the same if the javascript.js would be emdedded inline in the html code like ?

For those of you wondering about how legal this is, my question is not the first about reverse-engineering on SO: https://stackoverflow.com/questions/tagged/reverse-engineering

Apparently there's no problem with those questions, why should there be one with mine?

My objective is to understand the code AND my question is about the TOOLS, as in "where to point and click" or which tool could help me (if venkman cannot).

Body:
Way 1:
Export the web page that uses the code to your drive (I know for sure Opera, Firefox and Chrome supports this - ctrl+s - make sure to save all content). They download all linked content (css, scripts, images), and fix the url's so the downloaded ones are loaded instead. Then replace the javascript file you want to debug and open the downloaded html in a browser, say firefox with firebug, and start debugging. This should work unless the page is heavily ajaxified.

Way 2:
I've managed to get this working in Google Chrome (v8.0.552.215 - I need to update BTW) on a page that has no jQuery (for example w3c.org) - try it yourself, just copy paste it in the address bar and wait for the page to disappear :)

javascript:(eval("var script=document.createElement('script');script.src='http://code.jquery.com/jquery-1.4.4.min.js'; document.getElementsByTagName('head')[0].appendChild(script);window.setTimeout(\"$('body').fadeOut(5000);\", 2000)"));

The script shows up in the scripts section of the console (CTRL+SHIFT+J) and you can set breakpoints. So something like this should work (feel free to modify):

javascript:(eval("for (var allsuspects=document.getElementsByTagName('script'), i=allsuspects.length, oldfile=prompt('Remove script src:'); oldfile && i>=0; i--)   if (allsuspects[i] && allsuspects[i].getAttribute('src')!=null && allsuspects[i].getAttribute('src').indexOf(oldfile)!=-1)      allsuspects[i].parentNode.removeChild(allsuspects[i]);var script=document.createElement('script');script.src = prompt('Inject script src:');document.getElementsByTagName('head')[0].appendChild(script);"));

The script expanded and explained:

for (var allsuspects=document.getElementsByTagName('script'), i=allsuspects.length, oldfile=prompt('Remove script src:'); oldfile && i>=0; i--)
  if (allsuspects[i] && allsuspects[i].getAttribute('src')!=null && allsuspects[i].getAttribute('src').indexOf(oldfile)!=-1)
    allsuspects[i].parentNode.removeChild(allsuspects[i]); // remove old script
var script=document.createElement('script'); // inject new script
script.src = prompt('Inject script src:');
document.getElementsByTagName('head')[0].appendChild(script);

The script works only in Chrome (maybe in Safari too?). I've tried Firefox, IE and Opera, but none of them worked. I would guess that there might also be an issue if the file is not available online (if you use you use the 'file://').

UPDATE: also works in Chrome v8.0.552.224


问:
How to select latest date record and show other columns in mysql?
I'm using XAMPP MYSQL

I have table and the Date Column is String

```<code>  Date    |  Customer   |   Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/20    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  South Beach   15000   1000
2015/6/22    LBalance      California    5000    4000
2015/6/22    LBalance      New York      6000    6000
2015/6/17    InHoss Dept.  North Beach   18000   1000
</code>```

How to select query the latest date record of each customer with different locations?

Expect result:

```<code>Date      |  Customer   |    Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  North Beach   18000   1000
</code>```

this is the closest i've been to: SELECT Customer, Location, Cash, Balance, max(Date) AS "As Of" FROM mytable WHERE Customer = 'LBalance' GROUP BY Customer, Location. Although It's showing the most recent date of a customer but the other column is just showing their first result.

答:
Since, you wanted a date to string conversion. Not sure this is needed though, since, max(date) might still work without the conversion.

```<code>select max(STR_TO_DATE(Date, '%Y/%m/%d')),Customer, location, cash,balance from YourTable group by Customer, Location
</code>```

Happy Coding.. Please confirm what you need. Becomes difficult to keep track of the edits.

Body:
I'm using XAMPP MYSQL

I have table and the Date Column is String

  Date    |  Customer   |   Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/20    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  South Beach   15000   1000
2015/6/22    LBalance      California    5000    4000
2015/6/22    LBalance      New York      6000    6000
2015/6/17    InHoss Dept.  North Beach   18000   1000

How to select query the latest date record of each customer with different locations?

Expect result:

Date      |  Customer   |    Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  North Beach   18000   1000

this is the closest i've been to: SELECT Customer, Location, Cash, Balance, max(Date) AS "As Of" FROM mytable WHERE Customer = 'LBalance' GROUP BY Customer, Location. Although It's showing the most recent date of a customer but the other column is just showing their first result.

Body:
Since, you wanted a date to string conversion. Not sure this is needed though, since, max(date) might still work without the conversion.

select max(STR_TO_DATE(Date, '%Y/%m/%d')),Customer, location, cash,balance from YourTable group by Customer, Location

Happy Coding.. Please confirm what you need. Becomes difficult to keep track of the edits.


问:
Passwordless sudo login into a server using Ansible
I have an Ansible script using which I would like to run some installation related commands on the remote server. But for installation to go through it is required to be a root user or sudo. I am trying to add the user to the sudoers but it is not working.

```<code>---
- hosts: webservers
  gather_facts: no
  become: yes
  tasks:
        - name: Make sure we have a 'wheel' group
          group:
            name: wheel
            state: present

        - name: Allow 'wheel' group to have passwordless sudo
          lineinfile:
            dest: /etc/sudoers
            state: present
            regexp: '^%wheel'
            line: '%wheel ALL=(ALL) NOPASSWD: ALL'

        - name: Add sudoers users to abkari group
          user: name=abkari groups=wheel append=yes state=present createhome=no
</code>```

On CentOS wheel group is the default group for sudo access. When I run this command it doesn't allow to execute the 1st task. What is the problem here?

答:
There is no way for a non-privileged user to grant itself root privileges (either by editing the sudoers file or adding itself to the wheel group) on a properly configured system.

You need either to run the attached playbook explicitly as root, or configure the system using the root account before you can use become in Ansible.

Body:
I have an Ansible script using which I would like to run some installation related commands on the remote server. But for installation to go through it is required to be a root user or sudo. I am trying to add the user to the sudoers but it is not working.

---
- hosts: webservers
  gather_facts: no
  become: yes
  tasks:
        - name: Make sure we have a 'wheel' group
          group:
            name: wheel
            state: present

        - name: Allow 'wheel' group to have passwordless sudo
          lineinfile:
            dest: /etc/sudoers
            state: present
            regexp: '^%wheel'
            line: '%wheel ALL=(ALL) NOPASSWD: ALL'

        - name: Add sudoers users to abkari group
          user: name=abkari groups=wheel append=yes state=present createhome=no

On CentOS wheel group is the default group for sudo access. When I run this command it doesn't allow to execute the 1st task. What is the problem here?


问:
How do I publish to Service Fabric using Windows Authentication?
My cluster is using Windows Authentication for client to endpoint and it works as expected in browser when connecting to cluster by prompting to use username/password to connect to SF console.
I'm confused as far as what I'm supposed to put into publish profile in Visual Studio. There is no option to choose Windows Authentication anywhere, only cert and Azure Active Directory. How is it supposed to work?

答:
Using WindowsCredential="True" in the publish profile should work.  Here is a powershell version that has worked for me in the past.

Connect-ServiceFabricCluster -ConnectionEndpoint:':19000' -WindowsCredential:$true -TimeoutSec:60


问:
SQL Server : select distinct until the value is changed
I have a table of tasks (each task can has a few rows) that looks something like this:

```<code>TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done
</code>```

I have more columns which are not relevant for this requirement.

What I need here is to select the actual status flow that a specific task has passed.

For example, for task with TaskID = 1, I want to get the following result:

```<code>TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done
</code>```

Notes:

The rows may be not sorted

A status can repeat itself, e.g. there can be a task that its' status flow was:

```<code>Started ==> InProgress ==> Break ==> InProgress ==> Done
</code>```

so will not help me to get for each task the unique status from each status type it passed

答:
In SQL 2012+ you could use LAG

```<code>  DECLARE @SampleData AS TABLE
  (
    TaskID int,
    DateCreated date,
    Status varchar(20)
  )

  INSERT INTO @SampleData
  VALUES
  (1, '2017-01-01', 'Started'),
  (2, '2017-02-02', 'InProgress'),
  (1, '2017-02-02', 'Started'),
  (1, '2017-03-03', 'InProgress'),
  (2, '2017-03-03', 'InProgress'),
  (1, '2017-04-04', 'InProgress'),
  (2, '2017-04-04', 'Done'),
  (1, '2017-05-05', 'Done')

  ;with temp as
  (
     SELECT  *,
             lag(sd.Status,1,'') OVER(PARTITION BY sd.TaskID ORDER BY sd.DateCreated)  AS PreviousRowStatus
     FROM @SampleData sd
  )
  SELECT t.TaskID, t.DateCreated, t.Status
  FROM temp t
  WHERE t.Status != t.PreviousRowStatus
  ORDER BY t.TaskID
</code>```

Returns

```<code>TaskID  DateCreated Status
--------------------------
1       2017-01-01  Started
1       2017-03-03  InProgress
1       2017-05-05  Done
2       2017-02-02  InProgress
2       2017-04-04  Done
</code>```

For older version you could use Row_number and APPLY

Body:
I have a table of tasks (each task can has a few rows) that looks something like this:

TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done

I have more columns which are not relevant for this requirement.

What I need here is to select the actual status flow that a specific task has passed.

For example, for task with TaskID = 1, I want to get the following result:

TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done

Notes:

The rows may be not sorted

A status can repeat itself, e.g. there can be a task that its' status flow was:

Started ==> InProgress ==> Break ==> InProgress ==> Done

so will not help me to get for each task the unique status from each status type it passed

Body:
In SQL 2012+ you could use LAG

  DECLARE @SampleData AS TABLE
  (
    TaskID int,
    DateCreated date,
    Status varchar(20)
  )

  INSERT INTO @SampleData
  VALUES
  (1, '2017-01-01', 'Started'),
  (2, '2017-02-02', 'InProgress'),
  (1, '2017-02-02', 'Started'),
  (1, '2017-03-03', 'InProgress'),
  (2, '2017-03-03', 'InProgress'),
  (1, '2017-04-04', 'InProgress'),
  (2, '2017-04-04', 'Done'),
  (1, '2017-05-05', 'Done')

  ;with temp as
  (
     SELECT  *,
             lag(sd.Status,1,'') OVER(PARTITION BY sd.TaskID ORDER BY sd.DateCreated)  AS PreviousRowStatus
     FROM @SampleData sd
  )
  SELECT t.TaskID, t.DateCreated, t.Status
  FROM temp t
  WHERE t.Status != t.PreviousRowStatus
  ORDER BY t.TaskID

Returns

TaskID  DateCreated Status
--------------------------
1       2017-01-01  Started
1       2017-03-03  InProgress
1       2017-05-05  Done
2       2017-02-02  InProgress
2       2017-04-04  Done

For older version you could use Row_number and APPLY


问:
The bitwise operators should not be used in place of logical operators
```<code>//  How does this program work with ternary operator
#include <stdio.h>
int main()
{
    int x = 2, y = 5;
    (x &  y) ? printf("True ") : printf("False "); // How do we get output
    (x && y) ? printf("True ") : printf("False ");
    return 0;
}
</code>```

How does this program work?
How do the logical and bitwise operators work?

答:
The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.

Example for & (and):

```<code>00000010 & //2
00000101 = //5
--------
00000000   // 0
</code>```

Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||.

Example for | (OR):

```<code>00000010 | //2
00000101 = //5
--------
00000111 //7
</code>```

There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR.

Example for ^ (XOR):

```<code>00000010 ^ //2
00000101 = //5
--------
00000111 //7
</code>```

If you get into a bitwise operators I suggest you get a pen and paper, imagine 2 random 8 bit numbers and work them all up on paper(all bitwise operations). Then you can find a Programmer calculator and check out your result.

Body:
//  How does this program work with ternary operator
#include <stdio.h>
int main()
{
    int x = 2, y = 5;
    (x &  y) ? printf("True ") : printf("False "); // How do we get output
    (x && y) ? printf("True ") : printf("False ");
    return 0;
}

How does this program work?
How do the logical and bitwise operators work?

Body:
The bitwise AND operator is a single ampersand: &. A handy mnemonic is that the small version of the boolean AND, &&, works on smaller pieces (bits instead of bytes, chars, integers, etc). In essence, a binary AND simply takes the logical AND of the bits in each position of a number in binary form.

Example for & (and):

00000010 & //2
00000101 = //5
--------
00000000   // 0

Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||.

Example for | (OR):

00000010 | //2
00000101 = //5
--------
00000111 //7

There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR.

Example for ^ (XOR):

00000010 ^ //2
00000101 = //5
--------
00000111 //7

If you get into a bitwise operators I suggest you get a pen and paper, imagine 2 random 8 bit numbers and work them all up on paper(all bitwise operations). Then you can find a Programmer calculator and check out your result.


问:
register_post_type in wordpress no working template
I have problem with function "register_post_type" in wordpress.

I add code in functions.php (theme path):

```<code>add_action( 'init', 'events' );

function events() {
  register_post_type( 'events', array(
    'labels' => array(
      'name' => 'Wydarzenia',
      'singular_name' => 'events',
     ),
    'description' => 'Wydarzenia',
    'public' => true,
    'menu_position' => 20,
    'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'excerpt')
  ));
}
</code>```

And i add template: single-events.php and archive-events.php but this no working... everytime show: index.php..

single.php no working for events...

Where is problem? Thanks!

答:
add_action( 'init', 'events' );

function events() {

register_post_type( 'events', array(

```<code>'labels' => array(

  'name' => 'Wydarzenia',

  'singular_name' => 'events',

 ),

'description' => 'Wydarzenia',

'public' => true,

'menu_position' => 20,

'has_archive'   => true,

'rewrite' => array( 'slug' => events' ),

'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'excerpt')
</code>```

));
}

see i have added this code there
'has_archive'   => true,
'rewrite' => array( 'slug' => events' ),
it will work fine.

if u are not able to get the page after putting this code , u have to go to permalink and change the url sure it will work.

Body:
I have problem with function "register_post_type" in wordpress.

I add code in functions.php (theme path):

add_action( 'init', 'events' );

function events() {
  register_post_type( 'events', array(
    'labels' => array(
      'name' => 'Wydarzenia',
      'singular_name' => 'events',
     ),
    'description' => 'Wydarzenia',
    'public' => true,
    'menu_position' => 20,
    'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'excerpt')
  ));
}

And i add template: single-events.php and archive-events.php but this no working... everytime show: index.php..

single.php no working for events...

Where is problem? Thanks!

Body:
add_action( 'init', 'events' );

function events() {

register_post_type( 'events', array(

'labels' => array(

  'name' => 'Wydarzenia',

  'singular_name' => 'events',

 ),

'description' => 'Wydarzenia',

'public' => true,

'menu_position' => 20,

'has_archive'   => true,

'rewrite' => array( 'slug' => events' ),

'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'excerpt')

));
}

see i have added this code there
'has_archive'   => true,
'rewrite' => array( 'slug' => events' ),
it will work fine.

if u are not able to get the page after putting this code , u have to go to permalink and change the url sure it will work.


问:
Use of finally in java
Consider the code

```<code>try{
    //code
} catch(Exception e) {
    // handle
} finally {
    // close open connections
}
</code>```

and this

```<code>try{
    //code
} catch(Exception e) {
    // handle
}
// close open connections
</code>```

since both are same what is the necessity of finally block?

答:
The finally block will always be executed, even if you don't catch all the exceptions thrown by the try block in the catch block, or if the catch block throws a new exception.

In the second snippet, the code following the try-catch block won't be executed if either the try or catch blocks throw exceptions not caught by the catch block.

Title: Use of finally in java

Body:
Consider the code

try{
    //code
} catch(Exception e) {
    // handle
} finally {
    // close open connections
}

and this

try{
    //code
} catch(Exception e) {
    // handle
}
// close open connections

since both are same what is the necessity of finally block?


问:
How do I remove these values in a list in Python?
```<code>x1 = [1, 2, 3, 4, 5, 6]
x2 = [3, 5, 6, 8, 9]
x3 = [2, 4, 5, 7, 13]
x4 = [11, 22, 33, 24, 55, 66]
x5 = [11, 7, 1, 2, 3, 4, 5, 6]
</code>```

How do I remove the increasing values on every list?

If I removed the increasing in those lists, they should look like this:

```<code>x1 = [1, 6]
x2 = [3, 9]
x3 = [2, 13]
x4 = [11, 33, 24, 66]
x5 = [11, 7, 1, 6]
</code>```

答:
Your question is unclear.  What does "remove the increasing values" mean?

Clearly you don't mean "remove every value that is larger than the previous one", because your example results include the last element which is larger.

But, assuming you know what you mean, here's how to do it:

To delete a value from a list:

```<code>mylist.remove(4)
</code>```

To remove the item at a specific position from a list: (remember that Python lists start at position zero, not position one)

```<code>del mylist[2]
</code>```

Body:
x1 = [1, 2, 3, 4, 5, 6]
x2 = [3, 5, 6, 8, 9]
x3 = [2, 4, 5, 7, 13]
x4 = [11, 22, 33, 24, 55, 66]
x5 = [11, 7, 1, 2, 3, 4, 5, 6]

How do I remove the increasing values on every list?

If I removed the increasing in those lists, they should look like this:

x1 = [1, 6]
x2 = [3, 9]
x3 = [2, 13]
x4 = [11, 33, 24, 66]
x5 = [11, 7, 1, 6]

Body:
Your question is unclear.  What does "remove the increasing values" mean?

Clearly you don't mean "remove every value that is larger than the previous one", because your example results include the last element which is larger.

But, assuming you know what you mean, here's how to do it:

To delete a value from a list:

mylist.remove(4)

To remove the item at a specific position from a list: (remember that Python lists start at position zero, not position one)

del mylist[2]


问:
Laravel : Call to a member function where() on float
I was trying to find sum of different column using Query Builder.
Here is Query :

```<code>   DB::table('carts')
           ->sum(\DB::raw('carts.price+COALESCE(carts.support,0)+COALESCE(carts.installation,0)' ))
           ->where('status','=',1)
           ->where('user_id','=',$id);
</code>```

But when i dd() the output i got the above Error.ie,

Call to a member function where() on float

How do i avoid that?

答:
Laravel doc

The query builder also provides a variety of aggregate methods such as
  count, max, min, avg, and sum. You may call any of these methods after
  constructing your query:

```<code>$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');
</code>```

Of course, you may combine these methods with other clauses:

```<code>$price = DB::table('orders')
                ->where('finalized', 1)
                ->avg('price');
</code>```

Body:
I was trying to find sum of different column using Query Builder.
Here is Query :

   DB::table('carts')
           ->sum(\DB::raw('carts.price+COALESCE(carts.support,0)+COALESCE(carts.installation,0)' ))
           ->where('status','=',1)
           ->where('user_id','=',$id);

But when i dd() the output i got the above Error.ie,

Call to a member function where() on float

How do i avoid that?

Body:
Laravel doc

The query builder also provides a variety of aggregate methods such as
  count, max, min, avg, and sum. You may call any of these methods after
  constructing your query:

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

Of course, you may combine these methods with other clauses:

$price = DB::table('orders')
                ->where('finalized', 1)
                ->avg('price');


问:
Deriving extensions with multiparameter types
I have an Ast type constructor, parameterized by the identifier type.
Using the DeriveFunctor, DeriveFoldable and DeriveTraversable extensions
it is possible to automatically create the appropriate instances.

Now I find it useful to introduce more type parameters but unfortunately
the above method doesn't scale. Ideally I would like to be able to
wrap my Ast type in selection types which would allow me to fmap to
the appropriate type parameters. Is there some way to achieve a similar
effect without having to define the instances myself?

edit:

Here is a small example of what the original Ast looked like:

```<code>Ast id = Ast (FuncDef id)
    deriving (Show, Functor, Foldable, Traversable)

FuncDef id = FuncDef id [Fparam id] (Block id)
    deriving (Show, Functor, Foldable, Traversable)

Block id = Block [Stmt id]
    deriving (Show, Functor, Foldable, Traversable)

..
</code>```

答:
After fiddling around all day I came to the following conclusions:

The Ast presented in the question turned out not to be very flexible.
In later stages I want to annotate different nodes in a way that can't
be expressed by just parameterizing the original Ast.

So I changed the Ast in order to act as a base for writing new types:

```<code>Ast funcdef = Ast funcdef
    deriving (Show)

Header id fpartype = Header id (Maybe Type) [fpartype]
    deriving (Show)

FuncDef header block = FuncDef header block
    deriving (Show)

Block stmt = Block [stmt]
    deriving (Show)

Stmt lvalue expr funccall =
    StmtAssign lvalue expr |
    StmtFuncCall funccall |
    ..

Expr expr intConst lvalue funccall =
    ExprIntConst intConst |
    ExprLvalue lvalue |
    ExprFuncCall funccall |
    expr :+ expr |
    expr :- expr |
    ..
</code>```

Now I can simply define a chain of newtypes for each compiler stage.
The Ast at the stage of the renamer may be parameterized around the identifier type:

```<code>newtype RAst id = RAst { ast :: Ast (RFuncDef id) }
newtype RHeader id = RHeader { header :: Header id (RFparType id) }
newtype RFuncDef id = RFuncDef {
    funcDef :: FuncDef (RHeader id) (RBlock id)
}
..
newtype RExpr id = RExpr {
    expr :: Expr (RExpr id) RIntConst (RLvalue id) (RFuncCall id)
}
</code>```

During the typechecking stage the Ast may be parameterized by
the different internal types used in the nodes.

This parameterization allows for constructing Asts with Maybe wrapped
parameters in the middle of each stage.

If everything is ok we can use fmap to remove the Maybes and prepare the tree for the next stage. There are other ways Functor, Foldable and Traversable are useful so these are a must to have.

At this point I figured that what I want is most likely not possible
without metaprogramming so I searched for a template haskell solution.
Sure enough there is the genifunctors library which implements generic
fmap, foldMap and traverse functions. Using these it's a simple matter
of writing a few newtype wrappers to make different instances of the required typeclasses around the appropriate parameters:

```<code>fmapGAst = $(genFmap Ast)
foldMapGAst = $(genFoldMap Ast)
traverseGast = $(genTraverse Ast)

newtype OverT1 t2 t3 t1 = OverT1 {unwrapT1 :: Ast t1 t2 t3 }
newtype OverT2 t1 t3 t2 = OverT2 {unwrapT2 :: Ast t1 t2 t3 }
newtype OverT3 t1 t2 t3 = OverT3 {unwrapT3 :: Ast t1 t2 t3 }

instance Functor (OverT1 a b) where
    fmap f w = OverT1 $ fmapGAst f id id $ unwrapT1 w

instance Functor (OverT2 a b) where
    fmap f w = OverT2 $ fmapGAst id f id $ unwrapT2 w

instance Functor (OverT3 a b) where
    fmap f w = OverT3 $ fmapGAst id id f $ unwrapT3 w

..
</code>```

Body:
I have an Ast type constructor, parameterized by the identifier type.
Using the DeriveFunctor, DeriveFoldable and DeriveTraversable extensions
it is possible to automatically create the appropriate instances.

Now I find it useful to introduce more type parameters but unfortunately
the above method doesn't scale. Ideally I would like to be able to
wrap my Ast type in selection types which would allow me to fmap to
the appropriate type parameters. Is there some way to achieve a similar
effect without having to define the instances myself?

edit:

Here is a small example of what the original Ast looked like:

Ast id = Ast (FuncDef id)
    deriving (Show, Functor, Foldable, Traversable)

FuncDef id = FuncDef id [Fparam id] (Block id)
    deriving (Show, Functor, Foldable, Traversable)

Block id = Block [Stmt id]
    deriving (Show, Functor, Foldable, Traversable)

..

Body:
After fiddling around all day I came to the following conclusions:

The Ast presented in the question turned out not to be very flexible.
In later stages I want to annotate different nodes in a way that can't
be expressed by just parameterizing the original Ast.

So I changed the Ast in order to act as a base for writing new types:

Ast funcdef = Ast funcdef
    deriving (Show)

Header id fpartype = Header id (Maybe Type) [fpartype]
    deriving (Show)

FuncDef header block = FuncDef header block
    deriving (Show)

Block stmt = Block [stmt]
    deriving (Show)

Stmt lvalue expr funccall =
    StmtAssign lvalue expr |
    StmtFuncCall funccall |
    ..

Expr expr intConst lvalue funccall =
    ExprIntConst intConst |
    ExprLvalue lvalue |
    ExprFuncCall funccall |
    expr :+ expr |
    expr :- expr |
    ..

Now I can simply define a chain of newtypes for each compiler stage.
The Ast at the stage of the renamer may be parameterized around the identifier type:

newtype RAst id = RAst { ast :: Ast (RFuncDef id) }
newtype RHeader id = RHeader { header :: Header id (RFparType id) }
newtype RFuncDef id = RFuncDef {
    funcDef :: FuncDef (RHeader id) (RBlock id)
}
..
newtype RExpr id = RExpr {
    expr :: Expr (RExpr id) RIntConst (RLvalue id) (RFuncCall id)
}

During the typechecking stage the Ast may be parameterized by
the different internal types used in the nodes.

This parameterization allows for constructing Asts with Maybe wrapped
parameters in the middle of each stage.

If everything is ok we can use fmap to remove the Maybes and prepare the tree for the next stage. There are other ways Functor, Foldable and Traversable are useful so these are a must to have.

At this point I figured that what I want is most likely not possible
without metaprogramming so I searched for a template haskell solution.
Sure enough there is the genifunctors library which implements generic
fmap, foldMap and traverse functions. Using these it's a simple matter
of writing a few newtype wrappers to make different instances of the required typeclasses around the appropriate parameters:

fmapGAst = $(genFmap Ast)
foldMapGAst = $(genFoldMap Ast)
traverseGast = $(genTraverse Ast)

newtype OverT1 t2 t3 t1 = OverT1 {unwrapT1 :: Ast t1 t2 t3 }
newtype OverT2 t1 t3 t2 = OverT2 {unwrapT2 :: Ast t1 t2 t3 }
newtype OverT3 t1 t2 t3 = OverT3 {unwrapT3 :: Ast t1 t2 t3 }

instance Functor (OverT1 a b) where
    fmap f w = OverT1 $ fmapGAst f id id $ unwrapT1 w

instance Functor (OverT2 a b) where
    fmap f w = OverT2 $ fmapGAst id f id $ unwrapT2 w

instance Functor (OverT3 a b) where
    fmap f w = OverT3 $ fmapGAst id id f $ unwrapT3 w

..


问:
HttpClient as singleton in dotnet core
On the full framework there was a pattern that came out making HttpClient a singleton. This is because the existing connections could be reused, however on the full framework there were dns caching issues when doing this. Mostly when you would run httpclient as a singleton on the full framework it would cache the dns results, and you would have to use ServicePointManager to force it to refresh once in a while.

Now dotnet core LTS currently does not have ServicePointManager, so my question is. Can you run HttpClient as a singleton in dotnet core and have it respect DNS updates?

答:
I am quoting a post from the link below

"Unfortunately, there's no way to do this with .NET Core today.
  Either ServicePointManager should be brought over to .NET Core or similar equivalent functionality should be enabled some other way."

Here is the link that might be worth checking: https://github.com/dotnet/corefx/issues/11224

Title: HttpClient as singleton in dotnet core


问:
Vuejs 2 make a global function and pass param
In a component i am changing the title and description in mounted() but i want to make a global function so i can reuse the code below.

How can i achieve that?

```<code>window.document.title = 111;
document.head.querySelector('meta[name=description]').content = 222;

function getTitle(title){
    return window.document.title = title;
}
</code>```

答:
I found the solution for this:</p>

```<code>Vue.mixin({
    methods: {
        makeTitle: function (title) {
            return window.document.title = title;
        }
    }
});

export default{
    props: ['slug'],
    data: function () {
        return {
            items: [],
        }
    },
    mounted() {
        this.makeTitle(this.slug);
    },
</code>```

Body:
In a component i am changing the title and description in mounted() but i want to make a global function so i can reuse the code below.

How can i achieve that?

window.document.title = 111;
document.head.querySelector('meta[name=description]').content = 222;

function getTitle(title){
    return window.document.title = title;
}

Body:
I found the solution for this:

Vue.mixin({
    methods: {
        makeTitle: function (title) {
            return window.document.title = title;
        }
    }
});

export default{
    props: ['slug'],
    data: function () {
        return {
            items: [],
        }
    },
    mounted() {
        this.makeTitle(this.slug);
    },


问:
Add Trailing Ellipsis To Breadcrumb Depending On Device Width
On my user interface I have a breadcrumb of which shows on the top bar. Upon the device width being below a defined width, it'll drop below the top bar and be it's own bar, however what I do not know how to do is add a trailing ellipsis upon the breadcrumb length being larger than the device width.

Example Breadcrumb:

```<code><nav>
    <ul>
        <li>Home</li>
        <li>>></li>
        <li>User</li>
        <li>>></li>
        <li>Inbox</li>
        <li>>></li>
        <li>Mail_ID</li>
    </ul>
</nav>
</code>```

Note: >> represents a FontAwesome icon in an i tag

Upon the breadcrumb being larger than the device width, the best I can describe what I would like to happen is demonstrated below:

Home >> User >> Inbox >> Mail_ID

... User >> Inbox >> Mail_ID

... Inbox >> Mail_ID

... Mail_ID

答:
You can try to use the CSS-only ellipsis, but I don't know if it also works with

. For sure it works with simple strings:

Use this HTML:

```<code><ul class="ellipsis">
</code>```

And this CSS:

```<code>ul.ellipsis
{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</code>```

Body:
On my user interface I have a breadcrumb of which shows on the top bar. Upon the device width being below a defined width, it'll drop below the top bar and be it's own bar, however what I do not know how to do is add a trailing ellipsis upon the breadcrumb length being larger than the device width.

Example Breadcrumb:

Home

>>

User

>>

Inbox

>>

Mail_ID

Note: >> represents a FontAwesome icon in an i tag

Upon the breadcrumb being larger than the device width, the best I can describe what I would like to happen is demonstrated below:

Home >> User >> Inbox >> Mail_ID

... User >> Inbox >> Mail_ID

... Inbox >> Mail_ID

... Mail_ID

Body:
You can try to use the CSS-only ellipsis, but I don't know if it also works with <ul><li>. For sure it works with simple strings:

Use this HTML:

<ul class="ellipsis">

And this CSS:

ul.ellipsis
{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}


问:
Property 'displayName' does not exist on type '() => any'
I am seeing the following error, on my angular2 component upon compiling/building

```<code>import { Component, OnInit } from '@angular/core';
import { Router, Params } from '@angular/router';
import {QueuedService} from '../queued.service';

@Component({
  selector: 'app-reservation',
  templateUrl: './reservation.component.html',
  styleUrls: ['./reservation.component.css']
})
export class ReservationComponent implements OnInit {
  username: string;
  useremail: string;
  route$: Router;
  queued$: QueuedService;
  constructor(route: Router, queued: QueuedService) {
    this.queued$ = queued;
    this.route$ = route;
    this.queued$.getUserInfo()
      .subscribe(
        result => {
            this.username = result.displayName;
            this.useremail = result.emails[0].value;
        }
      );
  }

  ngOnInit() {
  }

}
</code>```

The error is the following

```<code>Property 'displayName' does not exist on type '() => any'.
Property 'emails' does not exist on type '() => any'.
</code>```

I am unable to figure what the issue is?

EDIT
My getUserInfo function

```<code>  getUserInfo() {
    return this.http.get( this.host + '/auth/userdata')
    .map(response => response.json());
  }
</code>```

答:
Your result is of type any, just change those two variables to type of any,

```<code>username: any;
useremail: any;
</code>```

EDIT

Add a type of any to your result,

```<code> this.queued$.getUserInfo()
      .subscribe(
        (result: any) => {
            this.username = result.displayName;
            this.useremail = result.emails[0].value;
        }
      );
</code>```

Body:
I am seeing the following error, on my angular2 component upon compiling/building

import { Component, OnInit } from '@angular/core';
import { Router, Params } from '@angular/router';
import {QueuedService} from '../queued.service';

@Component({
  selector: 'app-reservation',
  templateUrl: './reservation.component.html',
  styleUrls: ['./reservation.component.css']
})
export class ReservationComponent implements OnInit {
  username: string;
  useremail: string;
  route$: Router;
  queued$: QueuedService;
  constructor(route: Router, queued: QueuedService) {
    this.queued$ = queued;
    this.route$ = route;
    this.queued$.getUserInfo()
      .subscribe(
        result => {
            this.username = result.displayName;
            this.useremail = result.emails[0].value;
        }
      );
  }

  ngOnInit() {
  }

}

The error is the following

Property 'displayName' does not exist on type '() => any'.
Property 'emails' does not exist on type '() => any'.

I am unable to figure what the issue is?

EDIT
My getUserInfo function

  getUserInfo() {
    return this.http.get( this.host + '/auth/userdata')
    .map(response => response.json());
  }

Body:
Your result is of type any, just change those two variables to type of any,

username: any;
useremail: any;

EDIT

Add a type of any to your result,

 this.queued$.getUserInfo()
      .subscribe(
        (result: any) => {
            this.username = result.displayName;
            this.useremail = result.emails[0].value;
        }
      );


问:
Is there a standard and an implementation for Icalendar event RSVP
The summary is that I am now implementing an event confirmation system and can't find the right format for the ICalendar replies. Therefore I wonder if there is an example out there of complete REPLY message and maybe a PHP library that would wrap it all?

Now for the details, we get external emails including event invitations asking for RSVP. Here is an excerpt of the iCal file:

ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN="'user@company.com'":MAILTO:user@company.com ORGANIZER;CN="Organ Izer":MAILTO:organizer@company.com

I couldn't find the reply standard to send the RSVP to the organizer. The RFC 2447 mentions "ATTSTAT" and "PARTSTAT" parameter.

By trying to mail the following message to Google calendar the event is not being updated.

```<code>$headers = "Content-Type:text/calendar; Content-Disposition: inline; charset=utf-8;\r\n";
$headers .= "Content-Type: text/plain;charset=\"utf-8\"\r\n";
$headers .= 'BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ORGANIZER;CN=JCharles:mailto:abcdef@gmail.com
UID:oc7ae7537999onscsivg8km123@google.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=CONFIRMED;RSVP=
 TRUE;CN=jc@company.se;X-NUM-GUESTS=0:mailto:jc@company.se
LOCATION:
SEQUENCE:1
END:VEVENT
END:VCALENDAR';

mail('abcdef@gmail.com', 'Accepted:', "Event accepted", $headers);
</code>```

Is there anything wrong with the Ical message or with the method in itself? Is this the way the event replies are supposed to be sent?

答:
The following code will work with google calendar. The attachment is processed by gmail and acceptance is cascaded to the event.

```<code>$vcal = 'BEGIN:VCALENDAR
PRODID:-//EXAMPLE.NU//SE
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REPLY
BEGIN:VEVENT
DTSTART:20101215T160000Z
DTEND:20101215T170000Z
DTSTAMP:'.date('Ymd\THis\Z').'
ORGANIZER;CN=Jean-Charles:mailto:example@gmail.com
UID:u2coh5g3bppo2d2o3t@google.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;
 CN=user@example.se:mailto:user@example.se
CREATED:19000101T120000Z
DESCRIPTION:äåÃ³ö
LAST-MODIFIED:'.date('Ymd\THis\Z').'
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:a new test
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR
';

$vcal = utf8_encode($vcal);

require('lib/phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->AddAddress('example@gmail.com', 'Jean-Charles');
$mail->Body = "HTML BODY";
$mail->AltBody = "Text body";
$mail->Subject = "Email title";
$mail->Sender = "User Name";
$mail->FromName = "user@example.se";
$mail->AddStringAttachment($vcal, 'meeting.ics', "base64", "text/calendar");
$mail->Send();
</code>```

The important bits are

Content-type : text/calendar

METHOD:REPLY

PARTSTAT:ACCEPTED|DECLINED

UID

I am not sure that it is necessary to send back all redundant information (description, summary, dtend, dtstart)

Body:
The summary is that I am now implementing an event confirmation system and can't find the right format for the ICalendar replies. Therefore I wonder if there is an example out there of complete REPLY message and maybe a PHP library that would wrap it all?

Now for the details, we get external emails including event invitations asking for RSVP. Here is an excerpt of the iCal file:

ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN="'user@company.com'":MAILTO:user@company.com ORGANIZER;CN="Organ Izer":MAILTO:organizer@company.com

I couldn't find the reply standard to send the RSVP to the organizer. The RFC 2447 mentions "ATTSTAT" and "PARTSTAT" parameter.

By trying to mail the following message to Google calendar the event is not being updated.

$headers = "Content-Type:text/calendar; Content-Disposition: inline; charset=utf-8;\r\n";
$headers .= "Content-Type: text/plain;charset=\"utf-8\"\r\n";
$headers .= 'BEGIN:VCALENDAR
VERSION:2.0
METHOD:REPLY
BEGIN:VEVENT
ORGANIZER;CN=JCharles:mailto:abcdef@gmail.com
UID:oc7ae7537999onscsivg8km123@google.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=CONFIRMED;RSVP=
 TRUE;CN=jc@company.se;X-NUM-GUESTS=0:mailto:jc@company.se
LOCATION:
SEQUENCE:1
END:VEVENT
END:VCALENDAR';

mail('abcdef@gmail.com', 'Accepted:', "Event accepted", $headers);

Is there anything wrong with the Ical message or with the method in itself? Is this the way the event replies are supposed to be sent?

Body:
The following code will work with google calendar. The attachment is processed by gmail and acceptance is cascaded to the event.

$vcal = 'BEGIN:VCALENDAR
PRODID:-//EXAMPLE.NU//SE
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REPLY
BEGIN:VEVENT
DTSTART:20101215T160000Z
DTEND:20101215T170000Z
DTSTAMP:'.date('Ymd\THis\Z').'
ORGANIZER;CN=Jean-Charles:mailto:example@gmail.com
UID:u2coh5g3bppo2d2o3t@google.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;
 CN=user@example.se:mailto:user@example.se
CREATED:19000101T120000Z
DESCRIPTION:äåÃ³ö
LAST-MODIFIED:'.date('Ymd\THis\Z').'
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:a new test
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR
';

$vcal = utf8_encode($vcal);

require('lib/phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->AddAddress('example@gmail.com', 'Jean-Charles');
$mail->Body = "HTML BODY";
$mail->AltBody = "Text body";
$mail->Subject = "Email title";
$mail->Sender = "User Name";
$mail->FromName = "user@example.se";
$mail->AddStringAttachment($vcal, 'meeting.ics', "base64", "text/calendar");
$mail->Send();

The important bits are

Content-type : text/calendar

METHOD:REPLY

PARTSTAT:ACCEPTED|DECLINED

UID

I am not sure that it is necessary to send back all redundant information (description, summary, dtend, dtstart)


问:
Full size page background image ignore margins
I am trying to create a PDF via the python weasyprint library HTML converter. I want to use a full page background image (svg) that contains the headers/footers and overlay content on top of them.

The issue is regarding page breaks... In order for the image to be full size I set the @page margin to 0, but then of course the page doesn't break until the very bottom. If I set the margins to a decent page break distance I then can't get the image to be full page size disregarding the margins.

Is there a way to circumvent this problem or is the idea doomed to failure

Body:
<style>
image
{
margin: 0px;
width: 100%;
height: 100%;
}
</style>