问:
Trying to get counts through multiple associations
I have created a question an answer app for a client much like StackOverflow. I am not trying to implement some sort of point system (like SO reputation). I am trying to get certain record counts through associations (which I believe are set up correctly). Primarily I am trying to get counts for votes on users answers. Here is an example.

In /views/questions/show page I list all the answers to that question by calling a partial _answer.html.erb. With each answer I pull in the answer.user information (username, email, etc.) by simply doing answer.user.username. I am wanting to display in a badge like format some total point calculations. So if User A answered Question A, next to User A's answer I want to display a total of all User A's answer votes.

I can successfully get a count for a users answers in /views/answers/_answer.html.erb by doing the following:

```<code><%= answer.user.answers.count %>
</code>```

but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.

```<code><%= answer.user.answers.votes.count %>
</code>```

Is my set up fundamentally wrong here or am I missing something.

That is a bit confusing so let me know if you need more detail.

UPDATE:

Here are the associations:

Answers

```<code>class Answer < ActivRecord::Base
  belongs_to :question
  belongs_to :user
  has_many :votes, :dependent => :destroy
end
</code>```

Votes

```<code>class Vote < ActiveRecord::Base
  belongs_to :answer
  belongs_to :user
  belongs_to :question
end
</code>```

Users

```<code>class User < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  has_many :answers, :dependent => :destroy
  has_many :votes, :through => :answers , :dependent => :destroy
end
</code>```

答:
but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.

You can find complete listing of what you can do with user.answers collection in here (besides standard Array/Enumerable methods). And it's only collection instance, not Answer object, so you can't invoke methods from Answer model on it.

You can try setupping has_many :votes, :through => :answers relationship. (See here for details) Although, I'm not sure if :through would work in such case.

Alternatively, you can create a method in User model to return all Vote objects (simply by iterating through all answers)

But frankly, creating a horde of Vote objects simply to count them sounds like a terrible waste of resources to me.

Body:
I have created a question an answer app for a client much like StackOverflow. I am not trying to implement some sort of point system (like SO reputation). I am trying to get certain record counts through associations (which I believe are set up correctly). Primarily I am trying to get counts for votes on users answers. Here is an example.

In /views/questions/show page I list all the answers to that question by calling a partial _answer.html.erb. With each answer I pull in the answer.user information (username, email, etc.) by simply doing answer.user.username. I am wanting to display in a badge like format some total point calculations. So if User A answered Question A, next to User A's answer I want to display a total of all User A's answer votes.

I can successfully get a count for a users answers in /views/answers/_answer.html.erb by doing the following:

<%= answer.user.answers.count %>

but when I try to extend that syntax/association to get a count of votes on all User A's answers I get undefined method errors.

<%= answer.user.answers.votes.count %>

Is my set up fundamentally wrong here or am I missing something.

That is a bit confusing so let me know if you need more detail.

UPDATE:

Here are the associations:

Answers

class Answer < ActivRecord::Base
  belongs_to :question
  belongs_to :user
  has_many :votes, :dependent => :destroy
end

Votes

class Vote < ActiveRecord::Base
  belongs_to :answer
  belongs_to :user
  belongs_to :question
end

Users

class User < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  has_many :answers, :dependent => :destroy
  has_many :votes, :through => :answers , :dependent => :destroy
end


来源: stackexchange

问:
How can I change color of Page Title font in Kleanity WordPress theme
How can I change the color of Page Title font in Kleanity WordPress theme? I've looked everywhere but cannot see how.</p>

答:
It looks like you have to go in Appearance -> Customize -> Color and there you will find details.

Or you can go to Goodlayers and update the skin settings.

You can find more details here: http://demo.goodlayers.com/document/kleanity/

It is always good to read the documentation.

Edit 1: If neither of the 2 options above work, you can go to Appearance -> Customize -> Miscellaneous and put the a CSS rule to match the page title you wish to change

ContentLicense: CC BY-SA 3.0


问:
Why does my implementation of linear regression in Tensorflow done on Ames Housing dataset converge very very slowly?
I am trying to use Linear Regression on the Ames Housing dataset available on Kaggle.

I did some manual cleaning up of the data by removing many features first. Then, I used the following implementation to train.

```<code>train_size = np.shape(x_train)[0]
valid_size = np.shape(x_valid)[0]
test_size = np.shape(x_test)[0]
num_features = np.shape(x_train)[1]

graph = tf.Graph()
with graph.as_default():

    # Input
    tf_train_dataset = tf.constant(x_train)
    tf_train_labels = tf.constant(y_train)
    tf_valid_dataset = tf.constant(x_valid)
    tf_test_dataset = tf.constant(x_test)

    # Variables
    weights = tf.Variable(tf.truncated_normal([num_features, 1]))
    biases = tf.Variable(tf.zeros([1]))

    # Loss Computation
    train_prediction = tf.matmul(tf_train_dataset, weights) + biases
    loss = tf.losses.mean_squared_error(tf_train_labels, train_prediction)

    # Optimizer
    # Gradient descent optimizer with learning rate = alpha
    alpha = tf.constant(0.000000003, dtype=tf.float64)
    optimizer = tf.train.GradientDescentOptimizer(alpha).minimize(loss)

    # Predictions
    valid_prediction = tf.matmul(tf_valid_dataset, weights) + biases
    test_prediction = tf.matmul(tf_test_dataset, weights) + biases
</code>```

This is how my graph runs:

```<code>num_steps = 10001

def accuracy(prediction, labels):
    return ((prediction - labels) ** 2).mean(axis=None)

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    print('Initialized')
    for step in range(num_steps):
        _, l, predictions = session.run([optimizer, loss, train_prediction])
        if (step % 1000 == 0):
            print('Loss at step %d: %f' % (step, l))
            print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), y_valid))
     t_pred = test_prediction.eval()
     print('Test accuracy: %.1f%%' % accuracy(t_pred, y_test))
</code>```

Here is what I've tried:

I have tried increasing the learning rate. But, if I increase the learning rate beyond what I'm using right now, the model fails to converge i.e., the loss explodes to infinity.

Increased the number of iterations to 10,000,000. The loss converges slower the longer I iterate (which is understandable). But I'm still very far from a reasonable value. The loss is usually a 10 digit number

Am I doing something wrong with the graph? Or is linear regression a bad choice for this and I should try using another algorithm? Any help and suggestions is much appreciated!

答:
Working Code

```<code>import csv
import tensorflow as tf
import numpy as np

with open('train.csv', 'rt') as f:
    reader = csv.reader(f)
    your_list = list(reader)

def toFloatNoFail( data ) :
    try :
        return float(data)
    except :
        return 0

data = [ [ toFloatNoFail(x) for x in row ] for row in your_list[1:] ]
data = np.array( data ).astype( float )
x_train = data[:,:-1]
print x_train.shape
y_train = data[:,-1:]
print y_train.shape

num_features = np.shape(x_train)[1]

# Input
tf_train_dataset = tf.constant(x_train, dtype=tf.float32)
tf_train_labels = tf.constant(y_train, dtype=tf.float32)

# Variables
weights = tf.Variable(tf.truncated_normal( [num_features, 1] , dtype=tf.float32))
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32 ))

train_prediction = tf.matmul(tf_train_dataset, weights) + biases

loss = tf.reduce_mean( tf.square( tf.log(tf_train_labels) - tf.log(train_prediction) ))

optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)

num_steps = 10001

def accuracy(prediction, labels):
    return ((prediction - labels) ** 2).mean(axis=None)

with tf.Session() as session:
    tf.global_variables_initializer().run()
    print('Initialized')
    for step in range(num_steps):
        _, l, predictions = session.run([optimizer, loss, train_prediction])
        if (step % 1000 == 0):
            print('Loss at step %d: %f' % (step, l))
</code>```

Explanation of Critical Change

Your loss function wasn't scaled for the price.  The above loss function takes into account that you are really only interested in the error in prices scaled with the original price.  So, for a million dollar house being off by $5,000 shouldn't be as bad as being off by $5,000 for a $5,000 house.

The new loss function is :

```<code>loss = tf.reduce_mean( tf.square( tf.log(tf_train_labels) - tf.log(train_prediction) ))
</code>```

Body:
I am trying to use Linear Regression on the Ames Housing dataset available on Kaggle.

I did some manual cleaning up of the data by removing many features first. Then, I used the following implementation to train.

train_size = np.shape(x_train)[0]
valid_size = np.shape(x_valid)[0]
test_size = np.shape(x_test)[0]
num_features = np.shape(x_train)[1]

graph = tf.Graph()
with graph.as_default():

    # Input
    tf_train_dataset = tf.constant(x_train)
    tf_train_labels = tf.constant(y_train)
    tf_valid_dataset = tf.constant(x_valid)
    tf_test_dataset = tf.constant(x_test)

    # Variables
    weights = tf.Variable(tf.truncated_normal([num_features, 1]))
    biases = tf.Variable(tf.zeros([1]))

    # Loss Computation
    train_prediction = tf.matmul(tf_train_dataset, weights) + biases
    loss = tf.losses.mean_squared_error(tf_train_labels, train_prediction)

    # Optimizer
    # Gradient descent optimizer with learning rate = alpha
    alpha = tf.constant(0.000000003, dtype=tf.float64)
    optimizer = tf.train.GradientDescentOptimizer(alpha).minimize(loss)

    # Predictions
    valid_prediction = tf.matmul(tf_valid_dataset, weights) + biases
    test_prediction = tf.matmul(tf_test_dataset, weights) + biases

This is how my graph runs:

num_steps = 10001

def accuracy(prediction, labels):
    return ((prediction - labels) ** 2).mean(axis=None)

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    print('Initialized')
    for step in range(num_steps):
        _, l, predictions = session.run([optimizer, loss, train_prediction])
        if (step % 1000 == 0):
            print('Loss at step %d: %f' % (step, l))
            print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), y_valid))
     t_pred = test_prediction.eval()
     print('Test accuracy: %.1f%%' % accuracy(t_pred, y_test))

Here is what I've tried:

I have tried increasing the learning rate. But, if I increase the learning rate beyond what I'm using right now, the model fails to converge i.e., the loss explodes to infinity.

Increased the number of iterations to 10,000,000. The loss converges slower the longer I iterate (which is understandable). But I'm still very far from a reasonable value. The loss is usually a 10 digit number

Am I doing something wrong with the graph? Or is linear regression a bad choice for this and I should try using another algorithm? Any help and suggestions is much appreciated!

Body:
Working Code

import csv
import tensorflow as tf
import numpy as np

with open('train.csv', 'rt') as f:
    reader = csv.reader(f)
    your_list = list(reader)

def toFloatNoFail( data ) :
    try :
        return float(data)
    except :
        return 0

data = [ [ toFloatNoFail(x) for x in row ] for row in your_list[1:] ]
data = np.array( data ).astype( float )
x_train = data[:,:-1]
print x_train.shape
y_train = data[:,-1:]
print y_train.shape

num_features = np.shape(x_train)[1]

# Input
tf_train_dataset = tf.constant(x_train, dtype=tf.float32)
tf_train_labels = tf.constant(y_train, dtype=tf.float32)

# Variables
weights = tf.Variable(tf.truncated_normal( [num_features, 1] , dtype=tf.float32))
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32 ))

train_prediction = tf.matmul(tf_train_dataset, weights) + biases

loss = tf.reduce_mean( tf.square( tf.log(tf_train_labels) - tf.log(train_prediction) ))

optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)

num_steps = 10001

def accuracy(prediction, labels):
    return ((prediction - labels) ** 2).mean(axis=None)

with tf.Session() as session:
    tf.global_variables_initializer().run()
    print('Initialized')
    for step in range(num_steps):
        _, l, predictions = session.run([optimizer, loss, train_prediction])
        if (step % 1000 == 0):
            print('Loss at step %d: %f' % (step, l))

Explanation of Critical Change

Your loss function wasn't scaled for the price.  The above loss function takes into account that you are really only interested in the error in prices scaled with the original price.  So, for a million dollar house being off by $5,000 shouldn't be as bad as being off by $5,000 for a $5,000 house.

The new loss function is :

loss = tf.reduce_mean( tf.square( tf.log(tf_train_labels) - tf.log(train_prediction) ))


问:
Downgrade gcc/g++ in Ubuntu?
I am trying to downgrade gcc/g++ to 4.8.1.  I tried two options, both with problems.

use sudo apt install gcc-4.8 g++-4.8.  This option will install 4.8.5 etc. I wonder if there is any way to specify 4.8.1. sudo apt install gcc-4.8.1 g++-4.8.1 does not work as it will complain that "unable to locate package gcc-4.8.1".

Download "gcc-4.8.1" and follow the official steps ("configure, make, make install") but it fails at the make step with errors "CXXABI_1.3.8" not found.

I found another solution but I am not sure whether it is desirable (" install gcc-4.8.1 from source code on Ubuntu-16.04").

How do I downgrade gcc/g++ to 4.8.1 in Ubuntu?

Many thanks.

答:
How do I downgrade gcc/g++ to 4.8.1 in Ubuntu?

I think you want look into the command "update-alternatives" (instead of 'downgrade').

To learn some more browse "https://askubuntu.com/questions/529687/how-to-use-update-alternatives-to-manage-multiple-installed-version-of-the-sam"

The update-alternatives works by changing what the command g++ points at. Currently on my system, g++ points to g++-6.

I have sometimes experienced an install that simply does not work.  My recent g++ v6.2 install is broken, I don't know why.

But because my ubuntu is out of date, I plan to upgrade to the latest ubuntu.  I might as well wait to install the latest compiler.

In the mean time I have 6.2.0, which does not 'work' (cause unknown).  g++ points to this:

```<code>~$ g++ --version
g++ (GCC) 6.2.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Since I seldom remove (un-install) the previous version in use, it turns out that with a simple search to identify what is available, I can access an older compiler using a suffix.  For example

```<code>~$ g++-5 --version
g++-5 (Ubuntu 5.2.1-23ubuntu1~15.10) 5.2.1 20151028
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

So, I continue more or less the same as before the failed 6.2.0 install.

For you, I think this means that you can use your package manager to install your desired earlier compiler, but remember to search for it in case it already exists on your system.  Then use update-alternatives to make it the default, or just learn the new command name to invoke, i.e. g++-5, and continue developing with both commands easily available.

Title: Downgrade gcc/g++ in Ubuntu?

Body:
How do I downgrade gcc/g++ to 4.8.1 in Ubuntu?

I think you want look into the command "update-alternatives" (instead of 'downgrade').

To learn some more browse "https://askubuntu.com/questions/529687/how-to-use-update-alternatives-to-manage-multiple-installed-version-of-the-sam"

The update-alternatives works by changing what the command g++ points at. Currently on my system, g++ points to g++-6.

I have sometimes experienced an install that simply does not work.  My recent g++ v6.2 install is broken, I don't know why.

But because my ubuntu is out of date, I plan to upgrade to the latest ubuntu.  I might as well wait to install the latest compiler.

In the mean time I have 6.2.0, which does not 'work' (cause unknown).  g++ points to this:

~$ g++ --version
g++ (GCC) 6.2.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Since I seldom remove (un-install) the previous version in use, it turns out that with a simple search to identify what is available, I can access an older compiler using a suffix.  For example

~$ g++-5 --version
g++-5 (Ubuntu 5.2.1-23ubuntu1~15.10) 5.2.1 20151028
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

So, I continue more or less the same as before the failed 6.2.0 install.

For you, I think this means that you can use your package manager to install your desired earlier compiler, but remember to search for it in case it already exists on your system.  Then use update-alternatives to make it the default, or just learn the new command name to invoke, i.e. g++-5, and continue developing with both commands easily available.


问:
How to run a file.m from qt
I have a file.m, which is a file from matlab, and I want it to run when I run my qt project.

I noticed I could use this -r MATLAB_command    - Start MATLAB and execute the MATLAB_command.

and this,

```<code>-nodesktop           - Do not start the MATLAB desktop. Use the current
                           terminal for commands. The Java virtual machine
                           will be started.
</code>```

from the matlab help, but i'm not sure if I'm thinking the right way.

My main.cpp

```<code>#include <QtGui/QApplication>
#include <iostream>
using namespace std;
#include <cmath>

#include <QProcess>
#include "planevolume.h"
#include "dialog.h"

int main(int argc, char *argv[])
{
    // Start MATLAB MAIN.m
    QProcess* p = new QProcess(NULL);
    p->start( QString( "/usr/local/MATLAB/R2011b/bin/matlab"),
              QStringList() << QString("-r /home/matt/Desktop/PlaneVolumeExec/MAIN.m")
                            << QString("-nosplash")
                            << QString("-nodesktop"));

    QApplication app(argc, argv);

    Dialog *dialog= new Dialog;

    if (dialog->exec())
    {
        planevolume mainwindow(dialog->getdirprefix(),dialog->getxpax(), dialog->getypax(), dialog->getzpax(), dialog->getxmmax(), dialog->getymmax(), dialog->getzmmax(), dialog->getintzminp(), dialog->getintzmaxp(), dialog->getintzminm(), dialog->getintzmaxm());
        mainwindow.show();
        return app.exec();
    }

return 0;
}
</code>```

Matlab help

```<code>/*-h|-help             - Display arguments.
    -n                   - Display final environment variables,
                           arguments, and other diagnostic
                           information. MATLAB is not run.
    -e                   - Display ALL the environment variables and
                           their values to standard output. MATLAB
                           is not run. If the exit status is not
                           0 on return then the variables and values
                           may not be correct.
    -arch                - Start MATLAB assuming architecture arch.
    v=variant            - Start the version of MATLAB found
                           in bin/glnxa64/variant instead of bin/glnxa64.
    v=arch/variant       - Start the version of MATLAB found
                           in bin/arch/variant instead of bin/glnxa64.
    -c licensefile       - Set location of the license file that MATLAB
                           should use.  It can have the form port@host or
                           be a colon separated list of license files.
                           The LM_LICENSE_FILE and MLM_LICENSE_FILE
                           environment variables will be ignored.
    -display Xdisplay    - Send X commands to X server display, Xdisplay.
    -nodisplay           - Do not display any X commands. The MATLAB
                           desktop will not be started. However, unless
                           -nojvm is also provided the Java virtual machine
                           will be started.
    -nosplash            - Do not display the splash screen during startup.
    -mwvisual visualid   - The default X visual to use for figure windows.
    -debug               - Provide debugging information especially for X
                           based problems.
    -desktop             - Allow the MATLAB desktop to be started by a
                           process without a controlling terminal. This is
                           usually a required command line argument when
                           attempting to start MATLAB from a window manager
                           menu or desktop icon.
    -nodesktop           - Do not start the MATLAB desktop. Use the current
                           terminal for commands. The Java virtual machine
                           will be started.
    -nojvm               - Shut off all Java support by not starting the
                           Java virtual machine. In particular the MATLAB
                           desktop will not be started.
    -jdb [port]          - Enable remote Java debugging on port (default 4444)
    -r MATLAB_command    - Start MATLAB and execute the MATLAB_command.
    -logfile log         - Make a copy of any output to the command window
                           in file log. This includes all crash reports.
    -Ddebugger [options] - Start debugger to debug MATLAB.*/
</code>```

答:
Try this. It works.</p>

```<code>QString program = "C:\\Program Files\\MATLAB\\R2017a\\bin\\matlab.exe";
myProcess->start(program, QStringList() << QString("-nodisplay")<< QString("-nodesktop")<<  QString("-nosplash")<<QString("-r")<<QString("run('C:/Users/eleazar.balbon/Documents/MATLAB/Sample.slx');"));
myProcess->waitForFinished();
</code>```

Title: How to run a file.m from qt

Body:
I have a file.m, which is a file from matlab, and I want it to run when I run my qt project.

I noticed I could use this -r MATLAB_command    - Start MATLAB and execute the MATLAB_command.

and this,

-nodesktop           - Do not start the MATLAB desktop. Use the current
                           terminal for commands. The Java virtual machine
                           will be started.

from the matlab help, but i'm not sure if I'm thinking the right way.

My main.cpp

#include <QtGui/QApplication>
#include <iostream>
using namespace std;
#include <cmath>

#include <QProcess>
#include "planevolume.h"
#include "dialog.h"

int main(int argc, char *argv[])
{
    // Start MATLAB MAIN.m
    QProcess* p = new QProcess(NULL);
    p->start( QString( "/usr/local/MATLAB/R2011b/bin/matlab"),
              QStringList() << QString("-r /home/matt/Desktop/PlaneVolumeExec/MAIN.m")
                            << QString("-nosplash")
                            << QString("-nodesktop"));

    QApplication app(argc, argv);

    Dialog *dialog= new Dialog;

    if (dialog->exec())
    {
        planevolume mainwindow(dialog->getdirprefix(),dialog->getxpax(), dialog->getypax(), dialog->getzpax(), dialog->getxmmax(), dialog->getymmax(), dialog->getzmmax(), dialog->getintzminp(), dialog->getintzmaxp(), dialog->getintzminm(), dialog->getintzmaxm());
        mainwindow.show();
        return app.exec();
    }

return 0;
}

Matlab help

/*-h|-help             - Display arguments.
    -n                   - Display final environment variables,
                           arguments, and other diagnostic
                           information. MATLAB is not run.
    -e                   - Display ALL the environment variables and
                           their values to standard output. MATLAB
                           is not run. If the exit status is not
                           0 on return then the variables and values
                           may not be correct.
    -arch                - Start MATLAB assuming architecture arch.
    v=variant            - Start the version of MATLAB found
                           in bin/glnxa64/variant instead of bin/glnxa64.
    v=arch/variant       - Start the version of MATLAB found
                           in bin/arch/variant instead of bin/glnxa64.
    -c licensefile       - Set location of the license file that MATLAB
                           should use.  It can have the form port@host or
                           be a colon separated list of license files.
                           The LM_LICENSE_FILE and MLM_LICENSE_FILE
                           environment variables will be ignored.
    -display Xdisplay    - Send X commands to X server display, Xdisplay.
    -nodisplay           - Do not display any X commands. The MATLAB
                           desktop will not be started. However, unless
                           -nojvm is also provided the Java virtual machine
                           will be started.
    -nosplash            - Do not display the splash screen during startup.
    -mwvisual visualid   - The default X visual to use for figure windows.
    -debug               - Provide debugging information especially for X
                           based problems.
    -desktop             - Allow the MATLAB desktop to be started by a
                           process without a controlling terminal. This is
                           usually a required command line argument when
                           attempting to start MATLAB from a window manager
                           menu or desktop icon.
    -nodesktop           - Do not start the MATLAB desktop. Use the current
                           terminal for commands. The Java virtual machine
                           will be started.
    -nojvm               - Shut off all Java support by not starting the
                           Java virtual machine. In particular the MATLAB
                           desktop will not be started.
    -jdb [port]          - Enable remote Java debugging on port (default 4444)
    -r MATLAB_command    - Start MATLAB and execute the MATLAB_command.
    -logfile log         - Make a copy of any output to the command window
                           in file log. This includes all crash reports.
    -Ddebugger [options] - Start debugger to debug MATLAB.*/

Body:
Try this. It works.

QString program = "C:\\Program Files\\MATLAB\\R2017a\\bin\\matlab.exe";
myProcess->start(program, QStringList() << QString("-nodisplay")<< QString("-nodesktop")<<  QString("-nosplash")<<QString("-r")<<QString("run('C:/Users/eleazar.balbon/Documents/MATLAB/Sample.slx');"));
myProcess->waitForFinished();


问:
VBA Set value from above cell to range below
I have a number of files, it contains data of each and every day of a month.
I need to collect all the data to a master file and insert date for each file.
I set [the 1st day -1] in A1 cell and use the code below to set date to each day range but it is not working well. Any helps is appreciated!</p>

```<code>Do While buf <> ""
Set openWB = Workbooks.Open(fold_path & "\" & buf)

With openWB.ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    .Range(.Cells(2, "A"), .Cells(LastRow, LastCol)).Copy
End With

With ThisWorkbook.Worksheets("GA")
    .Range("B" & .Cells(.Rows.Count, "B").End(xlUp).Row + 1).PasteSpecial Paste:=xlPasteValues, _
                                                    Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Range(.Cells(Cells(.Rows.Count, "B").End(xlUp).Row, "A"), .Cells(.Cells(.Rows.Count, "A").End(xlUp).Row + 1, "A")).Value = .Cells(.Cells(.Rows.Count, "A").End(xlUp).Row, "A").Value + 1

End With

openWB.Close False
buf = Dir()　Loop
</code>```

答:
Try it this way:</p>

```<code>  With ThisWorkbook.Worksheets("GA")
     With .Cells(.Rows.count, "B").End(xlUp).Offset(1)
       .Offset(, -1).value = .Offset(, -1).End(xlUp).value + 1
       .PasteSpecial Paste:=xlPasteValues
    End With
  End With
</code>```

Body:
I have a number of files, it contains data of each and every day of a month.
I need to collect all the data to a master file and insert date for each file.
I set [the 1st day -1] in A1 cell and use the code below to set date to each day range but it is not working well. Any helps is appreciated!

Do While buf <> ""
Set openWB = Workbooks.Open(fold_path & "\" & buf)

With openWB.ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    .Range(.Cells(2, "A"), .Cells(LastRow, LastCol)).Copy
End With

With ThisWorkbook.Worksheets("GA")
    .Range("B" & .Cells(.Rows.Count, "B").End(xlUp).Row + 1).PasteSpecial Paste:=xlPasteValues, _
                                                    Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Range(.Cells(Cells(.Rows.Count, "B").End(xlUp).Row, "A"), .Cells(.Cells(.Rows.Count, "A").End(xlUp).Row + 1, "A")).Value = .Cells(.Cells(.Rows.Count, "A").End(xlUp).Row, "A").Value + 1

End With

openWB.Close False
buf = Dir()　Loop

Body:
Try it this way:

  With ThisWorkbook.Worksheets("GA")
     With .Cells(.Rows.count, "B").End(xlUp).Offset(1)
       .Offset(, -1).value = .Offset(, -1).End(xlUp).value + 1
       .PasteSpecial Paste:=xlPasteValues
    End With
  End With


问:
c# string to class from which I can call functions
on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

```<code>Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);
</code>```

what I want to do is call a function on this class for example:

```<code>class.foo();
</code>```

is this possible? and if it is how?

答:
```<code>Type yourType = Type.GetType("project.start");
object yourObject = Activator.CreateInstance(yourType);

object result = yourType.GetMethod("foo")
                        .Invoke(yourObject, null);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);

what I want to do is call a function on this class for example:

class.foo();

is this possible? and if it is how?

ContentLicense: CC BY-SA 2.5


问:
php header() Authentication
Can anyone tell me why this authentication won't work?

This is a breakdown:

1) I'm trying to create a simple authentication using WWW-Authenticate with the php header() function.

2) When I go to the page, the authentication box pops up like so:

3) If I remove the script (see script below), the page loads as expected.
4) No matter what password I put in or add/remove the Realm, Stale etc, nothing bites and the Authentication box just keeps looping when I click "Log In".

```<code>if( $_SERVER['PHP_AUTH_USER'] != NULL && $_SERVER['PHP_AUTH_PW'] != NULL && $_SERVER['PHP_AUTH_USER'] == ‘admin1’ && $_SERVER['PHP_AUTH_PW'] == ‘pwd1’ ) {
   $_SESSION['login_flag'] = true;
  } else {
header("WWW-Authenticate: Basic realm=\”Schoolroom\”, stale=FALSE");
    header("HTTP/1.0 401 Unauthorized");
    print "<h1>401 Unauthorized</h1>";
    exit();
  }
</code>```

Can anyone tell me what I am doing wrong? I've also tried in multiple browsers and various computers, same issue.

UPDATE: 10:44am PST, July 5 - This is where I am at so far with modified, updated and commented code:

```<code> <?php
header('WWW-Authenticate: Basic realm="Secret page"');
header('HTTP/1.0 401 Unauthorized');

// Status flag:
$LoginSuccessful = false;

// Check username and password:
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){

$Username = $_SERVER['PHP_AUTH_USER'];
$Password = $_SERVER['PHP_AUTH_PW'];

if ($Username == 'usrnm' && $Password == 'pswrd') {
$LoginSuccessful = true;
}
}

// Login passed successful?
if (!$LoginSuccessful){

/*
** The user gets here if:
**
** 1. The user entered incorrect login data (three times)
** --> User will see the error message from below
**
** 2. Or the user requested the page for the first time
** --> Then the 401 headers apply and the "login box" will
** be shown
*/

// The text inside the realm section will be visible for the
// user in the login box
//header('WWW-Authenticate: Basic realm="Secret page"');
//header('HTTP/1.0 401 Unauthorized');

print "Login failed!\n";

}
else {

// The user entered the correct login data, put
// your confidential data in here:

print 'you reached the secret page!';
}

?>
</code>```

However, the script does not prompt to login window but instead renders "Login Failed".

We tested it with all available PHP versions 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 7.0, 7.1, but to no avail.

答:
It doesn't look like you're testing to see if $_SESSION['login_flag'] is set and also true.

```<code>if(isset($_SESSION['login_flag'] && $_SESSION['login_flag'] == true)) {
//load the page without authentication
}
else {
//ask for authentication
}
</code>```

Title: php header() Authentication

Body:
Can anyone tell me why this authentication won't work?

This is a breakdown:

1) I'm trying to create a simple authentication using WWW-Authenticate with the php header() function.

2) When I go to the page, the authentication box pops up like so:

3) If I remove the script (see script below), the page loads as expected.
4) No matter what password I put in or add/remove the Realm, Stale etc, nothing bites and the Authentication box just keeps looping when I click "Log In".

if( $_SERVER['PHP_AUTH_USER'] != NULL && $_SERVER['PHP_AUTH_PW'] != NULL && $_SERVER['PHP_AUTH_USER'] == ‘admin1’ && $_SERVER['PHP_AUTH_PW'] == ‘pwd1’ ) {
   $_SESSION['login_flag'] = true;
  } else {
header("WWW-Authenticate: Basic realm=\”Schoolroom\”, stale=FALSE");
    header("HTTP/1.0 401 Unauthorized");
    print "
401 Unauthorized
";
    exit();
  }

Can anyone tell me what I am doing wrong? I've also tried in multiple browsers and various computers, same issue.

UPDATE: 10:44am PST, July 5 - This is where I am at so far with modified, updated and commented code:

 <?php
header('WWW-Authenticate: Basic realm="Secret page"');
header('HTTP/1.0 401 Unauthorized');

// Status flag:
$LoginSuccessful = false;

// Check username and password:
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){

$Username = $_SERVER['PHP_AUTH_USER'];
$Password = $_SERVER['PHP_AUTH_PW'];

if ($Username == 'usrnm' && $Password == 'pswrd') {
$LoginSuccessful = true;
}
}

// Login passed successful?
if (!$LoginSuccessful){

/*
** The user gets here if:
**
** 1. The user entered incorrect login data (three times)
** --> User will see the error message from below
**
** 2. Or the user requested the page for the first time
** --> Then the 401 headers apply and the "login box" will
** be shown
*/

// The text inside the realm section will be visible for the
// user in the login box
//header('WWW-Authenticate: Basic realm="Secret page"');
//header('HTTP/1.0 401 Unauthorized');

print "Login failed!\n";

}
else {

// The user entered the correct login data, put
// your confidential data in here:

print 'you reached the secret page!';
}

?>

However, the script does not prompt to login window but instead renders "Login Failed".

We tested it with all available PHP versions 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 7.0, 7.1, but to no avail.

Body:
It doesn't look like you're testing to see if $_SESSION['login_flag'] is set and also true.

if(isset($_SESSION['login_flag'] && $_SESSION['login_flag'] == true)) {
//load the page without authentication
}
else {
//ask for authentication
}


问:
Dealing with ThinkingSphinx realtime indices when destroying records
I'm trying to convert a delta-based index in ThinkingSphinx into a realtime one. Per the docs, I've added this callback:

after_save ThinkingSphinx::RealTime.callback_for(:location)

That works just fine for adding and updating records, woo. My problem is in deleting records, which according to the Rails docs, don't trigger after_save callbacks. I've confirmed this by deleting a record, which is not then deleted from my sphinx index.

I tried

after_destroy ThinkingSphinx::RealTime.callback_for(:location)

But this raises an error (as the realtime callbacks do not support after_destroy).

How can I remove an entry from my index when using a real time index?

(thinking-sphinx 3.3.0, rails 5.0.4, if that helps)

答: Thinking Sphinx automatically adds its own after_destroy callback to all indexed models, so removal of these records from real-time indices should happen without you needing to add any code.


问:
Function that returns a multiplication table fails with negative numbers
Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns

10.2 = 20

10.3 = 30

10.4 = 40

This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate

10.-4 = -40

10.-3 = -30

10.-2 = -20

10.-1 = -10

but it doesn't return anything. This is my code:

```<code>function tabmul(a,b,c){ \\function that generates the multiplication table
    var myarray = new Array();
    var x
    for(x=b; x<=c; x++){
        myarray[x - b] = a*x;
        document.write(a + "." + x + "=" + myarray[x - b] + "<br>")
    }
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
  tabmul(a,b,c);

} else {
    alert("The starting point is bigger than the ending point");
}
</code>```

答:
1)Make normal names for function arguments.

2)Use indentation and 'let' in 'for' loop instead of 'var' right before:

```<code>for(let x = b; x <= c; x++){}
</code>```

3)Don't forget semicolons.

```<code>function multiplication(val, start, end) {
  if(end - start <= 0) return;
  for(let i = start; i <= end; i++) {
    console.log(val + ' * ' + i + ' = ' + val * i);
  }
}
multiplication(10, -4, -1);

10 * -4 = -40
10 * -3 = -30
10 * -2 = -20
10 * -1 = -10
</code>```

Body:
Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns

10.2 = 20

10.3 = 30

10.4 = 40

This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate

10.-4 = -40

10.-3 = -30

10.-2 = -20

10.-1 = -10

but it doesn't return anything. This is my code:

function tabmul(a,b,c){ \\function that generates the multiplication table
    var myarray = new Array();
    var x
    for(x=b; x<=c; x++){
        myarray[x - b] = a*x;
        document.write(a + "." + x + "=" + myarray[x - b] + "
")
    }
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
  tabmul(a,b,c);

} else {
    alert("The starting point is bigger than the ending point");
}

Body:
1)Make normal names for function arguments.

2)Use indentation and 'let' in 'for' loop instead of 'var' right before:

for(let x = b; x <= c; x++){}

3)Don't forget semicolons.

function multiplication(val, start, end) {
  if(end - start <= 0) return;
  for(let i = start; i <= end; i++) {
    console.log(val + ' * ' + i + ' = ' + val * i);
  }
}
multiplication(10, -4, -1);

10 * -4 = -40
10 * -3 = -30
10 * -2 = -20
10 * -1 = -10


问:
How to get arrays one at a time?
If someone access my page, I want to 'echo' the values inside my array one-by-one to them.

if first user access my page, php will get first array value and issue to it.

if second user access my page, php will get second array value and issue to it once again... and this process keeps so on!

User 1 > Number 1 | User 2 > Number 2 | User 3 > Number 1 | User 4 > Number 2.....

and for other I thing I want:

*** if possible, to get first value more than the second.

For example: Number 1 viewed 8 times, number 2 viewed 4.

My simple array code:

```<code>$numbers = array(
            '+1111111111', // Number 1
            '+2222222222', // Number 2
);
</code>```

Any help or suggestion, thanks in advance!!!

答:
I think you are going to have to use a mix of an alternating server stored variable, and then cookies to pass out to each user as they enter your site.

There are many ways to store a server side variable, and cookies are pretty straight forward.

My knowledge is limited, hopefully someone with more insight can help break down some details for you.

Title: How to get arrays one at a time?

Body:
If someone access my page, I want to 'echo' the values inside my array one-by-one to them.

if first user access my page, php will get first array value and issue to it.

if second user access my page, php will get second array value and issue to it once again... and this process keeps so on!

User 1 > Number 1 | User 2 > Number 2 | User 3 > Number 1 | User 4 > Number 2.....

and for other I thing I want:

*** if possible, to get first value more than the second.

For example: Number 1 viewed 8 times, number 2 viewed 4.

My simple array code:

$numbers = array(
            '+1111111111', // Number 1
            '+2222222222', // Number 2
);

Any help or suggestion, thanks in advance!!!


问:
Error "Cannot use object of type stdClass as array"
I get a strange error using json_decode(). It decodes the data correctly (I saw it using print_r), but when I try to access to information inside the array I get:

Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108
```

I only tried to do: $result['context'] where $result has the data returned by json_decode()

How can I read values inside this array?

答:
Change it for</p>

```<code>$results->fetch_array()
</code>```

Body:
I get a strange error using json_decode(). It decodes the data correctly (I saw it using print_r), but when I try to access to information inside the array I get:

Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108

I only tried to do: $result['context'] where $result has the data returned by json_decode()

How can I read values inside this array?

Body:
Change it for

$results->fetch_array()


问:
Is this good design of a workflow-esque system?
I'm in the process of designing a system that will allow me to represent broad-scope tasks as workflows, which expose their workitems via an IEnumerable method. The intention here is to use C#'s 'yield' mechanism to allow me to write psuedo-procedural code that the workflow execution system can execute as it sees fit.

For example, say I have a workflow that includes running a query on the database and sending an email alert if the query returns a certain result. This might be the workflow:

```<code>public override IEnumerable<WorkItem> Workflow() {
    // These would probably be injected from elsewhere
    var db = new DB();
    var emailServer = new EmailServer();

    // other workitems here

    var ci = new FindLowInventoryItems(db);
    yield return ci;

    if (ci.LowInventoryItems.Any()) {
        var email = new SendEmailToWarehouse("Inventory is low.", ci.LowInventoryItems);
        yield return email;
    }

    // other workitems here
}
</code>```

CheckInventory and EmailWarehouse are objects deriving from WorkItem, which has an abstract Execute() method that the subclasses implement, encapsulating the behavior for those actions. The Execute() method gets called in the workflow framework - I have a WorkflowRunner class which enumerates the Workflow(), wraps pre- and post- events around the workitem, and calls Execute in between the events. This allows the consuming application to do whatever it needs in before or after workitems, including canceling, changing workitem properties, etc.

The benefit to all this, I think, is that I can express the core logic of a task in terms of the workitems responsible for getting the work done, and I can do it in a fairly straightforward, almost procedural way. Also because I'm using IEnumerable, and C#'s syntactic sugar that supports it, I can compose these workflows - like higher-level workflows that consume and manipulate sub-workflows. For example I wrote a simple workflow that just interleaves two child workflows together.

My question is this - does this sort of architecture seem reasonable, especially from a maintainability perspective? It seems to achieve several goals for me - self-documenting code (the workflow reads procedurally, so I know what will be executed in what steps), separation of concerns (finding low inventory items does not depend on sending email to the warehouse), etc. Also - are there any potential problems with this sort of architecture that I'm not seeing? Finally, has this been tried before - am I just re-discovering this?

答:
Personally, this would be a "buy before build" decision for me.  I'd buy something before I'd write it.

I work for a company that's rather large and can be foolish with its money, so if you're writing this for yourself and can't buy something I'll retract the comment.

Here are a few random ideas:

I'd externalize the workflow into a configuration that I could read in on startup, maybe from a file or a database.

It'd look something like a finite state machine with states, transitions, events, and actions.

I'd want to be able to plug in different actions so I could customize different flows on the fly.

I'd want to be able to register different subscribers who would want to be notified when a particular event happened.

I wouldn't expect to see anything as hard-coded as that e-mail server.  I'd rather encapsulate that into an EmailNotifier that I could plug into events that demanded it.  What about a beeper notification?  Or a cell phone?  Blackberry?  Same architecture, different notifier.

Do you want to include a handler for human interaction?  All the workflows that I deal with are a mix of human and automated processing.

Do you anticipate wanting to connect to other systems, like databases, other apps, web services?

It's a tough problem. Good luck.

OwnerDisplayName: Erik

Body:
I'm in the process of designing a system that will allow me to represent broad-scope tasks as workflows, which expose their workitems via an IEnumerable method. The intention here is to use C#'s 'yield' mechanism to allow me to write psuedo-procedural code that the workflow execution system can execute as it sees fit.

For example, say I have a workflow that includes running a query on the database and sending an email alert if the query returns a certain result. This might be the workflow:

public override IEnumerable<WorkItem> Workflow() {
    // These would probably be injected from elsewhere
    var db = new DB();
    var emailServer = new EmailServer();

    // other workitems here

    var ci = new FindLowInventoryItems(db);
    yield return ci;

    if (ci.LowInventoryItems.Any()) {
        var email = new SendEmailToWarehouse("Inventory is low.", ci.LowInventoryItems);
        yield return email;
    }

    // other workitems here
}

CheckInventory and EmailWarehouse are objects deriving from WorkItem, which has an abstract Execute() method that the subclasses implement, encapsulating the behavior for those actions. The Execute() method gets called in the workflow framework - I have a WorkflowRunner class which enumerates the Workflow(), wraps pre- and post- events around the workitem, and calls Execute in between the events. This allows the consuming application to do whatever it needs in before or after workitems, including canceling, changing workitem properties, etc.

The benefit to all this, I think, is that I can express the core logic of a task in terms of the workitems responsible for getting the work done, and I can do it in a fairly straightforward, almost procedural way. Also because I'm using IEnumerable, and C#'s syntactic sugar that supports it, I can compose these workflows - like higher-level workflows that consume and manipulate sub-workflows. For example I wrote a simple workflow that just interleaves two child workflows together.

My question is this - does this sort of architecture seem reasonable, especially from a maintainability perspective? It seems to achieve several goals for me - self-documenting code (the workflow reads procedurally, so I know what will be executed in what steps), separation of concerns (finding low inventory items does not depend on sending email to the warehouse), etc. Also - are there any potential problems with this sort of architecture that I'm not seeing? Finally, has this been tried before - am I just re-discovering this?

LastEditorDisplayName: Erik


答:
It is possible but you will have to use reflection or have class be cast as the proper type at runtime..

Reflection Example:

```<code>type.GetMethod("foo").Invoke(class, null);
</code>```

Title: c# string to class from which I can call functions

Body:
It is possible but you will have to use reflection or have class be cast as the proper type at runtime..

Reflection Example:

type.GetMethod("foo").Invoke(class, null);


问:
Downloading a image using Python Mechanize
I'm trying to write a Python script to download a image and set it as my wallpaper. Unfortunately, the Mechanize documentation is quite poor. My script is following the link correctly, but I'm having a hard time to actually save the image on my computer. From what I researched, the .retrieve() method should do the work, but How do I specify the path to where the file should be downloaded to? Here is what I have...</p>

```<code>def followLink(browser, fixedLink):
    browser.open(fixedLink)

if browser.find_link(url_regex = r'1600x1200'):

    browser.follow_link(url_regex = r'1600x1200')

elif browser.find_link(url_regex = r'1400x1050'):

    browser.follow_link(url_regex = r'1400x1050')

elif browser.find_link(url_regex = r'1280x960'):

    browser.follow_link(url_regex = r'1280x960')

 return
</code>```

答:
It's really crappy but It "works" for me, with 0xc0000022l anwer's

import mechanize, os
    from BeautifulSoup import BeautifulSoup
    import urllib2

```<code>def DownloadIMGs(url): # IMPORTANT URL WITH HTTP OR HTTPS
    print "From", url
    dir = 'F:\Downloadss' #Dir for Downloads
    basicImgFileTypes = ['png','bmp','cur','ico','gif','jpg','jpeg','psd','raw','tif']

    browser = mechanize.Browser()
    html = browser.open(url)
    soup = BeautifulSoup(html)
    image_tags = soup.findAll('img')
    print "N Images:", len(image_tags)
    print
    #---------SAVE PATH
    #check if available
    if not os.path.exists(dir):
        os.makedirs(dir)
    #---------SAVE PATH
    for image in image_tags:

        #---------SAVE PATH + FILENAME (Where It is downloading)
        filename = image['src']
        fileExt = filename.split('.')[-1]
        fileExt = fileExt[0:3]

        if (fileExt in basicImgFileTypes):
            print 'File Extension:', fileExt
            filename = filename.replace('?', '_')
            filename = os.path.join(dir, filename.split('/')[-1])
            num = filename.find(fileExt) + len(fileExt)
            filename = filename[:num]
        else:
            filename = filename.replace('?', '_')
            filename = os.path.join(dir, filename.split('/')[-1]) + '.' + basicImgFileTypes[0]
        print 'File Saving:', filename
        #---------SAVE PATH + FILENAME (Where It is downloading)

        #--------- FULL URL PATH OF THE IMG
        imageUrl = image['src']
        print 'IMAGE SRC:', imageUrl

        if (imageUrl.find('http://') > -1 or imageUrl.find('https://') > -1):
            pass
        else:
            if (url.find('http://') > -1):
                imageUrl = url[:len('http://')]
                imageUrl = 'http://' + imageUrl.split('/')[0] + image['src']
            elif(url.find('https://') > -1):
                imageUrl = url[:len('https://')]
                imageUrl = 'https://' + imageUrl.split('/')[0] + image['src']
            else:
                imageUrl = image['src']

        print 'IMAGE URL:', imageUrl
        #--------- FULL URL PATH OF THE IMG

        #--------- TRY DOWNLOAD
        try:
            browser.retrieve(imageUrl, filename)
            print "Downloaded:", image['src'].split('/')[-1]
            print
        except (mechanize.HTTPError,mechanize.URLError) as e:
            print "Can't Download:", image['src'].split('/')[-1]
            print
            pass
        #--------- TRY DOWNLOAD
    browser.close()

DownloadIMGs('https://stackoverflow.com/questions/15593925/downloading-a-image-using-python-mechanize')
</code>```

Body:
I'm trying to write a Python script to download a image and set it as my wallpaper. Unfortunately, the Mechanize documentation is quite poor. My script is following the link correctly, but I'm having a hard time to actually save the image on my computer. From what I researched, the .retrieve() method should do the work, but How do I specify the path to where the file should be downloaded to? Here is what I have...

def followLink(browser, fixedLink):
    browser.open(fixedLink)

if browser.find_link(url_regex = r'1600x1200'):

    browser.follow_link(url_regex = r'1600x1200')

elif browser.find_link(url_regex = r'1400x1050'):

    browser.follow_link(url_regex = r'1400x1050')

elif browser.find_link(url_regex = r'1280x960'):

    browser.follow_link(url_regex = r'1280x960')

 return

Body:
It's really crappy but It "works" for me, with 0xc0000022l anwer's

import mechanize, os
    from BeautifulSoup import BeautifulSoup
    import urllib2

def DownloadIMGs(url): # IMPORTANT URL WITH HTTP OR HTTPS
    print "From", url
    dir = 'F:\Downloadss' #Dir for Downloads
    basicImgFileTypes = ['png','bmp','cur','ico','gif','jpg','jpeg','psd','raw','tif']

    browser = mechanize.Browser()
    html = browser.open(url)
    soup = BeautifulSoup(html)
    image_tags = soup.findAll('img')
    print "N Images:", len(image_tags)
    print
    #---------SAVE PATH
    #check if available
    if not os.path.exists(dir):
        os.makedirs(dir)
    #---------SAVE PATH
    for image in image_tags:

        #---------SAVE PATH + FILENAME (Where It is downloading)
        filename = image['src']
        fileExt = filename.split('.')[-1]
        fileExt = fileExt[0:3]

        if (fileExt in basicImgFileTypes):
            print 'File Extension:', fileExt
            filename = filename.replace('?', '_')
            filename = os.path.join(dir, filename.split('/')[-1])
            num = filename.find(fileExt) + len(fileExt)
            filename = filename[:num]
        else:
            filename = filename.replace('?', '_')
            filename = os.path.join(dir, filename.split('/')[-1]) + '.' + basicImgFileTypes[0]
        print 'File Saving:', filename
        #---------SAVE PATH + FILENAME (Where It is downloading)

        #--------- FULL URL PATH OF THE IMG
        imageUrl = image['src']
        print 'IMAGE SRC:', imageUrl

        if (imageUrl.find('http://') > -1 or imageUrl.find('https://') > -1):
            pass
        else:
            if (url.find('http://') > -1):
                imageUrl = url[:len('http://')]
                imageUrl = 'http://' + imageUrl.split('/')[0] + image['src']
            elif(url.find('https://') > -1):
                imageUrl = url[:len('https://')]
                imageUrl = 'https://' + imageUrl.split('/')[0] + image['src']
            else:
                imageUrl = image['src']

        print 'IMAGE URL:', imageUrl
        #--------- FULL URL PATH OF THE IMG

        #--------- TRY DOWNLOAD
        try:
            browser.retrieve(imageUrl, filename)
            print "Downloaded:", image['src'].split('/')[-1]
            print
        except (mechanize.HTTPError,mechanize.URLError) as e:
            print "Can't Download:", image['src'].split('/')[-1]
            print
            pass
        #--------- TRY DOWNLOAD
    browser.close()

DownloadIMGs('https://stackoverflow.com/questions/15593925/downloading-a-image-using-python-mechanize')


问:
Trying to make navbar active - I include my single nav_bar.jsp file to all my files
So I have one file which has my nav bar: nav_bar.jsp. In this file, I have this:

```<code><ul class="nav navbar-nav">
                <!-- navbar links -->
                <li class="active"><a href="${pageContext.request.contextPath}/index/">Home</a></li>
                <li><a href="${pageContext.request.contextPath}/myinfo/">My Information</a></li>
                <li><a href="${pageContext.request.contextPath}/reimbursements/">Reimbursements</a></li>
                <li><a href="${pageContext.request.contextPath}/employees/">Employees</a></li>
            </ul>
</code>```

(My url has a regex which is checking for the path)

Anyway, all my files include this file with the following:

```<code><%@ include file="nav_bar.jsp" %>  <%-- Bringing in nav bar  --%>
</code>```

The navbar shows perfectly fine. However, I'm trying to change the class "active" depending on the tab that is open. I was trying to do it with JS, but it still doesn't work. I tried this

default.js

```<code>$('.navbar-nav li').click( function () {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
});
</code>```

Note: I'm getting my JS in the nav_bar.jsp and also every other page with this as the last tag in the head tag

```<code><script type="text/javascript" src="${pageContext.request.contextPath}/JS/default.js"></script>
</code>```

I read somewhere that I had to add JS in the bottom of the body tag? I wasn't sure if that was true. I tried it but it still didn't work

答:
You are navigating into a new page when you are clicking on a new tab so changing anything in javascript wouldn't do a thing as a new page will be loaded and the DOM will be refreshed.

One way to set the active class is based on the request url. You could do that either via HTML tags or JavaScript. For HTML tags do something like the below: (You will have to do it for every tab (adjust the condition as you need for each link))

```<code><li class="${pageContext.request.requestURI.endsWith('/index/') ? 'active' : ''}">
    <a href="${pageContext.request.contextPath}/index/">Home</a>
</li>
</code>```

Note: I just assumed the condition for your first link. You may want to adjust that to cover broader requests etc

Body:
So I have one file which has my nav bar: nav_bar.jsp. In this file, I have this:

Home

My Information

Reimbursements

Employees

(My url has a regex which is checking for the path)

Anyway, all my files include this file with the following:

<%@ include file="nav_bar.jsp" %>  <%-- Bringing in nav bar  --%>

The navbar shows perfectly fine. However, I'm trying to change the class "active" depending on the tab that is open. I was trying to do it with JS, but it still doesn't work. I tried this

default.js

$('.navbar-nav li').click( function () {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
});

Note: I'm getting my JS in the nav_bar.jsp and also every other page with this as the last tag in the head tag

I read somewhere that I had to add JS in the bottom of the body tag? I wasn't sure if that was true. I tried it but it still didn't work

Body:
You are navigating into a new page when you are clicking on a new tab so changing anything in javascript wouldn't do a thing as a new page will be loaded and the DOM will be refreshed.

One way to set the active class is based on the request url. You could do that either via HTML tags or JavaScript. For HTML tags do something like the below: (You will have to do it for every tab (adjust the condition as you need for each link))

<li class="${pageContext.request.requestURI.endsWith('/index/') ? 'active' : ''}">
    <a href="${pageContext.request.contextPath}/index/">Home</a>
</li>

Note: I just assumed the condition for your first link. You may want to adjust that to cover broader requests etc


问:
Mule: Application starts up but I get the following Error Message
My file upload application starts up fine, but I get the following error on the console:

java.lang.IllegalArgumentException: Domain 'default' is not accessible
    at org.mule.module.launcher.MuleSharedDomainClassLoader.validateAndGetDomainFolders(MuleSharedDomainClassLoader.java:119) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.MuleSharedDomainClassLoader.(MuleSharedDomainClassLoader.java:45) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.domain.MuleDomainClassLoaderRepository.getDefaultDomainClassLoader(MuleDomainClassLoaderRepository.java:54) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.domain.MuleDomainClassLoaderRepository.getDomainClassLoader(MuleDomainClassLoaderRepository.java:34) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.domain.DefaultMuleDomain.refreshClassLoaderAndLoadConfigResourceFile(DefaultMuleDomain.java:70) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.domain.DefaultMuleDomain.(DefaultMuleDomain.java:66) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.domain.DefaultDomainFactory.createArtifact(DefaultDomainFactory.java:52) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.domain.DefaultDomainFactory.createArtifact(DefaultDomainFactory.java:17) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.application.DefaultApplicationFactory.createAppFrom(DefaultApplicationFactory.java:70) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.application.DefaultApplicationFactory.createArtifact(DefaultApplicationFactory.java:52) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.application.DefaultApplicationFactory.createArtifact(DefaultApplicationFactory.java:24) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployExplodedApp(DefaultArchiveDeployer.java:269) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployExplodedArtifact(DefaultArchiveDeployer.java:108) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.DeploymentDirectoryWatcher.deployExplodedApps(DeploymentDirectoryWatcher.java:290) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.DeploymentDirectoryWatcher.start(DeploymentDirectoryWatcher.java:151) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.MuleDeploymentService.start(MuleDeploymentService.java:100) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.module.launcher.MuleContainer.start(MuleContainer.java:170) ~[mule-module-launcher-3.7.2.jar:3.7.2]
    at org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:15) ~[tooling-support-3.7.2.jar:?]
INFO  2017-03-13 15:04:51,966 [main] org.mule.module.launcher.DeploymentDirectoryWatcher:

Any ideas?

答:
If you are facing this error in Anypoint studio

go to project location and make sure domains folder exists ${ProjectLocation}./mule/domains/default  if not create one.

still issue, Pre-check:

```<code>1) make sure you project code checked in to stash ( dont loss any data)

2)close anypoint studio

3)Go to .mule folder of the your project workspace

4)delete .mule folder

5) start Anypoint studio
</code>```

Body:
If you are facing this error in Anypoint studio

go to project location and make sure domains folder exists ${ProjectLocation}./mule/domains/default  if not create one.

still issue, Pre-check:

1) make sure you project code checked in to stash ( dont loss any data)

2)close anypoint studio

3)Go to .mule folder of the your project workspace

4)delete .mule folder

5) start Anypoint studio


问:
How to bind to property of property in WPF?

What works

I have a window with a widget and such binding:

```<code><Button Name="button" IsEnabled="{Binding Path=CanBeEnabled}"/>
</code>```

and in code of the window I set main data context and the data context to this widget:

```<code>    public Controller controller { get; set; }

    public WorkflowWindow(Controller con) // constructor
    {
        controller = con;

        InitializeComponent();
        DataContext = this;
        button.DataContext = controller;
    }
</code>```

The property "controller" is in such simple form, because during the lifetime of the window it never changes.

What does not work

I would like to have one data context and use nested binding, such as:

```<code><Button Name="button" IsEnabled="{Binding Path=controller.CanBeEnabled}"/>
</code>```

And code

```<code>    public WorkflowWindow(Controller con)
    {
        controller = con;

        InitializeComponent();
        DataContext = this;
    }
</code>```

In this case widget is always disabled.

And little variation of it

```<code>    public WorkflowWindow(Controller con)
    {
        controller = con;

        InitializeComponent();
        DataContext = this;
        button.DataContext = this; // directly setting the data context
    }
</code>```

In this case widget is always enabled (this not a typo here).

The question

How to make the second form working? I prefer the second form because then I could bind to various sources, not only from one data context.

SOLVED

Tom hit the nail in the head -- the problem was because of the nesting -- the button is part of custom control, and I was setting the data context twice. Once when defining the control, the second time when using it (like here). So that is why WPF got confused -- and I spent two days tracking the problem, oh boy :-(

答:
well you can do it simpler because the DataContext property is among the few that are inherited, which means that when set on an element somewhere in the tree, all child elements get it implicitly if they do not override it.

So your windows's code could look something like:

```<code>public WorkflowWindow(Controller con)
{
   InitializeComponent();
   DataContext = con;
}
</code>```

and then your button should look like:

```<code><Button IsEnabled="{Binding Path=CanBeEnabled}"/>
</code>```

so what happens when wpf's binding engine tries to resolve the CanBeEnabled property:

it will look at button's DataContext.

the button's DataContext is not explicitly set, but is inherited from the Window in which the button is placed (WorkflowWindow).

wpf will get the CanBeEnabled property from the DataContext, which (as assigned) is the passed to the Window's contstructor controller.

Body:
What works

I have a window with a widget and such binding:

<Button Name="button" IsEnabled="{Binding Path=CanBeEnabled}"/>

and in code of the window I set main data context and the data context to this widget:

    public Controller controller { get; set; }

    public WorkflowWindow(Controller con) // constructor
    {
        controller = con;

        InitializeComponent();
        DataContext = this;
        button.DataContext = controller;
    }

The property "controller" is in such simple form, because during the lifetime of the window it never changes.

What does not work

I would like to have one data context and use nested binding, such as:

<Button Name="button" IsEnabled="{Binding Path=controller.CanBeEnabled}"/>

And code

    public WorkflowWindow(Controller con)
    {
        controller = con;

        InitializeComponent();
        DataContext = this;
    }

In this case widget is always disabled.

And little variation of it

    public WorkflowWindow(Controller con)
    {
        controller = con;

        InitializeComponent();
        DataContext = this;
        button.DataContext = this; // directly setting the data context
    }

In this case widget is always enabled (this not a typo here).

The question

How to make the second form working? I prefer the second form because then I could bind to various sources, not only from one data context.

SOLVED

Tom hit the nail in the head -- the problem was because of the nesting -- the button is part of custom control, and I was setting the data context twice. Once when defining the control, the second time when using it (like here). So that is why WPF got confused -- and I spent two days tracking the problem, oh boy :-(

Body:
well you can do it simpler because the DataContext property is among the few that are inherited, which means that when set on an element somewhere in the tree, all child elements get it implicitly if they do not override it.

So your windows's code could look something like:

public WorkflowWindow(Controller con)
{
   InitializeComponent();
   DataContext = con;
}

and then your button should look like:

<Button IsEnabled="{Binding Path=CanBeEnabled}"/>

so what happens when wpf's binding engine tries to resolve the CanBeEnabled property:

it will look at button's DataContext.

the button's DataContext is not explicitly set, but is inherited from the Window in which the button is placed (WorkflowWindow).

wpf will get the CanBeEnabled property from the DataContext, which (as assigned) is the passed to the Window's contstructor controller.


问:
"TypeError: undefined is not a constructor" with Capybara (PhantomJS)
I have a JavaScript error with Capybara feature test.
But the error is not occurring with normal chrome browser.
The JavaScript code is below.

```<code>document.addEventListener('DOMContentLoaded', function(){
  var enable = function(){
    document.querySelectorAll('input').forEach(function(e){ e.disabled = false });
  }
  /* do something ..*/
  enable();
}
</code>```

The error message is TypeError: undefined is not a constructor (evaluating 'form.querySelectorAll('input').forEach(function(e){ e.disabled = false })').
I think it is related to forEach returns undefined.

答: forEach is an ES 5.1/6 method, but the current version of PhantomJS only supports up to ES 5.  You will need to either polyfill forEach or rewrite your code using ES 5 compatible methods.

Body:
I have a JavaScript error with Capybara feature test.
But the error is not occurring with normal chrome browser.
The JavaScript code is below.

document.addEventListener('DOMContentLoaded', function(){
  var enable = function(){
    document.querySelectorAll('input').forEach(function(e){ e.disabled = false });
  }
  /* do something ..*/
  enable();
}

The error message is TypeError: undefined is not a constructor (evaluating 'form.querySelectorAll('input').forEach(function(e){ e.disabled = false })').
I think it is related to forEach returns undefined.


问:
Unhandled rejection TypeError: dbUser.validPassword is not a function Sequelize Node React Passport
I am attempting to use Passport Authentication on my web app. I am using Sequelize ORM, Reactjs front-end and express and node back end. Right now, when I register a user everything works fine. the problem comes when I try to login. I see the user querying the DB to find the user with correct email, but when it is time to compare passwords, i am catching an error.

"Unhandled rejection TypeError: dbUser.validPassword is not a function"

here is my config/passport.js file:

```<code>var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
var db = require("../models");
// Telling passport we want to use a Local Strategy. In other words, we
want login with a username/email and password
passport.use(new LocalStrategy(
// Our user will sign in using an email, rather than a "username"
{
  usernameField: "email"
 },
  function(email, password, done) {
// When a user tries to sign in this code runs
db.User.findOne({
  where: {
    email: email
  }
}).then(function(dbUser) {
  // If there's no user with the given email
  if (!dbUser) {
    return done(null, false, {
      message: "Incorrect email."
    });
  }
  // If there is a user with the given email, but the password the user
gives us is incorrect
  else if (!dbUser.validPassword(password)) {
    return done(null, false, {
      message: "Incorrect password."
    });
  }
  // If none of the above, return the user
  return done(null, dbUser);
});
}
));
// In order to help keep authentication state across HTTP requests,
// Sequelize needs to serialize and deserialize the user
// Just consider this part boilerplate needed to make it all work
passport.serializeUser(function(user, cb) {
  cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// Exporting our configured passport
module.exports = passport;
</code>```

Here is my User Model:

```<code>var bcrypt = require("bcrypt-nodejs");

[![enter image description here][1]][1]module.exports = function(sequelize, DataTypes){
var User = sequelize.define("User", {
   email: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      isEmail: true
    }
},
    password: {
  type: DataTypes.STRING,
  allowNull: false
},

},{

     classMethods: {
        associate: function(models) {
            User.hasOne(models.Educator, {
                onDelete: "cascade"
            });

            User.hasOne(models.Expert, {
                onDelete: "cascade"
            });
        }
     },

        instanceMethods: {
            validPassword: function(password) {
                return bcrypt.compareSync(password, this.password);
            }
        },
            // Hooks are automatic methods that run during various phases of the User Model lifecycle
            // In this case, before a User is created, we will automatically hash their password
        hooks: {
            beforeCreate: function(user, options) {
               console.log(user, options )
                user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);

            }
        }

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

I am also including an image of the error.

答:
As of sequelize version >4, it has changed the way instance methods are defined.

They follow a more class based approach now,
A sample from the Docs for how it has to be done

```<code> const Model = sequelize.define('Model', { ... });

 // Class Method
Model.associate = function (models) { ...associate the models };
// Instance Method
Model.prototype.someMethod = function () {..}
</code>```

The syntax you are using corresponds to sequelize < 4.

Body:
I am attempting to use Passport Authentication on my web app. I am using Sequelize ORM, Reactjs front-end and express and node back end. Right now, when I register a user everything works fine. the problem comes when I try to login. I see the user querying the DB to find the user with correct email, but when it is time to compare passwords, i am catching an error.

"Unhandled rejection TypeError: dbUser.validPassword is not a function"

here is my config/passport.js file:

var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
var db = require("../models");
// Telling passport we want to use a Local Strategy. In other words, we
want login with a username/email and password
passport.use(new LocalStrategy(
// Our user will sign in using an email, rather than a "username"
{
  usernameField: "email"
 },
  function(email, password, done) {
// When a user tries to sign in this code runs
db.User.findOne({
  where: {
    email: email
  }
}).then(function(dbUser) {
  // If there's no user with the given email
  if (!dbUser) {
    return done(null, false, {
      message: "Incorrect email."
    });
  }
  // If there is a user with the given email, but the password the user
gives us is incorrect
  else if (!dbUser.validPassword(password)) {
    return done(null, false, {
      message: "Incorrect password."
    });
  }
  // If none of the above, return the user
  return done(null, dbUser);
});
}
));
// In order to help keep authentication state across HTTP requests,
// Sequelize needs to serialize and deserialize the user
// Just consider this part boilerplate needed to make it all work
passport.serializeUser(function(user, cb) {
  cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// Exporting our configured passport
module.exports = passport;

Here is my User Model:

var bcrypt = require("bcrypt-nodejs");

[![enter image description here][1]][1]module.exports = function(sequelize, DataTypes){
var User = sequelize.define("User", {
   email: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      isEmail: true
    }
},
    password: {
  type: DataTypes.STRING,
  allowNull: false
},

},{

     classMethods: {
        associate: function(models) {
            User.hasOne(models.Educator, {
                onDelete: "cascade"
            });

            User.hasOne(models.Expert, {
                onDelete: "cascade"
            });
        }
     },

        instanceMethods: {
            validPassword: function(password) {
                return bcrypt.compareSync(password, this.password);
            }
        },
            // Hooks are automatic methods that run during various phases of the User Model lifecycle
            // In this case, before a User is created, we will automatically hash their password
        hooks: {
            beforeCreate: function(user, options) {
               console.log(user, options )
                user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);

            }
        }

})
return User;
}

I am also including an image of the error.

Body:
As of sequelize version >4, it has changed the way instance methods are defined.

They follow a more class based approach now,
A sample from the Docs for how it has to be done

 const Model = sequelize.define('Model', { ... });

 // Class Method
Model.associate = function (models) { ...associate the models };
// Instance Method
Model.prototype.someMethod = function () {..}

The syntax you are using corresponds to sequelize < 4.


问:
Sequencing futures to avoid race condition
In this example I have a race condition, the string s at the end of the program should print with @ and # replaced:

```<code>object TestFutures extends App {

  var s = "THIS IS A STRING"

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map {
    seq => seq.map {  i =>
          println("BEFORE ---> " + s)
          if (i == 0)
              s = s.replace ( "T", "@")
          else
              s = s.replace ("I", "#")
          println("AFTER ---> " + s)
        }
  }

  Thread.sleep(5000)
}
</code>```

But the code prints

```<code>BEFORE ---> THIS IS A STRING
BEFORE ---> THIS IS A STRING
AFTER ---> TH#S #S A STR#NG
AFTER ---> TH#S #S A STR#NG
</code>```

How to avoid this race condition? how to change the string?

答:
The only sure way to avoid race conditions is to not have mutable state.
Something like this would work: </p>

```<code> val s = "THIS IS A STRING"
 Future
   .sequence(Seq(Future(0), Future(1)))
   .map {
      _.foldLeft(s) {
        case (s, 0) => s.replaceAll("T", "@")
        case (s, _) => s.replaceAll("I", "#")
     }
   }.andThen {
     case Success(str) => println("RESULT: " + str)
   }
</code>```

Body:
In this example I have a race condition, the string s at the end of the program should print with @ and # replaced:

object TestFutures extends App {

  var s = "THIS IS A STRING"

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map {
    seq => seq.map {  i =>
          println("BEFORE ---> " + s)
          if (i == 0)
              s = s.replace ( "T", "@")
          else
              s = s.replace ("I", "#")
          println("AFTER ---> " + s)
        }
  }

  Thread.sleep(5000)
}

But the code prints

BEFORE ---> THIS IS A STRING
BEFORE ---> THIS IS A STRING
AFTER ---> TH#S #S A STR#NG
AFTER ---> TH#S #S A STR#NG

How to avoid this race condition? how to change the string?

Body:
The only sure way to avoid race conditions is to not have mutable state.
Something like this would work:

 val s = "THIS IS A STRING"
 Future
   .sequence(Seq(Future(0), Future(1)))
   .map {
      _.foldLeft(s) {
        case (s, 0) => s.replaceAll("T", "@")
        case (s, _) => s.replaceAll("I", "#")
     }
   }.andThen {
     case Success(str) => println("RESULT: " + str)
   }


问:
How to get route parameters from a url in angular2 app?
I have a constant ROUTES that is set up like this:

```<code>export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]
</code>```

I want to make it so that if the user goes to:

```<code>http://my-angular-app/#/custom/something?mode=CRAZY
</code>```

That within "MyCustomComponent", I can see access the "mode=CRAZY" and do something with it.

How do I access the variable "mode" from my MyCustomComponent? Or do I have to define a new route to be able to pass the parameters?

答:
This is what works for me to access the query parameters within a component.

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent {

  constructor(private activatedRoute: ActivatedRoute) {
    let mode = activatedRoute.snapshot.queryParams['mode']; //< HERE
    console.log(mode);
  }
}
</code>```

You need to import the ActivatedRoute, and inject it via the constructor. Then you can access what comes in on the query string via the injected service.

With a router link like this:

Go There!

The output from the console log is CRAZY.

Hope this helps.

Body:
I have a constant ROUTES that is set up like this:

export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]

I want to make it so that if the user goes to:

http://my-angular-app/#/custom/something?mode=CRAZY

That within "MyCustomComponent", I can see access the "mode=CRAZY" and do something with it.

How do I access the variable "mode" from my MyCustomComponent? Or do I have to define a new route to be able to pass the parameters?

Body:
This is what works for me to access the query parameters within a component.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent {

  constructor(private activatedRoute: ActivatedRoute) {
    let mode = activatedRoute.snapshot.queryParams['mode']; //< HERE
    console.log(mode);
  }
}

You need to import the ActivatedRoute, and inject it via the constructor. Then you can access what comes in on the query string via the injected service.

With a router link like this:

<a [routerLink]="['/custom']" [queryParams]="{mode: 'CRAZY'}">Go There!</a>

The output from the console log is CRAZY.

Hope this helps.


问:
Should I use returns in multiline Scala methods?
Perhaps this is just my background in more imperative programming, but I like having return statements in my code.

I understand that in Scala, returns are not necessary in many methods, because whatever the last computed value is is returned by default. I understand that this makes perfect sense for a "one-liner", e.g.

```<code>def square(x) = x * x
</code>```

I also understand the definitive case for using explicit returns (when you have several branches your code could take, and you want to break out of the method for different branches, e.g. if an error occurs). But what about multiline functions? Wouldn't it be more readable and make more sense if there was an explicit return, e.g.

```<code>def average(x: List[Int]) : Float = {
  var sum = 0
  x.foreach(sum += _)
  return sum / x.length.toFloat
}
</code>```

答:
I believe you should not use return, I think it somehow goes against the elegant concept that in Scala everything is an expression that evaluates to something.

Like your average method: it's just an expression that evaluates to Float, no need to return anything to make that work.

Body:
Perhaps this is just my background in more imperative programming, but I like having return statements in my code.

I understand that in Scala, returns are not necessary in many methods, because whatever the last computed value is is returned by default. I understand that this makes perfect sense for a "one-liner", e.g.

def square(x) = x * x

I also understand the definitive case for using explicit returns (when you have several branches your code could take, and you want to break out of the method for different branches, e.g. if an error occurs). But what about multiline functions? Wouldn't it be more readable and make more sense if there was an explicit return, e.g.

def average(x: List[Int]) : Float = {
  var sum = 0
  x.foreach(sum += _)
  return sum / x.length.toFloat
}


问:
Having a struct variable represent the label
I'm really new to c and was using a struct to return an array, I managed to generate the struct just fine and use the struct as well, but I made a really ugly way of importing my array into my struct. Is there some way that I can do this with a for loop?

Here's my code that I currently use to transfer the array into the struct:

```<code>result.a = input3[0];
result.b = input3[1];
result.c = input3[2];
result.d = input3[3];
result.e = input3[4];
result.f = input3[5];
result.g = input3[6];
result.h = input3[7];
result.i = input3[8];
</code>```

I tried to have it work like this:

```<code>for (char j = 'a'; j <= 'i'; j++)
{
    result.j = input[j - 97];
}
</code>```

But, as makes sense, the error I get is 'j': is not a member of values and it refuses to compile. What formatting would it take to make the program realize that I'm trying to refrence a variable, and not the index of the struct?
Thanks!

答:
In C, the names of members of structs are known to the compiler; they are used only while compiling. They are not part of the running program (except for debugging features and possible compiler-specific extensions to the language).

A primary purpose of arrays is to work with multiple elements in a programmatic way (that is, in a way that is computed when the program is running). Subscripts are for selecting members.

If you want to have multiple items in a struct that you can address programmatically, then you can define your struct to have an array in it, such as:

```<code>struct Foo;
{
    int MyArray[10];
}
…
struct Foo MyFoo;
</code>```

Then you can refer to items in the array inside MyFoo with MyFoo.MyArray[i]. You will have to use numbers for subscripts.

Body:
I'm really new to c and was using a struct to return an array, I managed to generate the struct just fine and use the struct as well, but I made a really ugly way of importing my array into my struct. Is there some way that I can do this with a for loop?

Here's my code that I currently use to transfer the array into the struct:

result.a = input3[0];
result.b = input3[1];
result.c = input3[2];
result.d = input3[3];
result.e = input3[4];
result.f = input3[5];
result.g = input3[6];
result.h = input3[7];
result.i = input3[8];

I tried to have it work like this:

for (char j = 'a'; j <= 'i'; j++)
{
    result.j = input[j - 97];
}

But, as makes sense, the error I get is 'j': is not a member of values and it refuses to compile. What formatting would it take to make the program realize that I'm trying to refrence a variable, and not the index of the struct?
Thanks!

Body:
In C, the names of members of structs are known to the compiler; they are used only while compiling. They are not part of the running program (except for debugging features and possible compiler-specific extensions to the language).

A primary purpose of arrays is to work with multiple elements in a programmatic way (that is, in a way that is computed when the program is running). Subscripts are for selecting members.

If you want to have multiple items in a struct that you can address programmatically, then you can define your struct to have an array in it, such as:

struct Foo;
{
    int MyArray[10];
}
…
struct Foo MyFoo;

Then you can refer to items in the array inside MyFoo with MyFoo.MyArray[i]. You will have to use numbers for subscripts.


答:
PHP itself doesn't store any information between requests so I don't think there is a way of determining which user you are up to without using another technology.

To save a number to each user you can store them as a session variable, then when the user returns you can check if they've already been given a number before. This might be a good place to start on sessions.

To give each new user a new number you'll most likely need to use a database to store all the previous values you've given to users, or simply store the index of the array that you are up to in your array in the database. The database will keep this information between different requests. I'm not sure of your level of expertise with PHP but databases are a slightly more advanced topic than session storage and may take some time to get up and running as you have to install them separately. The good news is that there are thousands of tutorials out there on them already.

Hope this helps.

Title: How to get arrays one at a time?

Body:
If someone access my page, I want to 'echo' the values inside my array one-by-one to them.

if first user access my page, php will get first array value and issue to it.

if second user access my page, php will get second array value and issue to it once again... and this process keeps so on!

User 1 > Number 1 | User 2 > Number 2 | User 3 > Number 1 | User 4 > Number 2.....

and for other I thing I want:

*** if possible, to get first value more than the second.

For example: Number 1 viewed 8 times, number 2 viewed 4.

My simple array code:

$numbers = array(
            '+1111111111', // Number 1
            '+2222222222', // Number 2
);

Any help or suggestion, thanks in advance!!!


问:
How to insert to database using silverlight Dataset
How can I enter dataset into the database using data
An example please</p>

答: You can't access a database directly from a Silverlight client.  There are several ways to accomplish this but you basically need to call a web service from Silverlight.  See the following article for a step by step example: https://technet.microsoft.com/en-us/library/cc197937(VS.95).aspx</p>


问:
O(n) algorithm for two identical points

The Problem Statement

Given n points in a 2D plane having x and y coordinate. Two points are identical if one can be obtained from the other by multiplication by the same number. Example: (10,15) and (2,3) are identical whereas (10,15) and (10,20) are not. Suggest an O(n) algorithm which determines whether the input n points contains two identical points or not.

The simple approach can be just checking for each points i.e. if there are 5 points, for the first one I have 4 comparisons, for the second one I have 3 comparisons and so on. But that isn't an O(n) time complexity solution. I really can't think ahead of that. Any suggestions?

答:
One obvious (but possibly inadequate) possibility would be to reduce each point to a floating point number representing the ratio, so (2,3) and (10,15) both become 0.66667, and (10, 20) become 0.5.

The reason this wouldn't work is that floating point numbers tend to be approximate, so you'd just about need to use an approximate comparison, and put up with the fact that it would show points as identical as long as they were equal to (say) 15 decimal places.

If you don't want that, you could create a rational number class that supported comparison (e.g., reduced each ratio to lowest terms).

Either way, once you've reduced a point to a single number, you just insert each into (for one possibility) a hash table. As you insert each you check whether that ratio is already in the hash table--if it is, you have an identical point. If not, insert it normally.

Title: O(n) algorithm for two identical points


问:
Math formula for first person 3d game
I want to make a first person 3d game but I can't set the camera formula right.

So I have a rotation: 0 to 359. Next the x,y coordinates, z remains the same.

Camera rotation : 0 - front, 90 - left, 180 - back, 270 - right but I can adapt it

What is the formula for the camera ?

Platform: Panda3d, python, opengl

Thank you

答:
OK, it looks like you need a Doom style camera movement, i.e., no up-down turns. Consider this:

You need to render the "world" as seen through the camera.

Assuming positive x is to the right and positive y is to your front, when the camera moves to the right the world's image moves to the left.

When the camera turns positively to the left, the world's image turns to the right.

Now, let's try to construct the equations:

1.First, translate the world coordinates to the camera's position:

```<code>Xwt = Xw - Xc;
Ywt = Yw - Yc;
Zwt = Zw;

(Xc,Yc,Zc) = camera position
(Xw,Yw,Zw) = world coordinates of object in the scene
(Xwt,Ywt,Zwt) = world coordinates of object translated to camera position
</code>```

2.Now, rotate the translated coordinates by an angle opposite to the camera's rotation:

```<code>Xwc =  Xwt * Cos(psi) + Ywt * Sin(psi);
Ywc = -Xwt * Sin(psi) + Ywt * Cos(psi);
Zwc =  Zwt

Psi = angle of camera rotation
(Xwc,Ywc,Zwc) = world coordinates of object transformed to camera orientation
</code>```

You can combine the two steps and transform it to a matrix form.

Title: Math formula for first person 3d game

Body:
OK, it looks like you need a Doom style camera movement, i.e., no up-down turns. Consider this:

You need to render the "world" as seen through the camera.

Assuming positive x is to the right and positive y is to your front, when the camera moves to the right the world's image moves to the left.

When the camera turns positively to the left, the world's image turns to the right.

Now, let's try to construct the equations:

1.First, translate the world coordinates to the camera's position:

Xwt = Xw - Xc;
Ywt = Yw - Yc;
Zwt = Zw;

(Xc,Yc,Zc) = camera position
(Xw,Yw,Zw) = world coordinates of object in the scene
(Xwt,Ywt,Zwt) = world coordinates of object translated to camera position

2.Now, rotate the translated coordinates by an angle opposite to the camera's rotation:

Xwc =  Xwt * Cos(psi) + Ywt * Sin(psi);
Ywc = -Xwt * Sin(psi) + Ywt * Cos(psi);
Zwc =  Zwt

Psi = angle of camera rotation
(Xwc,Ywc,Zwc) = world coordinates of object transformed to camera orientation

You can combine the two steps and transform it to a matrix form.


问:
PHP session isnot working
php session isnot working !!! Any idea why it is passing null value to the senond page ?? </p>

```<code>file1.php:
<?php
session_start();
$_SESSION['lat']=$_POST['lat'];
$_SESSION['lng']=$_POST['lng'];
session_write_close();
header('Location: http://sample.com/e_health/searchambulance.php');
?>

file2:
<?php
session_start();
$lat= $_SESSION['lat'];
$lng=$_SESSION['lng'];
echo $lat;
echo $lng;
?>
</code>```

答:
Change the code to this way. It will works......

file1.php:

```<code><?php
session_start();
$_SESSION['lat']=$_POST['lat'];
$_SESSION['lng']=$_POST['lng'];

header('Location: http://sample.com/e_health/searchambulance.php');
?>

file2:
<?php
session_start();
$lat= $_SESSION['lat'];
$lng=$_SESSION['lng'];
echo $lat;
echo $lng;
?>
</code>```

Title: PHP session isnot working

Body:
php session isnot working !!! Any idea why it is passing null value to the senond page ??

file1.php:
<?php
session_start();
$_SESSION['lat']=$_POST['lat'];
$_SESSION['lng']=$_POST['lng'];
session_write_close();
header('Location: http://sample.com/e_health/searchambulance.php');
?>

file2:
<?php
session_start();
$lat= $_SESSION['lat'];
$lng=$_SESSION['lng'];
echo $lat;
echo $lng;
?>

Body:
Change the code to this way. It will works......

file1.php:

<?php
session_start();
$_SESSION['lat']=$_POST['lat'];
$_SESSION['lng']=$_POST['lng'];

header('Location: http://sample.com/e_health/searchambulance.php');
?>

file2:
<?php
session_start();
$lat= $_SESSION['lat'];
$lng=$_SESSION['lng'];
echo $lat;
echo $lng;
?>