问:
Compartmentalisation and Design of Classes in C++
In my spare time, I've been taking code I've written for various purposes and appropriating them into other languages just to have a look at what's out there. Currently I'm taking a genetic programming graph colouring algorithm, originally written in Java, and trying to coerce it into C++.

The arbitrary data structure I'm using for the task has a few classes. In Java, it wasn't so much of an issue for me because I had been exposed to it for a while. The graph structure was only created once, and a Colouring was assigned to that. The Colouring (specifically finding a mostly optimal one) was the real point of the code. I could have a Graph class with inner classes like Node and Edge, for instance, or I could have a package graph with classes Graph, Node, Edge, etc.

The first case above might lend itself well to my idea of C++. A main *.cpp file might have some classes Node, Graph, Edge, defined in it. But this seems to really be missing the point of C++, from what I can tell. I'm just taking what I wrote in Java and forcing it into C++, adding destructors where appropriate and turning object references to pointers. I'm not yet thinking in C++. Do these classes bear separating into separate *.cpp files? Should they be separated, and then compiled as a library to use in the main program? What I really need are some good resources or contrived examples (or even rules of thumb) to say, in C++ programming, what are the different options that exist and when is it a good idea to thinking about one over the other?

EDIT: I've been asked by @Pawel Zubrycki to provide some example code. I'm not going to do this, because each component is fairly trivial - It generally has a reference to the next thing, and some get/set methods. I will, however, describe it.

It's essentially an incidence list. There is some unnecessary use of classes termed ...Pointer - they were a product of a literal translation of a diagram first used to explain incidence lists to me.

There is a container class, VertexList, which contains a head element VertexPointer, and methods to add new VertexPointer objects (Adding it to the graph, but not connecting it to any other nodes, allowing searches to search non-connected graphs), naive search for indices on Vertex objects, etc. Every VertexPointer has a Vertex object, as well as a VertexPointer next;, and all those handy hasNext() methods that you might expect. A Vertex also has an associated ConnectionList

The same is duplicated for EdgeList, EdgePointer, and Edge, except that an Edge is associated with two Connection objects.

ConnectionList and Connection: ConnectionList mimicking VertexList or EdgeList, having a Connection head; and all those handy methods you might expect, like addConnection(). A Connection has an Edge associated with it, as well as some Connection next;

This allows us to easily get the connected components of any one point in the graph, and have an arbitrary number of connections.

It seems pretty over-the-top complicated, but the same functionality could be duplicated with some LinkedList of Vertex objects, a LinkedList of Edge objects, and a number of LinkedList of Connection objects. The LinkedList of Vertex Objects allows us to iterate over all Vertices for exhaustive searches on Vertices, and the same applies for edges. The LinkedList objects of Connection allow us to quickly traverse to any connected Vertices and to arbitrarily add or connections in the graph. This step up in complexity was added to deal with the complexity of evaluating a certain colouring of a graph (weighted edges, quick traversal of local subgraphs, etc.)

答:
If you have classes like Node, Graph and Edge, and their implementation is not too large, it makes perfectly good sense to define them in one and the same .cpp file. After all, they are meant to be used together.

In C++, a package like this is called a component. Usually it makes more sense to think in components than classes, since C++ is not only an OOP language and classes are not always the preferred way do things.

If you want to learn more about the preferred way to organize code in C++, I recommend Large Scale C++ Software Design.

BTW: Making a library out of these classes really seems overkill.


来源: stackexchange

问:
vim in tmux will lose color schema when using `j` to move page down
I am open vim in tmux in development, There is problem that when i using j to move page down, the color schema will lose, I record my operation as a video and uploaded to youtube:

https://www.youtube.com/watch?v=ejNf2TPSc4E

normally the color schema should be following:

but when I trying to use j to move down, the spaces without contains words will lost and become white:

I am using stonewashed theme

答: export TERM=screen-256color resolved the issue

ContentLicense: CC BY-SA 3.0


问:
How to store array of modal iOS
In my application,

I have one NSMutableArray which contains modal objects, I want to store this array in NSUserDefaults.

When i try to store and retrieves it returns me nil values.
After doing some research i found we can't store objects in NSUserDefaults.

Is there any alternative and easy way to store?

Thank you in advance!

答:
Store custom objects of class in NSMutableArray. Archive that array using <NSCoding>Protocol and then store it in NSUserDefaults.:
check this link

Title: How to store array of modal iOS


问:
htaccess redirects affect administrator page on Joomla
I have a task - all somestuff.html/ pages with trailing slash must redirect to somestuff.html and all other pages without a trailing slash must redirect to add a trailing slash (e.g. /mypage must redirect to /mypage/). I have accomplished the task but now /administrator/ page returns 404 page. I tried to exclude the /administrator/ page but its not working:

```<code>DirectoryIndex index.php
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#this part breaks the admin panel entry

RewriteRule ^([^.]+).html/ http://somedomain.com/$1\.html [R=301,L]
RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$

#trying to exclude administrator page
RewriteCond %{REQUEST_URI} !^/administrator/

RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]

#end of part that breaks the admin panel entry

RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</code>```

Can anyone tell me what I am doing wrong or maybe offer some different solution to acocmplish the redirecting. Thanks.

答:
Found a solution:</p>

```<code>DirectoryIndex index.php
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+).html/ http://logosstudy.ru/$1\.html [R=301,L]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</code>```

Body:
I have a task - all somestuff.html/ pages with trailing slash must redirect to somestuff.html and all other pages without a trailing slash must redirect to add a trailing slash (e.g. /mypage must redirect to /mypage/). I have accomplished the task but now /administrator/ page returns 404 page. I tried to exclude the /administrator/ page but its not working:

DirectoryIndex index.php
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#this part breaks the admin panel entry

RewriteRule ^([^.]+).html/ http://somedomain.com/$1\.html [R=301,L]
RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$

#trying to exclude administrator page
RewriteCond %{REQUEST_URI} !^/administrator/

RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]

#end of part that breaks the admin panel entry

RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

Can anyone tell me what I am doing wrong or maybe offer some different solution to acocmplish the redirecting. Thanks.

Body:
Found a solution:

DirectoryIndex index.php
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+).html/ http://logosstudy.ru/$1\.html [R=301,L]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
RewriteCond %{REQUEST_URI} !^/administrator/
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]


问:
org.hibernate.MappingException: Unknown entity: annotations.Users
Consider the hierarchy :

And the following classes and xml :

HibernateUtil.java

```<code>package annotations;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 *
 * @author X3
 *
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static final String HIBERNATE_CFG = "hibernateAnnotations.cfg.xml";

    private static SessionFactory buildSessionFactory()
    {
        Configuration cfg = new Configuration().addResource(HIBERNATE_CFG).configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
                applySettings(cfg.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
</code>```

Users.java

```<code>package annotations;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Entity
@Table(name = "Users")
public class Users {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private long userID;

    @Column(name = "USERNAME", nullable = false, length = 100)
    private String username;

    @Column(name = "MessageTimeDate", nullable = false)
    private java.sql.Timestamp datetime;

    @Column(name = "UserMessage", nullable = false)
    private String message;

    public Users(String username , String message)
    {
        java.util.Date date = new java.util.Date();
        this.datetime = new Timestamp(date.getTime());

        this.username = username;
        this.message = message;
    }

    public long getUserID() {
        return userID;
    }

    public void setUserID(long userID) {
        this.userID = userID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public java.sql.Timestamp getDatetime() {
        return datetime;
    }

    public void setDatetime(java.sql.Timestamp datetime) {
        this.datetime = datetime;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
</code>```

Main.java

```<code>package annotations;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        try
        {
               SessionFactory sf = HibernateUtil.getSessionFactory();
               Session session = sf.openSession();
               session.beginTransaction();

               Users user1 = new Users("Jack" , "Hello");
               session.save(user1);
               session.getTransaction().commit();
               session.close();
        }

        catch (Exception e)
        {
            System.out.println(e.toString());
            e.getStackTrace();
        }

    }
}
</code>```

And hibernateAnnotations.cfg.xml

```<code><?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/CHAT_DB</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="annotations.Users"></mapping>
    </session-factory>
</hibernate-configuration>
</code>```

When I run main(), the following error appears in output window :

```<code>org.hibernate.MappingException: Unknown entity: annotations.Users
</code>```

But the entity Users is in annotations package , so what's wrong ?

答:
I was facing the same issue and I searched for almost 2 hours and tried with different possible ways like replacing old hibernate JARs and changing the DB table schema. But finally got the solution as below:

```<code>SessionFactory factory = new Configuration().configure().buildSessionFactory(); //This line to be replaced with below commented line
</code>```

Replace above for

```<code>//Configuration config = new Configuration().configure();
//ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
//SessionFactory factory = config.buildSessionFactory(servReg);
</code>```

It will then work fine..

Body:
Consider the hierarchy :

And the following classes and xml :

HibernateUtil.java

package annotations;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 *
 * @author X3
 *
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static final String HIBERNATE_CFG = "hibernateAnnotations.cfg.xml";

    private static SessionFactory buildSessionFactory()
    {
        Configuration cfg = new Configuration().addResource(HIBERNATE_CFG).configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
                applySettings(cfg.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Users.java

package annotations;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;

@Entity
@Table(name = "Users")
public class Users {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private long userID;

    @Column(name = "USERNAME", nullable = false, length = 100)
    private String username;

    @Column(name = "MessageTimeDate", nullable = false)
    private java.sql.Timestamp datetime;

    @Column(name = "UserMessage", nullable = false)
    private String message;

    public Users(String username , String message)
    {
        java.util.Date date = new java.util.Date();
        this.datetime = new Timestamp(date.getTime());

        this.username = username;
        this.message = message;
    }

    public long getUserID() {
        return userID;
    }

    public void setUserID(long userID) {
        this.userID = userID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public java.sql.Timestamp getDatetime() {
        return datetime;
    }

    public void setDatetime(java.sql.Timestamp datetime) {
        this.datetime = datetime;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Main.java

package annotations;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

    public static void main(String[] args) {

        try
        {
               SessionFactory sf = HibernateUtil.getSessionFactory();
               Session session = sf.openSession();
               session.beginTransaction();

               Users user1 = new Users("Jack" , "Hello");
               session.save(user1);
               session.getTransaction().commit();
               session.close();
        }

        catch (Exception e)
        {
            System.out.println(e.toString());
            e.getStackTrace();
        }

    }
}

And hibernateAnnotations.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/CHAT_DB</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="annotations.Users"></mapping>
    </session-factory>
</hibernate-configuration>

When I run main(), the following error appears in output window :

org.hibernate.MappingException: Unknown entity: annotations.Users

But the entity Users is in annotations package , so what's wrong ?

Body:
I was facing the same issue and I searched for almost 2 hours and tried with different possible ways like replacing old hibernate JARs and changing the DB table schema. But finally got the solution as below:

SessionFactory factory = new Configuration().configure().buildSessionFactory(); //This line to be replaced with below commented line

Replace above for

//Configuration config = new Configuration().configure();
//ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
//SessionFactory factory = config.buildSessionFactory(servReg);

It will then work fine..


问:
Convert data frame from wide to long with 2 variables
I have the following wide data frame (mydf.wide):

```<code>DAY JAN F1  FEB F2  MAR F3  APR F4  MAY F5  JUN F6  JUL F7  AUG F8  SEP F9  OCT F10 NOV F11 DEC F12
1   169 0   296 0   1095    0   599 0   1361    0   1746    0   2411    0   2516    0   1614    0   908 0   488 0   209 0
2   193 0   554 0   1085    0   1820    0   1723    0   2787    0   2548    0   1402    0   1633    0   897 0   411 0   250 0
3   246 0   533 0   1111    0   1817    0   2238    0   2747    0   1575    0   1912    0   705 0   813 0   156 0   164 0
4   222 0   547 0   1125    0   1789    0   2181    0   2309    0   1569    0   1798    0   1463    0   878 0   241 0   230 0
</code>```

I want to produce the following "semi-long":

```<code>DAY variable_month value_month value_F
1 JAN 169 0
</code>```

I tried:

```<code>library(reshape2)
mydf.long <- melt(mydf.wide, id.vars=c("YEAR","DAY"), measure.vars=c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"))
</code>```

but this skip the F variable and I don't know how to deal with two variables...

答:
melt() and dcast() are available from the reshape2 and data.table packages. The recent versions of data.table allow to melt multiple columns simultaneously. The patterns() parameter can be used to specify the two sets of columns by regular expressions:

```<code>library(data.table)   # CRAN version 1.10.4 used
regex_month <- toupper(paste(month.abb, collapse = "|"))
mydf.long <- melt(setDT(mydf.wide), measure.vars = patterns(regex_month, "F\\d"),
                  value.name = c("MONTH", "F"))
# rename factor levels
mydf.long[, variable := forcats::lvls_revalue(variable, toupper(month.abb))][]
</code>```

```<code>    DAY variable MONTH F
 1:   1      JAN   169 0
 2:   2      JAN   193 0
 3:   3      JAN   246 0
 4:   4      JAN   222 0
 5:   1      FEB   296 0
...
44:   4      NOV   241 0
45:   1      DEC   209 0
46:   2      DEC   250 0
47:   3      DEC   164 0
48:   4      DEC   230 0
    DAY variable MONTH F
</code>```

Note that "F\\d" is used as regular expression in patterns(). A simple "F" would have catched FEB as well as F1, F2, etc. producing unexpected results.

Also note that mydf.wide needs to be coerced to a data.table object. Otherwise, reshape2::melt() will be dispatched on a data.frame object which doesn't recognize patterns().

Data

```<code>library(data.table)
mydf.wide <- fread(
"DAY JAN F1  FEB F2  MAR F3  APR F4  MAY F5  JUN F6  JUL F7  AUG F8  SEP F9  OCT F10 NOV F11 DEC F12
  1   169 0   296 0   1095    0   599 0   1361    0   1746    0   2411    0   2516    0   1614    0   908 0   488 0   209 0
  2   193 0   554 0   1085    0   1820    0   1723    0   2787    0   2548    0   1402    0   1633    0   897 0   411 0   250 0
  3   246 0   533 0   1111    0   1817    0   2238    0   2747    0   1575    0   1912    0   705 0   813 0   156 0   164 0
  4   222 0   547 0   1125    0   1789    0   2181    0   2309    0   1569    0   1798    0   1463    0   878 0   241 0   230 0",
data.table = FALSE)
</code>```

Body:
I have the following wide data frame (mydf.wide):

DAY JAN F1  FEB F2  MAR F3  APR F4  MAY F5  JUN F6  JUL F7  AUG F8  SEP F9  OCT F10 NOV F11 DEC F12
1   169 0   296 0   1095    0   599 0   1361    0   1746    0   2411    0   2516    0   1614    0   908 0   488 0   209 0
2   193 0   554 0   1085    0   1820    0   1723    0   2787    0   2548    0   1402    0   1633    0   897 0   411 0   250 0
3   246 0   533 0   1111    0   1817    0   2238    0   2747    0   1575    0   1912    0   705 0   813 0   156 0   164 0
4   222 0   547 0   1125    0   1789    0   2181    0   2309    0   1569    0   1798    0   1463    0   878 0   241 0   230 0

I want to produce the following "semi-long":

DAY variable_month value_month value_F
1 JAN 169 0

I tried:

library(reshape2)
mydf.long <- melt(mydf.wide, id.vars=c("YEAR","DAY"), measure.vars=c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"))

but this skip the F variable and I don't know how to deal with two variables...

Body:
melt() and dcast() are available from the reshape2 and data.table packages. The recent versions of data.table allow to melt multiple columns simultaneously. The patterns() parameter can be used to specify the two sets of columns by regular expressions:

library(data.table)   # CRAN version 1.10.4 used
regex_month <- toupper(paste(month.abb, collapse = "|"))
mydf.long <- melt(setDT(mydf.wide), measure.vars = patterns(regex_month, "F\\d"),
                  value.name = c("MONTH", "F"))
# rename factor levels
mydf.long[, variable := forcats::lvls_revalue(variable, toupper(month.abb))][]

    DAY variable MONTH F
 1:   1      JAN   169 0
 2:   2      JAN   193 0
 3:   3      JAN   246 0
 4:   4      JAN   222 0
 5:   1      FEB   296 0
...
44:   4      NOV   241 0
45:   1      DEC   209 0
46:   2      DEC   250 0
47:   3      DEC   164 0
48:   4      DEC   230 0
    DAY variable MONTH F

Note that "F\\d" is used as regular expression in patterns(). A simple "F" would have catched FEB as well as F1, F2, etc. producing unexpected results.

Also note that mydf.wide needs to be coerced to a data.table object. Otherwise, reshape2::melt() will be dispatched on a data.frame object which doesn't recognize patterns().

Data

library(data.table)
mydf.wide <- fread(
"DAY JAN F1  FEB F2  MAR F3  APR F4  MAY F5  JUN F6  JUL F7  AUG F8  SEP F9  OCT F10 NOV F11 DEC F12
  1   169 0   296 0   1095    0   599 0   1361    0   1746    0   2411    0   2516    0   1614    0   908 0   488 0   209 0
  2   193 0   554 0   1085    0   1820    0   1723    0   2787    0   2548    0   1402    0   1633    0   897 0   411 0   250 0
  3   246 0   533 0   1111    0   1817    0   2238    0   2747    0   1575    0   1912    0   705 0   813 0   156 0   164 0
  4   222 0   547 0   1125    0   1789    0   2181    0   2309    0   1569    0   1798    0   1463    0   878 0   241 0   230 0",
data.table = FALSE)


问:
How to switch IIS Developer Express to "Classic Mode"
I know how to switch to "Classic Mode" (from "Integrated Mode") in the full IIS via application pool settings. But I can't find how to do it in the current IIS Developer Express beta.

The MS Developer Express FAQ says it can be done, but not how. It's not in the WebMatrix GUI, as far as I can tell. Maybe customization of the Developer Express project file, but I don't see any documentation for that at all.

FYI, there is a Settings area where you can set SSL, CLR version (2.0 in this case), which is where I figure the Pipeline mode (Classic/Integrated) would be, but it's not there.

答:
I found the following worked with my copy of the IIS Express beta ...

```<code>appcmd set app /app.name:ExampleApp/ /applicationPool:Clr4ClassicAppPool
</code>```

Note the forward slash at the end of ExampleApp !

ContentLicense: CC BY-SA 2.5

Body:
I found the following worked with my copy of the IIS Express beta ...

appcmd set app /app.name:ExampleApp/ /applicationPool:Clr4ClassicAppPool

Note the forward slash at the end of ExampleApp !


问:
List subfolders with number of files PHP
I have a folder with lots of subfolders and a large number of pdf files inside them...Now i want to list the folder names with the number of pdf files inside each folder using PHP.How to accomplish this?</p>

答:
Using PHP recursive function you can get simple array for folders.

PHP

```<code><?php
    $array=array();
    function getCount($path){
        $count=0;
        global $array;
        //$count=count(glob($path."/*"));
        foreach(new DirectoryIterator($path) as $fileInfo){
            if($fileInfo->isDir()){
                if($fileInfo->isDot()) continue;
                if(array_key_exists($fileInfo->getFilename(),$array)){
                    $array[$fileInfo->getFilename()] = array(
                        'is_file_directory' => 'file',
                        'count' => getCount($fileInfo->getPathname())
                    );
                }
                else{
                    $array[$fileInfo->getFilename()] = array(
                        'is_file_directory' => 'directory',
                        'count' => getCount($fileInfo->getPathname())
                    );
                }
            }
            else{
                $array[$fileInfo->getFilename()] = array(
                    'is_file_directory' => 'file',
                    'count' => 0
                );
                $count++;
            }
        }
        return $count;
    }
?>
</code>```

How to use : getCount('folder/inner_folder'); print_r($array);

Body:
Using PHP recursive function you can get simple array for folders.

PHP

<?php
    $array=array();
    function getCount($path){
        $count=0;
        global $array;
        //$count=count(glob($path."/*"));
        foreach(new DirectoryIterator($path) as $fileInfo){
            if($fileInfo->isDir()){
                if($fileInfo->isDot()) continue;
                if(array_key_exists($fileInfo->getFilename(),$array)){
                    $array[$fileInfo->getFilename()] = array(
                        'is_file_directory' => 'file',
                        'count' => getCount($fileInfo->getPathname())
                    );
                }
                else{
                    $array[$fileInfo->getFilename()] = array(
                        'is_file_directory' => 'directory',
                        'count' => getCount($fileInfo->getPathname())
                    );
                }
            }
            else{
                $array[$fileInfo->getFilename()] = array(
                    'is_file_directory' => 'file',
                    'count' => 0
                );
                $count++;
            }
        }
        return $count;
    }
?>

How to use : getCount('folder/inner_folder'); print_r($array);


问:
Setting readonly using ng-readonly dynamically is not working
I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table.
(b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

```<code>    <tbody>
           <tr ng-repeat="x in sensordata">
           <td>
             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>
           </td>
           <td>
              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>
           </td>
           <td>
                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>
           </td>
           <td>
               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>
           </td>
           </tr>
   </tbody>
</code>```

Controller code is as follows.

```<code>this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };
</code>```

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.

答:
you can try if else statement, which sets the variable properly

```<code>this.setReadOnly = function(name,idx) {
    console.log('name ' + name + ' idx ' + idx);
    if (name === undefined || name === null || name === '') $scope.namereadonly = false;
    else (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
};
</code>```

Body:
I am fetching some data from the database server and displaying the same in tabular format on my GUI. I want to achieve the following in my GUI design

(a) Any cell in the table should be editable except the first column in the table.
(b) The first row of the table, if added newly to the GUI for accepting new inputs from the user, should be exempted from the above rule i.e., all columns of the first row should be editable.

To achieve this I wrote the following code.

HTML Code

             <input class="form-control" type="text" ng-model="x.name" placeholder="Sensor name" ng-readonly="namereadonly" ng-init="ctrl2.setReadOnly(x.name,$index)"/>

              <input class="form-control" type="text" ng-model="x.unit" placeholder="Measurement Unit" required/>

                <input class="form-control" type="text" ng-model="x.type" placeholder="Sensor Type" required/>

                <input class="form-control" type="text" ng-model="x.periodicity" placeholder="Periodicity" required/>

                <input class="form-control" type="text" ng-model="x.formula" placeholder="Formula" required/>

               <input class="form-control" type="email" ng-model="x.vendor" placeholder="Email Id" required/>

Controller code is as follows.

this.setReadOnly = function(name,idx) {
        console.log('name ' + name + ' idx ' + idx);
        if (name === undefined || name === null || name === '') $scope.namereadonly = false;
        if (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
    };

When I am executing above code the first column of all the rows are getting uneditable as expected. But when I am adding new row to the (by adding new empty JSON object in the sensordata array in another function of the same controller) GUI, the first column of the row is getting uneditable which should not be the case as per the first if statement in the above method. I am unable to figure out why it is happening.

Body:
you can try if else statement, which sets the variable properly

this.setReadOnly = function(name,idx) {
    console.log('name ' + name + ' idx ' + idx);
    if (name === undefined || name === null || name === '') $scope.namereadonly = false;
    else (name !== '' || name !== undefined || name !== null) $scope.namereadonly = true;
};


问:
the best overloaded method match for has some invalid arguments in Unit test case
```<code>public void ApplicationNumberIsVaild_Test()
{
    MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber appno = new MFA.Convana.BusinessLayer.ObjectStore.ApplicationNumber();
    String Input;
    String Output;
    String TestCase;
    XMLHelper TestData = new XMLHelper();
    TestCase = TestData.GetTestDataString("IsValid");
    String[] arr = TestCase.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
    if (arr.Length > 0)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            Input = arr[i].Substring(0, arr[i].IndexOf(TestData.FieldDelimiter));
            Output = arr[i].Substring(arr[i].IndexOf(TestData.FieldDelimiter) + 3);
            Assert.AreEqual(appno.IsValid(Input), Convert.ToBoolean(Output));//Error in this line
        }
    }
</code>```

答:
```<code>MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber appno
    = new MFA.Convana.BusinessLayer.ObjectStore.ApplicationNumber();
String Input;
String Output;
String TestCase;
XMLHelper TestData = new XMLHelper();
TestCase = TestData.GetTestDataString("IsValid");
String[] arr = TestCase.Split(new string[] { Environment.NewLine },
        StringSplitOptions.None);
if (arr.Length > 0)
{
    for (int i = 0; i < arr.Length; i++)
    {
        Input = arr[i].Substring(0, arr[i].IndexOf(TestData.FieldDelimiter));
        Output = arr[i].Substring(arr[i].IndexOf(TestData.FieldDelimiter) + 3);
        Assert.AreEqual(appno.IsValid(Input), Convert.ToBoolean(Output));//Error in this line

    }
}
</code>```

There are three potential problems:

appno.IsValid() does not take a string for a parameter.

The string Output can not be converted to boolean.

The return value of appno.IsValid() can't convert to boolean.

Odds are appno.IsValid isn't returning a boolean. 1 is less likely to be the source of your error and 3 would most likely give you a different error message.

Body:
MFA.Convana.BusinessLayer.ObjectModel.ApplicationNumber appno
    = new MFA.Convana.BusinessLayer.ObjectStore.ApplicationNumber();
String Input;
String Output;
String TestCase;
XMLHelper TestData = new XMLHelper();
TestCase = TestData.GetTestDataString("IsValid");
String[] arr = TestCase.Split(new string[] { Environment.NewLine },
        StringSplitOptions.None);
if (arr.Length > 0)
{
    for (int i = 0; i < arr.Length; i++)
    {
        Input = arr[i].Substring(0, arr[i].IndexOf(TestData.FieldDelimiter));
        Output = arr[i].Substring(arr[i].IndexOf(TestData.FieldDelimiter) + 3);
        Assert.AreEqual(appno.IsValid(Input), Convert.ToBoolean(Output));//Error in this line

    }
}

There are three potential problems:

appno.IsValid() does not take a string for a parameter.

The string Output can not be converted to boolean.

The return value of appno.IsValid() can't convert to boolean.

Odds are appno.IsValid isn't returning a boolean. 1 is less likely to be the source of your error and 3 would most likely give you a different error message.


问:
How to replace Email id text before @ with * in swift 3.0
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

```<code>    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")
</code>```

Any suggestion is accepted.

Thank you.

答:
Write this code:</p>

```<code>let aString = "This is my string"
let newString = aString.replacingOccurrences(of: "@", with: "*")
</code>```

Body:
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")

Any suggestion is accepted.

Thank you.

Body:
Write this code:

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: "@", with: "*")


问:
How to exchange data between classes?
I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++.

So, let's assume we have 4 classes:

```<code>class Main_Window
{
    //...
    void load_data_menu_selected();
}

class Data
{
    //...
    double *data;
}

class Load_Data
{
    //...
    double *get_filename_and_load();
}

class Calculate
{
    //...
    int do_calculation()
}
</code>```

So, Main_Window is class for application's main window where it interacts with user input etc.

I want to do:

create an instance of class Data in the Main_Window

use Load_Data for loading data from file and store it in the Data

use Calculation class for doing something with read data in Data class

The question is: where I should create classes, to make Data class members available from other classes.  Should I use Inheritance?

答:
It sounds like you should not use inheritance here. The main reason for saying so is that you have a number of classes (Window, Calculator, etc.) using or doing something to an entity (i.e. Data). Inheritance is used to denote an "is a" relationship (i.e. if A inherits from B, A "is a" B).

In this case, you use composition, which denotes a "has a" relationship. So each class takes a reference to an instance of Data, and acts upon that object.

Who owns the Data object? To share a single Data object, you might want to look into Boost shared_ptr, which allows multiple reference-counting pointers to share an object allocated with "new".

Title: How to exchange data between classes?

Body:
I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++.

So, let's assume we have 4 classes:

class Main_Window
{
    //...
    void load_data_menu_selected();
}

class Data
{
    //...
    double *data;
}

class Load_Data
{
    //...
    double *get_filename_and_load();
}

class Calculate
{
    //...
    int do_calculation()
}

So, Main_Window is class for application's main window where it interacts with user input etc.

I want to do:

create an instance of class Data in the Main_Window

use Load_Data for loading data from file and store it in the Data

use Calculation class for doing something with read data in Data class

The question is: where I should create classes, to make Data class members available from other classes.  Should I use Inheritance?


问:
pycaffe cannot transfer the diff from top to bottom
I'm using the backward function of pycaffe to realize the deconvolution process. I first run the forward process and get the output data blob of the net, then assign the data blob to the diff blob of the top layer, then run the backward process. However, the diffs of bottom layers are not changed by the backward process, which are all zeros. I don't know why the diff is not transferred by backward.

```<code>def backward(fcn_net, im, name_list_, target_blob):
    start=name_list_[len(name_list_)-1]; end=name_list_[0]
    print(start, end)
    fcn_net.blobs[start].diff[...]=im[...]
    fcn_net.backward(start=start, end=end)
    return fcn_net.blobs[target_blob].diff
</code>```

In the code above the name_list_ contains all conv layers and pooling layers orderly, and the backward starts from the last conv layer. Thanks!

答:
It might be the case that your net does not pass gradients by default.

Consider setting force_backward in your net prototxt.

See this answer for example.

Body:
I'm using the backward function of pycaffe to realize the deconvolution process. I first run the forward process and get the output data blob of the net, then assign the data blob to the diff blob of the top layer, then run the backward process. However, the diffs of bottom layers are not changed by the backward process, which are all zeros. I don't know why the diff is not transferred by backward.

def backward(fcn_net, im, name_list_, target_blob):
    start=name_list_[len(name_list_)-1]; end=name_list_[0]
    print(start, end)
    fcn_net.blobs[start].diff[...]=im[...]
    fcn_net.backward(start=start, end=end)
    return fcn_net.blobs[target_blob].diff

In the code above the name_list_ contains all conv layers and pooling layers orderly, and the backward starts from the last conv layer. Thanks!


问:
"org.apache.http.ConnectionClosedException:" Error occurred while running jmeter
I have recorded reports in my application and running scripts for JMeter 3.0 in RedHat server. But, a ConnectionClosedException has error occurred as shown below

```<code>Error:
org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
    at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:268)
    at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:227)
    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:186)
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:73)
    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:150)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.readResponse(HTTPSamplerBase.java:1779)
    at org.apache.jmeter.protocol.http.sampler.HTTPAbstractImpl.readResponse(HTTPAbstractImpl.java:412)
    at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:400)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135)
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:465)
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:410)
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:241)
    at java.lang.Thread.run(Unknown Source)
</code>```

Error: Number format exception for input string: "" error showing in Assertion result window.

Does anyone know a solution for this exception?

答:
Download later version of Jmeter, in Jmeter 3.1 there were improvements with HTTP:

Since version 3.1, HTTP Request is able when using HttpClient4
  (default) implementation to handle responses bigger than 2147483647
  Bytes, that is 2GB

Body:
I have recorded reports in my application and running scripts for JMeter 3.0 in RedHat server. But, a ConnectionClosedException has error occurred as shown below

Error:
org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
    at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:268)
    at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:227)
    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:186)
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:73)
    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:137)
    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:150)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.readResponse(HTTPSamplerBase.java:1779)
    at org.apache.jmeter.protocol.http.sampler.HTTPAbstractImpl.readResponse(HTTPAbstractImpl.java:412)
    at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:400)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146)
    at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135)
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:465)
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:410)
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:241)
    at java.lang.Thread.run(Unknown Source)

Error: Number format exception for input string: "" error showing in Assertion result window.

Does anyone know a solution for this exception?


问:
Hive count number of matching rows in another table
Table1:

```<code>| ID | Timestamp
| 1  | 1970
| 2  | 1971
</code>```

Table2:

```<code>| Timestamp |
| 1970      |
| 1970      |
| 1970      |
| 1971      |
| 1971      |
</code>```

How can I perform a query that joins the tables in such a way that I get:

```<code>| ID | Timestamp | Count
| 1  | 1970      | 3
| 2  | 1971      | 2
</code>```

basically join on timestamp but only to get a count?

Body:
Table1:

| ID | Timestamp
| 1  | 1970
| 2  | 1971

Table2:

| Timestamp |
| 1970      |
| 1970      |
| 1970      |
| 1971      |
| 1971      |

How can I perform a query that joins the tables in such a way that I get:

| ID | Timestamp | Count
| 1  | 1970      | 3
| 2  | 1971      | 2

basically join on timestamp but only to get a count?

Body:
select  t1.ID
       ,t1.`Timestamp`
       ,coalesce (t2.`Count`,0) as `Count`

from    Table1 t1

        left join  (select      `Timestamp`
                                ,count(*)    as `Count`
                    from        Table2
                    group by    `Timestamp`
                    ) t2

        on          t2.`Timestamp` = t1.`Timestamp`

+----+-----------+-------+
| id | timestamp | count |
+----+-----------+-------+
|  1 |      1970 |     3 |
|  2 |      1971 |     2 |
+----+-----------+-------+


问:
array value not being properly emptied on a button click
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button></code>```

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

答:
Make following changes , your onclick function should not be inside another function.

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       //add_to_array(array);
       alert('Array emptied')
   })
   $("#btn_2").click(function(){
       array = [];
       alert('Array emptied')
       //add_to_array(array);
   })

function add_to_array(array){

     array.push(1)
     alert(array)

}

 $("#add").click(function(){

      add_to_array(array);
   })

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button></code>```

Body:
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}

<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

Body:
Make following changes , your onclick function should not be inside another function.

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       //add_to_array(array);
       alert('Array emptied')
   })
   $("#btn_2").click(function(){
       array = [];
       alert('Array emptied')
       //add_to_array(array);
   })

function add_to_array(array){

     array.push(1)
     alert(array)

}

 $("#add").click(function(){

      add_to_array(array);
   })

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>


问:
How to use Templates on javascript?
I Have A function that add html to a div.

```<code>var user = $("#ddlUser").val();
    var role = $("#ddlUserRole").val();

    var html = '<div class="calendaruser">';
    html += '<span>' + user + '</span> <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
    html += '<div>' + role + '</div>';
    html += '</div>';

    $("#divCalendarUsers").append(html);
</code>```

i'm looking for a better way to use the template.

答:
I male a function that creates the element taking two arguments (role and user).The return of this function you can bind it in every DOM element you want

 function createTemplate(user,role){
      var divCalendar=$('

');
      var buttonElm=$('<button type="button" class="btn btn-default btn-xs">הסר משתמש</button>');
      var spanElm=$(''+user+'');
      var divELm=$('
'+role+'
');
      divCalendar.append(buttonElm).append(spanElm).append(divELm);
      return divCalendar;
    }

//Example below:
$('body').append(createTemplate('user_value', 'role_value'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: How to use Templates on javascript?

Body:
I Have A function that add html to a div.

var user = $("#ddlUser").val();
    var role = $("#ddlUserRole").val();

    var html = '
';
    html += '' + user + ' <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
    html += '
' + role + '
';
    html += '
';

    $("#divCalendarUsers").append(html);

i'm looking for a better way to use the template.

Body:
I male a function that creates the element taking two arguments (role and user).The return of this function you can bind it in every DOM element you want

 function createTemplate(user,role){
      var divCalendar=$('<div class="calendaruser"></div>');
      var buttonElm=$('<button type="button" class="btn btn-default btn-xs">הסר משתמש</button>');
      var spanElm=$('<span>'+user+'</span>');
      var divELm=$('<div>'+role+'</div>');
      divCalendar.append(buttonElm).append(spanElm).append(divELm);
      return divCalendar;
    }

//Example below:
$('body').append(createTemplate('user_value', 'role_value'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
How can I create a div in jQuery that I can scroll left to right in
I am creating a movie search engine. So far when I type in a movie into my input I receive a list of movies as shown in the screenshot below.

The way my movies are shown. I have to scroll down to see more

Instead I want my images to be represented similar to how they are in google.

The way google shows its movies. You have to scroll right to see more, but the page remains static, only the movies change as you scroll

Hopefully someone can help. Thanks in advance!

答:
You can implement it with css but if the situation require JQuery you can do it like below </p>

```<code>$('#search-container').append(
  $('<div/>')
    .attr("id", "movie")
    .addClass("new-movie")
    .css({"width": "1000px", "overflow-x": "auto"})
);
</code>```

Body:
You can implement it with css but if the situation require JQuery you can do it like below

$('#search-container').append(
  $('<div/>')
    .attr("id", "movie")
    .addClass("new-movie")
    .css({"width": "1000px", "overflow-x": "auto"})
);


问:
Generic type 'Component
' requires 2 type argument(s)
I'm trying to use ts and react-router v4 to make a demo, and I will get the error.

```<code>Failed to compile.

Error in D:\data\code\taven\react-components-usage-ts\node_modules\@types\react-router\lib\withRouter.d.ts

(3,99): error TS2314: Generic type 'PureComponent<P, S>' requires 2 type argument(s).
</code>```

答:
You are missing the interfaces for the props and state above the component.</p>

```<code>interface P {
    sampleProp: string,
    awesomeProp2: number

}
interface S {}

PureComponent<P, S>
</code>```

Title: Generic type 'Component<P, S>' requires 2 type argument(s)

Body:
I'm trying to use ts and react-router v4 to make a demo, and I will get the error.

Failed to compile.

Error in D:\data\code\taven\react-components-usage-ts\node_modules\@types\react-router\lib\withRouter.d.ts

(3,99): error TS2314: Generic type 'PureComponent
' requires 2 type argument(s).

Body:
You are missing the interfaces for the props and state above the component.

interface P {
    sampleProp: string,
    awesomeProp2: number

}
interface S {}

PureComponent<P, S>


答:
try this

```<code><html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = [];
       add_to_array(array)
   })
   $("#btn_2").click(function(){
       array = [];
       add_to_array(array)
   })
  $("#add").click(function(){
     array = [];
     array.push(1);
     alert(array);
   })
})

function add_to_array(array){
     array.push(1);
}
</script>
<body>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>
</body>
</html>
</code>```

Hope this helps...

Title: array value not being properly emptied on a button click

Body:
try this

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = [];
       add_to_array(array)
   })
   $("#btn_2").click(function(){
       array = [];
       add_to_array(array)
   })
  $("#add").click(function(){
     array = [];
     array.push(1);
     alert(array);
   })
})

function add_to_array(array){
     array.push(1);
}
</script>
<body>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>
</body>
</html>

Hope this helps...


问:
Redirect hazelcast logs to log4j2 logs
I have hazelcast integrated in my application and it's working fine. My all application logs are correctly getting log in defined log file.

But all hazelcast specific logs are getting displayed on consol but not getting into log file.

do we need to do any specific configuration for hazelcast?

答:
Was able to solve this need to set below properties

```<code>System.setProperty( "hazelcast.logging.type", "log4j2" );
</code>```

http://docs.hazelcast.org/docs/latest-development/manual/html/Setting_Up_Clusters/Logging_Configuration.html

Title: Redirect hazelcast logs to log4j2 logs

Body:
Was able to solve this need to set below properties

System.setProperty( "hazelcast.logging.type", "log4j2" );

http://docs.hazelcast.org/docs/latest-development/manual/html/Setting_Up_Clusters/Logging_Configuration.html


问:
Mapping enums onto database in grails
My grails app uses a lot of enums, but the current GORM solution for enums isn't very satisfactory because it implies the data is in the code, since GORM doesn't map enums into the database.

Previously we used a big table containing different types of enumerations, e.g.: county and city selection in one table. Hence the table in database would contain 3 columns: the enum type (county or city), id and name (which county or city).

Right now I'd like to switch them to real enums, but it just seems unlikely with GORM. I tried to do it with transients in the domain class, but AFAIK it still requires you to have a static enum already present for the class to refer to.

I'm completely lost here, could anybody hint me from where or which function I might get what I wanted ?

答: Simply, do not use Enums for data which is not static and unlikely to change. Instead, use regular domain classes and bootstrap the required data.</p>

Title: Mapping enums onto database in grails


问:
Toggle two divs query
Hi i would like to toggle two divs. I made it basic way but i really want to write it this way and i have no idea what is wrong with this. Could someone help me with it ? </p>

```<code>    (function($) {

    var showAll = function() {
        this.$button = this.find('.btn-all-events');
        this.$all = this.find('.all-events');
        this.$recent = this.find('.recent-events');

        this.initEvents();
    };

    showAll.prototype = {
        initEvents: function() {

            if (this.$all) {
                this.$button.on('click', this.showEvents.bind(this));
            }
        },

        showEvents: function() {
            this.$recent.hide();
            this.$all.show();
        }
    };

    this.toggle = new showAll($(this));
})(jQuery);
</code>```

答:
Use $(this).find() not this.find() Like below

```<code>$(this).find('.btn-all-events');
</code>```

Title: Toggle two divs query

Body:
Hi i would like to toggle two divs. I made it basic way but i really want to write it this way and i have no idea what is wrong with this. Could someone help me with it ?

    (function($) {

    var showAll = function() {
        this.$button = this.find('.btn-all-events');
        this.$all = this.find('.all-events');
        this.$recent = this.find('.recent-events');

        this.initEvents();
    };

    showAll.prototype = {
        initEvents: function() {

            if (this.$all) {
                this.$button.on('click', this.showEvents.bind(this));
            }
        },

        showEvents: function() {
            this.$recent.hide();
            this.$all.show();
        }
    };

    this.toggle = new showAll($(this));
})(jQuery);

Body:
Use $(this).find() not this.find() Like below

$(this).find('.btn-all-events');


问:
Cordova browser opens a different Chrome?
When I use cordova run browser or alternatively cordova run browser --target=chrome the process starts a new Chrome window with a different version Chrome than my default.

<s>On my system I have my regular installation (currently at v58), a Chrome Canary installation (currently at v61) and Cordova opens a new Chrome with v59.</s>
(This weird reporting was probably due to a pending install on my regular Chrome, both regular Chrome and Cordova's opened Chrome are v59)

Why does Cordova not start in a new tab, or why can't I even drag the newly opened window into a tab of my already open regular Chrome?

答:
Based on @Gandhi 's comments I found that switching the var chromeArgs to an empty string in /Projectroot/platforms/browser/cordova/node_modules/cordova_serve/src/browserjs on line 82 achieves the desired result of opening the preview in my default Chrome with logged in user.

This seems a somewhat hacky approach, so I am glad for any more sophisticated solutions on how to reliably switch this from the default behaviour.


问:
Optimizing this Javascript code
I want to know if there's a way to make this code more efficient please, I am trying to improve my own code but I feel I need feedback, with this part:</p>

```<code>$(function(){
    $('#buscar').focus(function(){
        if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
            $(this).val('');
    }).change(function(){
        if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
            $(this).css({'color':'#999999'});
        else
            $(this).css({'color':'#000000'});
    }).blur(function(){
        if(($(this).val() === '') || ($(this).val() === ' '))
           $(this).val('Buscar...');
    });
});
</code>```

答:
Quick optimization:</p>

```<code>$(function(){
$('#buscar').focus(function(){
    var t = $(this);
        var v = $.trim(t.val());
 if(v === '' || 'Buscar...'){
    $(this).val('');
        }
}).change(function(){
    var t = $(this);
        var v = $.trim(t.val());
 (v === '' || 'Buscar...' ? t.css({'color':'#999999'}) : t.css({'color':'#000000'}))
}).blur(function(){
    var t = $(this);
        var v = $.trim(t.val());
    if(v === '')
       t.val('Buscar...');
});
});
</code>```

Title: Optimizing this Javascript code

Body:
I want to know if there's a way to make this code more efficient please, I am trying to improve my own code but I feel I need feedback, with this part:

$(function(){
    $('#buscar').focus(function(){
        if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
            $(this).val('');
    }).change(function(){
        if(($(this).val() === '') || ($(this).val() === ' ') || ($(this).val() === 'Buscar...'))
            $(this).css({'color':'#999999'});
        else
            $(this).css({'color':'#000000'});
    }).blur(function(){
        if(($(this).val() === '') || ($(this).val() === ' '))
           $(this).val('Buscar...');
    });
});

Body:
Quick optimization:

$(function(){
$('#buscar').focus(function(){
    var t = $(this);
        var v = $.trim(t.val());
 if(v === '' || 'Buscar...'){
    $(this).val('');
        }
}).change(function(){
    var t = $(this);
        var v = $.trim(t.val());
 (v === '' || 'Buscar...' ? t.css({'color':'#999999'}) : t.css({'color':'#000000'}))
}).blur(function(){
    var t = $(this);
        var v = $.trim(t.val());
    if(v === '')
       t.val('Buscar...');
});
});


问:
Android studio action bar not showing in new activity
style.xml

<resources>

答:
Try this with activity theme as AppTheme.NoActionBar, hope this help you.</p>

```<code>  <?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:id="@+id/activity_login"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <TextView
                    style="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:text="@string/login_title"
                    android:textColor="@color/colorPrimary"
                    />
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.AppBarLayout>

    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
style.xml

<resources>

Body:
Try this with activity theme as AppTheme.NoActionBar, hope this help you.

  <?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:id="@+id/activity_login"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:popupTheme="@style/AppTheme.PopupOverlay">

                <TextView
                    style="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:text="@string/login_title"
                    android:textColor="@color/colorPrimary"
                    />
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.AppBarLayout>

    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>


问:
Spring Boot with Application authentication (403 Fobidden) CSRF token was null. Has your session expired?
I have a Spring Boot application with thymeleaf template and using HTML with AngularJS as my frontend with mysql as DATABASE and data is passed in JSON

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
</head>
</code>```

My JS file which value gets posted to :

```<code>$scope.logincheck = function() {

var dataObj = {
        userId : $scope.userId,
        password : $scope.password
};

var res = $http.post('http://localhost:9393/company/login', dataObj);
</code>```

and the corresponding controller which handles mysql authentication :

```<code>@RequestMapping(value = "/company/login", method = RequestMethod.POST)
</code>```

not getting called if CSRF is enabled. Upon CSRF enabling, i got 403 error saying CSRF token null was found.

My webconfig.java :

```<code>@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
            .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/", "/login").permitAll()
                .antMatchers("/hello").access("hasRole('ADMIN')")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login")
            .permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/accessdenied")
            .and()
            .csrf()
            .csrfTokenRepository(csrfTokenRepository());
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("ADMIN")
    }

    private CsrfTokenRepository csrfTokenRepository()
    {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }

    public class CsrfHeaderFilter extends OncePerRequestFilter {
          @Override
          protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
              throws ServletException, IOException {
              System.out.println("Inside Webappconfig.java");
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
              Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
              String token = csrf.getToken();
              if (cookie==null || token!=null && !token.equals(cookie.getValue())) {
                cookie = new Cookie("XSRF-TOKEN", token);
                cookie.setPath("/");
                response.addCookie(cookie);
              }
            }
            filterChain.doFilter(request, response);
          }
        }
</code>```

答:
In my case, I had js files under app dir.  This dir threw 403

Adding the following code helped.

.antMatchers("/static/**", "/app/**").permitAll()

Body:
I have a Spring Boot application with thymeleaf template and using HTML with AngularJS as my frontend with mysql as DATABASE and data is passed in JSON

<!DOCTYPE html>

    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>

My JS file which value gets posted to :

$scope.logincheck = function() {

var dataObj = {
        userId : $scope.userId,
        password : $scope.password
};

var res = $http.post('http://localhost:9393/company/login', dataObj);

and the corresponding controller which handles mysql authentication :

@RequestMapping(value = "/company/login", method = RequestMethod.POST)

not getting called if CSRF is enabled. Upon CSRF enabling, i got 403 error saying CSRF token null was found.

My webconfig.java :

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
            .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/", "/login").permitAll()
                .antMatchers("/hello").access("hasRole('ADMIN')")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login")
            .permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/accessdenied")
            .and()
            .csrf()
            .csrfTokenRepository(csrfTokenRepository());
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("ADMIN")
    }

    private CsrfTokenRepository csrfTokenRepository()
    {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }

    public class CsrfHeaderFilter extends OncePerRequestFilter {
          @Override
          protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
              throws ServletException, IOException {
              System.out.println("Inside Webappconfig.java");
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
              Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
              String token = csrf.getToken();
              if (cookie==null || token!=null && !token.equals(cookie.getValue())) {
                cookie = new Cookie("XSRF-TOKEN", token);
                cookie.setPath("/");
                response.addCookie(cookie);
              }
            }
            filterChain.doFilter(request, response);
          }
        }


答:
```<code>        let delimiter = "@"
        var newstr = "Himmoradiya@gmail.com"
        let arr = newstr.components(separatedBy: delimiter)
        let strMail = arr.first!
        let strReplaceStr = String(repeating: "*", count: strMail.characters.count)
        newstr =  newstr.replacingOccurrences(of: strMail, with: strReplaceStr)
</code>```

and output (newstr) will be : ***********@gmail.com

Title: How to replace Email id text before @ with * in swift 3.0

Body:
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")

Any suggestion is accepted.

Thank you.

Body:
        let delimiter = "@"
        var newstr = "Himmoradiya@gmail.com"
        let arr = newstr.components(separatedBy: delimiter)
        let strMail = arr.first!
        let strReplaceStr = String(repeating: "*", count: strMail.characters.count)
        newstr =  newstr.replacingOccurrences(of: strMail, with: strReplaceStr)

and output (newstr) will be : ***********@gmail.com


问:
AnjularJS ng-repeat get item from different scope object
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
        $scope.FindSpecificItem = function(obj, field, value, returnField) {
            return jQuery.grep(obj, function(item) {
                return (item[field] == value);
            })[0][returnField];
        };
        $scope.details = [{
            "Name": "John",
            "CountryId": "1"
        }, {
            "Name": "Dave",
            "CountryId": "2"
        }]
        $scope.Countries = [{
            "Id": "1",
            "Country": "USA"
        }, {
            "Id": "2",
            "Country": "England"
        }]
    });
</script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}</td>
            </tr>
        </table>
    </div>

</body>

</html>
</code>```

答:
Try use angular forEach loop. like this:

  var app = angular.module("myApp", []);
    app.controller("myCtrl", function ($scope) {

        $scope.FindSpecificItem  = function(id) {
        var country1 = "";
          angular.forEach($scope.Countries,function(country){
              if(country.Id == id)
                country1 = country.Country;
          })

          return country1;
        };

        $scope.details = [
            {
                "Name": "John",
                "CountryId": "1"
            },
            {
                "Name": "Dave",
                "CountryId": "2"
            }]

        $scope.Countries = [
            {
                "Id": "1",
                "Country": "USA"
            },
            {
                "Id": "2",
                "Country": "England"
            }]
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(d.CountryId)}}</td>
            </tr>
        </table>
    </div></code>```

Body:
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

<!DOCTYPE html>

                {{d.Name}}
                {{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}

Body:
Try use angular forEach loop. like this:

  var app = angular.module("myApp", []);
    app.controller("myCtrl", function ($scope) {

        $scope.FindSpecificItem  = function(id) {
        var country1 = "";
          angular.forEach($scope.Countries,function(country){
              if(country.Id == id)
                country1 = country.Country;
          })

          return country1;
        };

        $scope.details = [
            {
                "Name": "John",
                "CountryId": "1"
            },
            {
                "Name": "Dave",
                "CountryId": "2"
            }]

        $scope.Countries = [
            {
                "Id": "1",
                "Country": "USA"
            },
            {
                "Id": "2",
                "Country": "England"
            }]
    });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(d.CountryId)}}</td>
            </tr>
        </table>
    </div>


问:
Shake effect doesn't work
Can you help with understanding why the shake effect doesn't work in my case?
Code:

```<code>$('.vote').on('click', function (e) {
        e.preventDefault();
        $("body, html").animate({
            scrollTop: $( $(this).attr('href') ).offset().top
        },{
            duration: 600,
            complete: $('#shake').effect('shake')
        });
    });
</code>```

I tried also to put the effect after the preventDefault but again without success. If i call it outside of the on click event it works properly.
Thank you in advance!

EDIT:
Html part:

```<code><div class="col-xs-6 col-sm-6">
                                <span class="upper">
                                    <a href="#force-reg"><span style="cursor:pointer;font-size: 40px;color: deepskyblue" class="unsigned glyphicon glyphicon-thumbs-up"></span></a>
                                </span>
                                    <span style="font-size: 40px; color: grey" class="thumb-post-up_<?= $post->id ?>"><?= $vote_up ?></span>
                                </div>
                                <div class="col-xs-6 col-sm-6">
                                <span class="upper">
                                    <a href="#force-reg"><span style="cursor:pointer;font-size: 40px;color: grey" class="unsigned glyphicon glyphicon-thumbs-down"></span></a>
                                </span>
                                    <span style="font-size: 40px; color: grey" class="thumb-post-down_<?= $post->id ?>"><?= $vote_down ?></span>
                                </div>
</code>```

#shake div:

```<code><?php if(!(\Yii::$app->user->isGuest)) : ?>
            <div class="col-md-6 text-right custom-title">
                <span style="cursor:pointer;margin-right: 12px;" id="add-comment" class="button button-accent">Добави коментар</span>
            </div>
        <?php else : ?>
            <div id="shake" class="col-md-6 col-sm-6 col-xs-12 text-right custom-title">
                <a href="http://find-doctor.webbuild.com/user/register"><span style="cursor:pointer;margin-right: 12px;"class="button button-accent">Само регистрираните потребители могат да коментират и гласуват!</span></a>
            </div>
        <?php endif; ?>
</code>```

答:
Problem with this object use,In your example you're trying to get href of clicked link but this refer to Current function animate. I've create an example from your code try this:

$('.vote').on('click', function(e) {
  e.preventDefault();
  $("body, html").animate({
    scrollTop: $('.vote').offset().top
  }, {
    duration: 600,
    complete: $('#shake').effect('shake')
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

            <div id="shake" class="col-md-6 col-sm-6 col-xs-12 text-right custom-title">
                <span style="cursor:pointer;margin-right: 12px;"class="button button-accent">Само регистрираните потребители могат да коментират и гласуват!</span>
            </div>

            vote </code>```

Title: Shake effect doesn't work

Body:
Can you help with understanding why the shake effect doesn't work in my case?
Code:

$('.vote').on('click', function (e) {
        e.preventDefault();
        $("body, html").animate({
            scrollTop: $( $(this).attr('href') ).offset().top
        },{
            duration: 600,
            complete: $('#shake').effect('shake')
        });
    });

I tried also to put the effect after the preventDefault but again without success. If i call it outside of the on click event it works properly.
Thank you in advance!

EDIT:
Html part:

                                    <span style="font-size: 40px; color: grey" class="thumb-post-up_<?= $post->id ?>"><?= $vote_up ?>

                                    <span style="font-size: 40px; color: grey" class="thumb-post-down_<?= $post->id ?>"><?= $vote_down ?>

#shake div:

<?php if(!(\Yii::$app->user->isGuest)) : ?>

                Добави коментар

        <?php else : ?>

                Само регистрираните потребители могат да коментират и гласуват!

        <?php endif; ?>

Body:
Problem with this object use,In your example you're trying to get href of clicked link but this refer to Current function animate. I've create an example from your code try this:

$('.vote').on('click', function(e) {
  e.preventDefault();
  $("body, html").animate({
    scrollTop: $('.vote').offset().top
  }, {
    duration: 600,
    complete: $('#shake').effect('shake')
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

            <div id="shake" class="col-md-6 col-sm-6 col-xs-12 text-right custom-title">
                <a href="http://find-doctor.webbuild.com/user/register"><span style="cursor:pointer;margin-right: 12px;"class="button button-accent">Само регистрираните потребители могат да коментират и гласуват!</span></a>
            </div>

            <a href="#" class="vote">vote </a>


问:
Python: split on two different expressions?

Possible Duplicate:

  Python strings split with multiple separators

Is there a way in Python to split a string on two different keys?

Say I have a string like this:

```<code>mystr = "wketjwlektjwltjkw<br/>wwwweltjwetlkwjww" + \
         "wwetlwjtwlet<strong>wwwwketjwlektjwlk</strong"
</code>```

I'd like to split on EITHER
wwww or wwww.

How should I do this?

Thanks!

答:
```<code>import re
re.split(r'<(br\/|strong)>wwww', mystr)[::2]
</code>```

Body:
Possible Duplicate:

  Python strings split with multiple separators

Is there a way in Python to split a string on two different keys?

Say I have a string like this:

mystr = "wketjwlektjwltjkw
wwwweltjwetlkwjww" + \
         "wwetlwjtwletwwwwketjwlektjwlk</strong"

I'd like to split on EITHER
wwww or wwww.

How should I do this?

Thanks!


问:
Exported UWP template is not running
I have created a UWP blank app in VS2017 and ran it. Its working perfectly.

It has x86 and Local Machine in the bar.

Then I export it by going to Project->Export Template and include the template in my VSIX. Then I installed the VSIX. Then created a project with that template. Now that project couldn't run.

It has ARM and Device in the bar. So that I cannot run the project. If I run the project, the below error is coming.

If I change to x86 manually, the project is running fine. What is the problem here? How can I set to x86 by default to my template. I have checked the project and solution files. There is no entry is available for this. Please help.

答:
Found solution. There is an entry in .vstemplate file itself to set the default configuration like below.</p>

```<code><TemplateContent PreferedSolutionConfiguration="Debug|x86">
</code>```

Title: Exported UWP template is not running

Body:
Found solution. There is an entry in .vstemplate file itself to set the default configuration like below.

<TemplateContent PreferedSolutionConfiguration="Debug|x86">


问:
Chart.js not installing with NPM
I am trying to install chart.js . Their documentation for how to install the package with NPM is here : http://www.chartjs.org/docs/latest/getting-started/installation.html

It says to enter the following with NPM to install.

```<code>npm install chart.js --save
</code>```

However, it doesn't work for me. I get the followin error in my console when I try to install chart.js with NPM.

```<code>C:\Users\Hashim AHmed\Desktop\Hashim\coding\Project_PlasmaBird\yahoo_finance>npm install chart.js --save
npm ERR! not a package (MY PROJECT DIRECTORY)\yahoo_finance\chart.js
npm ERR! addLocal Could not install (MY PROJECT DIRECTORY)\yahoo_finance\chart.js
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "chart.js" "--save"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! path C:\Users\HASHIM~1\AppData\Local\Temp\npm-6480-170f285f\unpack-fccf9cad\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\HASHIM~1\AppData\Local\Temp\npm-6480-170f285f\unpack-fccf9cad\package.json'
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\HASHIM~1\AppData\Local\Temp\npm-6480-170f285f\unpack-fccf9cad\package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     (mydirectory)\npm-debug.logwing error:
</code>```

EDIT: As some have pointed out, the error may lie in my Package.json so here is the code of my package file  (i have censored out some private info) :

```<code>{
  "name": "projectplasma",
  "version": "1.0.0",
  "description": "projectplasma",
  "main": "index.js",
  "dependencies": {
    "colors": "^1.1.2",
    "yahoo-finance": "^0.3.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/(my username)/(my repo).git"
  },
  "keywords": [
    "stk"
  ],
  "author": "Hashim",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/(myusername)/(my repo)/issues"
  },
  "homepage": "https://github.com/(my username)/(my repo)#readme"
}
</code>```

Any ideas of what's going wrong here? I am doing exactly as the documentation is saying. If someone could test install this to see if it is working, that would be great. Thanks

答:
You need to have the package.json file in your directory to have this chart.js module saved locally.

To create a package.json file, use the below command,

npm init (which will ask you few questions and will create the file at the end).

Once you create your package.json try executing the npm install chart.js --save command and see if it works.

Hope this helps!

Title: Chart.js not installing with NPM

Body:
I am trying to install chart.js . Their documentation for how to install the package with NPM is here : http://www.chartjs.org/docs/latest/getting-started/installation.html

It says to enter the following with NPM to install.

npm install chart.js --save

However, it doesn't work for me. I get the followin error in my console when I try to install chart.js with NPM.

C:\Users\Hashim AHmed\Desktop\Hashim\coding\Project_PlasmaBird\yahoo_finance>npm install chart.js --save
npm ERR! not a package (MY PROJECT DIRECTORY)\yahoo_finance\chart.js
npm ERR! addLocal Could not install (MY PROJECT DIRECTORY)\yahoo_finance\chart.js
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "chart.js" "--save"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10
npm ERR! path C:\Users\HASHIM~1\AppData\Local\Temp\npm-6480-170f285f\unpack-fccf9cad\package.json
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall open

npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\HASHIM~1\AppData\Local\Temp\npm-6480-170f285f\unpack-fccf9cad\package.json'
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\HASHIM~1\AppData\Local\Temp\npm-6480-170f285f\unpack-fccf9cad\package.json'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! Please include the following file with any support request:
npm ERR!     (mydirectory)\npm-debug.logwing error:

EDIT: As some have pointed out, the error may lie in my Package.json so here is the code of my package file  (i have censored out some private info) :

{
  "name": "projectplasma",
  "version": "1.0.0",
  "description": "projectplasma",
  "main": "index.js",
  "dependencies": {
    "colors": "^1.1.2",
    "yahoo-finance": "^0.3.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/(my username)/(my repo).git"
  },
  "keywords": [
    "stk"
  ],
  "author": "Hashim",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/(myusername)/(my repo)/issues"
  },
  "homepage": "https://github.com/(my username)/(my repo)#readme"
}

Any ideas of what's going wrong here? I am doing exactly as the documentation is saying. If someone could test install this to see if it is working, that would be great. Thanks


答:
The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

You call your function add_to_array() every time you click on .btn_1 or .btn_2 and it defines a new event listener on #add each time.
Plus you push 1 into your array in the same function.
The click event should call your function, not the other way around.

```<code>$(document).ready(function(){
   var array = [];
   $("#btn_1").click(function(){
       empty_array(array);
   });
   $("#btn_2").click(function(){
       empty_array(array);
   });
   $("#add").click(function(){
       add_to_array(array);
       alert(array);
   })
});

function empty_array(array) {
    array = [];
}

function add_to_array(array){
    array.push(1);
}
</code>```

Body:
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}

<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

Body:
The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

You call your function add_to_array() every time you click on .btn_1 or .btn_2 and it defines a new event listener on #add each time.
Plus you push 1 into your array in the same function.
The click event should call your function, not the other way around.

$(document).ready(function(){
   var array = [];
   $("#btn_1").click(function(){
       empty_array(array);
   });
   $("#btn_2").click(function(){
       empty_array(array);
   });
   $("#add").click(function(){
       add_to_array(array);
       alert(array);
   })
});

function empty_array(array) {
    array = [];
}

function add_to_array(array){
    array.push(1);
}