{"QuestionId": 34276484, "AnswerCount": 1, "Tags": "", "CreationDate": "2015-12-14T20:58:50.917", "AcceptedAnswerId": "34276942", "Title": "How to redirect URL while maintaining all GET parameters using express / Node.js", "Body": "

Using Express/Node.js I receive GET requests with an unknown number of parameters. The names of parameters are not always known in advance. I need to redirect these requests to a new URL while maintaining all existing GET parameters.

\n\n

ie. I might get any of these

\n\n
http://example.com/example\nhttp://example.com/example?id=xxx\nhttp://example.com/example?a=xxx&_b=xxx...\netc\n
\n\n

which in turn need to be redirected to:

\n\n
http://newexample.com/example\nhttp://otherdomain.org/sample?type=new&id=xxx\nhttp://newexample.com/sample?a=xxx&_b=xxx...\netc\n
\n\n

I've written this code to achieve this, but it feels like this would be common functionality that would already exist in the framework. Is there a better way?

\n\n
app.get('/example', function(req, res){\n    var oldParams = \"\"\n    var redirectUrl = config.exampleUrlNew;\n    if (req.originalUrl != null && req.originalUrl.indexOf('?') > 0) {\n      oldParams = req.originalUrl.split(\"?\")[1];\n    }\n    if (oldParams != \"\" && redirectUrl.indexOf('?') > 0) {\n      oldParams = \"&\" + oldParams;\n    } else {\n      oldParams = \"?\" + oldParams;\n    }\n    res.redirect(redirectUrl + oldParams)\n});\n
\n", "Lable": "No"} {"QuestionId": 34328467, "AnswerCount": 1, "Tags": "", "CreationDate": "2015-12-17T06:59:02.813", "AcceptedAnswerId": null, "Title": "How Can I use my GPU on Ipython Notebook?", "Body": "

OS : Ubuntu 14.04LTS
\nLanguage : Python Anaconda 2.7 (keras, theano)
\nGPU : GTX980Ti\nCUDA : CUDA 7.5

\n\n

I wanna run keras python code on IPython Notebook by using my GPU(GTX980Ti)\n
But I can't find it.

\n\n

I want to test below code. When I run it on to Ubuntu terminal,\nI command as below (It uses GPU well. It doesn't have any problem)

\n\n

First I set the path like below

\n\n
export PATH=/usr/local/cuda/bin:$PATH\nexport LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \n
\n\n

Second I run the code as below

\n\n
THEANO_FLAGS='floatX=float32,device=gpu0,nvcc.fastmath=True'  python myscript.py\n
\n\n


And it runs well.

\n\n

But when i run the code on pycharm(python IDE) or\nWhen I run it on Ipython Notebook, It doesn't use gpu.\nIt only uses CPU

\n\n

myscript.py code is as below.

\n\n
from theano import function, config, shared, sandbox\nimport theano.tensor as T\nimport numpy\nimport time\nvlen = 10 * 30 * 768  # 10 x #cores x # threads per core\niters = 1000\nrng = numpy.random.RandomState(22)\nx = shared(numpy.asarray(rng.rand(vlen), config.floatX))\nf = function([], T.exp(x))\nprint(f.maker.fgraph.toposort())\nt0 = time.time()\nfor i in xrange(iters):\n    r = f()\nt1 = time.time()\nprint(\"Looping %d times took %f seconds\" % (iters, t1 - t0))\nprint(\"Result is %s\" % (r,))\nif numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):\n    print('Used the cpu')\nelse:\n    print('Used the gpu')\n
\n\n

To solve it, I force the code use gpu as below\n(Insert two lines more on myscript.py)

\n\n
import theano.sandbox.cuda\ntheano.sandbox.cuda.use(\"gpu0\")\n
\n\n

Then It generate the error like below

\n\n
ERROR (theano.sandbox.cuda): nvcc compiler not found on $PATH. Check your nvcc installation and try again.\n
\n\n

how to do it??? I spent two days..
\nAnd I surely did the way of using '.theanorc' file at home directory.

\n", "Lable": "D"} {"QuestionId": 34362457, "AnswerCount": 2, "Tags": "", "CreationDate": "2015-12-18T19:13:57.120", "AcceptedAnswerId": "34476743", "Title": "Configuring webpack with bootstrap", "Body": "

I use webpack with bootstrap, but can't get bootstrap fonts in my application.

\n\n

Path /Users/and/devel/webpack_bootstrap/ is root folder of project.

\n\n

I get errors:

\n\n
jquery.js:9077 GET file:///Users/and/devel/webpack_bootstrap/448c34a56d699c29117adc64c43affeb.woff2 net::ERR_FILE_NOT_FOUND\nGET file:///Users/and/devel/webpack_bootstrap/fa2772327f55d8198301fdb8bcfc8158.woff net::ERR_FILE_NOT_FOUND\nGET file:///Users/and/devel/webpack_bootstrap/e18bbf611f2a2e43afc071aa2f4e1512.ttf net::ERR_FILE_NOT_FOUND\n
\n\n

Files

\n\n

448c34a56d699c29117adc64c43affeb.woff2, fa2772327f55d8198301fdb8bcfc8158.woff, e18bbf611f2a2e43afc071aa2f4e1512.ttf

\n\n

are generated into /Users/and/devel/webpack_bootstrap/dist folder after compilation

\n\n

I tried bootstrap-webpack, but still get the same errors.

\n\n

package.json

\n\n
{\n  \"name\": \"Webpack_bootstrap\",\n  \"version\": \"1.0.0\",\n  \"description\": \"webpack bootstrap test\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"npm run serve | npm run dev\",\n    \"serve\": \"./node_modules/.bin/http-server -p 8080\",\n    \"dev\": \"webpack-dev-server -d --progress --colors --port 8090\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"bootstrap\": \"^3.3.6\",\n    \"bootstrap-select\": \"^1.9.3\",\n    \"bootstrap-table\": \"^1.9.1\",\n    \"bootstrap-webpack\": \"0.0.5\",\n    \"bower-webpack-plugin\": \"^0.1.9\",\n    \"css-loader\": \"^0.23.0\",\n    \"eonasdan-bootstrap-datetimepicker\": \"^4.15.35\",\n    \"events\": \"^1.1.0\",\n    \"exports-loader\": \"^0.6.2\",\n    \"extract-text-webpack-plugin\": \"^0.9.1\",\n    \"file-loader\": \"^0.8.5\",\n    \"http-server\": \"^0.8.5\",\n    \"jquery\": \"^2.1.4\",\n    \"jquery-resizable-columns\": \"^0.2.3\",\n    \"jquery-slimscroll\": \"^1.3.6\",\n    \"jquery-ui\": \"^1.10.5\",\n    \"less\": \"^2.5.3\",\n    \"less-loader\": \"^2.2.2\",\n    \"lodash\": \"^3.10.1\",\n    \"moment\": \"^2.10.6\",\n    \"node-sass\": \"^3.4.2\",\n    \"object-assign\": \"^4.0.1\",\n    \"path\": \"^0.12.7\",\n    \"sass-loader\": \"^3.1.2\",\n    \"select2\": \"^4.0.1\",\n    \"select2-bootstrap-css\": \"^1.4.6\",\n    \"style-loader\": \"^0.13.0\",\n    \"svg-sprite-loader\": \"0.0.15\",\n    \"typeahead.js\": \"^0.11.1\",\n    \"url-loader\": \"^0.5.7\",\n    \"webpack\": \"^1.12.9\",\n    \"webpack-dev-server\": \"^1.14.0\"\n  }\n}\n
\n\n

webpack.config.js

\n\n
var CommonsChunkPlugin = require(\"webpack/lib/optimize/CommonsChunkPlugin\");\nvar BowerWebpackPlugin = require(\"bower-webpack-plugin\");\nvar path = require('path');\n\nmodule.exports = {\n    cache: true,\n    entry: {\n      index: './src/script/index.js'\n    },\n    output: {\n        path: path.join(__dirname, './dist'),\n        filename: '[name].js',\n        sourceMapFilename: \"[file].map\"\n    },\n    debug: true,\n    devtool: 'source-map',\n    module: {\n      loaders: [\n      // **IMPORTANT** This is needed so that each bootstrap js file required by\n      // bootstrap-webpack has access to the jQuery object\n      { test: /bootstrap\\/js\\//, loader: 'imports?jQuery=jquery' },\n\n      // Needed for the css-loader when [bootstrap-webpack](https://github.com/bline/bootstrap-webpack)\n      // loads bootstrap's css.\n      {\n        test: /\\.scss$/,\n        loaders: [ 'style', 'css', 'sass' ]\n      },\n      {\n        test: /\\.less$/,\n        loaders: [ 'style', 'css', 'less' ]\n      },\n      {\n        test: /\\.css$/,\n        loaders: [ 'style', 'css']\n      },\n      {test: /\\.(woff|woff2)(\\?v=\\d+\\.\\d+\\.\\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'},\n      {test: /\\.ttf(\\?v=\\d+\\.\\d+\\.\\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},\n      {test: /\\.eot(\\?v=\\d+\\.\\d+\\.\\d+)?$/, loader: 'file'},\n      {test: /\\.svg(\\?v=\\d+\\.\\d+\\.\\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}\n    ]\n    },\n    plugins: [\n        new BowerWebpackPlugin(),\n        new CommonsChunkPlugin('index', 'index.js', Infinity)\n    ],\n    resolve: {\n        extensions: ['', '.js', '.jsx']\n    }\n};\n
\n\n

index.html

\n\n
<!DOCTYPE html>\n<html>\n<head>\n    <title>Won</title>\n</head>\n<body>\n\n    <script type=\"text/javascript\" src=\"./dist/index.js\"></script>\n\n    <div id=\"content\">\n\n      <!-- Button trigger modal -->\n      <button type=\"button\" class=\"btn btn-primary btn-lg\" data-toggle=\"modal\" data-target=\"#myModal\">\n        Launch demo modal\n      </button>\n\n      <!-- Modal -->\n      <div class=\"modal fade\" id=\"myModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\">\n        <div class=\"modal-dialog\" role=\"document\">\n          <div class=\"modal-content\">\n            <div class=\"modal-header\">\n              <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n              <h4 class=\"modal-title\" id=\"myModalLabel\">Modal title</h4>\n            </div>\n            <div class=\"modal-body\">\n              <button type=\"button\" class=\"btn btn-default btn-lg\">\n                <span class=\"glyphicon glyphicon-star\" aria-hidden=\"true\"></span> Star\n              </button>\n            </div>\n            <div class=\"modal-footer\">\n              <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n              <button type=\"button\" class=\"btn btn-primary\">Save changes</button>\n            </div>\n          </div>\n        </div>\n      </div>\n\n</body>\n</html>\n
\n\n

src -> script -> index.js

\n\n
var bootstrap = require('bootstrap-webpack');\n
\n\n

Edit: I use this webpack config and everything works.

\n", "Lable": "No"} {"QuestionId": 34389010, "AnswerCount": 2, "Tags": "", "CreationDate": "2015-12-21T04:35:04.020", "AcceptedAnswerId": null, "Title": "Changing dataset data for datagrid", "Body": "

I'm trying to update an attribute inside a dataset, which is then displayed in a datagrid. However, when I attempt to assign the date to my row.ItemArray[0] it doesn't appear to be updating. Not in debug nor in the datagrid.

\n\n
DataSet ds = new DataSet();\nconnection.Open();\nadapter.Fill(ds);\n\nforeach (DataTable table in ds.Tables)\n{\n    foreach (DataRow row in table.Rows)\n    {\n        string date = row.ItemArray[0].ToString();\n        date = date.Remove(date.Length - 12);\n        row.ItemArray[0] = date;\n\n        foreach (object item in row.ItemArray)\n        {\n            // read item\n            //Console.WriteLine(item.ToString());\n        }\n    }\n}\nds.AcceptChanges();\ninvoicesDataGrid.AutoGenerateColumns = true;\ninvoicesDataGrid.ItemsSource = ds.Tables[0].DefaultView;\n
\n", "Lable": "No"} {"QuestionId": 34448306, "AnswerCount": 2, "Tags": "", "CreationDate": "2015-12-24T06:27:49.213", "AcceptedAnswerId": null, "Title": "Issue while iterating a json response", "Body": "

From the Ajax call I am getting the following JSON response.

\n\n
    studentList:\n{\n\"currentStudent\":0,\n\"totalStudent\":11,\n\"studentDetails\": \n    [{\n     \"adId\":1,\n     \"adName\":\"BMB X5\",\n     \"sfImage\":{\n            \"imageName\":\"Desert\",\n            \"imagePath\":\"/images/updatedUI/companylogo.png\",\n            \"ext\":null\n           }\n    }]}\n
\n\n

Now I wanted to print the studentName and Phone number in the console.log()\nI have iterated the loop and able to print the studentName in the console, To print the Phone number I tried the Nested loop still facing some issues with printing the Phone number in the console.

\n\n

My code is:

\n\n
var data = studentList.studentDetails;\nfor (var key in data) {         \n    console.log(data[key].studentName); // Here Student Name is printing            \n   }\n
\n\n

How can I iterate inside the loop and print the phone number in the console?

\n", "Lable": "No"} {"QuestionId": 34454901, "AnswerCount": 1, "Tags": "", "CreationDate": "2015-12-24T15:28:22.223", "AcceptedAnswerId": "34458812", "Title": "Transfer parameters from training to inference graph", "Body": "\n\n

To not to carry optimizer and gradient nodes into inference environment, I'm trying to create two versions of graph - one with training nodes and the other one without.

\n\n

And idea was to use tensorflow.train.Saver to pass variables from train graph version into inference graph version.

\n\n

So I've tried the following:

\n\n
# Create training graph\ntrainingGraph = tf.Graph()\nwith (trainingGraph.as_default()):\n  trainOp, lossOp = self.CreateTrainingGraph()\n  trainInitOp = tf.initialize_variables(tf.all_variables(), \"init_variables\")\n\n  # Add saver op\n  self.saverOp = tf.train.Saver()\n\n# Create inference graph\ninferenceGraph = tf.Graph()\nwith (inferenceGraph.as_default()):\n  self.CreateInferenceGraph()\n\n  # Add saver op, compatible with training saver\n  tf.train.Saver(saver_def=self.saverOp.as_saver_def())\n
\n\n

In this case CreateTrainingGraph() calls CreateInferenceGraph() and adds optimizer and loss on top of it.

\n\n

For some reason, tf.train.Saver constructor doesn't add save/restore_all node into the inference graph (or I just don't understand what saver_def option does). I've tried empty constructor and

\n\n
sess.run([model.saverOp._restore_op_name],\n         { model.saverOp._filename_tensor_name : \"Params/data.pb\" })\n
\n\n

failed with error

\n\n
<built-in function delete_Status> returned a result with an error set\n
\n\n

What is the proper way to achieve this?

\n", "Lable": "D"} {"QuestionId": 34464220, "AnswerCount": 2, "Tags": "", "CreationDate": "2015-12-25T15:49:46.723", "AcceptedAnswerId": null, "Title": "BASH - loop through argument", "Body": "

I have been trying many different ways to loop through the arguments, using different ways with for and while loops, yet it doesn't work. My script should take arguments and answer if they are files, directoies etc.

\n\n
while $1 in \"$@\" ;do\n\nif [ -f $1 ];then\n        echo \"$1        regular file\"\n\nelif [ -d $1 ];then\n        echo \"$1        directory\"\n\nelif [ -f $1 ];then\n        echo \"$1        excuteable file\"\n\nelif [ -h $1 ];then\n        echo \"$1        symbolic\"\n\nelse\n        echo \"$1        Does not exist\"\nfi\n\n1=$(( $1 + 1 ))\n\ndone\n
\n\n

How do I loop though each arguments?

\n", "Lable": "No"} {"QuestionId": 34488236, "AnswerCount": 1, "Tags": "", "CreationDate": "2015-12-28T05:42:03.830", "AcceptedAnswerId": null, "Title": "Apache mod_proxy_load balancer giving internal 500 error", "Body": "

I was trying to load balance the requests coming uri /v1.0/api to my backend instances using Apache mod_proxy_load balancer:

\n\n

I tried with following configuration:

\n\n
    <Proxy *>\n    Require all granted\n    </Proxy>\n\n    ProxyPass /v1.0/api/ !\n    ProxyPass / balancer://mycluster/ stickysession=BALANCEID nofailover=On\n    ProxyPassReverse / https://10.23.45.66:8081/v1.0/api/\n    ProxyPassReverse / https://10.23.45.67:8081/v1.0/api/\n    <Proxy balancer://mycluster>\n      BalancerMember https://10.23.45.66:8081/v1.0/api/ route=http1\n      BalancerMember https://10.23.45.67:8081/v1.0/api/ route=http2\n    </Proxy>\n\n    <Location /v1.0/api/>\n      SetHandler /v1.0/api/\n      Require all granted\n    </Location>\n
\n\n

Kindly help me in fixing this problem.

\n\n

Thanks,\nPradeep

\n", "Lable": "No"} {"QuestionId": 34495297, "AnswerCount": 3, "Tags": "", "CreationDate": "2015-12-28T14:23:58.453", "AcceptedAnswerId": "34495962", "Title": "CORS problems with Auth0 and React", "Body": "

I am currently trying implement Auth0 in my NodeJS + React App.\nThis tutorial given is really good and helpful, though I have one big problem.\nEvery time I try to login/register via Auth0 I get

\n\n
\n

XMLHttpRequest cannot load\n https://XYZ.eu.auth0.com/usernamepassword/login. Response to preflight\n request doesn't pass access control check: No\n 'Access-Control-Allow-Origin' header is present on the requested\n resource. Origin 'http://localhost:3000' is therefore not allowed\n access. Response to preflight request doesn't pass access control\n check: No 'Access-Control-Allow-Origin' header is present on the\n requested resource. Origin 'http://localhost:3000' is therefore not\n allowed access.

\n
\n\n

So I have a rough understanding what that means. But I just don't know where to set the needed options to allow this request to Auth0. On the Server side? In the Browser code?

\n\n

Best regards

\n\n
\n\n

EDIT:\nas Rodrigo L\u00f3pez Dato pointed out, I can write Origins in my app here: https://manage.auth0.com/#/applications

\n\n

What should I put there when I am developing locally? My IP?

\n", "Lable": "No"} {"QuestionId": 34496032, "AnswerCount": 1, "Tags": "", "CreationDate": "2015-12-28T15:14:08.460", "AcceptedAnswerId": "34496314", "Title": "Adding one layout on top of another programatically", "Body": "

I've got a button that when tapped, creates a RelativeLayout with simple Views like text in it. They're all to be contained in a vertical linear layout.

\n\n

When tapping in succession, multiple relative layouts get created, with the latest layout created stacked below the previous one. I would, however, like to reverse this order - the latest layout gets stacked ABOVE the previous one.

\n\n

Relative layouts don't have attributes like layout_below etc, however. The only messy way I can do this is with a grid layout, with the latest ones having a row number less than the previous one. Again, this is messy and consumes unnecessarily memory by preloading a bunch of invisible rows.

\n\n

Does anyone have an elegant way of doing this? I would be extremely grateful!

\n", "Lable": "No"} {"QuestionId": 34553457, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-01T04:10:15.573", "AcceptedAnswerId": null, "Title": "Error in populating line chart on google graph using their api", "Body": "

Below is my code to chart the graph through google graph api:

\n\n
var data = new google.visualization.DataTable();\n          var newData =[];\n         for(var j = 0; j<dates.length;j++){\n                newData.push([dates[j],close[j]]);\n                document.write(newData[j] + \"<br>\");\n              }\n var numRows = newData.length;\n              var numCols = newData[0].length;\n              data.addColumn('number', \"X\");\n              data.addColumn('number', \"Y\");\n\nfor (var j = 0; j < numRows; j++){\n              data.addRow(newData[j]);\n          }\n
\n\n

The line document.write(newData[j] + \"<br>\"); in the code above prints out values below:

\n\n
20151229,108.74\n20151228,106.82\n20151224,108.03\n20151223,108.61\n20151222,107.23\n
\n\n

From that I guess that, my values are in newData are properly stored but when I tried adding to data.addRow it just couldn't work. What's wrong ?

\n", "Lable": "No"} {"QuestionId": 34572990, "AnswerCount": 0, "Tags": "", "CreationDate": "2016-01-03T03:19:56.130", "AcceptedAnswerId": null, "Title": "How to Avoid Self Referrals in Universal Analytics?", "Body": "

I'm getting a lot of referral traffic listed with my own domain name in my Google Analytics tracking reports. I'm running the same Universal Analytics tracking code on multiple subdomains for the same domain.

\n\n

The tracking code (with placeholders for the Analytics account and domain name) is like this (for all the subdomains, including the www one):

\n\n
<script type=\"text/javascript\">\n          (function (i, s, o, g, r, a, m) {\n              i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {\n                  (i[r].q = i[r].q || []).push(arguments)\n              }, i[r].l = 1 * new Date(); a = s.createElement(o),\n              m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)\n          })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');\n\n          ga('create', 'UA-1111111-1', {\n              cookieDomain: 'domain.com',\n              legacyCookieDomain: 'domain.com'\n          });\n          ga('send', 'pageview');\n    </script>\n
\n\n

The traffic is getting listed in the report as:\ndomain.com / referral

\n\n

Am I doing something wrong that would result in the referral tracking I'm receiving?

\n", "Lable": "No"} {"QuestionId": 34575046, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-03T09:27:13.623", "AcceptedAnswerId": "34576796", "Title": "Get the value of tensor in theano", "Body": "

In my program, I want to use the shape value of a tensor. For example, the tensor x has shape of (3,4,5). I want to get the value of 4, i tried the way below:

\n\n
t=x.shape[1] #returns a scalar\nt=x.shape[1].eval() #returns a array(4)\n
\n\n

how can i get a value of 4, what i want is a type of int, not scalar or other types.

\n", "Lable": "D"} {"QuestionId": 34582669, "AnswerCount": 0, "Tags": "", "CreationDate": "2016-01-03T23:06:02.580", "AcceptedAnswerId": null, "Title": "How to generate the predicted label in caffe from the output of the last layer?", "Body": "

I have trained my own dataset of images (traffic light images 11x27) with LeNet, using caffe and DIGITS interface. I get 99% accuracy and when I give new images via DIGITS, it predicts the good label, so the network seems to work very well.

\n\n

However, I struggle to predict the labels through Python/Matlab API for caffe. The last layer output (ip2) is a vector with 2 elements (I have 2 classes), which looks like [4.8060, -5.2608] for example (the first component is always positive, the second always negative and the absolute values range from 4 to 20). I know it from many tests in Python, Matlab and DIGITS.

\n\n

My problem is :

\n\n
    \n
  • Argmax can't work directly on this layer (it always gives 0)
  • \n
  • If I use a softmax function, it will always give me [1, 0] (and that's actually the value of net.blobs['prob'] or out['prob'] in the python interface, no matter the class of my image)
  • \n
\n\n

So, how can I get the good label predicted ?

\n\n

Thanks!

\n", "Lable": "D"} {"QuestionId": 34679139, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-08T14:15:11.657", "AcceptedAnswerId": "34748184", "Title": "How to change date and time in MongoDB?", "Body": "

I have the DB with names and dates. I need to change the old date with the date that is +3 days after that. For example oldaDate is 01.02.2015 the new one is 03.02.2015.\nI was trying just to put another date for all files, but that mean that all exams are going to be in one day.

\n\n

$ db.getCollection('school.exam').update( {}, { $set : { \"oldDay\" : new ISODate(\"2016-01-11T03:34:54Z\") } }, true, true);

\n\n

The problem is just to replace old date with some random days.

\n", "Lable": "No"} {"QuestionId": 34704461, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-10T10:42:01.630", "AcceptedAnswerId": "34705071", "Title": "Optimize nested for loops in Matlab using Vectorization", "Body": "

I am a newbie to Matlab and I am currently trying to optimize a nested for loop as below. The loop is currently running forever for my input.

\n\n
for i = 1:size(mat,1)\n    for j = 1:size(mat,2)\n          mat(i,j) = some_mapping(mat(i,j)+1);\n    end\nend\n
\n\n

However I can't find a way to vectorize it. I have tried bsxfun and arrayfun but it does not seem to work (or even run more slowly than the loop).

\n\n

Maybe I was doing it in a wrong way. Any help is appreciated!

\n", "Lable": "No"} {"QuestionId": 34758978, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-13T05:24:30.540", "AcceptedAnswerId": "34761247", "Title": "Is there any way to cache the theano compiling result?", "Body": "

I ask this question because the compiling process of theano is quite time consuming, and what making it worse is that each time I run the code, the function will be recompiled. So, is there any way to make theano cache the previous compiling result if there is no code change?

\n", "Lable": "D"} {"QuestionId": 34849532, "AnswerCount": 0, "Tags": "", "CreationDate": "2016-01-18T07:44:41.437", "AcceptedAnswerId": null, "Title": "JNDI lookup issue in WildFly - 9.0.2 Final for accessing JMS hornetq via spring JMS listener with connection factory", "Body": "

I am configuring JNDI look parameters for getting connection factory to consume messages using Spring JMS listener from web application.

\n\n

It is throwing below error,

\n\n
\"No connection Provider avilable for http-remoting\"\n
\n\n

And we are using below parameters,

\n\n
jms.jndiTemplate.provider.url=http-remoting://localhost:8080\njms.jndiTemplate.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory\njms.connectionFactory.jndiName=jms/RemoteConnectionFactory\n
\n\n

But it is working fine for standalone client with above parameter and is throwing error when deployed using web application on the same server.

\n\n

Even I tried with JNP client,

\n\n
jms.jndiTemplate.provider.url=hostname:1099\njms.jndiTemplate.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\n
\n\n

And I end up with server port issues as mentioned below,

\n\n
ERROR [org.jboss.as.controller.client] (Controller Boot Thread) WFLYCTL0190: Step handler org.jboss.as.controller.AbstractAddStepHandler$1@30a0f455 for operation {\"address\" => [(\"socket-binding-group\" => \"standard-sockets\"),(\"socket-binding\" => \"iiop\")],\"operation\" => \"add\",\"interface\" => \"unsecure\",\"port\" => 3528,\"fixed-port\" => undefined,\"multicast-address\" => undefined,\"multicast-port\" => undefined,\"client-mappings\" => undefined} at address [\n    (\"socket-binding-group\" => \"standard-sockets\"),\n    (\"socket-binding\" => \"iiop\")\n] failed handling operation rollback -- java.util.concurrent.TimeoutException\n
\n\n

Could you please provide the information If I miss anything.

\n", "Lable": "No"} {"QuestionId": 34866678, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-19T00:41:59.387", "AcceptedAnswerId": "34866766", "Title": "Modify a shell variable inside awk block of code", "Body": "

Is there any way to modify a shell variable inside awk block of code?

\n\n
--------- [shell_awk.sh]---------------------\n #!/bin/bash\n\nshell_variable_1=<value A>\nshell_variable_2=<value B>\nshell_variable_3=<value C>\n\nawk 'function A(X)\n{ return X+1 }\n{ a=A('$shell_variable_1')\n  b=A('$shell_variable_2')\n  c=A('$shell_variable_3')\n  shell_variable_1=a\n  shell_variable_2=b\n  shell_variable_3=c\n}' FILE.TXT\n--------- [shell_awk.sh]---------------------\n
\n\n

This is a very simple example, the real script load a file and make some changes using functions, I need to keep each value before change into a specific variable, so then I can register into MySQL the before and after value.

\n\n

The after value is received from parameters ($1, $2 and so on).

\n\n

The value before I already know how to get it from the file.

\n\n

All is done well, except the shell_variable been set by awk variable. Outside from awk block code is easy to set, but inside, is it possible?

\n", "Lable": "No"} {"QuestionId": 34890925, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-20T03:14:46.750", "AcceptedAnswerId": "34960747", "Title": "How to map one matrix value to another in theano function", "Body": "

I want to implement the following function in theano function,

\n\n
a=numpy.array([ [b_row[dictx[idx]] if idx in dictx else 0 for idx in range(len(b_row))]\n               for b_row in b])\nwhere a, b are narray, and dictx is a dictionary\n
\n\n

I got the error TensorType does not support iteration\nDo I have to use scan? or is there any simpler way?\nThanks!

\n", "Lable": "D"} {"QuestionId": 34918851, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-21T08:35:48.597", "AcceptedAnswerId": null, "Title": "TensorFlow installation results in ImportError: No module named tensorflow", "Body": "

I'm trying to get TensorFlow to work on my Mac (OSX El Capitan 10.11.2). I tried the pip install from the setup guide and also followed the instructions in the accepted answer here.

\n\n

In both cases I am able to successfully activate the virtualenv and my prompt changes to tensorflow. Python works fine, I'm able to do simple computations on the command line. But when I try to import tensorflow:

\n\n
import tensorflow as tf\n
\n\n

I repeatedly get this error:

\n\n
ImportError: No module named tensorflow\n
\n\n

Any help would be appreciated.

\n", "Lable": "D"} {"QuestionId": 34929254, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-21T16:34:33.470", "AcceptedAnswerId": null, "Title": "Tensorflow implementation of loss of Q-network with slicing", "Body": "

I'm implementing a Q-network as described in Human-level control through deep reinforcement learning (Mnih et al. 2015) in TensorFlow.

\n\n

To approximate the Q-function they use a neural network. The Q-function maps a state and an action to a scalar value, known as the Q-value. I.e. it's a function like Q(s,a) = qvalue.

\n\n

But instead of taking both state and action as input, they only take the state as input and output a vector with one element per legal action in a given order. Thus Q(s,a) becomes Q'(s) = array([val_a1, val_a2, val_a3,...]), where val_a1 is Q(s,a1).

\n\n

This raises the question of how to modify the loss function. The loss function is a L2 loss function computed on the difference of a target (y) and Q(s,a).

\n\n

My idea is to create a new TF operation and use a binary mask indicating which action I want to train on and multiply it with the output of the network. Effectively producing a vector like [0, 0, val_a3, 0, ...] if the action in question is a3.

\n\n

And then feed the result of the new operation to the loss operation, which TF is then minimizing.

\n\n

Questions:

\n\n
    \n
  1. Is this a sound idea? Or is there a better way of solving this?

  2. \n
  3. How can this be solved with TensorFlow?

    \n\n

    There is a SO thread on something similar (Adjust Single Value within Tensor -- TensorFlow), but I would like to choose the column value with the help of a tf.placeholder that I can feed to the network at runtime. It doesn't seem to work when just replacing the static lists in that examples with placeholders.

  4. \n
\n", "Lable": "D"} {"QuestionId": 34970818, "AnswerCount": 1, "Tags": "", "CreationDate": "2016-01-24T00:34:50.717", "AcceptedAnswerId": "45060104", "Title": "Training, testing, and validation sets for bidirectional LSTM (BLSTM)", "Body": "

When it comes to normal ANNs, or any of the standard machine learning techniques, I understand what the training, testing, and validation sets should be (both conceptually, and the rule-of-thumb ratios). However, for a bidirectional LSTM (BLSTM) net, how to split the data is confusing me.

\n\n

I am trying to improve prediction on individual subject data that consists of monitored health values. In the simplest case, for each subject, there is one long time series of values (>20k values), and contiguous parts of that time series are labeled from a set of categories, depending on the current health of the subject. For a BLSTM, the net is trained on all of the data going forwards and backwards simultaneously. The problem then is, how does one split a time series for one subject?

\n\n
    \n
  • I can't just take the last 2,000 values (for example), because they might all fall into a single category.
  • \n
  • And I can't chop the time series up randomly, because then both the learning and testing phases would be made of disjointed chunks.
  • \n
\n\n

Finally, each of the subjects (as far as I can tell) has slightly different (but similar) characteristics. So, maybe, since I have thousands of subjects, do I train on some, test on some, and validate on others? However, since there are inter-subject differences, how would I set up the tests if I was only considering one subject to start?

\n", "Lable": "D"} {"QuestionId": 34982492, "AnswerCount": 5, "Tags": "", "CreationDate": "2016-01-24T22:45:31.080", "AcceptedAnswerId": "35004257", "Title": "Restoring TensorFlow model", "Body": "

I'm trying to restore TensorFlow model. I followed this example:\nhttp://nasdag.github.io/blog/2016/01/19/classifying-bees-with-google-tensorflow/

\n\n

At the end of the code in the example I added these lines:

\n\n
saver = tf.train.Saver()\nsave_path = saver.save(sess, \"model.ckpt\")\nprint(\"Model saved in file: %s\" % save_path)\n
\n\n

Two files were created: checkpoint and model.ckpt.

\n\n

In a new python file (tomas_bees_predict.py), I have this code:

\n\n
import tensorflow as tf\n\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n  # Restore variables from disk.\n  saver.restore(sess, \"model.ckpt\")\n  print(\"Model restored.\")\n
\n\n

However when I execute the code, I get this error:

\n\n
Traceback (most recent call last):\n  File \"tomas_bees_predict.py\", line 3, in <module>\n    saver = tf.train.Saver()\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py\", line 705, in __init__\nraise ValueError(\"No variables to save\")\n
\n\n

ValueError: No variables to save

\n\n

Is there a way to read mode.ckpt file and see what variables are saved?\nOr maybe someone can help with saving the model and restoring it based on the example described above?

\n\n

EDIT 1:

\n\n

I think I tried running the same code in order to recreate model structure and I was getting the error. I think it could be related to the fact that code described here isn't using named variables:\nhttp://nasdag.github.io/blog/2016/01/19/classifying-bees-with-google-tensorflow/

\n\n
def weight_variable(shape):\n  initial = tf.truncated_normal(shape, stddev=0.1)\n  return tf.Variable(initial)\n\ndef bias_variable(shape):\n  initial = tf.constant(0.1, shape=shape)\n  return tf.Variable(initial)\n
\n\n

So I did this experiment. I wrote two versions of the code (with and without named variables) to save the model and the code to restore the model.

\n\n

tensor_save_named_vars.py:

\n\n
import tensorflow as tf\n\n# Create some variables.\nv1 = tf.Variable(1, name=\"v1\")\nv2 = tf.Variable(2, name=\"v2\")\n\n# Add an op to initialize the variables.\ninit_op = tf.initialize_all_variables()\n\n# Add ops to save and restore all the variables.\nsaver = tf.train.Saver()\n\n# Later, launch the model, initialize the variables, do some work, save the\n# variables to disk.\nwith tf.Session() as sess:\n  sess.run(init_op)\n  print \"v1 = \", v1.eval()\n  print \"v2 = \", v2.eval()\n  # Save the variables to disk.\n  save_path = saver.save(sess, \"/tmp/model.ckpt\")\n  print \"Model saved in file: \", save_path\n
\n\n

tensor_save_not_named_vars.py:

\n\n
import tensorflow as tf\n\n# Create some variables.\nv1 = tf.Variable(1)\nv2 = tf.Variable(2)\n\n# Add an op to initialize the variables.\ninit_op = tf.initialize_all_variables()\n\n# Add ops to save and restore all the variables.\nsaver = tf.train.Saver()\n\n# Later, launch the model, initialize the variables, do some work, save the\n# variables to disk.\nwith tf.Session() as sess:\n  sess.run(init_op)\n  print \"v1 = \", v1.eval()\n  print \"v2 = \", v2.eval()\n  # Save the variables to disk.\n  save_path = saver.save(sess, \"/tmp/model.ckpt\")\n  print \"Model saved in file: \", save_path\n
\n\n

tensor_restore.py:

\n\n
import tensorflow as tf\n\n# Create some variables.\nv1 = tf.Variable(0, name=\"v1\")\nv2 = tf.Variable(0, name=\"v2\")\n\n# Add ops to save and restore all the variables.\nsaver = tf.train.Saver()\n\n# Later, launch the model, use the saver to restore variables from disk, and\n# do some work with the model.\nwith tf.Session() as sess:\n  # Restore variables from disk.\n  saver.restore(sess, \"/tmp/model.ckpt\")\n  print \"Model restored.\"\n  print \"v1 = \", v1.eval()\n  print \"v2 = \", v2.eval()\n
\n\n

Here is what I get when I execute this code:

\n\n
$ python tensor_save_named_vars.py \n\nI tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4\nI tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4\nv1 =  1\nv2 =  2\nModel saved in file:  /tmp/model.ckpt\n\n$ python tensor_restore.py \n\nI tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4\nI tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4\nModel restored.\nv1 =  1\nv2 =  2\n\n$ python tensor_save_not_named_vars.py \n\nI tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4\nI tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4\nv1 =  1\nv2 =  2\nModel saved in file:  /tmp/model.ckpt\n\n$ python tensor_restore.py \nI tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4\nI tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4\nW tensorflow/core/common_runtime/executor.cc:1076] 0x7ff953881e40 Compute status: Not found: Tensor name \"v2\" not found in checkpoint files /tmp/model.ckpt\n     [[Node: save/restore_slice_1 = RestoreSlice[dt=DT_INT32, preferred_shard=-1, _device=\"/job:localhost/replica:0/task:0/cpu:0\"](_recv_save/Const_0, save/restore_slice_1/tensor_name, save/restore_slice_1/shape_and_slice)]]\nW tensorflow/core/common_runtime/executor.cc:1076] 0x7ff953881e40 Compute status: Not found: Tensor name \"v1\" not found in checkpoint files /tmp/model.ckpt\n     [[Node: save/restore_slice = RestoreSlice[dt=DT_INT32, preferred_shard=-1, _device=\"/job:localhost/replica:0/task:0/cpu:0\"](_recv_save/Const_0, save/restore_slice/tensor_name, save/restore_slice/shape_and_slice)]]\nTraceback (most recent call last):\n  File \"tensor_restore.py\", line 14, in <module>\n    saver.restore(sess, \"/tmp/model.ckpt\")\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py\", line 891, in restore\n    sess.run([self._restore_op_name], {self._filename_tensor_name: save_path})\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py\", line 368, in run\n    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py\", line 444, in _do_run\n    e.code)\ntensorflow.python.framework.errors.NotFoundError: Tensor name \"v2\" not found in checkpoint files /tmp/model.ckpt\n     [[Node: save/restore_slice_1 = RestoreSlice[dt=DT_INT32, preferred_shard=-1, _device=\"/job:localhost/replica:0/task:0/cpu:0\"](_recv_save/Const_0, save/restore_slice_1/tensor_name, save/restore_slice_1/shape_and_slice)]]\nCaused by op u'save/restore_slice_1', defined at:\n  File \"tensor_restore.py\", line 8, in <module>\n    saver = tf.train.Saver()\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py\", line 713, in __init__\n    restore_sequentially=restore_sequentially)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py\", line 432, in build\n    filename_tensor, vars_to_save, restore_sequentially, reshape)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py\", line 191, in _AddRestoreOps\n    values = self.restore_op(filename_tensor, vs, preferred_shard)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py\", line 106, in restore_op\n    preferred_shard=preferred_shard)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/io_ops.py\", line 189, in _restore_slice\n    preferred_shard, name=name)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_io_ops.py\", line 271, in _restore_slice\n    preferred_shard=preferred_shard, name=name)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py\", line 664, in apply_op\n    op_def=op_def)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py\", line 1834, in create_op\n    original_op=self._default_original_op, op_def=op_def)\n  File \"/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py\", line 1043, in __init__\n    self._traceback = _extract_stack()\n
\n\n

So perhaps the original code (see the external link above) could be modified to something like this:

\n\n
def weight_variable(shape):\n  initial = tf.truncated_normal(shape, stddev=0.1)\n  weight_var = tf.Variable(initial, name=\"weight_var\")\n  return weight_var\n\ndef bias_variable(shape):\n  initial = tf.constant(0.1, shape=shape)\n  bias_var = tf.Variable(initial, name=\"bias_var\")\n  return bias_var\n
\n\n

But then the question I have: is restoring weight_var and bias_var variables sufficient to implement the prediction? I did the training on the powerful machine with GPU and I would like to copy the model to the less powerful computer without GPU to run predictions.

\n", "Lable": "D"} {"QuestionId": 34998888, "AnswerCount": 2, "Tags": "", "CreationDate": "2016-01-25T17:45:46.470", "AcceptedAnswerId": null, "Title": "What is the \".\" parameter in php?", "Body": "
<?php\n$dit = new DirectoryIterator('.');\nwhile ($dit->valid()) {\n    if (!$dit->isDot()) {\n        echo $dit->getFilename() . \"\\n\";\n    }\n    $dit->next();\n}\nunset($dit); \n?>\n
\n\n

what does '.' parameter mean in DirectoryIterator method?

\n", "Lable": "No"}