问:
JPA Transaction - CrudRepository #save(List) not rolled back
I'm using Spring Boot 1.5.9 with spring-boot-starter-data-jpa and Camel 2.20.1.
As input I get an XML file with a sequence of elements, which I unmarshal with JAXB and after that I aggregate them to a list of elements.

For that I defined a Element class where I associate a root element for JAXB and annotated it as a JPA entity.

```<code>@Entity
@Table (name="tblElement", schema="comp")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column (name="name")
    @XmlElement(required = true)
    private String name;

    public void Element(){}

    //getter and setter methods
    ...
}
</code>```

So my camel route processes a list of entries which I want to store to a MySQL database (version: 5.1.73).

```<code>@Component
public class CompRoute extends RouteBuilder {

    @Autowired
    private ElementDao elementDao;

    @Override
    public void configure() throws Exception {
        DataFormat jaxbDataFormat = new JaxbDataFormat("com.comp.beans");

        from(file:src/test/resources/input)
                .convertBodyTo(byte[].class, "UTF-8")
                .split().tokenizeXML("element")
                .unmarshal(jaxbDataFormat)
                .setProperty("SplitSize", simple("${header.CamelSplitSize}"))

                .aggregate(constant(true), new ArrayListAggregationStrategy())
                    .completionSize(simple("${property.SplitSize}"))

                .bean(elementDao, "insertElementList");
    }
}
</code>```

I'm not so familiar with JPA and the transaction manager, so I configured it according these documentations:

https://spring.io/guides/gs/accessing-data-jpa/

https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html

application.properties

```<code>spring.datasource.url=jdbc:mysql://compserver:3306/comp
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

JpaConfig.java

```<code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = CompApplication.class)
class JpaConfig {
    @Autowired
    DataSource dataSource;

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        String entities = ClassUtils.getPackageName(CompApplication.class);
        factory.setPackagesToScan(entities);
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Qualifier (value = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}
</code>```

CompApplication.java

```<code>@SpringBootApplication
public class CompApplication {
  public static void main(String[] args) {
          SpringApplication app = new SpringApplication(CompApplication.class);
          app.setBannerMode(Banner.Mode.OFF);
          app.run(args);
  }
</code>```

}

ElementDao.java

```<code>@Service
public class ElementDao {
    @Autowired
    ElementRepository elementRepository;

    @Transactional (transactionManager = "jpaTransactionManager", readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertElementList(Exchange exchange) {
        if(exchange.getIn().getBody() instanceof List) {
             List<Element> elements= convertListToElementList(exchange.getIn().getBody(List.class));
             if (elements != null) {
                 elementRepository.save(elements);
             }
        }
    }
}
</code>```

ElementRepository.java

```<code>@Repository
public interface ElementRepository extends CrudRepository<Element, Long> {

}
</code>```

But my transaction configuration is not working correct. Because if an error occured e.g. while storing the 5th element, the whole transaction  is not rolled back. It should not insert any elements. But still the first 4 elements are stored and commited.

I don't understand this behavor? How can I set my service #insertElementList transactional that the whole operation is rolled back when an exception occured during database storage?

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.company</groupId>
     <artifactId>company</artifactId>
     <version>0.0.1</version>
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.9.RELEASE</version>
     </parent>
     <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
       <camel.version>2.20.1</camel.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-spring-boot-starter</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jdbc</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.45</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jaxb</artifactId>
             <version>2.20.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-artemis</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jms</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>com.ibm</groupId>
             <artifactId>com.ibm.mq.allclient</artifactId>
             <version>9.0.0.1</version>
         </dependency>
          <dependency>
             <groupId>net.logstash.logback</groupId>
             <artifactId>logstash-logback-encoder</artifactId>
             <version>4.8</version>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-core</artifactId>
             <version>1.1.8</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.5</version>
         </dependency>
     </dependencies>
 </project>
</code>```

答:
According to Spring documentation.

@Transactional on beans in the same application context it is defined in. This means that, if you put annotation in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.

So, your save method is not transactional , include that package also in which
save method is defined.

Body:
I'm using Spring Boot 1.5.9 with spring-boot-starter-data-jpa and Camel 2.20.1.
As input I get an XML file with a sequence of elements, which I unmarshal with JAXB and after that I aggregate them to a list of elements.

For that I defined a Element class where I associate a root element for JAXB and annotated it as a JPA entity.

@Entity
@Table (name="tblElement", schema="comp")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column (name="name")
    @XmlElement(required = true)
    private String name;

    public void Element(){}

    //getter and setter methods
    ...
}

So my camel route processes a list of entries which I want to store to a MySQL database (version: 5.1.73).

@Component
public class CompRoute extends RouteBuilder {

    @Autowired
    private ElementDao elementDao;

    @Override
    public void configure() throws Exception {
        DataFormat jaxbDataFormat = new JaxbDataFormat("com.comp.beans");

        from(file:src/test/resources/input)
                .convertBodyTo(byte[].class, "UTF-8")
                .split().tokenizeXML("element")
                .unmarshal(jaxbDataFormat)
                .setProperty("SplitSize", simple("${header.CamelSplitSize}"))

                .aggregate(constant(true), new ArrayListAggregationStrategy())
                    .completionSize(simple("${property.SplitSize}"))

                .bean(elementDao, "insertElementList");
    }
}

I'm not so familiar with JPA and the transaction manager, so I configured it according these documentations:

https://spring.io/guides/gs/accessing-data-jpa/

https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html

application.properties

spring.datasource.url=jdbc:mysql://compserver:3306/comp
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

JpaConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = CompApplication.class)
class JpaConfig {
    @Autowired
    DataSource dataSource;

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        String entities = ClassUtils.getPackageName(CompApplication.class);
        factory.setPackagesToScan(entities);
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Qualifier (value = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

CompApplication.java

@SpringBootApplication
public class CompApplication {
  public static void main(String[] args) {
          SpringApplication app = new SpringApplication(CompApplication.class);
          app.setBannerMode(Banner.Mode.OFF);
          app.run(args);
  }

}

ElementDao.java

@Service
public class ElementDao {
    @Autowired
    ElementRepository elementRepository;

    @Transactional (transactionManager = "jpaTransactionManager", readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertElementList(Exchange exchange) {
        if(exchange.getIn().getBody() instanceof List) {
             List<Element> elements= convertListToElementList(exchange.getIn().getBody(List.class));
             if (elements != null) {
                 elementRepository.save(elements);
             }
        }
    }
}

ElementRepository.java

@Repository
public interface ElementRepository extends CrudRepository<Element, Long> {

}

But my transaction configuration is not working correct. Because if an error occured e.g. while storing the 5th element, the whole transaction  is not rolled back. It should not insert any elements. But still the first 4 elements are stored and commited.

I don't understand this behavor? How can I set my service #insertElementList transactional that the whole operation is rolled back when an exception occured during database storage?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.company</groupId>
     <artifactId>company</artifactId>
     <version>0.0.1</version>
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.9.RELEASE</version>
     </parent>
     <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
       <camel.version>2.20.1</camel.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-spring-boot-starter</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jdbc</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.45</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jaxb</artifactId>
             <version>2.20.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-artemis</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jms</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>com.ibm</groupId>
             <artifactId>com.ibm.mq.allclient</artifactId>
             <version>9.0.0.1</version>
         </dependency>
          <dependency>
             <groupId>net.logstash.logback</groupId>
             <artifactId>logstash-logback-encoder</artifactId>
             <version>4.8</version>
         </dependency>
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-core</artifactId>
             <version>1.1.8</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.5</version>
         </dependency>
     </dependencies>
 </project>


来源: stackexchange

问:
how to empty an array when the value of the array changes?
lets assume i have an array @atom. i am pushing three elements $a, $b, $c (residue name, chain and residue number respectively fetched from pdb file) into that array. for instance, $b has values AAAAAAAAA, BBBBBBB, CCCCCCC. how to empty the array every time when $b changes?

The array is as follows,

```<code>push(@atom,"$a $b $c");
</code>```

答:
I'm not sure why you are using an array when you're only storing a single value in it. You think you are storing three values, but you are putting those into a single string before storing them in the array.

To store three values in your array, you might use code like this:

```<code>my @atom = ($residue_name, $chain, $residue_number);
</code>```

(Notice that I have also changed your variable names. $a, $b and $c are terrible names for variables and $a and $b are special variables for Perl and should not be used in random code.)

I don't really know what you are doing here, but it seems to me that it might make more sense to store this data in a hash.

```<code>my %atom = (
    residue_name   => $residue_name,
    chain          => $chain,
    residue_number => $residue_number,
);
</code>```

Of course, that's only a guess as I don't know what you need to do with your data - but an important part of programming is to get your data structures right.

But let's assume for now that you're still using your original array and you want to a) see if the $chain variable has changed its value and b) empty the array at that point. You would need to write code something like this:

```<code>my @atom = ($residue_name, $chain, $residue_number);
# Store the current value of $chain
my $original_chain = $chain;
</code>```

Then, later on, you need to check the value has changed and take appropriate action.

```<code>if ($chain ne $original_chain) {
  @atom = ();
}
</code>```

Of course, this is all just the sketchiest of suggestions. I have no idea how your code is structured.

ContentLicense: CC BY-SA 3.0

Body:
lets assume i have an array @atom. i am pushing three elements $a, $b, $c (residue name, chain and residue number respectively fetched from pdb file) into that array. for instance, $b has values AAAAAAAAA, BBBBBBB, CCCCCCC. how to empty the array every time when $b changes?

The array is as follows,

push(@atom,"$a $b $c");

Body:
I'm not sure why you are using an array when you're only storing a single value in it. You think you are storing three values, but you are putting those into a single string before storing them in the array.

To store three values in your array, you might use code like this:

my @atom = ($residue_name, $chain, $residue_number);

(Notice that I have also changed your variable names. $a, $b and $c are terrible names for variables and $a and $b are special variables for Perl and should not be used in random code.)

I don't really know what you are doing here, but it seems to me that it might make more sense to store this data in a hash.

my %atom = (
    residue_name   => $residue_name,
    chain          => $chain,
    residue_number => $residue_number,
);

Of course, that's only a guess as I don't know what you need to do with your data - but an important part of programming is to get your data structures right.

But let's assume for now that you're still using your original array and you want to a) see if the $chain variable has changed its value and b) empty the array at that point. You would need to write code something like this:

my @atom = ($residue_name, $chain, $residue_number);
# Store the current value of $chain
my $original_chain = $chain;

Then, later on, you need to check the value has changed and take appropriate action.

if ($chain ne $original_chain) {
  @atom = ();
}

Of course, this is all just the sketchiest of suggestions. I have no idea how your code is structured.


问:
condition_variable, mutex and flag in one struct
Is to ok to combine all three variables into one struct?

```<code>struct lock_struct
{
    std::mutex mutex;
    std::conditional_variable cv;
    bool flag;
};
</code>```

Are there any hidden synchronization problems with this approach?
I do not intend to modify struct itself, only it's fields.

By the way, should I use bool or std::atomic<bool> when dealing with std::condition_variable's flag?

Edit: implemented it based on the answers.

```<code>class ConditionLock
{
public:
    void wait();
    void notify();
    bool getFlag() const;
private:
    mutable std::mutex _mutex;
    std::condition_variable _cv;
    bool flag;
};

void ConditionLock::wait()
{
    std::unique_lock<std::mutex> lock(_mutex);
    _cv.wait(lock, [&] { return flag; });
}

void ConditionLock::notify()
{
    std::unique_lock<std::mutex> lock(_mutex);
    flag = true;
    lock.unlock();
    _cv.notify_all();
}

bool ConditionLock::getFlag() const
{
    std::lock_guard<std::mutex> lock(_mutex);
    return flag;
}
</code>```

I hope it's a correct implementation.

答:
Is to ok to combine all three variables into one struct?

Yes.

Are there any hidden synchronization problems with this approach?

Structure definition does not describe or enforce its intended usage. Since all the members are publicly accessible nothing prevents from incorrect or unintended usage.

A safer definition is make it a class with no public data members but public member functions.

By the way, should I use bool or std::atomic<bool> when dealing with std::condition_variable's flag

bool is enough as long as accessing that bool happens only when the mutex is locked. You can enforce this by making it a class with no public data members.

Note that if you make it std::atomic<bool> and modify it and signal the condition variable without locking the mutex, that leads to a race condition that causes the notifications from the condition variable to be lost, e.g.:

```<code>Thread 1             |  Thread 2
                     |  check the bool
modify the bool      |
signal the condition |  <notification not received>
                     |  wait on the codition
</code>```

Body:
Is to ok to combine all three variables into one struct?

struct lock_struct
{
    std::mutex mutex;
    std::conditional_variable cv;
    bool flag;
};

Are there any hidden synchronization problems with this approach?
I do not intend to modify struct itself, only it's fields.

By the way, should I use bool or std::atomic<bool> when dealing with std::condition_variable's flag?

Edit: implemented it based on the answers.

class ConditionLock
{
public:
    void wait();
    void notify();
    bool getFlag() const;
private:
    mutable std::mutex _mutex;
    std::condition_variable _cv;
    bool flag;
};

void ConditionLock::wait()
{
    std::unique_lock<std::mutex> lock(_mutex);
    _cv.wait(lock, [&] { return flag; });
}

void ConditionLock::notify()
{
    std::unique_lock<std::mutex> lock(_mutex);
    flag = true;
    lock.unlock();
    _cv.notify_all();
}

bool ConditionLock::getFlag() const
{
    std::lock_guard<std::mutex> lock(_mutex);
    return flag;
}

I hope it's a correct implementation.

Body:
Is to ok to combine all three variables into one struct?

Yes.

Are there any hidden synchronization problems with this approach?

Structure definition does not describe or enforce its intended usage. Since all the members are publicly accessible nothing prevents from incorrect or unintended usage.

A safer definition is make it a class with no public data members but public member functions.

By the way, should I use bool or std::atomic<bool> when dealing with std::condition_variable's flag

bool is enough as long as accessing that bool happens only when the mutex is locked. You can enforce this by making it a class with no public data members.

Note that if you make it std::atomic<bool> and modify it and signal the condition variable without locking the mutex, that leads to a race condition that causes the notifications from the condition variable to be lost, e.g.:

Thread 1             |  Thread 2
                     |  check the bool
modify the bool      |
signal the condition |  <notification not received>
                     |  wait on the codition


问:
css floating and iexplorer
i have two divs, that float correctly in chrome, ff and safari but not iexplorer, the right div appears below the left div floated to the right- the two divs are wrapped by an outer div with a width of 800px;</p>

```<code><div class="b_left">

</div>

<div class="b_right">

</div>

.b_left{
        width:350px;
        margin-left:80px;
        float:left;
        display: block;
    }

    .b_right{
        float:right;
        width:350px;
        height:280px;
        background-color:#c8c8c8;
        display: block;

    }
</code>```

答:
it is a bug of ie, it doubles the margins. you must add display inline to the .b_left.</p>

```<code>display: inline
</code>```

ContentLicense: CC BY-SA 2.5

Title: css floating and iexplorer

Body:
i have two divs, that float correctly in chrome, ff and safari but not iexplorer, the right div appears below the left div floated to the right- the two divs are wrapped by an outer div with a width of 800px;

.b_left{
        width:350px;
        margin-left:80px;
        float:left;
        display: block;
    }

    .b_right{
        float:right;
        width:350px;
        height:280px;
        background-color:#c8c8c8;
        display: block;

    }

Body:
it is a bug of ie, it doubles the margins. you must add display inline to the .b_left.

display: inline


问:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the import line in main.js

I've got the following files:

assets/js/menu.module.js

```<code>'use strict';

export default class Menu
{ ... }
</code>```

assets/js/main.js

```<code>import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});
</code>```

index.html

```<code><script type="module" src="assets/js/menu.module.js"></script>
<script src="assets/js/main.js">
</code>```

Note that these are only the relevant lines of code.

Using the

答:
From what I can see you are trying to load the file menu.module.js while it's actually named menu.js.

PS: From what I recall you could also drop the .js from the import statement.

ContentLicense: CC BY-SA 4.0

Body:
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the import line in main.js

I've got the following files:

assets/js/menu.module.js

'use strict';

export default class Menu
{ ... }

assets/js/main.js

import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});

index.html


问:
Regex to match rails get index urls
I'm trying to create a regex to match only index urls (with or without parameters) in rails.

The following three match what I expect:

```<code>regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true
</code>```

I expect the regex not to match these:

```<code>regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true
</code>```

Edit:

I'm so sorry but I forgot to mention that it should match:

```<code>regex.match?('http://localhost:3000/v2/manufacturers/1/models')
</code>```

as it is a valid index url

答:
The ? character makes the character optional

This works for me: http:\/\/localhost:3000\/v2\/manufacturers?\/?

r = /http://localhost:3000/v2/manufacturers?/?$/

r.match('http://localhost:3000/v2/manufacturers/1?enabled=true')
  => nil

r.match('http://localhost:3000/v2/manufacturers/1')
  => nil

Title: Regex to match rails get index urls

Body:
I'm trying to create a regex to match only index urls (with or without parameters) in rails.

The following three match what I expect:

regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true

I expect the regex not to match these:

regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true

Edit:

I'm so sorry but I forgot to mention that it should match:

regex.match?('http://localhost:3000/v2/manufacturers/1/models')

as it is a valid index url


问:
Reference Error : patternSourceCanvas is not defined fabric js loadFromJSON
I am applying pattern to SVG, and using toJSON save data in database. When I am trying to load that on canvas using loadFromJSON its throwing error pattern source is undefined.

Here is my code I am using to set pattern.

```<code>fabric.Image.fromURL(url,function(img){
            img.scaleToWidth(width);
            if (angle > 0) img.set('angle', angle);
            var patternSourceCanvas = new fabric.StaticCanvas();
            patternSourceCanvas.add(img);
            patternSourceCanvas.renderAll();
            var pattern = new fabric.Pattern({
                source: function() {
                    patternSourceCanvas.setDimensions({
                        width:img.getWidth() + padding,
                        height:img.getHeight() + padding
                    });
                    patternSourceCanvas.renderAll();
                    return patternSourceCanvas.getElement();
                },
                repeat: isrepeat,
                src: url,
            });

            if(left_offset > 0) { pattern.offsetX = (left_offset); } else{ pattern.offsetX = 0;}
            if(top_offset > 0) { pattern.offsetY = (top_offset); } else { pattern.offsetY = 0;}
            var applyPatternto = 0;
            if(activeView != 1){ applyPatternto = $("#sel_applyPatternto").val(); }
            currentElement.paths[applyPatternto].setFill(pattern);
            canvas.renderAll();
        });
</code>```

to load save JSON and load from JSON I am using following,

```<code>var frontJson  = JSON.stringify(canvas.toJSON());
</code>```

while loading from JSON I also add delay to check same issue,

```<code>canvas.loadFromJSON(frontJson);
    setTimeout(function(){
        canvas.renderAll.bind(canvas);
 },3000);
</code>```

答:
Is scope problem.

You can't reload a function from JSON that has references outside of itself.

When the function gets rebuilded there is no patternSourceCanvas defined for it to run.

```<code>source: function() {
  patternSourceCanvas.setDimensions({
    width:img.getWidth() + padding,
    height:img.getHeight() + padding
  });
  patternSourceCanvas.renderAll();
  return patternSourceCanvas.getElement();
},
</code>```

in this context patternSourceCanvas is undefined.

Even if you provide the patternSourceCanvas internally that would be helpless since the img will not be painted on it.

If you need to build a pattern with a function you have to be sure that those vars are available in the global namespace at render time.

is also unclear where padding comes from, it may be affected from the same problem.

Body:
I am applying pattern to SVG, and using toJSON save data in database. When I am trying to load that on canvas using loadFromJSON its throwing error pattern source is undefined.

Here is my code I am using to set pattern.

fabric.Image.fromURL(url,function(img){
            img.scaleToWidth(width);
            if (angle > 0) img.set('angle', angle);
            var patternSourceCanvas = new fabric.StaticCanvas();
            patternSourceCanvas.add(img);
            patternSourceCanvas.renderAll();
            var pattern = new fabric.Pattern({
                source: function() {
                    patternSourceCanvas.setDimensions({
                        width:img.getWidth() + padding,
                        height:img.getHeight() + padding
                    });
                    patternSourceCanvas.renderAll();
                    return patternSourceCanvas.getElement();
                },
                repeat: isrepeat,
                src: url,
            });

            if(left_offset > 0) { pattern.offsetX = (left_offset); } else{ pattern.offsetX = 0;}
            if(top_offset > 0) { pattern.offsetY = (top_offset); } else { pattern.offsetY = 0;}
            var applyPatternto = 0;
            if(activeView != 1){ applyPatternto = $("#sel_applyPatternto").val(); }
            currentElement.paths[applyPatternto].setFill(pattern);
            canvas.renderAll();
        });

to load save JSON and load from JSON I am using following,

var frontJson  = JSON.stringify(canvas.toJSON());

while loading from JSON I also add delay to check same issue,

canvas.loadFromJSON(frontJson);
    setTimeout(function(){
        canvas.renderAll.bind(canvas);
 },3000);

Body:
Is scope problem.

You can't reload a function from JSON that has references outside of itself.

When the function gets rebuilded there is no patternSourceCanvas defined for it to run.

source: function() {
  patternSourceCanvas.setDimensions({
    width:img.getWidth() + padding,
    height:img.getHeight() + padding
  });
  patternSourceCanvas.renderAll();
  return patternSourceCanvas.getElement();
},

in this context patternSourceCanvas is undefined.

Even if you provide the patternSourceCanvas internally that would be helpless since the img will not be painted on it.

If you need to build a pattern with a function you have to be sure that those vars are available in the global namespace at render time.

is also unclear where padding comes from, it may be affected from the same problem.


问:
How to set the output of the Asynchronous Task to the text view of the Main Activity
```<code>public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}
</code>```

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

答:
// Try this with on post execute </p>

```<code>Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
</code>```

<p>// write this code in your activity where you want to use it . </p>

```<code>public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}
</code>```

Body:
public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

Body:
// Try this with on post execute

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}

// write this code in your activity where you want to use it .

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}


问:
Apache Solr- Parent Child Indexing
I am new to Apache Solr and need little help in understanding the parent-child or Nested documents indexing because I can't find anything on google regarding what I am looking for. So here it is what I need to ask

If I index a document with doc-id comment1 and then I index a nested document with parent doc-id post1 and child document with doc-id comment1. Will solr index  comment1 twice? Once individually and once with its parent?

Secondly,
Will it have any effect on the relevancy score calculation of the document?

Thanks.

答:
referring back to Yonik's Blog, you'll have to form a single document object which will be posted to SOLR in one go.

Lucene Index Representation: Lucene has a flat object model and does not really support “nesting” of documents in the index. Lucene
  does support adding a list of documents atomically and contiguously (i.e. a virtual “block”), and this is the feature used by Solr to
  implement “nested objects”.

When you add a parent document with 3 children, these appear in the
  index contiguously as

child1, child2, child3, parent There is no Lucene-level information
  that links parent and child, or distinguishes this parent/child block
  from the other documents in the index that come before or after.
  Successfully using parent/child relationships relies on more
  information being provided at query time.

Limitations: All children of a parent document must be indexed
  together with the parent document. One cannot update any document
  (parent or child) individually. The entire block needs to be
  re-indexed of any changes need to be made.

Hope this helps, cheers!

Title: Apache Solr- Parent Child Indexing


问:
Apply font family file effect at a time in whole application
I have font file roboto in my asset folder. I want to change the normal font to roboto at once . If i use typeface like below:

```<code> TextView forgotPwd = (TextView) findViewById(R.id.tv_forgot_pwd_text);

     Typeface type = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
            forgotPwd.setTypeface(type);
</code>```

Then i have to check and give the same code for every text view manually.But my need is if i set Typeface or any thing it should reflect in the whole application's text or text view.

Now i used

```<code> public class MyApp extends Application {
              @Override
              public void onCreate() {
                 super.onCreate();
                TypefaceUtil.overrideFont(getApplicationContext(), "Roboto", "fonts/Roboto-Regular.ttf");
              }
              }

I used application class and also took the help of some custom class but its not working .
</code>```

public class TypefaceUtil {

```<code>public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

    final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Map<String, Typeface> newMap = new HashMap<String, Typeface>();
        newMap.put("Roboto", customFontTypeface);
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField("sSystemFontMap");
            staticField.setAccessible(true);
            staticField.set(null, newMap);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } else {
        try {
            final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
            defaultFontTypefaceField.setAccessible(true);
            defaultFontTypefaceField.set(null, customFontTypeface);
        } catch (Exception e) {
            Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
        }
    }
}
</code>```

}

now style.xml is

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorControlNormal">#FFFFFF</item>
        <item name="colorControlActivated">#FFFFFF</item>
        <item name="android:textColorHint">@color/black</item>
        <item name="android:typeface">Roboto</item>
    </style>
</code>```

And in the manifest:

```<code>    android:name="pkgname.MyApp"
</code>```

But still i am not getting the reflection in my application please let me know that where i am missing. And guide me

答:
Just try changing the Font name to Default.

previous:-

     TypefaceUtil.overrideFont(getApplicationContext(), "Roboto", "fonts/Roboto-Regular.ttf");

change it to
    TypefaceUtil.overrideFont(getApplicationContext(), "Default", "fonts/Roboto-Regular.ttf");

Better you follow this link
Is it possible to set a custom font for entire of application?

Body:
I have font file roboto in my asset folder. I want to change the normal font to roboto at once . If i use typeface like below:

 TextView forgotPwd = (TextView) findViewById(R.id.tv_forgot_pwd_text);

     Typeface type = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
            forgotPwd.setTypeface(type);

Then i have to check and give the same code for every text view manually.But my need is if i set Typeface or any thing it should reflect in the whole application's text or text view.

Now i used

 public class MyApp extends Application {
              @Override
              public void onCreate() {
                 super.onCreate();
                TypefaceUtil.overrideFont(getApplicationContext(), "Roboto", "fonts/Roboto-Regular.ttf");
              }
              }

I used application class and also took the help of some custom class but its not working .

public class TypefaceUtil {

public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

    final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Map<String, Typeface> newMap = new HashMap<String, Typeface>();
        newMap.put("Roboto", customFontTypeface);
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField("sSystemFontMap");
            staticField.setAccessible(true);
            staticField.set(null, newMap);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } else {
        try {
            final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
            defaultFontTypefaceField.setAccessible(true);
            defaultFontTypefaceField.set(null, customFontTypeface);
        } catch (Exception e) {
            Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
        }
    }
}

}

now style.xml is

And in the manifest:

    android:name="pkgname.MyApp"

But still i am not getting the reflection in my application please let me know that where i am missing. And guide me


问:
Facebook Extended permissions in canvas via php
I'm working on my new project, Woobook. I used the Old REST API until now but i should learn to work with latest one (with OAuth). First i want to get extended permissions but the attached code redirect me to a wrong page (instead of permissions dialog directly).

My app link: http://apps.facebook.com/woobook/

and the source code:

```<code><?php
// Facebook API inc
require_once "inc/facebook.php";

// API init
$cid = "162513840463126";
$asi = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$facebook = new Facebook(array(
  'appId'  => $cid,
  'secret' => $asi,
  'cookie' => true,
));
// Session
$session = $facebook->getSession();

if(!$facebook->getUser()) {
        header("Location:".$facebook->getLoginUrl(array("next" => "http://apps.facebook.com/woobook/", "canvas" => 1, "req_perms" => "user_status,publish_stream,user_photos"))."");
        exit;
}
?>
</code>```

答:
You're using an iframe app, which means you need to do this a little differently.

See my answer here

Body:
I'm working on my new project, Woobook. I used the Old REST API until now but i should learn to work with latest one (with OAuth). First i want to get extended permissions but the attached code redirect me to a wrong page (instead of permissions dialog directly).

My app link: http://apps.facebook.com/woobook/

and the source code:

<?php
// Facebook API inc
require_once "inc/facebook.php";

// API init
$cid = "162513840463126";
$asi = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$facebook = new Facebook(array(
  'appId'  => $cid,
  'secret' => $asi,
  'cookie' => true,
));
// Session
$session = $facebook->getSession();

if(!$facebook->getUser()) {
        header("Location:".$facebook->getLoginUrl(array("next" => "http://apps.facebook.com/woobook/", "canvas" => 1, "req_perms" => "user_status,publish_stream,user_photos"))."");
        exit;
}
?>


问:
Need help to write mysql update query in node.js with callback
I am a beginner for Node.js. Please help to fix this.

Without giving WHERE clause update is working fine. Below is the script without "WHERE" clause:

```<code>var post  = {name: 'Amit', mobile:'123456'};
var query = connection.query('UPDATE contacts SET ? ', post , function(err, result) {});
console.log(query.sql);
</code>```

Output:

Now I added 'WHERE' clause..getting error:

```<code>var post  = {name: 'Amit', mobile:'123456'};
var condition = {id:4};
var query = connection.query('UPDATE contacts SET ? ',post,' WHERE '+ condition , function(err, result) {});
console.log(query.sql);
</code>```

Output:

答:
Check My code also work for you.</p>

```<code>router.all('/setLoginDetails', function (req, res) {
    if(req.method == 'POST')
    {
        var Req = req.body;
    }
    else
    {
        var Req = req.query;
    }
    if(Req.lang == undefined || Req.lang == 'en')
    {
        const message = require('../lang/messages_en.json');
    }

    if(Req.id == undefined || Req.id == '')
    {
        return res.json({"success" : false, "Message" : message.REQUIRED , "data" : {} });
    }

    qb.select('id')
        .where({id: Req.id})
        .get('table', (err,rows) => {
            if (err || rows.length == 0)
            {

                return res.json({"success" : false, "Message" : "No data found", "data" : Response});
            }
            else
            {
                _.each(rows, function(record) {
                    var token = tokenGenerate();
                    qb.update('token', {token: token}, {driver_id:record.id}, (err, result) => {
                        if (err) return console.error(err);
                    });

                    qb.select('*').where({driver_id: record.id}).get(model.DriverLogin, (err,rows) => {
                        var lat = Req.lat;
                        var lng = Req.lng;
                        if(Req.lat == '')
                        {
                            lat = 0.0;
                        }
                        if(Req.lng == '')
                        {
                            lng = 0.0;
                        }
                        var updateData = {lat : lat ,lng : lng, status : 'free', screen : Req.device_info, driver_id : record.id};
                        if(rows.length > 0)
                        {
                            qb.update('localtion', updateData, {driver_id:record.id}, (err, result) => {
                                if (err) return console.error(err);
                            });
                        }
                        else
                        {
                            qb.insert(model.DriverLogin, updateData, (err, res) => {
                                if (err) return console.error(err);
                            });
                        }
                    });
                });

                return res.json({"success" : true, "Message" : "Data Updated", "data" : Response});
            }
        }
    );
});
</code>```

Body:
I am a beginner for Node.js. Please help to fix this.

Without giving WHERE clause update is working fine. Below is the script without "WHERE" clause:

var post  = {name: 'Amit', mobile:'123456'};
var query = connection.query('UPDATE contacts SET ? ', post , function(err, result) {});
console.log(query.sql);

Output:

Now I added 'WHERE' clause..getting error:

var post  = {name: 'Amit', mobile:'123456'};
var condition = {id:4};
var query = connection.query('UPDATE contacts SET ? ',post,' WHERE '+ condition , function(err, result) {});
console.log(query.sql);

Output:

Body:
Check My code also work for you.

router.all('/setLoginDetails', function (req, res) {
    if(req.method == 'POST')
    {
        var Req = req.body;
    }
    else
    {
        var Req = req.query;
    }
    if(Req.lang == undefined || Req.lang == 'en')
    {
        const message = require('../lang/messages_en.json');
    }

    if(Req.id == undefined || Req.id == '')
    {
        return res.json({"success" : false, "Message" : message.REQUIRED , "data" : {} });
    }

    qb.select('id')
        .where({id: Req.id})
        .get('table', (err,rows) => {
            if (err || rows.length == 0)
            {

                return res.json({"success" : false, "Message" : "No data found", "data" : Response});
            }
            else
            {
                _.each(rows, function(record) {
                    var token = tokenGenerate();
                    qb.update('token', {token: token}, {driver_id:record.id}, (err, result) => {
                        if (err) return console.error(err);
                    });

                    qb.select('*').where({driver_id: record.id}).get(model.DriverLogin, (err,rows) => {
                        var lat = Req.lat;
                        var lng = Req.lng;
                        if(Req.lat == '')
                        {
                            lat = 0.0;
                        }
                        if(Req.lng == '')
                        {
                            lng = 0.0;
                        }
                        var updateData = {lat : lat ,lng : lng, status : 'free', screen : Req.device_info, driver_id : record.id};
                        if(rows.length > 0)
                        {
                            qb.update('localtion', updateData, {driver_id:record.id}, (err, result) => {
                                if (err) return console.error(err);
                            });
                        }
                        else
                        {
                            qb.insert(model.DriverLogin, updateData, (err, res) => {
                                if (err) return console.error(err);
                            });
                        }
                    });
                });

                return res.json({"success" : true, "Message" : "Data Updated", "data" : Response});
            }
        }
    );
});


问:
How to ignore HTML component with specific CSS class
i have many links in page but few links has few specific css class attached. i want to avoid those link which has .noclass attached. the below code solve my problem.

```<code><a href="#" class="noclass">Link with No class1</a><br/>
<a href="#" class="noclass">Link with No class2</a><br/>
<a href="#" >Link without No class</a><br/><br/>

<div id="footer_column6">
  <a href="#" class="noclass">Link with No class</a><br/>
  <a href="#" class="">Link without No class</a><br/>
  <a href="#" class="">Link without No class</a>
</div>
</code>```

$(document).ready(function() {
    var hyperLink = $("a:not(.noclass)");
    $.each(hyperLink, function(index, value) {
      var href = $(value).attr("href");
      //Test code to update the back ground
      $(value).css("background-color", "red");
      $(value).attr("href", "/" + countrycode + (href == '/' ? '' : href));
      href = $(value).attr("href");
    });
});
```

when the scenario is bit different like i want to ignore anything with css class .noclass then above code is not working.

suppose if few links are there in div where noclass has been attached to div and i do not want to iterate links in those div which has no class attached.

so if noclass is attached directly with links or may be noclass may attached to parent like div or span. in this case i do not want to iterate links if its parent has no class attached. so tell me what little modification i have to add in above jquery code.

thanks

答:
I have revised my previous code, I realised there was a logic flaw and also didn't like that it relied on adding an extra outer div to make it work. This version selects all links initially and then from within your .each, it tests if the link as the .noclass or has an ancestor with .noclass:

```<code>$(document).ready(function() {
    var hyperLink = $("a");
    $.each(hyperLink, function(index, value) {
        if($(this).hasClass('noclass') || $(this).parents('.noclass').length) {
        return;
      }
      var href = $(value).attr("href");
      //Test code to update the back ground
      $(value).css("background-color", "red");
      $(value).attr("href", "/" + countrycode + (href == '/' ? '' : href));
      href = $(value).attr("href");
    });
});
</code>```

This is more robust as it also works with links at the root of the page, and for any kind of wrapper element (div, span, section, article, etc).

Here's a Fiddle example (note, I had to comment out the countrycode line to make the Fiddle work, as countrycode is not defined).

Body:
i have many links in page but few links has few specific css class attached. i want to avoid those link which has .noclass attached. the below code solve my problem.

Link with No class1

Link with No class2

Link without No class

  Link with No class

  Link without No class

  Link without No class

$(document).ready(function() {
    var hyperLink = $("a:not(.noclass)");
    $.each(hyperLink, function(index, value) {
      var href = $(value).attr("href");
      //Test code to update the back ground
      $(value).css("background-color", "red");
      $(value).attr("href", "/" + countrycode + (href == '/' ? '' : href));
      href = $(value).attr("href");
    });
});

when the scenario is bit different like i want to ignore anything with css class .noclass then above code is not working.

suppose if few links are there in div where noclass has been attached to div and i do not want to iterate links in those div which has no class attached.

so if noclass is attached directly with links or may be noclass may attached to parent like div or span. in this case i do not want to iterate links if its parent has no class attached. so tell me what little modification i have to add in above jquery code.

thanks

Body:
I have revised my previous code, I realised there was a logic flaw and also didn't like that it relied on adding an extra outer div to make it work. This version selects all links initially and then from within your .each, it tests if the link as the .noclass or has an ancestor with .noclass:

$(document).ready(function() {
    var hyperLink = $("a");
    $.each(hyperLink, function(index, value) {
        if($(this).hasClass('noclass') || $(this).parents('.noclass').length) {
        return;
      }
      var href = $(value).attr("href");
      //Test code to update the back ground
      $(value).css("background-color", "red");
      $(value).attr("href", "/" + countrycode + (href == '/' ? '' : href));
      href = $(value).attr("href");
    });
});

This is more robust as it also works with links at the root of the page, and for any kind of wrapper element (div, span, section, article, etc).

Here's a Fiddle example (note, I had to comment out the countrycode line to make the Fiddle work, as countrycode is not defined).


问:
Active transactions on a specific time every day using 'start date' and 'end date'
I'm trying to calculate the number of active transactions on the first of each month at a specific time. I can calculate that for a specific day for the time I want. For example I can run:

```<code>SELECT
A.country_code,
A.transaction_type,
COUNT (*)

FROM table A
JOIN table_history h ON h.listing_id = A.listing_id

WHERE h.start_date <= '2017-12-01 08:01:03' and NVL(h.end_date, '31-DEC-2099') >= '2017-12-01 08:01:03'

GROUP BY
A.country_code,
A.transaction_type
</code>```

That code works fine for the first of December. However, I want to expand that to get all active transactions at that specific time (08:01:03) for every first of the month.

Thank you

答:
You can cast a timestamp as a time to get just the time and use extract to get the day of the month:

```<code>where
  cast (start_date as time) = '08:01:03' and
  extract (day from start_date) = 1
</code>```

Body:
I'm trying to calculate the number of active transactions on the first of each month at a specific time. I can calculate that for a specific day for the time I want. For example I can run:

SELECT
A.country_code,
A.transaction_type,
COUNT (*)

FROM table A
JOIN table_history h ON h.listing_id = A.listing_id

WHERE h.start_date <= '2017-12-01 08:01:03' and NVL(h.end_date, '31-DEC-2099') >= '2017-12-01 08:01:03'

GROUP BY
A.country_code,
A.transaction_type

That code works fine for the first of December. However, I want to expand that to get all active transactions at that specific time (08:01:03) for every first of the month.

Thank you

Body:
You can cast a timestamp as a time to get just the time and use extract to get the day of the month:

where
  cast (start_date as time) = '08:01:03' and
  extract (day from start_date) = 1


问:
Prevent Session Hijacking in asp.net mvc application
How can we prevent session hijacking in an asp.net mvc application? The following steps were performed by the testers to hijack the session - OWASP A2.

Login as a low-privilege user.

Login as a admin user. (in a separate browser - from the same machine)

Copied the ASP.Net Session ID of the admin user

Replaced the ASP.Net Session ID of the low-prev user with the that of the admin user.

By doing the above steps, the low-prev user was able to access the admin areas of the app.

The application is hosted with SSL (https).

Cookies have been set to Secure and HttpOnly.

Cookies are set to expire on Session_End and Signout.

Still, I am able to reproduce the scenario explained above using Fiddler. Could someone please help on ways to arrest the above issue.

Thanks.

答: I would argue that if someone were able to still the cookie, then she should be able to log in. The mitigation should be using short-lived cookies for sensitive resources, and require the user to re-enter her credentials before doing any sensitive data. For example, setting a password, granting permissions etc. Also, you should make it hard to still a cookie - which seems like you already did. Worth also adding Same-Site), and keeping your site secure.</p>


问:
Filter on multiple columns in a table using one pipe in Angular

Hi everyone.
  I want to make a custom filter for my table which intakes more than one argument
  to search multiple columns .. in my case right now only one argument can be passed .
  thanks in advance

component.html

```<code><tr *ngFor = "let builder of builderDetailsArray[0] | filter :'groupName': searchString; let i = index" >
    <td style="text-align: center;"><mat-checkbox></mat-checkbox></td>
    <td>{{builder.builderId}}</td>
    <td>{{builder.viewDateAdded}}</td>
    <td>{{builder.viewLastEdit}}</td>
    <td>{{builder.groupName}}</td>
    <td>{{builder.companyPersonName}}</td>
    <td style="text-align: center;"><button mat-button color="primary">UPDATE</button></td>
</tr>
</code>```

pipe.ts

```<code>@Pipe({
    name: "filter",
    pure:false
})

export class FilterPipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
    if (!items) {
        return [];
    }
    if (!field || !value) {
        return items;
    }
    return items.filter(singleItem =>
        singleItem[field].toLowerCase().includes(value.toLowerCase()) );
}
</code>```

答:
Below is the sample code where I have passed 10 and 2 as arguments to pipes similarly you can pass multiple arguments and get it through parameters in pipe component. increase the arguments in pipe component with respect to number of inputs. working demo

Template

```<code><p>Super power boost: {{2 | exponentialStrength:10:2}}</p>
</code>```

Pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent1: any,exponent2: any): number {
    let exp = parseFloat(exponent2);
    return Math.pow(value, isNaN(exp) ? 1 : exp);
  }
}
</code>```

Body:
Hi everyone.
  I want to make a custom filter for my table which intakes more than one argument
  to search multiple columns .. in my case right now only one argument can be passed .
  thanks in advance

component.html

    <mat-checkbox></mat-checkbox>
    {{builder.builderId}}
    {{builder.viewDateAdded}}
    {{builder.viewLastEdit}}
    {{builder.groupName}}
    {{builder.companyPersonName}}
    <button mat-button color="primary">UPDATE</button>

pipe.ts

@Pipe({
    name: "filter",
    pure:false
})

export class FilterPipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
    if (!items) {
        return [];
    }
    if (!field || !value) {
        return items;
    }
    return items.filter(singleItem =>
        singleItem[field].toLowerCase().includes(value.toLowerCase()) );
}

Body:
Below is the sample code where I have passed 10 and 2 as arguments to pipes similarly you can pass multiple arguments and get it through parameters in pipe component. increase the arguments in pipe component with respect to number of inputs. working demo

Template

<p>Super power boost: {{2 | exponentialStrength:10:2}}</p>

Pipe

import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent1: any,exponent2: any): number {
    let exp = parseFloat(exponent2);
    return Math.pow(value, isNaN(exp) ? 1 : exp);
  }
}


问:
How to Load multiple SegmentedControl into a ViewController
I am trying to load multiple SegmentedControls into one ViewController on Xcode. Below are the buttons.

When I click on one of the buttons, I want the SegmentedControl to load.

These SegmentedControls will load onto a ViewController. Is there any way to make that happen?

My current code is similar to below:

```<code>    @IBAction func action(_ sender: Any) {

    //let url = URL(string: sender.accessibilityIdentifier!)!

    let alertController = UIAlertController(title: (sender as AnyObject).accessibilityLabel, message: (sender as AnyObject).accessibilityHint, preferredStyle: .actionSheet)

    let HSAction = UIAlertAction(title: "Upper Building", style: .default) { action in

        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "one", sender: nil)
        }

        //UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    alertController.addAction(HSAction)
    }
</code>```

答:
After moving to the other view controller, you can create segmentedcontrol with multiple buttons, like below.</p>

```<code>segmentedControl = UISegmentedControl (items: ["First","Second","Third"])
    segmentedControl.frame = CGRectMake(60, 250,200, 30)
    segmentedControl.selectedSegmentIndex = 0
    segmentedControl.addTarget(self, action: "segmentedControlAction:", forControlEvents: .ValueChanged)
    self.view.addSubview(segmentedControl)
</code>```

Body:
I am trying to load multiple SegmentedControls into one ViewController on Xcode. Below are the buttons.

When I click on one of the buttons, I want the SegmentedControl to load.

These SegmentedControls will load onto a ViewController. Is there any way to make that happen?

My current code is similar to below:

    @IBAction func action(_ sender: Any) {

    //let url = URL(string: sender.accessibilityIdentifier!)!

    let alertController = UIAlertController(title: (sender as AnyObject).accessibilityLabel, message: (sender as AnyObject).accessibilityHint, preferredStyle: .actionSheet)

    let HSAction = UIAlertAction(title: "Upper Building", style: .default) { action in

        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "one", sender: nil)
        }

        //UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    alertController.addAction(HSAction)
    }

Body:
After moving to the other view controller, you can create segmentedcontrol with multiple buttons, like below.

segmentedControl = UISegmentedControl (items: ["First","Second","Third"])
    segmentedControl.frame = CGRectMake(60, 250,200, 30)
    segmentedControl.selectedSegmentIndex = 0
    segmentedControl.addTarget(self, action: "segmentedControlAction:", forControlEvents: .ValueChanged)
    self.view.addSubview(segmentedControl)


问:
Vue.js - Pagination
I have the following pagination component.

If users adds remove items dynamically i.e via some ajax call, how do i ensure the correct active or disabled classes are applied on the pagination links?

For example if the user is currently on the last page which only has 1 item, if the user deletes that item, the pagination links re-render but then i lose the active disable class becuase that page no longer exists. i.e. the links should update to move the user to previous page.

```<code> <div class="comment-pager ">
    <div class="panel panel-default panel-highlight no-border ">
        <div class="panel-body padded-5">
            <nav v-if="totalItems > pageSize">
                <ul class="pagination">
                    <li v-bind:class="[currentPage == 1 ? disabled : '']">
                        <a v-on:click.prevent="previous()" aria-label="Previous">
                        <span aria-hidden="true">«</span>
                        </a>
                    </li>
                    <li v-bind:class="[currentPage == pages ? active : '']" v-for="page in pages" v-on:click.prevent="changePage(page)">
                        <a>{{ page }}</a>
                    </li>
                    <li v-bind:class="[currentPage == pages.length ? disabled : '']">
                        <a v-on:click.prevent="next()" aria-label="Next">
                        <span aria-hidden="true">»</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
   </div>
</div>

</template>

<script>

export default {

    props: ['totalItems', 'pageSize']

    data: function () {

        return {
            currentPage: 1,
            pages: [],
        }

    },

    watch: {
        totalItems: function () {

           var pagesCount = Math.ceil(this.totalItems / this.pageSize);
           this.pages = [];
           for (var i = 1; i <= pagesCount; i++)
            this.pages.push(i);
        }
    },

    methods: {

        changePage: function (page){

            this.currentPage = page;
            this.$emit('pageChanged', page);
        }

        previous: function (){
            if (this.currentPage == 1)
                return;

            this.currentPage--;

            this.$emit('pageChanged', this.currentPage);
        }

        next: function () {
            if (this.currentPage == this.pages.length)
                return;

            this.currentPage++;

            this.$emit('pageChanged', this.currentPage);
        }
    },

}

</script>

  <paginator v-bind:total-items="totalItems" v-bind:page-size="query.pageSize" v-on:pageChanged="onPageChange"></paginator>
</code>```

答:
There is no complete equivalent to ngOnChanges() in vue.

ngOnChanges() is a lifecycle hook which takes in an object that maps each changed property name to a SimpleChange object holding the current and previous property values.

If you want the lifecycle hook that gets invoked after every change in data and before re-rendering the virtual DOM then you should be using beforeUpdate()  hook.

But as in ngOnChanges() you can't get the hold of which property is updated or what is it's oldvalue or newValue is.

As mklimek answered you can set up watcher on the properties you want to watch for changes.

In watcher you get what the oldValue is and what it's changed new value is

```<code>new Vue({
    el:'#app',
    data:{
        prop1: '',
        prop2: '' // property to watch changes for
    },
    watch:{
        prop@(newValue, oldValue){
            console.log(newValue);
            console.log(oldValue);
        }
    }
});
</code>```

EDIT

For your case you do not need a watcher. You can setup the pages[] property as a computed property:

```<code>computed:{
    pages(){
        var pageArray = [];
        var pagesCount = Math.ceil(this.totalItems / this.pageSize);

        for (var i = 1; i <= pagesCount; i++)
            pages.push(i);
        }
        return pageArray;
}
</code>```

computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed in your case the props
totalItems and pageSize

Now you can use the pages computed property as normal data property

Title: Vue.js - Pagination

Body:
I have the following pagination component.

If users adds remove items dynamically i.e via some ajax call, how do i ensure the correct active or disabled classes are applied on the pagination links?

For example if the user is currently on the last page which only has 1 item, if the user deletes that item, the pagination links re-render but then i lose the active disable class becuase that page no longer exists. i.e. the links should update to move the user to previous page.

             pageSize">

                        «

                        {{ page }}

                        »

</template>

  <paginator v-bind:total-items="totalItems" v-bind:page-size="query.pageSize" v-on:pageChanged="onPageChange"></paginator>

Body:
There is no complete equivalent to ngOnChanges() in vue.

ngOnChanges() is a lifecycle hook which takes in an object that maps each changed property name to a SimpleChange object holding the current and previous property values.

If you want the lifecycle hook that gets invoked after every change in data and before re-rendering the virtual DOM then you should be using beforeUpdate()  hook.

But as in ngOnChanges() you can't get the hold of which property is updated or what is it's oldvalue or newValue is.

As mklimek answered you can set up watcher on the properties you want to watch for changes.

In watcher you get what the oldValue is and what it's changed new value is

new Vue({
    el:'#app',
    data:{
        prop1: '',
        prop2: '' // property to watch changes for
    },
    watch:{
        prop@(newValue, oldValue){
            console.log(newValue);
            console.log(oldValue);
        }
    }
});

EDIT

For your case you do not need a watcher. You can setup the pages[] property as a computed property:

computed:{
    pages(){
        var pageArray = [];
        var pagesCount = Math.ceil(this.totalItems / this.pageSize);

        for (var i = 1; i <= pagesCount; i++)
            pages.push(i);
        }
        return pageArray;
}

computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed in your case the props
totalItems and pageSize

Now you can use the pages computed property as normal data property


问:
How to make a proper Javascript regex?
I would like to make regular expression so it matches only value as bellow, but I want to make it so you have to have at least one (i know it works with the "+" symbol) a-z letter, but I don't know where to put the "+" to make it work correctly. Any help on this?

```<code>.match(/^[0-9a-z]{3,10}$/i)
</code>```

Edit:
It should match for string like "12a", but it shouldn't match for "123" cause it has to have at least one a-z in it.

```<code>if( ! ($Username.match(/^[0-9a-z]{3,10}$/i) && $Username.match(/[a-z]/i)) ) {
    return false;
}
</code>```

Edit:
Thanks to Felix now the example code above works perfect.

答:
Assuming you mean:

Between 3 and 10 characters (inclusive)

All letters or numbers

At least one letter in any position

Then the simplest way to achieve this would be:

```<code>foo.match(/^[0-9a-z]{3,10}$/i) && foo.match(/[a-z]/i);
</code>```

Title: How to make a proper Javascript regex?

Body:
I would like to make regular expression so it matches only value as bellow, but I want to make it so you have to have at least one (i know it works with the "+" symbol) a-z letter, but I don't know where to put the "+" to make it work correctly. Any help on this?

.match(/^[0-9a-z]{3,10}$/i)

Edit:
It should match for string like "12a", but it shouldn't match for "123" cause it has to have at least one a-z in it.

if( ! ($Username.match(/^[0-9a-z]{3,10}$/i) && $Username.match(/[a-z]/i)) ) {
    return false;
}

Edit:
Thanks to Felix now the example code above works perfect.

Body:
Assuming you mean:

Between 3 and 10 characters (inclusive)

All letters or numbers

At least one letter in any position

Then the simplest way to achieve this would be:

foo.match(/^[0-9a-z]{3,10}$/i) && foo.match(/[a-z]/i);


问:
Replace class in order to replace image on click with jquery
I read a number of articles and answers here on Stack Overflow but none of them answered my question as I'm really a noob when it comes to jQuery and I'm not sure how to do this.

I have a HTML landing page on which I'm trying to show several images on which you click and they get replaced with another image and when clicked again or at another image the original one is shown.

I have this so far:

```<code><div class="santa">
  <img class="show" src="images/santa.png" alt="">
  <img class="hide" src="images/bubble.png" alt="">
</div>
</code>```

.hide { display: none; }
.show { display: block; }
```

I want to show santa.png by default and when clicked on to change it to bubble.png, meaning default class is show and when clicked on it's hide for santa and vice versa.

Thanks in advance!

答:
Try this...if you have two images only...

HTML

```<code><div class="santa">
                <img class="show" src="http://via.placeholder.com/350x150" alt="img">
                <img class="hide" src="http://via.placeholder.com/250x150" alt="img">
 </div>
</code>```

CSS

```<code>.show{
    display:block;
 }
 .hide{
    display:none;
 }
 img{
    max-width:100%;
    height:auto;
    cursor:pointer;
 }
</code>```

JS

```<code> jQuery('.show, .hide').click(function() {
      jQuery('.show, .hide').toggle();
    });
</code>```

Thanks !

Body:
I read a number of articles and answers here on Stack Overflow but none of them answered my question as I'm really a noob when it comes to jQuery and I'm not sure how to do this.

I have a HTML landing page on which I'm trying to show several images on which you click and they get replaced with another image and when clicked again or at another image the original one is shown.

I have this so far:

.hide { display: none; }
.show { display: block; }

I want to show santa.png by default and when clicked on to change it to bubble.png, meaning default class is show and when clicked on it's hide for santa and vice versa.

Thanks in advance!

Body:
Try this...if you have two images only...

HTML

<div class="santa">
                <img class="show" src="http://via.placeholder.com/350x150" alt="img">
                <img class="hide" src="http://via.placeholder.com/250x150" alt="img">
 </div>

CSS

.show{
    display:block;
 }
 .hide{
    display:none;
 }
 img{
    max-width:100%;
    height:auto;
    cursor:pointer;
 }

JS

 jQuery('.show, .hide').click(function() {
      jQuery('.show, .hide').toggle();
    });

Thanks !


问:
Image Linear Transformation graph interpretation
While revesing some image processing material, I was faced to some grahs which I can't understand.

How should I interpret these graphs?

答:
The graphs simply plot the function that describes a gray value transformation in image processing.
Looking at a graph is more intuitive than looking at a formula. Like in other disciplines, function graphs are just a quick and convenient way to discuss what's going on.

It shows two very simple examples.

The first one inverts the image.

O(x,y) or better O(I(x,y)) = 255 - I(x,y)

The second example clips anything below I1 and above I2 and normalizes the interval [I1,I2] to [0,255].

```<code>O(I(x,y)) =
</code>```

0,  if I(x,y) < I1

255, if I(x,y) > I2

(I(x,y) - I1) * 255/(I2-I1), else

Of course these graphs gain value with more complex or even non-linear tranformations.

Body:
The graphs simply plot the function that describes a gray value transformation in image processing.
Looking at a graph is more intuitive than looking at a formula. Like in other disciplines, function graphs are just a quick and convenient way to discuss what's going on.

It shows two very simple examples.

The first one inverts the image.

O(x,y) or better O(I(x,y)) = 255 - I(x,y)

The second example clips anything below I1 and above I2 and normalizes the interval [I1,I2] to [0,255].

O(I(x,y)) =

0,  if I(x,y) < I1

255, if I(x,y) > I2

(I(x,y) - I1) * 255/(I2-I1), else

Of course these graphs gain value with more complex or even non-linear tranformations.


问:
How to create a full page overlay except 70px from the top?
I have a full page overlay div which appears on a button click and covers the full page.

```<code><div class="overlay">
</div>

.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 71px;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(255,255,255, 1);
    overflow-x: hidden;
    transition: 0.5s;
}
</code>```

What I'd like to do is to start this overlay 70px from the top, so I can see/click/use the menu.

I've tried changing top:70px however it also messes up the scrolling of the overlay div (moving the bottom scroll down by 70px as well).

I believe that I need to define the height of the overlay div somehow. However, I'd rather not define a certain height in px but rather do something that's flexible. I've tried defining it by using % but it's not an option at all - because the screen size or the overlay's size can change anytime.

Is there any way to achieve this?

答: You can use height: calc(100vh - 70px); to achieve the desired result

Body:
I have a full page overlay div which appears on a button click and covers the full page.

.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 71px;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(255,255,255, 1);
    overflow-x: hidden;
    transition: 0.5s;
}

What I'd like to do is to start this overlay 70px from the top, so I can see/click/use the menu.

I've tried changing top:70px however it also messes up the scrolling of the overlay div (moving the bottom scroll down by 70px as well).

I believe that I need to define the height of the overlay div somehow. However, I'd rather not define a certain height in px but rather do something that's flexible. I've tried defining it by using % but it's not an option at all - because the screen size or the overlay's size can change anytime.

Is there any way to achieve this?


问:
Html parser to dataframe
I am struggled trying to convert a html table to a dataframe. I would like to write the table in a csv file.

```<code>from requests import session
import sys
import csv
from bs4 import BeautifulSoup

c = session()

outfile = open("Weather2017.csv", 'wb')
response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA')
soup = BeautifulSoup(response.text, "html.parser")
soup = soup.find(id="obsTable").text.replace('\n','',1)
outfile.write(soup.replace('\n',',London\n'))
</code>```

the type error is the following

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-1e149d844e15> in <module>()
     11 soup = BeautifulSoup(response.text, "html.parser")
     12 soup = soup.find(id="obsTable").text.replace('\n','',1)
---> 13 outfile.write(soup.replace('\n',',London\n'))
     14
     15

TypeError: a bytes-like object is required, not 'str'
</code>```

this is the table I want to covert in to a csv file

Can anyone help me?

Thanks in advance!

答:
How about this,</p>

```<code>from requests import session
import sys
import csv
from bs4 import BeautifulSoup

c = session()

response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA')
soup = BeautifulSoup(response.text, "html.parser")

table = soup.find(id="obsTable")

headers = [header.text.encode('utf-8').strip() for header in table.find_all('th')]

rows = []

for row in table.find_all('tr'):
  rows.append([val.text.encode('utf-8').strip() for val in row.find_all('td')])

del rows[0] # Remove header row. Added as empty.

with open('Weather2017.csv', 'wb') as f:
  writer = csv.writer(f)
  writer.writerow(headers)
  writer.writerows(row for row in rows if row)
</code>```

Title: Html parser to dataframe

Body:
I am struggled trying to convert a html table to a dataframe. I would like to write the table in a csv file.

from requests import session
import sys
import csv
from bs4 import BeautifulSoup

c = session()

outfile = open("Weather2017.csv", 'wb')
response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA')
soup = BeautifulSoup(response.text, "html.parser")
soup = soup.find(id="obsTable").text.replace('\n','',1)
outfile.write(soup.replace('\n',',London\n'))

the type error is the following

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-1e149d844e15> in <module>()
     11 soup = BeautifulSoup(response.text, "html.parser")
     12 soup = soup.find(id="obsTable").text.replace('\n','',1)
---> 13 outfile.write(soup.replace('\n',',London\n'))
     14
     15

TypeError: a bytes-like object is required, not 'str'

this is the table I want to covert in to a csv file

Can anyone help me?

Thanks in advance!

Body:
How about this,

from requests import session
import sys
import csv
from bs4 import BeautifulSoup

c = session()

response = c.get('http://www.wunderground.com/history/airport/EGLL/2017/1/1/CustomHistory.html?dayend=31&monthend=12&yearend=2017&req_city=NA&req_state=NA&req_statename=NA')
soup = BeautifulSoup(response.text, "html.parser")

table = soup.find(id="obsTable")

headers = [header.text.encode('utf-8').strip() for header in table.find_all('th')]

rows = []

for row in table.find_all('tr'):
  rows.append([val.text.encode('utf-8').strip() for val in row.find_all('td')])

del rows[0] # Remove header row. Added as empty.

with open('Weather2017.csv', 'wb') as f:
  writer = csv.writer(f)
  writer.writerow(headers)
  writer.writerows(row for row in rows if row)


答:
Instead of using a height and a width, use bottom and right:

.overlay {
  position: fixed;
  z-index: 1;
  top: 71px;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  overflow-x: hidden;
  transition: 0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="overlay">
</div></code>```

Title: How to create a full page overlay except 70px from the top?

Body:
Instead of using a height and a width, use bottom and right:

.overlay {
  position: fixed;
  z-index: 1;
  top: 71px;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  overflow-x: hidden;
  transition: 0.5s;
}

<div class="overlay">
</div>


答:
If you want to show/hide an element I suggest you to use .hide() and .show()
It's pure JQuery and no need of CSS.

"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value"
  http://api.jquery.com/hide/

Here is an exemple:

HTML

```<code><div>
    <img class="santa_img" src="images/santa.png" alt="santa">
    <img class="bubble_img" src="images/bubble.png" alt="bubble">
</div>
</code>```

JS (JQuery)

```<code>$(".santa_img").click(function(){

    $(".santa_img").hide();
    $(".bubble_img").show();

})

$(".bubble_img").click(function(){

    $(".bubble_img").hide();
    $(".santa_img").show();

})

$(".bubble_img").hide(); //Hidden by default
</code>```

Title: Replace class in order to replace image on click with jquery

Body:
If you want to show/hide an element I suggest you to use .hide() and .show()
It's pure JQuery and no need of CSS.

"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value"
  http://api.jquery.com/hide/

Here is an exemple:

HTML

<div>
    <img class="santa_img" src="images/santa.png" alt="santa">
    <img class="bubble_img" src="images/bubble.png" alt="bubble">
</div>

JS (JQuery)

$(".santa_img").click(function(){

    $(".santa_img").hide();
    $(".bubble_img").show();

})

$(".bubble_img").click(function(){

    $(".bubble_img").hide();
    $(".santa_img").show();

})

$(".bubble_img").hide(); //Hidden by default


问:
Splitting column values into rows DB2
I'm using DB2 db for fetching data. I have scenerio like to fetch values from the database like this:

```<code>Select user, attributes
From Data
Order By DATE desc
fetch first 1 rows only;
</code>```

Output:

```<code>user                 attributes
------               ------------
user1                Name=Rahul|Branch=CSE|Year of Joining=2017
</code>```

I need to get splitted column of "attribute" into rows like below.

```<code>Name            Branch        Year of Joining
-----           ------        ----------------
Rahul           CSE           2017
</code>```

Could we achieve this in query? Please guide me.

答:
DB@ supports regexp_substr().  This allows you to do:

```<code>select regexp_substr(regexp_substr(attributes, '[^|]+', 1, 1), '[^=]+$', 1, 2) as name,
       regexp_substr(regexp_substr(attributes, '[^|]+', 1, 2), '[^=]+$', 1, 2) as branch,
       regexp_substr(regexp_substr(attributes, '[^|]+', 1, 3), '[^=]+$', 1, 2) as name
from t;
</code>```

Title: Splitting column values into rows DB2

Body:
I'm using DB2 db for fetching data. I have scenerio like to fetch values from the database like this:

Select user, attributes
From Data
Order By DATE desc
fetch first 1 rows only;

Output:

user                 attributes
------               ------------
user1                Name=Rahul|Branch=CSE|Year of Joining=2017

I need to get splitted column of "attribute" into rows like below.

Name            Branch        Year of Joining
-----           ------        ----------------
Rahul           CSE           2017

Could we achieve this in query? Please guide me.

Body:
DB@ supports regexp_substr().  This allows you to do:

select regexp_substr(regexp_substr(attributes, '[^|]+', 1, 1), '[^=]+$', 1, 2) as name,
       regexp_substr(regexp_substr(attributes, '[^|]+', 1, 2), '[^=]+$', 1, 2) as branch,
       regexp_substr(regexp_substr(attributes, '[^|]+', 1, 3), '[^=]+$', 1, 2) as name
from t;


问:
From where can I find Grails/Groovy tool suite for working with Grails 2.1.0
I am new to Grails/Groovy. I wanted to install GGTS for Grails 2.1.0.
Which version of GGTS I have to use and from where I can download that?</p>

答: Downloads are available at https://spring.io/tools/ggts/all, e.g. for Linux you would download this.</p>


问:
Do all voice-to-text algorithms operate in real-time?
Do all voice-to-text algorithms of current technology operate in real-time? I don't mean with a person sitting at a computer with a microphone, but rather inputing a pre-recorded audio file.

i.e. If you have a 30 minute voice recording, will it always take 30 minutes to be transcribed?

Are there different approaches out there?

答:
There is nothing stopping the algorithm running faster than realtime.
The Naturally Speaking 10 Professional software program provide a "transcribe from file" option for converting dictation taken while away from a computer, this operates as fast as the computer on which it is running can achieve.

I believe batch processing implementations exist in the area of signals intelligence but such programs would, naturally, be unavailable to the general populace.

OwnerDisplayName: frou


问:
How to change chart's width to fill up div using angular2-highcharts when hide/open left side nav menu?
How to change chart's width to fill up div when hide/open left side nav menu using angular2-highcharts??

I tried to use style="display:block; width: 100% !important;" as recommended on most resources I found, but it didn't help.

Here is an example of using chart inside mat-sidenav-container and mat-sidenav-content:

Html

```<code>`<mat-sidenav-container class="sidenavContainer">
  <mat-sidenav #sideNav opened="true" mode="side" class="filters-viewer-sidenav">
    mat-sidenav
  </mat-sidenav>
  <mat-sidenav-content>
    mat-sidenav-content
    <button (click)="sideNav.toggle()">
      mat-sidenav-button
    </button>
    <div style="width: 100%; height: 100%">
      <chart [options]="options"  style="display:block; width: 100% !important;"></chart>
    </div>
  </mat-sidenav-content>
</mat-sidenav-container>`
</code>```

css

```<code>`html, body, mat-sidenav-container, .chart-wrapper {
  margin: 0;
  width: 100%;
  height: 100%;
}
.sidenav {
  width: 240px;
  height: 100%;
  box-shadow: 3px 0 6px rgba(0,0,0,.24);
}`
</code>```

Added also screenshot: after I close left side nav menu, chart width stays the same.
still_same_chart_width_size

答:
This can be done with css

```<code>chart {
    width: 100% !important;
    margin: 0 auto;
    display: block;
}
</code>```

Check https://github.com/gevgeny/angular2-highcharts/issues/11

Body:
How to change chart's width to fill up div when hide/open left side nav menu using angular2-highcharts??

I tried to use style="display:block; width: 100% !important;" as recommended on most resources I found, but it didn't help.

Here is an example of using chart inside mat-sidenav-container and mat-sidenav-content:

Html

`<mat-sidenav-container class="sidenavContainer">
  <mat-sidenav #sideNav opened="true" mode="side" class="filters-viewer-sidenav">
    mat-sidenav
  </mat-sidenav>
  <mat-sidenav-content>
    mat-sidenav-content
    <button (click)="sideNav.toggle()">
      mat-sidenav-button
    </button>

      <chart [options]="options"  style="display:block; width: 100% !important;"></chart>

  </mat-sidenav-content>
</mat-sidenav-container>`

css

`html, body, mat-sidenav-container, .chart-wrapper {
  margin: 0;
  width: 100%;
  height: 100%;
}
.sidenav {
  width: 240px;
  height: 100%;
  box-shadow: 3px 0 6px rgba(0,0,0,.24);
}`

Added also screenshot: after I close left side nav menu, chart width stays the same.
still_same_chart_width_size

Body:
This can be done with css

chart {
    width: 100% !important;
    margin: 0 auto;
    display: block;
}

Check https://github.com/gevgeny/angular2-highcharts/issues/11