w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Read from file in nodejs and display it
You are trying to reference file index.html and using relative path. This might not work on heroku, and it will try to load file from somewhere else. So what you want is to load it relatively to your app.js is: fs.readFile(path.join(process.cwd(), 'index.html'), function(err, data) { As well all it will do (your code) is console log your stuff. While there is no http server and anything, and you are trying to access it through browser. There is nothing server as response. Please read this answer, in order to learn how to send files via http: Nodejs send file in response

Categories : Node Js

nodejs and express error when uploading file, "cannot read property of undefined"
I didn't understand why you kept the name of input as "thumbnails[thumb]". You have to add the method = "POST" to your form. I changed the name attribute to "theFile" and here is the html <div class="holdingDiv"> <form action="/file-upload" name="upload" class="dropzone dz-clickable" id="dropzoneArea" enctype="multipart/form-data" method = "post"> <input type="file" name="theFile" /> <button id="uploadSubmitter" class="btn btn-primary btn-large" type="submit">Finished</button> </form> </div> Now in your node js server do this. app.post('/file-upload',function(req,res){ console.log('FIRST TEST: ' + JSON.stringify(req.files)); console.log('second TEST: ' +req.files.theFile.name); fs.readFile(req.

Categories : Node Js

Why nodejs test case with nodeunit keep loading in webstorm after successfully passed the test cases?
Are you calling done() at the end? For example exports.globalSetterTest = function(test){ var app = require('../helpers/globalsetter'); app.setData("abc"); var res = app.getData(); test.equal(res, "abc", "msg"); test.done(); }; I have the same setup as you and here are some sample tests I wrote. https://github.com/captainchung/webstormNodeUnitTests/blob/master/test/spec.js

Categories : Node Js

Read from a file different types of variables (1 per line)
Since you're using C++ (not just C) I suggest you use the standard iostreams library instead of C stdio. In particular, std::ifstream is good at reading formatted data from a file. #include <fstream> #include <string> // ... std::ifstream f("parameters.txt"); int val1; f >> val1; double val2; f >> val2; std::string val3; std::getline(f, val3); // etc Depending on your application, you might want error checks as well. See http://www.cplusplus.com/reference/iolibrary/ for iostream details.

Categories : C++

C# read from text file and store in variables
I would need to see more of your input data to determine the most reliable method. But one approach would be to split each address into words. You can then loop through the words and find each word that contains only digits. This will be your street number. You could look after the street number and look for S, So, or South but as your example illustrates, there might be no such indicator. Also, you haven't provided what you want to happen if more than one number is found. As far as removing the quotes, just remove the first and last characters. I'd recommend checking that they are in fact quotes before removing them.

Categories : C#

Can't read unit test success rate, can read unit test coverage generated by jacoco
Thanks for Jeanne's answer. I solved it now. As Jeanne said, sonar doesn't support TestNG, it supports JUnit. So I use ReportNG to generated test report in xml format. The report file will be named as com.abc.classTest1.xml. In order to show the Unit Test Success in sonar successfully, we should change it's name to TEST-com.abc.classTest1.xml. Below is my final version of build.xml. <!-- ========= Define the main properties of this project ========= --> <property name="src.dir" value="${basedir}/src" /> <property name="test.dir" value="${basedir}/test" /> <property name="lib.dir" value="${basedir}/lib" /> <property name="build.dir" value="${basedir}/build" /> <property name="classes.dir" value="${build.dir}/classes" /> <property name="dist.dir" va

Categories : Java

How do I get the command line to read file paths and variables in C
Your question is not clear. If you need to input from the standard input (keyboard) use scanf. If you need to input from a file, use fscanf. There is only one difference between them: fscanf has an extra first FILE* argument which is the pointer to a structure which represents a file. You can get it for your file like this: FILE* f = fopen("C:/file.txt", "r"); // 'r' means the file is used for reading

Categories : C

How to read a text file in java and assign lines to variables
You should change your Flight_Inputs to a dynamic size list, for example: change: //as Pshemo pointed out, this is null, //and is causing your NullPointerException String[] Flight_Inputs = null; ... Flight_Inputs[counter++] = in.nextLine(); ... for(int i = 0,j=0; i < Flight_Inputs.length; i++){ to: List<String> Flight_Inputs = new ArrayList<String>(); ... Flight_Inputs.add(in.next()); ... for(String filghtInput : Flight_Inputs){

Categories : Java

Windows Batch to read file and parse lines into tokens and variables
this works here: for /f "tokens=1-10delims=," %%a in ("AA8315,"United States",N777AN,"American Airlines",AAL98,B772,"Boeing 777-223",AAL,"2013-06-11 23:30:47.923","2013-06-12 00:01:14.459"") do ( set hexcode=%%a set country=%%b set reg=%%c set owner=%%d set callsegn=%%e set planefype=%%f set model=%%g set opflag=%%h set firstseen=%%i set lastseen=%%j set THISLINE=%%a,%%b,%%c,%%d,%%e,%%f,%%g,%%h,%%i,%%j ) >"c:FlightsNew.csv" echo %THISLINE% I'm not sure, why you need the tokens.

Categories : Windows

How to pass variables from Android to be read by a PHP file, which then reads MYSQL Database and returns other data?
use link String link = "http://localhost/login.php?username=" +username+"&password="+password; write insert or any query in php and then send data to php by passing variables in link also (hint) send data from android with AsyncTask

Categories : PHP

How to test if an object is a Stream in NodeJS
The prototype you are looking for is the stream.Readable stream for readable streams, and stream.Writable for writable streams. They work in the same way as when you check for Buffer.

Categories : Node Js

NodeJS: Use environment variables in front end scripts
It's very possible. Either use foreman or use a configuration script like this one: var url = require('url'); var config = {}; var dbUrl; if (typeof(process.env.DATABASE_URL) !== 'undefined') { dbUrl = url.parse(process.env.DATABASE_URL); } else { dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/db'); } config.dialect = 'postgres'; config.protocol = dbUrl.protocol.substr(0, dbUrl.protocol.length - 1); // Remove trailing ':' config.username = dbUrl.auth.split(':')[0]; config.password = dbUrl.auth.split(':')[1]; config.host = dbUrl.hostname; config.port = dbUrl.port; config.database = dbUrl.path.substring(1); console.log('Using database ' + config.database); module.exports = config;

Categories : Node Js

Initializing client javascript variables from nodejs
You could use a templating engine and send your data like so: res.render('index.html', { myVar : someVar }): and in your index.html you'd have some expression evaluating myVar, for example <% myVar %> in ejs, or something like span=myVar in jade.

Categories : Javascript

JavaScript variables hoisting in nodejs/async
You can have the 3 mentionned functions defined like this : function fetcher(locals) { return function _fetcher(callback) { // this function body will have access to locals } } and rewrite your code as: function task() { var locals = [] //<-- declared here async.series([ fetcher(locals), //<-- can now access "locals" parser(locals), //<-- can now access "locals" saveToDb(locals) //<-- can now access "locals" ], function (err) { if (err) return callback(err); callback(null); }); }

Categories : Javascript

What's the most optimal way to define module variables in nodejs?
...which of the two methods produce the most optimized code... I'd be surprised if there were a difference in the actual machine code V8 produces when it compiles the source (other than debug info). I can't believe there's any difference that has any real-world impact from the difference in character count, and the fact that the one produces a single statement using the comma operator to join multiple expressions and the other produces a series of statements (one expression/statement). It really is just a style thing. For this: // Style 1 var express = require('express') , socketio = require('socket.io') , bench = require('./bench'); The engine actually processes this: // Style 1 var express, socketio, bench; express = require('express'), socketio = require('socket.io'), benc

Categories : Javascript

NodeJS load test poor performance (EADDRNOTAVAIL)
As robertklep suggested, this is a problem of the SO running out virtual ports when opening too many outgoing connections. Follow his link for a detailed explanation. When I increased the ports as the article says I still got the problem. With a some more googling I found out about problems with garbage collector and node network objects. It seems a good idea (when you need many many outgoing connections) to manually handle garbage collector. Check out this post.

Categories : Node Js

NodeJS FileUpload - Cannot read property Undefined
I had this same issue and what I did was pass a couple of options into the bodyParser object. app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/photos' })); After I put added the option everything seemed to work fine for me.

Categories : Node Js

nodejs unit testing framework that does not require an external test runner
The node.js project itself simply uses the built-in assert module and JavaScript exceptions. They have a fairly straightforward script that runs every .js file in a directory tree and if the file doesn't throw any exceptions, the test is considered passing. You could use something like that. However, although most frameworks do have a command line runner, you absolutely never need to install them (or anything) with -g. If you understand the basic concept of the unix PATH environment variable, you can npm install --save-dev mocha (for example) and then run your tests with ./node_modules/.bin/mocha. No -g required. See also http://peterlyons.com/problog/2012/09/managing-per-project-interpreters-and-the-path

Categories : Node Js

javascript to read file selects a file but doesn't read it
Seems like a simple syntax error to me, but maybe just an error inserting it into stack overflow. The entire thing, the slicing of the file, the insertion into the document, everything, is inside of the if (!files.length) statement. Therefore, the script only executes when there is no file (catching on to the problem yet :) but it is actually meant to do the opposite. All of the important stuff is supposed to be outside of the if statement.

Categories : Javascript

Error "Unable parse file browser.yml" when running a test with Magento automation test framework
I've resolved this by upgrading the Symfony Yaml package to the latest version: pear channel-discover pear.symfony-project.com pear install symfony/YAML Seems that the "---" syntax is supported on v. 1.0.6 (the latest stable at this moment).

Categories : Magento

How to save variables to a file so that those variables are loaded the next time the site runs?
You can use local storage or even cookies. local storage is your best bet, although it doesn't work in older browsers. cookies are (more) limited in their capacity (4KB vs 5MB for local storage) and also are sent to the server with each request, which may not be what you want. Alternatively, you can store the state on your server (you'll need some server side scripting as well), and only store a user/gamer id in a cookie.

Categories : Javascript

NIO load file in an unit test from src/test/resources
Well, it's a matter of obtaining the correct Path for you test resource in the classpath in your test. EDIT: this is more concise: Paths.get(getClass().getResource("/"+filename).toURI()).toString()

Categories : Java

How to set variables inside a mocha test
So mocha + coffeescript sometimes requires an explicit declare in the right scope if you want a variable that a whole suite of tests can use and can be manipulated during before/beforeEach/after/afterEach. describe 'spark.isTriple', -> dice = null #force coffeescript var declaration it "should blah blah", -> dice = [1,2,2,2,4,5] I'm pretty sure something along those lines will fix your problem, but if you post a full file that demonstrates the issue I can be sure.

Categories : Javascript

Is it ok to place all JS / jQuery variables at top of file? Global variables?
Global variables are scoped to the program, so if you pull in other javascript that also uses the same global variable names you will almost certainly encounter bugs. If you're writing something fairly small there's certainly nothing (technically) wrong with declaring all of your variables as global, but if you're writing something that's going to grow it might be to your benefit to use some form of module pattern to provide another level of scope to your variables and minimize the use of Globals. With a module pattern you can usually reduce your global variables down to the Module namespace, with what would normally be globals, scoped only up to the module.

Categories : File

Arquillian test class variables lose value
Junit does not allow to share the variables between/among test cases. During execution, each test case will have its own local copy of the variables. The rationale behind such a design is simple that test cases should not depend on each other. And that is why it is called unit testing, where each unit should be independently tested. But if you really need to do it then you may create a static class variable to store the info.

Categories : Java

Junit Test Fixure - initialize variables
The way variables work in jUnit is that they get initialized before each test. So if you assigned temp = "abc" in test1, it will be reinitialized when test2 run. If you want to some kind of initialization before each test, use the setup method. For unit tests your aim should be to test the smallest isolated piece of code,usually, method one by one. So sharing variables between test cases does not seem to be a good idea. But if you really need to do something like that, then one approach can be to club the two methods in one method and use the variable set by the first in the second.

Categories : Java

Passing variables down Mocha test suites
Use environment variables. At the top of your mocha file, include: process.env.TEST = 'true'; // Use test database Then, include use a database config like this one: var url = require('url'); var config = {}; var dbUrl; if (typeof(process.env.DATABASE_URL) !== 'undefined') { dbUrl = url.parse(process.env.DATABASE_URL); } else if (process.env.TEST === 'true') { dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/test'); } else { dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/db'); } config.dialect = 'postgres'; config.protocol = dbUrl.protocol.substr(0, dbUrl.protocol.length - 1); // Remove trailing ':' config.username = dbUrl.auth.split(':')[0]; config.password = dbUrl.auth.split(':')[1]; config.host = dbUrl.hostname; config.port = dbUrl.port; config.data

Categories : Node Js

Best way to write unit test for multiple variables
In pure unit testing you should test one class, e.g. Person, completely separated from other and test methods of your unit for all (edge) cases. Completely separated is very important thing as you want to do unit testing so you should test only one unit - e.g. person class. What about all dependencies? You should mock them as you must be 100% sure that they work according to your requirements - it could mean: they are not broken - there is a chance that your colleague break code of Address they must be adjusted also for edge cases, e.g. if music interests can be null, you can't trust somebody's API Sometimes it's very hard to achieve those requirements from outside. I mean you can't be sure that someone does not commit a piece of code which will not return null instead of address's s

Categories : Java

Ensure that file.read will read entire file?
You might want to use open(fn, "rb") to open it in binary mode. Windows and Linux have different encoding and decoding. When you open a file in binary mode and read data from it, what you get back is a bytes object. No decoding takes place on input, and no encoding on output. When a bytes object is read or written, you get the data transmitted, with no attempts to change it.

Categories : Python

Read file in chunks - RAM-usage, read Strings from binary files
yield is the keyword in python used for generator expressions. That means that the next time the function is called (or iterated on), the execution will start back up at the exact point it left off last time you called it. The two functions function identically; the only difference is that the first one uses a tiny bit more call stack space than the second. However, the first one is far more reusable, so from a program design standpoint, the first one is actually better. EDIT: Also, one other difference is that the first one will stop reading once all the data has been read, the way it should, but the second one will only stop once either f.read() or process_data() throws an exception. In order to have the second one work properly, you need to modify it like so: f = open(file, 'rb')

Categories : Python

How to test via rspec that session variables updated in controller
the problem is that rspec doesn't know this is a controller test (is not in spec/controllers folder) you need to specify that describe GamesController, :type => :controller do ... end

Categories : Ruby On Rails

Re-loading static variables at the start of every unit test
The only time static variables are unloaded is when the classloader that loaded the class in question is garbage collected. One way to solve your problem is to use your own classloader. There's a great SO question here that covers this in fairly extensive detail. Another option would be simply resetting the values prior to each test. You can supply a @Before annotated method in your test class that would reset them, using reflection if necessary.

Categories : Java

Test NFC android Read only 12 sector
Try to change: for (int k = 0; k < nbrBlock; k++){ byte[] data = mfc.readBlock(k); Log.w("ISI", "Block num " + k + " - data " + ByteArrayToHexString(data)); } with this byte[] data = mfc.readBlock(bIndex); for (int k = 0; k < nbrBlock; k++){ bIndex = mfc.sectorToBlock(Cpt); bIndex++; Log.w("ISI", "Block num " + k + " - data " + ByteArrayToHexString(data)); } from: http://mifareclassicdetectiononandroid.blogspot.it/

Categories : Android

test for read-only property vs. set/get key -- obj-c / cocoa
Assuming you're fine with asking the metaclass (ie, you don't want to allow for potential instance-specific patches to the dispatch table), you can get property attributes from the runtime. Specifically: // get the property; yes: that's a C string. This can see only things // declared as @property objc_property_t property = class_getProperty([instance class], "propertyName"); /* check property for NULL here */ // get the property attributes. const char *propertyAttributes = property_getAttributes(property); You can then check those attributes for read-only: NSArray *attributes = [[NSString stringWithUTF8String:propertyAttributes] componentsSeparatedByString:@","]; return [attributes containsObject:@"R"]; If you want to be completely thorough, you should also che

Categories : Objective C

Batch file to read txt file with file names then search for that file and copy to folder
you can try this: FOR /D /R "%~dp0" %%I IN (*) DO for /f "usebackq delims=" %%a in ("%~dp0list.txt") do xcopy "%%~I\%%~a" "C:your_files" /e /i For more help show list.txt.

Categories : Windows

Converting read variables to lowercase
It's probably because you didn't assign the translated output to a variable yet. Also I suggest quoting your variables around doublequotes to prevent word splitting and pathname expansion. foobar=$(echo "$foobar" | tr '[:upper:]' '[:lower:]') If you're using case and you just need to check if an input is y or Y either way you can use a glob pattern like this. There's no need to transliterate it to lowercase form. case $foobar in [yY]) echo "User said yes." ;; *) echo "User said no." ;; esac Also you can somehow suppress showing user input by using -s: read -s foobar As a whole to make your code work well in both bash and sh you should already remove the part which is bash specific: #!/bin/bash echo "Please enter a word:" read -s foobar foobar=$(echo "$foobar" | tr

Categories : Linux

how to read out variables from a opegles shader?
You are thinking about shaders in completely the wrong way. They take input (e.g. in attributes, uniforms, sampled textures) do some calculations and then output them for the next stage of the render pipeline. You cannot write to a uniform, because it would not make any sense. Hundreds or thousands of instances of your shader run simultaneously and each one uses the same set of uniforms. That said, what you can do is write to a texture attachment if you use FBOs. If you do it intelligently, you can then lookup values in this texture in your vertex shader to determine the new position for your particle. You will have to come up with a scheme for addressing which texel corresponds to which particle, how to pack the properties into a 3 or 4 channel texel, etc. But this is how GPU-based part

Categories : Android

How to set environment variables for nginx to read?
You can define environment variable inside of supervisor's config with directive environment=VAR1=<VAR1>,VAR2=<VAR2> Something like that: [program:gunicorn] directory=/home/<USER>/.virtualenvs/<DOMAIN>/<PROJECT>/ command=/home/<USER>/.virtualenvs/<DOMAIN>/bin/gunicorn <PROJECT>.wsgi:application -c /home/<USER>/.virtualenvs/<DOMAIN>/<PROJECT>/<APP>/gunicorn_conf.py user = <USER> environment=SECRET_KEY=<SECRET_KEY>

Categories : Django

predict.glmnet on test data with different number of predictor variables
glmnet requires the exact same number/names of variables from the training dataset to be in the validation/test set. For example: library(caret) library(glmnet) df <- ... # a dataframe with 200 variables, some of which you want to predict on # & some of which you don't care about. # Variable 13 ('Response.Variable') is the dependent variable. # Variables 1-12 & 14-113 are the predictor variables # All training/testing & validation datasets are derived from this single df. # Split dataframe into training & testing sets inTrain <- createDataPartition(df$Response.Variable, p = .75, list = FALSE) Train <- df[ inTrain, ] # Training dataset for all model development Test <- df[ -inTrain, ] # Final sample for model validation # Run logistic

Categories : R

How to write junit test for a class that has member variables that are topComponents?
Your biggest problem is that you have global state. Global state is generally poor programming, including with tests. Testing for particular implementation class, probably isn't a very good test. I suggest removing your global state and dependency upon the global state that you are lumbered with from your libraries, then test that.

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.