问:
Postgres incorrect update on join
I am trying to run some update queries on Postgres where tables are joined on common field. This is run with SQL Server and the update count is 1 which is expected whereas postgres the update count is 3. It seems that postgres does not perform implicit join when the destination table is the same name as the source table involved in the join. The script could be more descript than what is being said and here it is:

```<code>drop table test;
drop table test2;
create table test(col1 int, col2 varchar(10));
insert into test values(1, 'aaa');
insert into test values(2, 'bbb');
insert into test values(3, 'ccc');
create table test2(col1 int);
insert into test2 values(2);
select * from test;
select * from test2;

// Select join = rowcount 1
select count(*) from test t2, test2 t3
where t2.col1 = t3.col1;

// SQL Server update = 1; postgres =3
update test set col2 = 'changed'
from test t2, test2 t3
where t2.col1 = t3.col1;
</code>```

The above query can be simplified with:

```<code>update test set col2 = 'changed'
from test2 where test.col1 = test2.col1;
</code>```

but that is not my intention as the join clause might involve some more join statements.
The desired intention was to run a query like this:

```<code>UPDATE IDMAP_CHILD_JOBID SET RESTORESUCCESS = IDMAP_TABLE_JOBID.RESTORESUCCESS, RESTOREERRMSG = IDMAP_TABLE_JOBID.RESTOREERRMSG
FROM CHILD, IDMAP_TABLE_JOBID
WHERE CHILD.ID = IDMAP_CHILD_JOBID.OLDID AND CHILD.FK1 = IDMAP_TABLE_JOBID.OLDID
AND IDMAP_TABLE_JOBID.RESTORESUCCESS = $FALSE
</code>```

Postgres complains with table specified more than once if IDMAP_CHILD_JOBID is the same as IDMAP_TABLE_JOBID. How can this be rewritten?
My application is supposed to generate an update statement where this is unified query is supposed to be run whereas the behaviour is different. It is obvious that join is performed on select while it is not under update.

答:
I am a little confused as there seems to be a difference between the Simplified Query (SQry)
2 tables: test,test2 and
Final Query (FQry)
3 tables: IDMAP_CHILD_JOBID, CHILD, IDMAP_TABLE_JOBID

To update the single row in SQry: (Note the t1 alias to hopefully prevent table specified more than once error)

```<code>update test t1
   set col2 = 'changed'
  from test t2, test2 t3
 where t2.col1   = t3.col1
   and t1.col1 = t3.col1;
</code>```

So the FQry will update the rows returned from this query and if there are multiple rows in IDMAP_CHILD_JOBID which match CHILD.ID, they will all get updated.

```<code>select IDMAP_CHILD_JOBID.RESTORESUCCESS,
       IDMAP_TABLE_JOBID.RESTORESUCCESS, RESTOREERRMSG,
       IDMAP_TABLE_JOBID.RESTOREERRMSG
FROM IDMAP_CHILD_JOBID, CHILD, IDMAP_TABLE_JOBID
WHERE CHILD.ID = IDMAP_CHILD_JOBID.OLDID
  AND CHILD.FK1 = IDMAP_TABLE_JOBID.OLDID
  AND IDMAP_TABLE_JOBID.RESTORESUCCESS = $FALSE
</code>```

Title: Postgres incorrect update on join

Body:
I am trying to run some update queries on Postgres where tables are joined on common field. This is run with SQL Server and the update count is 1 which is expected whereas postgres the update count is 3. It seems that postgres does not perform implicit join when the destination table is the same name as the source table involved in the join. The script could be more descript than what is being said and here it is:

drop table test;
drop table test2;
create table test(col1 int, col2 varchar(10));
insert into test values(1, 'aaa');
insert into test values(2, 'bbb');
insert into test values(3, 'ccc');
create table test2(col1 int);
insert into test2 values(2);
select * from test;
select * from test2;

// Select join = rowcount 1
select count(*) from test t2, test2 t3
where t2.col1 = t3.col1;

// SQL Server update = 1; postgres =3
update test set col2 = 'changed'
from test t2, test2 t3
where t2.col1 = t3.col1;

The above query can be simplified with:

update test set col2 = 'changed'
from test2 where test.col1 = test2.col1;

but that is not my intention as the join clause might involve some more join statements.
The desired intention was to run a query like this:

UPDATE IDMAP_CHILD_JOBID SET RESTORESUCCESS = IDMAP_TABLE_JOBID.RESTORESUCCESS, RESTOREERRMSG = IDMAP_TABLE_JOBID.RESTOREERRMSG
FROM CHILD, IDMAP_TABLE_JOBID
WHERE CHILD.ID = IDMAP_CHILD_JOBID.OLDID AND CHILD.FK1 = IDMAP_TABLE_JOBID.OLDID
AND IDMAP_TABLE_JOBID.RESTORESUCCESS = $FALSE

Postgres complains with table specified more than once if IDMAP_CHILD_JOBID is the same as IDMAP_TABLE_JOBID. How can this be rewritten?
My application is supposed to generate an update statement where this is unified query is supposed to be run whereas the behaviour is different. It is obvious that join is performed on select while it is not under update.

Body:
I am a little confused as there seems to be a difference between the Simplified Query (SQry)
2 tables: test,test2 and
Final Query (FQry)
3 tables: IDMAP_CHILD_JOBID, CHILD, IDMAP_TABLE_JOBID

To update the single row in SQry: (Note the t1 alias to hopefully prevent table specified more than once error)

update test t1
   set col2 = 'changed'
  from test t2, test2 t3
 where t2.col1   = t3.col1
   and t1.col1 = t3.col1;

So the FQry will update the rows returned from this query and if there are multiple rows in IDMAP_CHILD_JOBID which match CHILD.ID, they will all get updated.

select IDMAP_CHILD_JOBID.RESTORESUCCESS,
       IDMAP_TABLE_JOBID.RESTORESUCCESS, RESTOREERRMSG,
       IDMAP_TABLE_JOBID.RESTOREERRMSG
FROM IDMAP_CHILD_JOBID, CHILD, IDMAP_TABLE_JOBID
WHERE CHILD.ID = IDMAP_CHILD_JOBID.OLDID
  AND CHILD.FK1 = IDMAP_TABLE_JOBID.OLDID
  AND IDMAP_TABLE_JOBID.RESTORESUCCESS = $FALSE


来源: stackexchange

问:
How can I call javascript funtion in react js to show style correctly with html theme
In my react js, I used html theme but the design is not appeared correctly according to html style design,It is shown as normal checkbox.How can I do that and how can I render javascript function switchery theme.</p>

```<code> <div id="tab5" className="tab-pane fade">
 <input type="checkbox" data-render="switchery" data-theme="lime" checked />
   </div>
</code>```

答:
Add a selector(class or Id) to the input element

```<code> <div id="tab5" className="tab-pane fade">
    <input className="js-switch" type="checkbox" data-render="switchery" data-theme="lime" checked />
</div>
</code>```

and call Switchery as shown below.

```<code>var elem = document.querySelector('.js-switch');
var init = new Switchery(elem);
</code>```

You can read the documentation to apply for multiple input elements here

Here is the working codepen link

And I believe you are loading the switchery css file into your webpage.

```<code><head>
  <link rel="stylesheet" href="assets/switchery.css">
</head>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my react js, I used html theme but the design is not appeared correctly according to html style design,It is shown as normal checkbox.How can I do that and how can I render javascript function switchery theme.

 <input type="checkbox" data-render="switchery" data-theme="lime" checked />

Body:
Add a selector(class or Id) to the input element

 <div id="tab5" className="tab-pane fade">
    <input className="js-switch" type="checkbox" data-render="switchery" data-theme="lime" checked />
</div>

and call Switchery as shown below.

var elem = document.querySelector('.js-switch');
var init = new Switchery(elem);

You can read the documentation to apply for multiple input elements here

Here is the working codepen link

And I believe you are loading the switchery css file into your webpage.

<head>
  <link rel="stylesheet" href="assets/switchery.css">
</head>


问:
Preventing classes from being instantiated on the stack or as data member
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

```<code>// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };
</code>```

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

```<code>typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };
</code>```

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

```<code>class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));
</code>```

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

```<code>Module m(RingAlertPtr(&m_myRingAlert,[](void *){});
</code>```

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?

答: Make the constructor for RingAlert private and create a static method that calls new and returns the pointer (or better yet, returns the shared_ptr).

ContentLicense: CC BY-SA 2.5

Body:
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

Module m(RingAlertPtr(&m_myRingAlert,[](void *){});

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?


问:
2D Button Array ActionListener, color change?
I have this 2D JButton array (color white), and what I want to do is when I click on a square, it'll turn into orange. When I click another square, that square becomes orange as well but the first square I clicked will return to its normal white color. How do I do it without having all the squares turn into orange?

Here's a visualization:

Btw, when I click the squares with the numbers, their colors do not change, think of them as like setEnabled(false) buttons. I already know how to change the colors of the buttons, I just want to know how the color gets passed on square after square.

Thanks to anyone who can help!

Edit: My "attempt" but it's making all of my null valued buttons orange.

```<code>button[i][j].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e){
       for(int i = 0; i < button.length; i++)
           for(int j = 0; j < button.length; j++){
               if(g.gameBoard[i][j] == null){
                   //must find the position where the user clicks and make it orange
                    button[i][j].setBackground(Color.ORANGE);
               }
           }
       }
});
</code>```

答:
```<code>if(e.getSource()== null)
{
    //must find the position where the user clicks and make it orange
     button[i][j].setBackground(Color.ORANGE);
}
</code>```

Try This above code  in the public void actionPerformed(ActionEvent e) method.

Body:
I have this 2D JButton array (color white), and what I want to do is when I click on a square, it'll turn into orange. When I click another square, that square becomes orange as well but the first square I clicked will return to its normal white color. How do I do it without having all the squares turn into orange?

Here's a visualization:

Btw, when I click the squares with the numbers, their colors do not change, think of them as like setEnabled(false) buttons. I already know how to change the colors of the buttons, I just want to know how the color gets passed on square after square.

Thanks to anyone who can help!

Edit: My "attempt" but it's making all of my null valued buttons orange.

button[i][j].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e){
       for(int i = 0; i < button.length; i++)
           for(int j = 0; j < button.length; j++){
               if(g.gameBoard[i][j] == null){
                   //must find the position where the user clicks and make it orange
                    button[i][j].setBackground(Color.ORANGE);
               }
           }
       }
});

Body:
if(e.getSource()== null)
{
    //must find the position where the user clicks and make it orange
     button[i][j].setBackground(Color.ORANGE);
}

Try This above code  in the public void actionPerformed(ActionEvent e) method.


问:
how to detect all dollar signs in different encoding with javascript
Suppose I have a string "$ $ $ ＄ ＄", Google chrome can detect each dollar sign in the string with ctrl+F. But Javascript cannot detect all of them.

I wish to detect and replace all dollar signs in the string with Javascript . Please help.

答:
You can search for the rest of the dollar signs  http://www.fileformat.info/search/google.htm?q=dollar

console.log("$ $ $ ＄ ＄".replace(/[$＄﹩]/g, 0))```


问:
MXNet R package on an Amazon Linux Deep Learning EC2 instance
I'm attempting to setup an Amazon Linux EC2 instance with MXNet and R (and the MXNet r package available as well). Unfortunately this has been a lot harder than I expected.

I've attempted to follow the instructions from MXNet using Amazon's deep learning AMI with CUDA 8.0 on a p2.xlarge (https://mxnet.incubator.apache.org/get_started/install.html)

However I get the same error when attempting to compile the mxnet r package from this SO post:

Issues installing mxnet GPU R package for Amazon deep learning AMI

The solution discussed in that post are somewhat beyond my abilities to fully test/debug. i.e. I'm not particularly familiar with linux environment variables and such to modify. I've also reviewed some issues raised on the apache-incubator github for MXnet and those were pretty unhelpful as well.

So my questions are,

Is anyone aware of any available AMI's which come pre-packaged with R and MXNet? The ones I see seem to only include python.

Have a working set of instructions (or a script) to run on an Amazon Linux EC2 instance to install the required dependencies (assuming Im using some type of deep learning AMI that comes with CUDA 8.0 at least) to install the MXnet R package?

答:
Right so I was the guy on the other post and I DID eventually get it working. Took 50+ hours and I'm not 100% sure where the issue was because...linux.

```<code>sudo yum install R
sudo yum install libxml2-devel
sudo yum install cairo-devel
sudo yum install giflib-devel
sudo yum install libXt-devel
sudo R
install.packages("devtools")
library(devtools)
install_github("igraph/rigraph")
install.packages(c(“DiagrammeR”, “roxygen2”, “rgexf”, “influenceR”,  “Cairo”, “imager”))
cd
cd /src/mxnet
cp make/config.mk .
echo "USE_BLAS=openblas" >>config.mk
echo "ADD_CFLAGS += -I/usr/include/openblas" >>config.mk
echo "ADD_LDFLAGS += /usr/local/lib" >>config.mk
echo "USE_CUDA=1" >>config.mk
echo "USE_CUDA_PATH=/usr/local/cuda-9.0/lib64" >>config.mk
echo "USE_CUDNN=1" >>config.mk
*add another LD flag for /usr/local/lib

cd /etc/ld.so.conf.d/
sudo nano  cuda.conf
    Insert     /usr/local/cuda-9.0/lib64
cd
export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64/:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH
sudo ldconfig

cd R-package
Rscript -e "install.packages('devtools', repo = 'https://cran.rstudio.com')"
Rscript -e "library(devtools); library(methods);options(repos=c(CRAN='https://cran.rstudio.com'));install_deps(dependencies = TRUE)"
cd ..

sudo make rpkg
</code>```

THEN you gotta make sure R/Rstudio can actually find those libraries:

```<code>cd /etc/rstudio
sudo nano rserver.conf
</code>```

You can add elements to the default LD_LIBRARY_PATH for R sessions (as determined by the R ldpaths script) by adding an rsession-ld-library-path entry to the server config file. This might be useful for ensuring that packages can locate external library dependencies that aren't installed in the system standard library paths. For example:

```<code>rsession-ld-library-path=/opt/local/lib:/usr/local/cuda/lib64
</code>```

Body:
Right so I was the guy on the other post and I DID eventually get it working. Took 50+ hours and I'm not 100% sure where the issue was because...linux.

sudo yum install R
sudo yum install libxml2-devel
sudo yum install cairo-devel
sudo yum install giflib-devel
sudo yum install libXt-devel
sudo R
install.packages("devtools")
library(devtools)
install_github("igraph/rigraph")
install.packages(c(“DiagrammeR”, “roxygen2”, “rgexf”, “influenceR”,  “Cairo”, “imager”))
cd
cd /src/mxnet
cp make/config.mk .
echo "USE_BLAS=openblas" >>config.mk
echo "ADD_CFLAGS += -I/usr/include/openblas" >>config.mk
echo "ADD_LDFLAGS += /usr/local/lib" >>config.mk
echo "USE_CUDA=1" >>config.mk
echo "USE_CUDA_PATH=/usr/local/cuda-9.0/lib64" >>config.mk
echo "USE_CUDNN=1" >>config.mk
*add another LD flag for /usr/local/lib

cd /etc/ld.so.conf.d/
sudo nano  cuda.conf
    Insert     /usr/local/cuda-9.0/lib64
cd
export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64/:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/local/lib/:$LD_LIBRARY_PATH
sudo ldconfig

cd R-package
Rscript -e "install.packages('devtools', repo = 'https://cran.rstudio.com')"
Rscript -e "library(devtools); library(methods);options(repos=c(CRAN='https://cran.rstudio.com'));install_deps(dependencies = TRUE)"
cd ..

sudo make rpkg

THEN you gotta make sure R/Rstudio can actually find those libraries:

cd /etc/rstudio
sudo nano rserver.conf

You can add elements to the default LD_LIBRARY_PATH for R sessions (as determined by the R ldpaths script) by adding an rsession-ld-library-path entry to the server config file. This might be useful for ensuring that packages can locate external library dependencies that aren't installed in the system standard library paths. For example:

rsession-ld-library-path=/opt/local/lib:/usr/local/cuda/lib64


问:
How can Increase performance on my Ionic3 Anguar4 app?
Now I am working with Ionic3, Angular4 android app. It is taking a while to load initially. I mean I got a black blank screen for few seconds.How can I speed up this and avoid the black screen?</p>

答: Performance can be improved by breaking down your application into modules and follow lazy loading for the modules.


问:
jQuery .hover() not changing image
I've looked around and tried a few things I've seen on here to try to fix this issue but I can't seem to find out why. I have five images in the toppic class. I want to be able to hover over an image in the toppic class and change the big image (id = Biggin) in my screen with the image that is being hovered over, and then change back to the default when the mouse leaves the image. Is there anything blatantly wrong? I copied and pasted from a previous working function and I'm not sure as to what I did wrong this time.

```<code>$(".toppic").hover(function() {
  var imgsrc = this.src;
  $("#Biggin").attr("src", imgsrc);

})
$(".toppic").mouseout(function() {
  $("#Biggin").attr("src", ".//Images/IMG_3604.JPG");
})
</code>```

答:
I had similar issues when starting out using jQuery, and there could be a few reasons why your code isn't working as intended. The most common reason mine wasn't working is that the jQuery script element was getting activated before the DOM existed.

Make sure that the jQuery script element in your html file loads after your DOM loads. You can place the jQuery script element at the end of the HTML file so your jQuery would be loaded after the HTML loads.

I hope that helps.

Title: jQuery .hover() not changing image

Body:
I've looked around and tried a few things I've seen on here to try to fix this issue but I can't seem to find out why. I have five images in the toppic class. I want to be able to hover over an image in the toppic class and change the big image (id = Biggin) in my screen with the image that is being hovered over, and then change back to the default when the mouse leaves the image. Is there anything blatantly wrong? I copied and pasted from a previous working function and I'm not sure as to what I did wrong this time.

$(".toppic").hover(function() {
  var imgsrc = this.src;
  $("#Biggin").attr("src", imgsrc);

})
$(".toppic").mouseout(function() {
  $("#Biggin").attr("src", ".//Images/IMG_3604.JPG");
})


问:
Redux state wont propagate to component
I've been attempting to make a component using Reacts component functionality. In this case I was particularly interested in componentDidMount.

However, no matter what I try, my state wont propagate to the component.

Here is the component:

```<code>class MainPage extends React.Component
{
    componentDidMount() {
        this.props.actions.requestPosts();
    }
    render() {
        return(
            <div className="main-page">
                <PreviewList posts={this.props.posts}/>
            </div>
        );
    }
}

const mapStateToProps = state => ({
    posts: state.main_posts,
    errors: state.main_errors
});

const mapDispatchToProps = dispatch => {
    return {
        actions: {
            requestPosts: () => dispatch(requestPosts())
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
</code>```

The reducer:

```<code>export default (state = {main_posts: [], main_errors: []}, action) => {
    switch(action.type) {
        case USER_REQUESTS_POSTS_SUCCEEDED:
            return Object.assign({}, state, {
                main_posts: action.posts
            });
        case USER_REQUESTS_POSTS_FAILED:
            return Object.assign({}, state, {
                main_errors: action.errors
            });
        default:
            return state;
    }
};
</code>```

For the purpose of simplicity, I did not include the import statements. I use redux-thunk. I've tested the actions, they successfully arrive at the reducer. The new state is successfully created and returned. It simply does not arrive at the desired component however.

I have tried researching and I've only found examples of reducers that mutated the state, but I can't see anything where I mutate the state. What am I doing wrong? (Ironically the code is similiar to my other react apps that work fine).

In case it is helpful, here is my store:

```<code>export const history = createHistory();

const middleware = [
    thunk,
    routerMiddleware(history)
];

const reducers = {
    main: mainReducer,
    router: routerReducer
};

const store = createStore(
    combineReducers(reducers),
    {},
    applyMiddleware(...middleware)
);

export default store;
</code>```

EDIT: As requested, here are my actions:

```<code>export const USER_REQUESTS_POSTS_SUCCEEDED = 'user/REQUESTS/POSTS/SUCCESS';
export const USER_REQUESTS_POSTS_FAILED = 'user/REQUESTS/POSTS/FAILURE';

export const requestPosts = () => {
    return function(dispatch) {
        return fetchPosts().then(
            posts => dispatch(requestPostsSucceeded(posts)),
            errors => dispatch(requestPostsFailed(errors))
        );
    };
};

function fetchPosts() {
    return Promise.resolve([{title: 'Test Post', content_short: 'Hello World', author: 'Extremo', category: 'development', tags: ['test'], date: '15.11.17'}]);
}

export const requestPostsSucceeded = (posts) => {
    return {type: USER_REQUESTS_POSTS_SUCCEEDED, posts: posts};
};

export const requestPostsFailed = (errors) => {
    return {type: USER_REQUESTS_POSTS_FAILED, errors: errors};
};
</code>```

答:
From store definition

```<code>const reducers = {
    main: mainReducer,
    router: routerReducer
};
</code>```

You should access your component state using your component reducer's key

which is main.

```<code>const mapStateToProps = state => ({
    posts: state.main.main_posts,
    errors: state.main.main_errors
});
</code>```

Title: Redux state wont propagate to component

Body:
I've been attempting to make a component using Reacts component functionality. In this case I was particularly interested in componentDidMount.

However, no matter what I try, my state wont propagate to the component.

Here is the component:

class MainPage extends React.Component
{
    componentDidMount() {
        this.props.actions.requestPosts();
    }
    render() {
        return(

                <PreviewList posts={this.props.posts}/>

        );
    }
}

const mapStateToProps = state => ({
    posts: state.main_posts,
    errors: state.main_errors
});

const mapDispatchToProps = dispatch => {
    return {
        actions: {
            requestPosts: () => dispatch(requestPosts())
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(MainPage);

The reducer:

export default (state = {main_posts: [], main_errors: []}, action) => {
    switch(action.type) {
        case USER_REQUESTS_POSTS_SUCCEEDED:
            return Object.assign({}, state, {
                main_posts: action.posts
            });
        case USER_REQUESTS_POSTS_FAILED:
            return Object.assign({}, state, {
                main_errors: action.errors
            });
        default:
            return state;
    }
};

For the purpose of simplicity, I did not include the import statements. I use redux-thunk. I've tested the actions, they successfully arrive at the reducer. The new state is successfully created and returned. It simply does not arrive at the desired component however.

I have tried researching and I've only found examples of reducers that mutated the state, but I can't see anything where I mutate the state. What am I doing wrong? (Ironically the code is similiar to my other react apps that work fine).

In case it is helpful, here is my store:

export const history = createHistory();

const middleware = [
    thunk,
    routerMiddleware(history)
];

const reducers = {
    main: mainReducer,
    router: routerReducer
};

const store = createStore(
    combineReducers(reducers),
    {},
    applyMiddleware(...middleware)
);

export default store;

EDIT: As requested, here are my actions:

export const USER_REQUESTS_POSTS_SUCCEEDED = 'user/REQUESTS/POSTS/SUCCESS';
export const USER_REQUESTS_POSTS_FAILED = 'user/REQUESTS/POSTS/FAILURE';

export const requestPosts = () => {
    return function(dispatch) {
        return fetchPosts().then(
            posts => dispatch(requestPostsSucceeded(posts)),
            errors => dispatch(requestPostsFailed(errors))
        );
    };
};

function fetchPosts() {
    return Promise.resolve([{title: 'Test Post', content_short: 'Hello World', author: 'Extremo', category: 'development', tags: ['test'], date: '15.11.17'}]);
}

export const requestPostsSucceeded = (posts) => {
    return {type: USER_REQUESTS_POSTS_SUCCEEDED, posts: posts};
};

export const requestPostsFailed = (errors) => {
    return {type: USER_REQUESTS_POSTS_FAILED, errors: errors};
};

Body:
From store definition

const reducers = {
    main: mainReducer,
    router: routerReducer
};

You should access your component state using your component reducer's key

which is main.

const mapStateToProps = state => ({
    posts: state.main.main_posts,
    errors: state.main.main_errors
});


问:
JAVA Looping a formula
To start, I'm a relatively new programmer as it pertains to JAVA. I've searched for many things but it's possible I'm not search for the right thing. I'm basically trying to list from the first "year" to the 10th "year" a starting amount, multiplied by the percentage, and added to the starting amount. Then, I want to take that new amount and do the same thing over and over again until it gets to 10. Or, even a specified total ex:2000.</p>

```<code>public static void main(String[] args)
{
    double startAmount = 1000;
    double ratePercentage = 0.05;
    double newAmount;

    for (int i = 0; i <= 10; i++){
        newAmount = startAmount + (startAmount * ratePercentage);
        System.out.println(i + " " + newAmount);

    }

}
</code>```

答:
Try this</p>

```<code>public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;

for (int i = 0; i < 10; i++){
    newAmount = startAmount + (startAmount * ratePercentage);
    System.out.println(i + " " + newAmount);
    startAmount=newAmount;

}

}
</code>```

Title: JAVA Looping a formula

Body:
To start, I'm a relatively new programmer as it pertains to JAVA. I've searched for many things but it's possible I'm not search for the right thing. I'm basically trying to list from the first "year" to the 10th "year" a starting amount, multiplied by the percentage, and added to the starting amount. Then, I want to take that new amount and do the same thing over and over again until it gets to 10. Or, even a specified total ex:2000.

public static void main(String[] args)
{
    double startAmount = 1000;
    double ratePercentage = 0.05;
    double newAmount;

    for (int i = 0; i <= 10; i++){
        newAmount = startAmount + (startAmount * ratePercentage);
        System.out.println(i + " " + newAmount);

    }

}

Body:
Try this

public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;

for (int i = 0; i < 10; i++){
    newAmount = startAmount + (startAmount * ratePercentage);
    System.out.println(i + " " + newAmount);
    startAmount=newAmount;

}

}


问:
Create a set of files based off a date range
How would you go about doing a few lines of code in Bash to accomplish the following. I'm trying to build up my skills in Bash and learn how to handle more small tasks directory from the command line.

Steps:

Specify a start date and an end date. Load all the dates in between including the start and end date into a "list"

Loop over the list creating a file like this each time.
(requires date formatting)

```<code>2017-11-10.w
2017-11-11.w
2017-11-12.w
</code>```

答:
You could convert the input dates to Unix timestamps, then add the number of seconds per day and touch a file named after the result until you are past the end date:

```<code>#!/bin/bash

startstamp=$(date -d "$1" +'%s')
endstamp=$(date -d "$2" +'%s')

secs_per_day=$(( 24 * 3600 ))

for (( thedate = startstamp; thedate <= endstamp; thedate += secs_per_day )); do
    touch "$(date -d "@$thedate" '+%F.w')"
done
</code>```

The %s formatting string (a GNU extension) prints the number of seconds since the Unix epoch, and @ in the argument to the -d option indicates that the date is in that format. %F is short for %Y-%m-%d, which translates to YYYY-MM-DD.

Example usage:

```<code>$ ./dates 2017-11-10 2017-11-15
$ ls -1
2017-11-10.w
2017-11-11.w
2017-11-12.w
2017-11-13.w
2017-11-14.w
2017-11-15.w
dates
</code>```

Body:
How would you go about doing a few lines of code in Bash to accomplish the following. I'm trying to build up my skills in Bash and learn how to handle more small tasks directory from the command line.

Steps:

Specify a start date and an end date. Load all the dates in between including the start and end date into a "list"

Loop over the list creating a file like this each time.
(requires date formatting)

2017-11-10.w
2017-11-11.w
2017-11-12.w

Body:
You could convert the input dates to Unix timestamps, then add the number of seconds per day and touch a file named after the result until you are past the end date:

#!/bin/bash

startstamp=$(date -d "$1" +'%s')
endstamp=$(date -d "$2" +'%s')

secs_per_day=$(( 24 * 3600 ))

for (( thedate = startstamp; thedate <= endstamp; thedate += secs_per_day )); do
    touch "$(date -d "@$thedate" '+%F.w')"
done

The %s formatting string (a GNU extension) prints the number of seconds since the Unix epoch, and @ in the argument to the -d option indicates that the date is in that format. %F is short for %Y-%m-%d, which translates to YYYY-MM-DD.

Example usage:

$ ./dates 2017-11-10 2017-11-15
$ ls -1
2017-11-10.w
2017-11-11.w
2017-11-12.w
2017-11-13.w
2017-11-14.w
2017-11-15.w
dates


问:
unwraping div tags between two elements
I want to remove the div's between two specific elements

item1

item2

item3

item4

```
</div>
</div>
</p>

<p>i want to remove the div's between  id test1 and id ulid
how to use unwrap here
expected output</p>

```

item1

item2

item3

item4

```

答:
$( "#test2" ).replaceWith($('#ulid'));```
<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>
    <div id="test1">
      <div id="test2">
        <div id="test3">
          <div id="test4">
            <div id="test5">
              <div id="test6">
                <ul id="ulid">
                  <li>item1</li>
                  <li>item2</li>
                  <li>item3</li>
                  <li>item4</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div></code>```

Title: unwraping div tags between two elements

Body:
I want to remove the div's between two specific elements

item1

item2

item3

item4

i want to remove the div's between  id test1 and id ulid
how to use unwrap here
expected output

item1

item2

item3

item4

Body:
$( "#test2" ).replaceWith($('#ulid'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="test1">
      <div id="test2">
        <div id="test3">
          <div id="test4">
            <div id="test5">
              <div id="test6">
                <ul id="ulid">
                  <li>item1</li>
                  <li>item2</li>
                  <li>item3</li>
                  <li>item4</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


答:
I'm not 100% sure what you are trying to achive. But assuming you are trying to do some sort of compounding interest. This should help.</p>

```<code>public static void main(String[] args)
{
    double startAmount = 1000;
    double ratePercentage = 0.05;
    double newAmount;

    newAmount = startAmount;

    for (int i = 0; i <= 10; i++){
        newAmount = newAmount + (newAmount * ratePercentage);
        System.out.println(i + " " + newAmount);

    }

}
</code>```

Title: JAVA Looping a formula

Body:
I'm not 100% sure what you are trying to achive. But assuming you are trying to do some sort of compounding interest. This should help.

public static void main(String[] args)
{
    double startAmount = 1000;
    double ratePercentage = 0.05;
    double newAmount;

    newAmount = startAmount;

    for (int i = 0; i <= 10; i++){
        newAmount = newAmount + (newAmount * ratePercentage);
        System.out.println(i + " " + newAmount);

    }

}


问:
how to `bindActionCreators` with redux-thunk
I am quite new to JavaScript and react-native and I have existing project that I need to add functionality to. It is using redux and redux-thunk with redux-saga to send API requests. Currently it supports only 1 dispatch function per component and I need to dispatch several types of requests to the saga. I am trying to bindActionCreators to add the dispatch to the stores but to no avail.. I am totally lost on the mapDispatchToProps part and how do I "fire the action" afterwards..

in single dispatch to props, I did this:

```<code>let sdtp = (arg) => {
   return (dispatch) => {
     dispatch({
       type: 'GET_TEST_HASHMAP_SAGA',
       hashmap: arg
     })
   }
 }

export default MainPage = connect(
   mapStateToProps,
   { sdtp }
)(MainPage);
</code>```

and I can "access the function" (is this the right term? at least my saga gets called) inside the MainPage.render() component :

```<code>`this.props.sdtp({'hello':'world'});`
</code>```

but when I change to use bindActionCreators, I cannot access it in the props anymore (I have tried so many different experiments I almost give up)

Here is how I construct my multiple dispatches:

```<code>let action1 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA',
         hashmap: arg
      });
   }
}

let action2 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA2',
         params: arg
      });
   }
}

let action3 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA3',
         args: arg
      });
   }
}

let mdtp = (dispatch) => {
  return {
    actions: bindActionCreators(action1, action2, action3, dispatch)
  }
}

export default MainPage = connect(
   mapStateToProps,
       { mdtp }
)(MainPage);
</code>```

I am trying to access the actions like this:

this.props.mdtp.action1({arg: 'hello'});

Thanks in advance!

答:
connect takes four arguments...most people usually only need the first two.

mapStateToProps you have, and I'm assuming it's a function.

mapDispatchToProps is the second...the issue is there.

bindActionCreators is nothing but a for loop...leave it out and you will better understand what is happening.

Try this:

```<code>function mapDispatchToProps(dispatch) {
  return {
     action1: (args) => dispatch(action1(args)),
     action2: (args) => dispatch(action2(args)),
  }
}

 export default MainPageContainer = connect(
   mapStateToProps,
   mapDispatchToProps
 )(MainPage)
</code>```

And call them as
this.props.action1(args) and this.props.action2(args)

If you insist on using the overrated bindActionCreators the syntax would be:

```<code> function mapDispatchToProps(dispatch){
   return {
     actions: bindActionCreators({
       action1,
       action2,
     }, dispatch)
   }
 }
</code>```

Also, use const instead of let since you are not redefining the value. It is also best to export the connected component under a different name than the class name of the component.

Body:
I am quite new to JavaScript and react-native and I have existing project that I need to add functionality to. It is using redux and redux-thunk with redux-saga to send API requests. Currently it supports only 1 dispatch function per component and I need to dispatch several types of requests to the saga. I am trying to bindActionCreators to add the dispatch to the stores but to no avail.. I am totally lost on the mapDispatchToProps part and how do I "fire the action" afterwards..

in single dispatch to props, I did this:

let sdtp = (arg) => {
   return (dispatch) => {
     dispatch({
       type: 'GET_TEST_HASHMAP_SAGA',
       hashmap: arg
     })
   }
 }

export default MainPage = connect(
   mapStateToProps,
   { sdtp }
)(MainPage);

and I can "access the function" (is this the right term? at least my saga gets called) inside the MainPage.render() component :

`this.props.sdtp({'hello':'world'});`

but when I change to use bindActionCreators, I cannot access it in the props anymore (I have tried so many different experiments I almost give up)

Here is how I construct my multiple dispatches:

let action1 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA',
         hashmap: arg
      });
   }
}

let action2 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA2',
         params: arg
      });
   }
}

let action3 = (args) => {
   return (dispatch) => {
      dispatch({
         type: 'GET_TEST_HASHMAP_SAGA3',
         args: arg
      });
   }
}

let mdtp = (dispatch) => {
  return {
    actions: bindActionCreators(action1, action2, action3, dispatch)
  }
}

export default MainPage = connect(
   mapStateToProps,
       { mdtp }
)(MainPage);

I am trying to access the actions like this:

this.props.mdtp.action1({arg: 'hello'});

Thanks in advance!

Body:
connect takes four arguments...most people usually only need the first two.

mapStateToProps you have, and I'm assuming it's a function.

mapDispatchToProps is the second...the issue is there.

bindActionCreators is nothing but a for loop...leave it out and you will better understand what is happening.

Try this:

function mapDispatchToProps(dispatch) {
  return {
     action1: (args) => dispatch(action1(args)),
     action2: (args) => dispatch(action2(args)),
  }
}

 export default MainPageContainer = connect(
   mapStateToProps,
   mapDispatchToProps
 )(MainPage)

And call them as
this.props.action1(args) and this.props.action2(args)

If you insist on using the overrated bindActionCreators the syntax would be:

 function mapDispatchToProps(dispatch){
   return {
     actions: bindActionCreators({
       action1,
       action2,
     }, dispatch)
   }
 }

Also, use const instead of let since you are not redefining the value. It is also best to export the connected component under a different name than the class name of the component.

ContentLicense: CC BY-SA 4.0


问:
Angular structural directive: wrap the host element with some another component
I have simplest Angular structural directive:

import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[hello]' })
export class HelloDirective {
  constructor(
    private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
      this.viewContainer.createEmbeddedView(this.templateRef);
  }
}
```

<p>I use it this way:</p>

```
Hello Directive

```

<p>It shows me "Hello Directive" message as expected. Now I want to change the content by wrapping it with some another component:</p>

```<my-component>Hello Directive</my-component>
```

And I want the directive to do it for me. I know that I can use a Component paradigm and create HelloComponent instead of HelloDirective and use ng-template etc with the template defined by template or templateUrl property on the @Component decorator... But is there an approach that could be used with a Directive paradigm to achieve such a result?

答:
You can create component dynamically and pass projectable nodes to it. So it could look like

@Directive({ selector: '[hello]' })
export class HelloDirective implements OnInit, DoCheck {
  templateView: EmbeddedViewRef<any>;
  constructor(
      private templateRef: TemplateRef<any>,
      private viewContainer: ViewContainerRef,
      private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    this.templateView = this.templateRef.createEmbeddedView({});
    const compFactory = this.resolver.resolveComponentFactory(MyComponent);
    this.viewContainer.createComponent(
      compFactory, null, this.viewContainer.injector, [this.templateView.rootNodes])
  }

  ngDoCheck(): void {
    if (this.templateView) {
        this.templateView.detectChanges();
    }
  }
}
```

You have to add MyComponent to entryComponents array of your @NgModule

Complete example can be found on Stackblitz

See also

Creating a angular2 component with ng-content dynamically

Body:
I have simplest Angular structural directive:

import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[hello]' })
export class HelloDirective {
  constructor(
    private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
      this.viewContainer.createEmbeddedView(this.templateRef);
  }
}

I use it this way:

Hello Directive

It shows me "Hello Directive" message as expected. Now I want to change the content by wrapping it with some another component:

<my-component>Hello Directive</my-component>

And I want the directive to do it for me. I know that I can use a Component paradigm and create HelloComponent instead of HelloDirective and use ng-template etc with the template defined by template or templateUrl property on the @Component decorator... But is there an approach that could be used with a Directive paradigm to achieve such a result?

Body:
You can create component dynamically and pass projectable nodes to it. So it could look like

@Directive({ selector: '[hello]' })
export class HelloDirective implements OnInit, DoCheck {
  templateView: EmbeddedViewRef<any>;
  constructor(
      private templateRef: TemplateRef<any>,
      private viewContainer: ViewContainerRef,
      private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    this.templateView = this.templateRef.createEmbeddedView({});
    const compFactory = this.resolver.resolveComponentFactory(MyComponent);
    this.viewContainer.createComponent(
      compFactory, null, this.viewContainer.injector, [this.templateView.rootNodes])
  }

  ngDoCheck(): void {
    if (this.templateView) {
        this.templateView.detectChanges();
    }
  }
}

You have to add MyComponent to entryComponents array of your @NgModule

Complete example can be found on Stackblitz

See also

Creating a angular2 component with ng-content dynamically


问:
how can a application be the first to receive input without being the foreground application using C#
Is there a way to be always the first application to receive input from devices(e.g. keyboard and mouse) even if it's not the foreground application? Is this possible to do with a standalone application without needing to tweak the registry?</p>

答:
There's a nuget package for that:

nuget install MouseKeyHook

From the project's readme

```<code>private IKeyboardMouseEvents m_GlobalHook;

public void Subscribe()
{
    // Note: for the application hook, use the Hook.AppEvents() instead
    m_GlobalHook = Hook.GlobalEvents();

    m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
    m_GlobalHook.KeyPress += GlobalHookKeyPress;
}

private void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
{
    Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
}

private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
    Console.WriteLine("MouseDown: \t{0}; \t System Timestamp: \t{1}", e.Button, e.Timestamp);

    // uncommenting the following line will suppress the middle mouse button click
    // if (e.Buttons == MouseButtons.Middle) { e.Handled = true; }
}

public void Unsubscribe()
{
    m_GlobalHook.MouseDownExt -= GlobalHookMouseDownExt;
    m_GlobalHook.KeyPress -= GlobalHookKeyPress;

    //It is recommened to dispose it
    m_GlobalHook.Dispose();
}
</code>```

Body:
There's a nuget package for that:

nuget install MouseKeyHook

From the project's readme

private IKeyboardMouseEvents m_GlobalHook;

public void Subscribe()
{
    // Note: for the application hook, use the Hook.AppEvents() instead
    m_GlobalHook = Hook.GlobalEvents();

    m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
    m_GlobalHook.KeyPress += GlobalHookKeyPress;
}

private void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
{
    Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
}

private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
    Console.WriteLine("MouseDown: \t{0}; \t System Timestamp: \t{1}", e.Button, e.Timestamp);

    // uncommenting the following line will suppress the middle mouse button click
    // if (e.Buttons == MouseButtons.Middle) { e.Handled = true; }
}

public void Unsubscribe()
{
    m_GlobalHook.MouseDownExt -= GlobalHookMouseDownExt;
    m_GlobalHook.KeyPress -= GlobalHookKeyPress;

    //It is recommened to dispose it
    m_GlobalHook.Dispose();
}


问:
How to combine strings inside foreach into single string PHP
I have code like this

```<code>$word = 'foo';
$char_buff = str_split($word);

foreach ($char_buff as $chars){
    echo var_dump($chars);
}
</code>```

The output was

```<code>string(1) "f"
string(1) "o"
string(1) "o"
</code>```

For some reasons, I want to make the output become only 1 string like this:

```<code>string(3) "foo"
</code>```

I tried with this

```<code>$char.=$chars;
echo var_dump($char);
</code>```

But it shows error Undefined variable: char.

答:
Maybe some of you are looking for this answer.
I think var_dump() is no longer necessary for this problem.

```<code><?php
    if(isset($_POST['test'])){
        $result = '';
        for($x=1;$x<=4;$x++){
            $ans = $_POST['ans'.$x];
            $result .= $ans;
        }
    echo $result;
    }
?>
</code>```

Here is the HTML

<form role="form" method="post" action="<?php echo $url;?>">
 <input type="checkbox" name="ans1" value="A">A
 <input type="checkbox" name="ans2" value="B">B
 <input type="checkbox" name="ans3" value="C">C
 <input type="checkbox" name="ans4" value="D">D
 <input type="submit" name="test" value="Submit Answer">
</form>```

Body:
I have code like this

$word = 'foo';
$char_buff = str_split($word);

foreach ($char_buff as $chars){
    echo var_dump($chars);
}

The output was

string(1) "f"
string(1) "o"
string(1) "o"

For some reasons, I want to make the output become only 1 string like this:

string(3) "foo"

I tried with this

$char.=$chars;
echo var_dump($char);

But it shows error Undefined variable: char.

Body:
Maybe some of you are looking for this answer.
I think var_dump() is no longer necessary for this problem.

<?php
    if(isset($_POST['test'])){
        $result = '';
        for($x=1;$x<=4;$x++){
            $ans = $_POST['ans'.$x];
            $result .= $ans;
        }
    echo $result;
    }
?>

Here is the HTML

<form role="form" method="post" action="<?php echo $url;?>">
 <input type="checkbox" name="ans1" value="A">A
 <input type="checkbox" name="ans2" value="B">B
 <input type="checkbox" name="ans3" value="C">C
 <input type="checkbox" name="ans4" value="D">D
 <input type="submit" name="test" value="Submit Answer">
</form>


问:
Where is the list of the types of exceptions?
Please help me find the official documentation with a list of the types of  of exceptions. I wrote this action:

```<code>def show
  begin
    @user = User.find(params[:id])
  rescue ActiveRecord::RecordNotFound => e
    logger.debug e
    logger.debug "Error #{$!}"
    render_404
  end
end
</code>```

I need to mention several types of exceptions:

```<code>def show
  begin
    @user = User.find(params[:id])
  rescue ActiveRecord::RecordNotFound => e
    logger.debug e
    logger.debug "Error #{$!}"
    render_404
  rescue anotherExceptionType1 => e
    ......
    ......
    .....
  rescue anotherExceptionType2 => e
    ......
    ......
    .....
  rescue anotherExceptionType3 => e
    ......
    ......
    .....
  end
end
</code>```

but I did not find the list of exceptions in the documentation.

答:
Get all classes that inherit from Exception:

```<code>exceptions = ObjectSpace.each_object(Class).select{|c| c < Exception  }
</code>```

Print:

```<code>exceptions.map(&:to_s).sort.each{|s| puts s}
</code>```

Body:
Please help me find the official documentation with a list of the types of  of exceptions. I wrote this action:

def show
  begin
    @user = User.find(params[:id])
  rescue ActiveRecord::RecordNotFound => e
    logger.debug e
    logger.debug "Error #{$!}"
    render_404
  end
end

I need to mention several types of exceptions:

def show
  begin
    @user = User.find(params[:id])
  rescue ActiveRecord::RecordNotFound => e
    logger.debug e
    logger.debug "Error #{$!}"
    render_404
  rescue anotherExceptionType1 => e
    ......
    ......
    .....
  rescue anotherExceptionType2 => e
    ......
    ......
    .....
  rescue anotherExceptionType3 => e
    ......
    ......
    .....
  end
end

but I did not find the list of exceptions in the documentation.

Body:
Get all classes that inherit from Exception:

exceptions = ObjectSpace.each_object(Class).select{|c| c < Exception  }

Print:

exceptions.map(&:to_s).sort.each{|s| puts s}


问:
How to use the fixture 'test_client in pytest-aiohttp
there is an elementary test

```<code>from aiohttp import web

async def hello(request):
    return web.Response(text='Hello, world')

async def test_hello(test_client, loop):
    app = web.Application()
    app.router.add_get('/', hello)
    client = await test_client(app)
    resp = await client.get('/')
    assert resp.status == 200
    text = await resp.text()
    assert 'Hello, world' in text
</code>```

fixture 'test_client' not found

```<code>  available fixtures: cache, capfd, capsys, doctest_namespace, event_loop, event_loop_process_pool, loop, monkeypatch,
</code>```

pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory, unused_tcp_port, unused_tcp_port_factory

答:
You need to install pytest-aiohttp plugin.

```<code>pip install pytest-aiohttp
</code>```

It is described in very begin of testing chapter in aiohttp documentation.

Body:
there is an elementary test

from aiohttp import web

async def hello(request):
    return web.Response(text='Hello, world')

async def test_hello(test_client, loop):
    app = web.Application()
    app.router.add_get('/', hello)
    client = await test_client(app)
    resp = await client.get('/')
    assert resp.status == 200
    text = await resp.text()
    assert 'Hello, world' in text

fixture 'test_client' not found

  available fixtures: cache, capfd, capsys, doctest_namespace, event_loop, event_loop_process_pool, loop, monkeypatch,

pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory, unused_tcp_port, unused_tcp_port_factory

Body:
You need to install pytest-aiohttp plugin.

pip install pytest-aiohttp

It is described in very begin of testing chapter in aiohttp documentation.


问:
Using Bootstrap 4 with Grails
I'm using Grails for a web project for a CSE class in college. I've noticed many of the other groups doing this project are using Bootstrap 4 for the web design (I'm in the only group using Grails). I looked into Bootstrap 4 and I really love the way it looks. Personally I don't like the way Grails looks with standard HTML. I was wondering if there is a way that I can use Bootstrap 4 with Grails. For example in standard HTML I can have a button and forms that will submit data to a controller and some action will happen, it doesn't seem to work the same way with Grails.

Would anyone know if I can integrate Bootstrap 4 with Grails and if so how I can do it?

答:
In your newly created app you will see that under grails-app/assets/stylesheets/ are a number of .css files including bootstrap.css and under grails-app/assets/javascripts/ you will find bootstrap.js.  We put those there by default and many people use them, but you don't have to.  Drop whatever assets you like in those folders and then you can use them.  You may want to edit grails-app/assets/javascripts/application.js and grails-app/assets/stylesheets/application.css to pull in whatever assets you add to the project and you would do that with the require directive.  See the contents of those files for examples.

I hope that helps.

Title: Using Bootstrap 4 with Grails


问:
AngularJS V1.2 - Error: $q is not a function
```<code>(function () {
angular.module('Testing')
    .controller('Testing', Testing);
    Testing.$inject('$q', '$location', 'authentication');
    function  Testing($q, $location, authentication) {
    var vm = this;

    function asyncGreet(name) {
    return $q(function (resolve, reject) {
        setTimeout(function(){
            if(username){
                resolve('Hello, ' + username);
            }
            else {
                reject('Greeting ' +  name + 'is not allowed');
            }
        }, 3000)
    });
}

var promise = asyncGreet("oo");
promise.then(function (greeting) {
    console.log('Success: ' + greeting);
}, function (reason) {
    console.log('Failed: ' + reason);
});

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

I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

Can someone please point me to what i am doing wrong? Thank you.

答:
I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

The error occurs because the ES6 style of making a promise with $q was introduced in AngularJS V1.3. For more information, see Github commit - feat($q): add streamlined ES6-style interface for using $q.

Instead of manufacturing a promise with $q, I recommend using the $timeout service:

```<code>function asyncGreet(name) {
    ̶r̶e̶t̶u̶r̶n̶ ̶$̶q̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶r̶e̶s̶o̶l̶v̶e̶,̶ ̶r̶e̶j̶e̶c̶t̶)̶ ̶{̶
        ̶s̶e̶t̶T̶i̶m̶e̶o̶u̶t̶(̶f̶u̶n̶c̶t̶i̶o̶n̶(̶)̶{̶
    return $timeout(function () {
        if(username){
            return ('Hello, ' + username);
        }
        else {
            return $q.reject('Greeting ' +  name + 'is not allowed');
        }
    }, 3000);
});
</code>```

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

The $timeout service is AngularJS's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.

The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed.

For more information, see AngularJS $timeout Service API Reference.

Body:
(function () {
angular.module('Testing')
    .controller('Testing', Testing);
    Testing.$inject('$q', '$location', 'authentication');
    function  Testing($q, $location, authentication) {
    var vm = this;

    function asyncGreet(name) {
    return $q(function (resolve, reject) {
        setTimeout(function(){
            if(username){
                resolve('Hello, ' + username);
            }
            else {
                reject('Greeting ' +  name + 'is not allowed');
            }
        }, 3000)
    });
}

var promise = asyncGreet("oo");
promise.then(function (greeting) {
    console.log('Success: ' + greeting);
}, function (reason) {
    console.log('Failed: ' + reason);
});

} ());

I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

Can someone please point me to what i am doing wrong? Thank you.

Body:
I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

The error occurs because the ES6 style of making a promise with $q was introduced in AngularJS V1.3. For more information, see Github commit - feat($q): add streamlined ES6-style interface for using $q.

Instead of manufacturing a promise with $q, I recommend using the $timeout service:

function asyncGreet(name) {
    ̶r̶e̶t̶u̶r̶n̶ ̶$̶q̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶r̶e̶s̶o̶l̶v̶e̶,̶ ̶r̶e̶j̶e̶c̶t̶)̶ ̶{̶
        ̶s̶e̶t̶T̶i̶m̶e̶o̶u̶t̶(̶f̶u̶n̶c̶t̶i̶o̶n̶(̶)̶{̶
    return $timeout(function () {
        if(username){
            return ('Hello, ' + username);
        }
        else {
            return $q.reject('Greeting ' +  name + 'is not allowed');
        }
    }, 3000);
});

AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

The $timeout service is AngularJS's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.

The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed.

For more information, see AngularJS $timeout Service API Reference.


问:
In dynamic query storing count(*) value into variable in sap hana procedure
I have a requirement to store the count(*) value into a variable and then use this variable for business logic.I have written below code, but its not working. We have requirement to pass the schema name through input parameter hence using dynamic query inside procedure.

Code :

```<code>Begin

DECLARE v_count INT DEFAULT 0;
DECLARE v_Count_Query NVARCHAR(5000);

CREATE GLOBAL TEMPORARY TABLE RECORD_CNT_TABLE(RECORDS_CNT INTEGER);

v_Count_Query = 'INSERT INTO RECORD_CNT_TABLE(SELECT COUNT(*) FROM "'||:IP_Schema_Name||'"."TABLE_NAME" where to_dats(to_char("LastRunDay", ''yyyymmdd'')) = '||current_date||';';

EXECUTE IMMEDIATE :v_Count_Query;

EXECUTE IMMEDIATE 'SELECT RECORDS_CNT INTO '||v_count||' FROM RECORD_CNT_TABLE;';

IF :v_count >= 1 then
/**business logic**/
ELSE
/**business logic**/
END IF;

END;
</code>```

Thanks in advance.

答:
The following works with HANA2 but not with HANA1.

```<code>create or replace procedure check_and_do_clients (IN schema_name Nvarchar(256))
as
begin

DECLARE v_count INT := 0;

    exec 'select count(*) from "' || :schema_name || '"."APPL_DATA"'
         ||' where "LastRunDay" = date''01.06.2017'' ' into v_count ;

    IF :v_count >= 1 then
              select 'WE HAVE A WINNER!', :v_count as vcnt, :schema_name as schema_name from dummy;
    ELSE
             select 'NO LUCK THIS TIME!', :v_count as vcnt, :schema_name as schema_name from dummy;
    END IF;

end;
</code>```

'WE HAVE A WINNER!'   VCNT    SCHEMA_NAME

     WE HAVE A WINNER!    1       CLNT1

There really is no need for a temporary table here. And even if you plan to reuse the values outside the scope of the current transaction, then creating a global temporary table should not happen at runtime.
Create it once and use TRUNCATE TABLE to empty it before you use it. The data will anyhow only survive as long as your session is active and only be visible to the session that created it.

More concerning than this is the broader design of the application for which you write this procedure.
Schemas in SQL are namespaces and as SQL is statically typed, a table "CLNT1"."APPL_DATA" is different from "CLNT2"."APPL_DATA", which of course is the reason for why dynamic SQL has to be used in this setup.

Often, when I come across such designs, the schema concept is used for something more, specifically to have structurally identical copies of the same schema in different namespaces. The goal is to separate the data from different tenants or clients (in classic SAP speak) in the same database.

A common requirement then is to have the ability to do something from a "higher" position, accessing data in any of those client schemas.
This is where your requirement seems to come into play.

There are a couple of issues with this approach:

dynamic SQL is generally heavy on resource usage and prone to SQL injection

it's - as seen - more difficult to write and only gets checked by the database at runtime

the data access pattern breaks the model of a self-containing client-schema by opening direct data access by code not contained in the schema

An alternative approach for this could be to invert the design in this case.
Instead of having dynamic views onto X tables (one for each schema), create a  schema for tables common across the schemas and create filtered views in each schema instead.

That way the "master" schema could easily access the shared table without the need for any dynamic SQL just as the "client" schemas can access "their" version of the table in the shape of a view.
With the help of an INSTEAD OF triggers, it's easy to redirect INSERT/UPDATE statements against the views so that the filter condition is added appropriately.

This approach, just as the dynamic SQL approach, leave out the option for the actual client application that should run the procedure to dynamically switch to the schema of interest with the SET SCHEMA <schema name> command.
While SET SCHEMA doesn't help in the procedure (object references get checked statically at compile time, remember?) it is easy in a client application to issue the command and feed the result of the SELECT COUNT(*) back to the procedure that handles the further business logic.

Body:
I have a requirement to store the count(*) value into a variable and then use this variable for business logic.I have written below code, but its not working. We have requirement to pass the schema name through input parameter hence using dynamic query inside procedure.

Code :

Begin

DECLARE v_count INT DEFAULT 0;
DECLARE v_Count_Query NVARCHAR(5000);

CREATE GLOBAL TEMPORARY TABLE RECORD_CNT_TABLE(RECORDS_CNT INTEGER);

v_Count_Query = 'INSERT INTO RECORD_CNT_TABLE(SELECT COUNT(*) FROM "'||:IP_Schema_Name||'"."TABLE_NAME" where to_dats(to_char("LastRunDay", ''yyyymmdd'')) = '||current_date||';';

EXECUTE IMMEDIATE :v_Count_Query;

EXECUTE IMMEDIATE 'SELECT RECORDS_CNT INTO '||v_count||' FROM RECORD_CNT_TABLE;';

IF :v_count >= 1 then
/**business logic**/
ELSE
/**business logic**/
END IF;

END;

Thanks in advance.

Body:
The following works with HANA2 but not with HANA1.

create or replace procedure check_and_do_clients (IN schema_name Nvarchar(256))
as
begin

DECLARE v_count INT := 0;

    exec 'select count(*) from "' || :schema_name || '"."APPL_DATA"'
         ||' where "LastRunDay" = date''01.06.2017'' ' into v_count ;

    IF :v_count >= 1 then
              select 'WE HAVE A WINNER!', :v_count as vcnt, :schema_name as schema_name from dummy;
    ELSE
             select 'NO LUCK THIS TIME!', :v_count as vcnt, :schema_name as schema_name from dummy;
    END IF;

end;

'WE HAVE A WINNER!'   VCNT    SCHEMA_NAME

     WE HAVE A WINNER!    1       CLNT1

There really is no need for a temporary table here. And even if you plan to reuse the values outside the scope of the current transaction, then creating a global temporary table should not happen at runtime.
Create it once and use TRUNCATE TABLE to empty it before you use it. The data will anyhow only survive as long as your session is active and only be visible to the session that created it.

More concerning than this is the broader design of the application for which you write this procedure.
Schemas in SQL are namespaces and as SQL is statically typed, a table "CLNT1"."APPL_DATA" is different from "CLNT2"."APPL_DATA", which of course is the reason for why dynamic SQL has to be used in this setup.

Often, when I come across such designs, the schema concept is used for something more, specifically to have structurally identical copies of the same schema in different namespaces. The goal is to separate the data from different tenants or clients (in classic SAP speak) in the same database.

A common requirement then is to have the ability to do something from a "higher" position, accessing data in any of those client schemas.
This is where your requirement seems to come into play.

There are a couple of issues with this approach:

dynamic SQL is generally heavy on resource usage and prone to SQL injection

it's - as seen - more difficult to write and only gets checked by the database at runtime

the data access pattern breaks the model of a self-containing client-schema by opening direct data access by code not contained in the schema

An alternative approach for this could be to invert the design in this case.
Instead of having dynamic views onto X tables (one for each schema), create a  schema for tables common across the schemas and create filtered views in each schema instead.

That way the "master" schema could easily access the shared table without the need for any dynamic SQL just as the "client" schemas can access "their" version of the table in the shape of a view.
With the help of an INSTEAD OF triggers, it's easy to redirect INSERT/UPDATE statements against the views so that the filter condition is added appropriately.

This approach, just as the dynamic SQL approach, leave out the option for the actual client application that should run the procedure to dynamically switch to the schema of interest with the SET SCHEMA <schema name> command.
While SET SCHEMA doesn't help in the procedure (object references get checked statically at compile time, remember?) it is easy in a client application to issue the command and feed the result of the SELECT COUNT(*) back to the procedure that handles the further business logic.


问:
sp_xml_preparedocument go with error "Only one top level element is allowed in an XML document"
I'am trying to execute sp_xml_preparedocument and geting error "Only one top level element is allowed in an XML document"

my T-SQL commands:

```<code>DECLARE @aa XML
DECLARE @idoc int
SET @aa =(select * from db_name for xml auto, xmldata)
</code>```

@aa now is

```<code><Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
  <AttributeType name="preson_id" dt:type="i4" />
  <AttributeType name="Name" dt:type="string" />
  <AttributeType name="Surname" dt:type="string" />
  <AttributeType name="guid" dt:type="uuid" />
  <AttributeType name="version" dt:type="bin.base64" />
  <attribute type="preson_id" />
  <attribute type="Name" />
  <attribute type="Surname" />
  <attribute type="guid" />
  <attribute type="version" />
 </ElementType>
</Schema>
  <Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
  <Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
  <Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />
</code>```

```<code>EXEC sp_xml_preparedocument @idoc OUTPUT, @aa
</code>```

```<code>The XML parse error 0xc00ce555 occurred on line number 1, near the XML text ""
Msg 6602, Level 16, State 2, Procedure sp_xml_preparedocument, Line 1
The error description is 'Only one top level element is allowed in an XML document
</code>```

I'am new in this, and i need help)))
An one more question - How parse timestamp type?

if i use

```<code>SET @aa =(select * from db_name for xml elements, root('root'), type)
</code>```

sp_xml_preparedocument works fine, OPENXML returns all values of my db_table, but timestamp values looks not the same as were..

Sorry for my bad English

答:
SELECT @aa returns</p>

```<code><Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
  <AttributeType name="preson_id" dt:type="i4" />
  <AttributeType name="Name" dt:type="string" />
  <AttributeType name="Surname" dt:type="string" />
  <AttributeType name="guid" dt:type="uuid" />
  <AttributeType name="version" dt:type="bin.base64" />
  <attribute type="preson_id" />
  <attribute type="Name" />
  <attribute type="Surname" />
  <attribute type="guid" />
  <attribute type="version" />
 </ElementType>
</Schema>
  <Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
  <Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
  <Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />
</code>```

Body:
I'am trying to execute sp_xml_preparedocument and geting error "Only one top level element is allowed in an XML document"

my T-SQL commands:

DECLARE @aa XML
DECLARE @idoc int
SET @aa =(select * from db_name for xml auto, xmldata)

@aa now is

<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
  <AttributeType name="preson_id" dt:type="i4" />
  <AttributeType name="Name" dt:type="string" />
  <AttributeType name="Surname" dt:type="string" />
  <AttributeType name="guid" dt:type="uuid" />
  <AttributeType name="version" dt:type="bin.base64" />
  <attribute type="preson_id" />
  <attribute type="Name" />
  <attribute type="Surname" />
  <attribute type="guid" />
  <attribute type="version" />
 </ElementType>
</Schema>
  <Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
  <Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
  <Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />

EXEC sp_xml_preparedocument @idoc OUTPUT, @aa

The XML parse error 0xc00ce555 occurred on line number 1, near the XML text ""
Msg 6602, Level 16, State 2, Procedure sp_xml_preparedocument, Line 1
The error description is 'Only one top level element is allowed in an XML document

I'am new in this, and i need help)))
An one more question - How parse timestamp type?

if i use

SET @aa =(select * from db_name for xml elements, root('root'), type)

sp_xml_preparedocument works fine, OPENXML returns all values of my db_table, but timestamp values looks not the same as were..

Sorry for my bad English

Body:
SELECT @aa returns

<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes" name="Schema7">
<ElementType name="Person" content="empty" model="closed">
  <AttributeType name="preson_id" dt:type="i4" />
  <AttributeType name="Name" dt:type="string" />
  <AttributeType name="Surname" dt:type="string" />
  <AttributeType name="guid" dt:type="uuid" />
  <AttributeType name="version" dt:type="bin.base64" />
  <attribute type="preson_id" />
  <attribute type="Name" />
  <attribute type="Surname" />
  <attribute type="guid" />
  <attribute type="version" />
 </ElementType>
</Schema>
  <Person xmlns="x-schema:#Schema7" preson_id="1" Name="Иван" Surname="Иванов" guid="2E739E87-3CA4-4ED8-ADD0-8B59957668B8" version="AAAAAAAAB9E=" />
  <Person xmlns="x-schema:#Schema7" preson_id="2" Name="Николай" Surname="Николаев" guid="BDC41C59-D70F-4B70-954E-4918B9516AF8" version="AAAAAAAAB9I=" />
  <Person xmlns="x-schema:#Schema7" preson_id="3" Name="Максим" Surname="Максимов" guid="740E57F3-56BA-48B8-92AF-978D7B1D2712" version="AAAAAAAAB9M=" />


问:
Second largest in negative numbers
I am using this to find second largest in the array, it works fine in case of positive numbers but it fails in case of negative numbers.
Can you suggest this solution so it works for negative numbers also?</p>

```<code>arr = [-3,3,-3,3];
k = max(arr)
m= arr[0];
i=0;
k = max(arr)
while i <(len(arr)-1):
    if(m<arr[i+1] and arr[i+1] !=k ):
        m= arr[i+1]
    i+=1
print m
</code>```

答:
The bespoke tool for this kind of problem is the heapq module in the standard lib:

```<code>import heapq

scnd = heapq.nlargest(2, yourarray)[1]
</code>```

This is O(n), much faster than sorting, though you'll only start feeling the difference north of a million entries or so.

Note: if you instead want the second largest by value one quick fix would be converting to a set if your elements are hashable:

```<code>scnd = heapq.nlargest(2, set(yourarray))[1]
</code>```

If that's not an option:

```<code>frst = max(yourarray)
scnd = max(i for i in yourarray if i<first)
</code>```

Title: Second largest in negative numbers

Body:
I am using this to find second largest in the array, it works fine in case of positive numbers but it fails in case of negative numbers.
Can you suggest this solution so it works for negative numbers also?

arr = [-3,3,-3,3];
k = max(arr)
m= arr[0];
i=0;
k = max(arr)
while i <(len(arr)-1):
    if(m<arr[i+1] and arr[i+1] !=k ):
        m= arr[i+1]
    i+=1
print m

Body:
The bespoke tool for this kind of problem is the heapq module in the standard lib:

import heapq

scnd = heapq.nlargest(2, yourarray)[1]

This is O(n), much faster than sorting, though you'll only start feeling the difference north of a million entries or so.

Note: if you instead want the second largest by value one quick fix would be converting to a set if your elements are hashable:

scnd = heapq.nlargest(2, set(yourarray))[1]

If that's not an option:

frst = max(yourarray)
scnd = max(i for i in yourarray if i<first)


问:
Asynchronicity of a Mongoose Promise
First, pardon my slightly ambiguous title; I could not find a more appropriate one:

Scenario

I am using Mongoose to fetch some data and then render them with ejs. For the sake of illustration, consider the following:

```<code>// Schema
var UserSchema = mongoose.Schema({
  Username: String,
  City: String
})
// Model
var User = mongoose.model('User', UserSchema);
</code>```

From my server file:

```<code>app.get('/view', function (req, res) {
  // What I am trying to do
  User.find({}).exec().then(vals=>{
            res.send(vals)
        })
</code>```

The Problem

The above code works as intended but, to the code accessible to other files as well as making upgrades easier, I want to move it another file, then require() that file.

handler.js

```<code>// Promise: Get All Names
function FetchData(){
    return User
    .find({})
    .exec();
}

module.exports = {
    Get: function(){
        val = User.find({}).exec()
        .then(vals=>{
            // Expected to return only after the above is complete
            return vals
        })
    }

}
</code>```

Then, from my server file:

```<code>var handler = require('handler')

app.get('/view', function (req, res) {
  res.send(handler.Get())
});
</code>```

Unfortunately, this code does not work as intended

My thoughts

I varied the parameters and tweaked the code around a few times but am unable to figure out what is going wrong.
It seems that the values from Get() is being returned even before the promise is consumed (which is puzzling).

Any help would be greatly welcomed :)

答:
Here's the code that may help you.

Change your main server file to something like this

```<code>app.get('/view', function (req, res) {
  handler.Get().then(vals => {
       res.send(vals);
  });
</code>```

And in handler.js file, you can do

```<code>module.exports.Get = function(){
     return new Promise((resolve, reject) => {
          User.find({}).exec(function(err, users){
               if(!err){
                    resolve(users);
               }
          });
     });
}
</code>```

Title: Asynchronicity of a Mongoose Promise

Body:
First, pardon my slightly ambiguous title; I could not find a more appropriate one:

Scenario

I am using Mongoose to fetch some data and then render them with ejs. For the sake of illustration, consider the following:

// Schema
var UserSchema = mongoose.Schema({
  Username: String,
  City: String
})
// Model
var User = mongoose.model('User', UserSchema);

From my server file:

app.get('/view', function (req, res) {
  // What I am trying to do
  User.find({}).exec().then(vals=>{
            res.send(vals)
        })

The Problem

The above code works as intended but, to the code accessible to other files as well as making upgrades easier, I want to move it another file, then require() that file.

handler.js

// Promise: Get All Names
function FetchData(){
    return User
    .find({})
    .exec();
}

module.exports = {
    Get: function(){
        val = User.find({}).exec()
        .then(vals=>{
            // Expected to return only after the above is complete
            return vals
        })
    }

}

Then, from my server file:

var handler = require('handler')

app.get('/view', function (req, res) {
  res.send(handler.Get())
});

Unfortunately, this code does not work as intended

My thoughts

I varied the parameters and tweaked the code around a few times but am unable to figure out what is going wrong.
It seems that the values from Get() is being returned even before the promise is consumed (which is puzzling).

Any help would be greatly welcomed :)

Body:
Here's the code that may help you.

Change your main server file to something like this

app.get('/view', function (req, res) {
  handler.Get().then(vals => {
       res.send(vals);
  });

And in handler.js file, you can do

module.exports.Get = function(){
     return new Promise((resolve, reject) => {
          User.find({}).exec(function(err, users){
               if(!err){
                    resolve(users);
               }
          });
     });
}


问:
Can I use bindParam always?
I see so many people using "execute(array [...]" in their SQL methods, I always used

execute->bindParam('[...]', $string);

Can I still using bindParam? If no, when should I use it? Thanks

答:
Also as a third parameter you can specify the data type. That's the advantage of using bindParam() over executing array.

```<code>$sql->bindParam(':key', 23, PDO::PARAM_INT);//telling pdo that's it is integer type.
</code>```

With executing array,  you can't specify type

```<code>$sql->execute([':key' => 23]);
</code>```

Title: Can I use bindParam always?

Body:
Also as a third parameter you can specify the data type. That's the advantage of using bindParam() over executing array.

$sql->bindParam(':key', 23, PDO::PARAM_INT);//telling pdo that's it is integer type.

With executing array,  you can't specify type

$sql->execute([':key' => 23]);