samedi 31 octobre 2015

Code to print out number of lines and integer values

i created a data file called program.txt I need to create a code that prints out number of lines and integer values from that program.txt Heres the text I made





the program.text has these values in it

   #include <iostream>
    #include <string>
   #include <fstream>

   using namespace std;

  int main()
string calc;
int test;
int cool;
int book;
ifstream myfile;
ifstream outof; ("program.txt");"program.txt");
if (
    cerr<<"Error Opening file"<<endl;


if( ())
    cerr<<"Error Opening file"<<endl;

while (!myfile.eof ())

cout <<calc<<endl;
while (!outof.eof ())
    outof<<test;// Problem Here<-- Its saying Unspecified operator


also after cerr I tried exit (1) and it said exit was not defined. I am new to this any help would be greatly appreciated Thanks This is C++ btw And This is my first Post YAY!

Is there a way to recover a file after having removed it using NSFileManger?

I was currently working on files and a wrote a simple program to remove a file than copy some other contents from another folder to the folder i had removed(program written by author of Objective-C Stephen G.Kochan). I ended up by accidentally putting the path of a folder i had alot of work in. Is there any way to possible recover this(since it is not in the trash)?

Python in-place write to file at arbitrary position

I'm trying to edit a text file in-place in python. It is very large (so loading it into memory is not an option). I intend to replace byte-for-byte strings I find inside.

with f as open("filename.txt", "r+b"):
    if == "01234567":, 1)

However, the write() operation adds onto the end of the file when I tried it:

>>> n.write("sdf")

I want the result of that to be sdsdf.

Trying to read back binary data from a file, causing crash

thanks in advance for your help.

I'm trying to call a function which will read back date from the binary file I've just created of a sine wave. The file has already been opened in w+b in the main function. I want to copy the data to my buffer array, then print them out.

end_time is the total number of samples in the file. The samples have been written as floats. Code Blocks gives no errors, but the program crashes when it gets to this point and I'm not sure why.

void printwave(FILE *fp, int end_time)
   int i;

   float buffer[end_time];
   fseek(fp, 0, SEEK_SET);

   for(i=0; i==end_time; i++)
        fread(buffer, sizeof(float), 1, fp);
        printf("%d\t%.2f\n", i, buffer[i]);


Thanks for your help, Andy.

How to create many files (with different names) in a specifc directory?

The goal is to every time a person gives a name on a TextField, I can create a file with that name + "messageLog.txt". And these creations are send to specific folder.

What I have now is:

String ficheiro = localDoNome.getText() + "_messageLo.txt");
PrintWriter writer = new PrintWriter(ficheiro);

This allows me to create files with the desired names, but have yet to enter the directory I want. I know the following code allows me to write a file in directory I want.

PrintWriter writer = new PrintWriter("confdir/ficheiro.txt");

The problem is, I can't see a way to combine this two codes. Because if I do

PrintWriter writer = new PrintWriter ("confdir / ficheiro");

It's gonna always create a file named ficheiro. And what I want is to create in that directory "confdir" files like banana.messageLo.txt, laranja.messageLo.txt, etc....

While loop to read numbers from file

Write a program that uses a while loop to read 10 integer numbers from file “” and prints their sum and average on the screen as follows:

The sum is n and average is m.

how do i use the while loop in this question ? Help Help !!

How Can I create a file (the name can change) in a specific directory?

I want to create different files (ended with .txt but with different names(depends on what I put in the textfield "localDoNome") into a specific directory.

What I have now is:

String ficheiro = localDoNome.getText() + "_messageLo.txt");
PrintWriter writer = new PrintWriter(ficheiro);

This code works fine for creating different files. Miss the part "to a specific directory".

I know that I can do something like:

 PrintWriter writer = new PrintWriter("confdir/ficheiro.txt");

The problem with this last code is that is all String, this means the initial "ficheiro" would be all String too, which leads to not creating different files.

Converting file to string Issue in C++

I'm having a little trouble of converting a file to a string. This post is a continuation of this post.

This is the function I'm calling:

std::string fileToString(std::string const& file){

    std::ifstream in(file);
    if (!in){
        std::cout << "Error: file does not exist\n"; 

    std::stringstream buffer;
    buffer << in.rdbuf() << std::flush;

    return buffer.str();

And I called this to test it out:

std::ofstream file("test.txt");
file << fileToString("fileTest.txt").c_str();

In my scenario, I have to end up returning a char*, so in the end I want it to work like this: (where GLchar is a typedef for char in OpenGL)

const GLchar* vertexShaderSource = fileToString("Shaders\\shader.vsglsl").c_str();

However, this time, the test.txt file is empty. What happened here?

How to go at the beginning of a line with fseek()

I have a function where I check if the passed arguments match with the ones in a .dat file within an error margin.

What I would like to do is find the best match. So, I read the whole file and keep track of the line which gives me the best match. After I am done with reading the file I would like to go back that specific line and read it as my final result.

But, I could not do that "going back" part.

My function is:

int isObjectMatches(FILE *rPtr, struct objectDatabaseList *db, double area, double length)
    double sum;
    errno_t err;
    double const errorThreshold = 0.4;
    double minError = 100.0;
    int lineNo = 0, bestMatchNo = 0;
    bool match = false;

    if ((err = fopen_s(&rPtr, "objects.dat", "r")) != 0)
        printf("Couldn't open the file to read.\n");
        while (fscanf_s(rPtr, "%14s%lf%lf", db->dName, sizeof db->dName, &db->dArea, &db->dLength) == 3)
            sum = pow((1 - (area / db->dArea)), 2) + pow((1 - (length / db->dLength)), 2);

            if (sum > errorThreshold) // No possible match
                continue; // Keep reading
                if (sum < minError) // One possible match
                    minError = sum;
                    bestMatchNo = lineNo; // Take the line number
                    match = true;
                    continue; // Keep reading

        if (match)
            fseek(rPtr, (bestMatchNo - 1)*sizeof(struct objectDatabaseList), SEEK_SET); // Find the line
            fscanf_s(rPtr, "%14s%lf%lf", db->dName, sizeof db->dName, &db->dArea, &db->dLength);
            return 0;
    return -1;

And my struct is:

struct objectDatabaseList
    char dName[15];
    double dArea;
    double dLength;

Please note that the length of a line is not a fixed number as the "name" could be different.

Looking for an upload file type of structure used in HTML (PHP) for Android (Java)

Looking for an upload file type of structure used in HTML for Android (Java) The HTML + PHP version can be seen in the fllowing link h[ttp://][1]

Do we have something like this for Android (Java)?

All comments appreciated. Thank you in advance Note: Of course I checked the internet but came across with Read File type of code structures which is not what I am talking about

Converting file to char* Issue

I am a beginner at C++ programming, and I encountered an issue. I want to be able to convert the contents of a file to a char*, and I used file and string streams. However, it's not working.

This is my function that does the work:

char* fileToChar(std::string const& file){

    std::ifstream in(file);
    if (!in){
        std::cout << "Error: file does not exist\n"; 

    std::stringstream buffer;
    buffer << in.rdbuf() << std::flush;

    return const_cast<char *>(buffer.str().c_str());

However, when I test the method out by outputting its contents into another file like this:

std::ofstream file("test.txt");
file << fileToChar("fileTest.txt");

I just get tons of strange characters like this:


What exactly is going on here? Is there anything I missed? And if there's a better way to do this, I would be glad to know!

Scan in 2D array txt file in Java

When I scan in my 2d array text file, I get an exception error if I don't have a number in the first line. My text file is as follows:

8, 3, 5, 4, 1, 6, 9, 2, 7
2, 9, 6, 8, 5, 7, 4, 3, 1
4, 1, 7, 2, 9, 3, 6, 5, 8
5, 6, 9, 1, 3, 4, 7, 8, 2
1, 2, 3, 6, 7, 8, 5, 4, 9
7, 4, 8, 5, 2, 9, 1, 6, 3
6, 5, 2, 7, 8, 1, 3, 9, 4
9, 8, 1, 3, 4, 5, 2, 7, 6
3, 7, 4, 9, 6, 2, 8, 1, 5

The zero at the top, should not be there. However, I have found that if I take it out, my code doesn't work. The number doesn't have to be a zero, it works with any number as long as there is something there. Here is my code:

public static void main(String[] args) throws FileNotFoundException {
    String fileName = "Sudoku2d.txt";
    Scanner inputStream = null;
    System.out.println("The file " + fileName + "\ncontains the following lines:\n");
    inputStream = new Scanner(new File("C:\\Users\\ZachsLaptop\\Documents\\NetBeansProjects\\Sudoku\\Sudoku2d.txt"));
    String line = inputStream.nextLine();
    int[][] puzzel = new int[9][9];
    for (int row = 0; row < 9; row++) {
        for (int column = 0; column < 9; column++) {
            puzzel[row][column] = Integer.parseInt(line);

    while (inputStream.hasNextLine()) {
        line = inputStream.nextLine();


Here is my output with the zero at the top of the text file:

The file Sudoku2d.txt contains the following lines: (in a 9x9 matrix with commas separating numbers)

8, 3, 5, 4, 1, 6, 9, 2, 7
2, 9, 6, 8, 5, 7, 4, 3, 1
4, 1, 7, 2, 9, 3, 6, 5, 8
5, 6, 9, 1, 3, 4, 7, 8, 2
1, 2, 3, 6, 7, 8, 5, 4, 9
7, 4, 8, 5, 2, 9, 1, 6, 3
6, 5, 2, 7, 8, 1, 3, 9, 4
9, 8, 1, 3, 4, 5, 2, 7, 6
3, 7, 4, 9, 6, 2, 8, 1, 5
BUILD SUCCESSFUL (total time: 0 seconds)

Here is my code if I remove the zero:

The file Sudoku2d.txt contains the following lines:

I do not want to have to put a random number at the top of my text files for them to run. Can anyone please tell me why this is happening?

How to add multiple entries to a file in C?

I am working on basic file streaming in C and the aim is, to create a sort of database, which contains,, name and attendance of a student. The problem I am facing is, when I enter a new entry, into the database; it replaces the previous entry. Whereas I want to do add multiple entries.

Any help is highly appreciated.

Thank You

The Code that i have written till now:

char file_write()

    char nm[80];
    int a,d,i=0;
    char e[10]="Absent";
    char f[10]="Present";
    FILE *fp;
    fp = fopen("/Users/kartik/Desktop/stdb.txt","w+");


printf("\nEnter Roll Number: ");           //Input Multiple Variable Integer

printf("\nEnter Name: ");                  //Input Variable Character
scanf("%s", &nm);
fprintf(fp,"%s", nm);

printf("Attendance ('0' For Present, '1' for absent): ");   //Input Attendance




} while(i!='\0');

return 0;

Finding all words different by one letter Perl

I'm working on a word chain program, and given two words and a file of words the program finds how to go from one word to the other by only changing one letter at a time(Changing to one word from another based off of the words in the file).

I'm working on a subroutine that will return a list of words from the file that are only different by one letter.

I know I'd probably use regular expressions to find the words and add it to a list. Thanks for any help someone can give.

Beginner: Just imported a csv time series file into canopy

Please advise how I can read/reference the data (2 columns date, price) in ipython code and perform simple manipulation as follows: look up the min or max value and return it along with the associated date calculate the average value of each consecutive (non overlapping) 10 prices.

how to separate entering data to C program: bit from file, bit from keyboard?

I've some C program which must first load numbers from file to array and then allow user to enter different numbers and check if they exists in red array. Executing happens using command line:

program.exe < numbers.txt

Reading from file is done so

for (t = 0; t < n; t++){//n is array count set before
        scanf("%d", &values[t]);

So the problem that program starts with data from file and finishing without possibility to enter any data from keyboard. How can I make this able to be?

writing a new text file in python

I am writing a code that go over text file and counting how many eords are in every line. Im having trouble puting the result (many lines that each consist a number) into a new text.file i wrote it like that:

 in_file = open("our_input.txt")
 out_file =open("output.txt", "w")

for line in in_file:
line= (str(line)).split()


but the file im getting has all the number together in one line. how do i seperate them in the file im making?

How can I run an embedded .exe file in C# Windows Forms Applications?

How can I run an embedded .exe file (installer) in C# Windows Forms Applications with the easiest way?

I just want to click a button and installer should open. My .exe file's name is setup

If I try this: Process.Start(setup.exe); I got an error:

The name 'setup' does not exist in the current context

and if I try this:


It will open this folder: C:\Windows\System32\setup

Android read text file in Activity that filters opening text files

I have Activity that "listening" to open text files, which means in manifest:

    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/*" />

So I navigate to file browser, find some text file and try to open it, and as expected this Activity exists on the list of available applications to complete the action. When the activity launches I know the Activity got the correct file name but it treats the file as empty (not printing to the log the content).

Remarks: The file is not empty, other apps can read him, the file path not contains white spaces, no exceptions or crashes.

What i'm doing wrong here?

protected void onCreate(Bundle savedInstanceState) {
    //Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    if (Intent.ACTION_VIEW.equals(action) && type != null && "text/plain".equals(type)) {
        handleViewText(intent);  //Handle text being sent

private void handleViewText(Intent intent) {
    Uri uri = intent.getData();
    BufferedReader br = null;
    try {
        String sCurrentLine;
        InputStream is = getContentResolver().openInputStream(uri);
        br = new BufferedReader(new InputStreamReader(is));
        //This is also not working: br = new BufferedReader(new FileReader(uri.getPath()));
        while ((sCurrentLine = br.readLine()) != null) {
            Log.e("TAG", sCurrentLine);  //never enters here
    } catch (Exception e) {
    } finally {
        try {
            if (br != null) br.close();
        } catch (Exception e) {

Execute zgrep command and write results to a file

I have a folder containing lots of files like file_1.gz to file_250.gz and increasing. A zgrep command which searches through them is like:

zgrep -Pi "\"name\": \"bob\"" ../../LM/DATA/file_*.gz 

I want to execute this command in a python subprocess like:

out_file = os.path.join(out_file_path, file_name)
search_command = ['zgrep', '-Pi', "\"name\": \"bob\"", "../../LM/DATA/file_*.gz "]
process = subprocess.Popen(search_command, stdout=out_file)

The problem is the out_file is created but it is empty and these errors are raised:

<type 'exceptions.AttributeError'>
'str' object has no attribute 'fileno'

What is the solution? Thanks in advanced.

vendredi 30 octobre 2015

change the behaviour of browse button

Assume that you have a html page with browse button if you click the browse button it ll open folder in your computer or laptop right from their you can select the file what you want to upload but what my question is instead of opening a folder in our computer/laptop it ll open cloud server like one drive, google drive, etc., from their i want to select the files and upload it to my computer/laptop how to do that, actually i did some research about this but i didn't get any worthy website to learn about this.

Mahout recommender, how to use different CSV files for training and testing

I am building a recommender system in mahout. I have two files (train.csv, and test.csv) which should be used separately for training and testing. I searched a lot online on how to pass the train.csv to the training model and test.csv to the testing model, but I didn't get any luck in understanding what others suggested. In this question: Test and training with different dataset with MAHOUT they mentioned that we can change the evaluate class and add two different files. Can someone explain to me how to do that exactly? I am using eclipse, and I couldn't find the (evaluate) class or modify it as suggested. I am new to mahout, and I not sure what are they talking about!

Or, if you have any other solutions to add train.csv and test.csv separately I will really appreciate that... Thanks for help Here is some of my code:

        DataModel model = new FileDataModel(new File("train.csv"));
        UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
        UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);
        UserBasedRecommender recommender = 
                new GenericUserBasedRecommender(model, neighborhood, similarity);

    RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
    RecommenderBuilder builder = new MyRecommenderBuilder();
    double result = evaluator.evaluate(builder, null, model, 0.9, 1.0);
        double result = evaluator.evaluate(builder, null, model, 0.9, 1.0);//how can I use evalute for both train.csv and test.csv?

How feasible is it to repair this corrupt file (missing aproximately 10 hex values in 2000 possible positions).)?

Alright, let's assume that a file has 2000 instances of \x0A, and 10 of those instances are directly preceded by \x0D. If any of the \x0D bits are deleted the file won't parse. If you deleted all 10 instances of \x0D from the file which are followed by \x0A would it be possible to put them back?

Some things that may help:

If the first instance of \x0D is found, the image (.gif or .png) will be partially visible, if your further find the second position, more of the image is revealed and so on, but it must be found in order (top to bottom).

In other words, you could technically repair the file by placing \x0d before each instance of \x0A in the file until a block is solved and more of the image becomes visible, then move on to the next block, and so on until all \x0D's are placed.

However, it would take time to test each position, meaning for this particular image if you kept a good pace and did it by hand, you could solve it in about 6 hours. Is there any way to write a script to do this?

This would enable recovery of .png and animated .gif files which were corrupted by being transferred in ascii mode.

AutoIt Find Average Paycheck Through Script?

I'm trying to take data from a GUI Input Box and save it to a file to average it out with new data. (I know, I'm terrible at explaining things.)

For example:

$paycheck = GUICtrlCreateInput("", 784, 229, 81, 21)
$paycheckHistory = GUICtrlCreateButton("$000.00", 881, 429, 60, 20)

While 1
   $nMsg = GUIGetMsg ()
   Switch $nMsg
      Case $paycheckHistory
         $paycheck = GUICtrlRead($paycheck)
         $file = "averageCheck.au3"
         if NOT FileExists($file) then
            if $paycheck == "" then
               FileWriteLine ( $File, "$check1 = 0")
               FileWriteLine ($file, "$check = " & $paycheck)

I want the script to add a new variable to the averageCheck.au3 file each time the button is pressed (while saving the previous data), and then average it out. Thanks in advance!

Password protect file within directory htaccess issue

Ok, so I've been using this to password protect my files:

<FilesMatch "visitors.log">
AuthName "no"
AuthType Basic
AuthUserFile /var/www/html/.htpasswd
require valid-user

and this works fine in my /var/www/html (root dir for my site), but for some reason it doesn't work if i were to do the same thing but inside a directory. For example, if i were to create a .htaccess file in /var/www/html/new_directory with the same code to password a file in there, it doesn't work for some reason. Any suggestions? What am I doing wrong?

Why can't I find my File?

I'm trying to open a CSV file name "logger.csv" which I have saved in the source folder itself.

public static void main(String[] args) {
    String filename = "logger.csv";
    File motor_readings = new File(filename);
    try {
        Scanner inputStream = new Scanner(motor_readings);
        while (inputStream.hasNext()){
    } catch (FileNotFoundException e) {
        System.out.println("Error: File not found!");

However, this keeps on giving me a "File not found" error.

file_get_contents does not find file

The following code tries to load the file content into a string.

    // Loads the forecast from json
    public function loadForecast()
        try {

            $filename = "../../forecast/forecast.json";

            echo "Dateiname: '" . $filename . "'\n";
            echo "Pfad: '" . realpath($filename) . "'\n";

            if ($forecastContent = file_get_contents($filename) !== false) {

                echo "got content";
            else {

                echo "no content";
        catch (Exception $e) {

            echo "Caught exception: " . $e->getMessage();

Can anybody tell me my fault? I'm always getting "no content". realpath does print "" (empty string).

My Webspace hierachie is

  • /
    • Backend
      • my PHP file
    • forecast
      • forecast.json

Does O_DIRECT bypass filesystem journaling?

The man page for open(2) only suggests that O_DIRECT bypasses the page cache, but many descriptions around the net describe it as causing the user buffer to be DMA'd straight to the drive. If this is the case I imagine it would also bypass journaling done by the filesystem (e.g. xfs, ext4, etc.). Is this the case?

I can't find anyone claiming one way or the other. It seems to me this would be consistent with O_DIRECT being used by databases -- the common example use for O_DIRECT is when an application like a database is doing its own caching in userspace, and similarly I can imagine databases doing their own transaction logs.

Can mmap and O_DIRECT be used together?

As I understand it, when you mmap a file you are basically mapping the pages from the page cache for that file directly into your process, and when you use O_DIRECT you are bypassing the page cache. Does it ever make sense to use the two together? If my understanding is right how would it even work? mmap seems to rely on the file being in the page cache and O_DIRECT seems to prevent it from going there (assuming nothing else on the system has the file open). I found this question but the answerer seems to think it's perfectly normal to do.

Reading from file into array, line by line

I am trying to read from a file in C. My code is the following. It seems to read everything fine into the array, but when I try to print it, I get the error Segmentation fault (core dumped)

  FILE *fp;
   char * text[7][100];
   int i=0;

   fp = fopen("userList.txt", "r");

   //Read over file contents until either EOF is reached or maximum characters is read and store in character array
   while(fgets((*text)[i++],100,fp) != NULL) ;

   printf("%s", &text[0]);


Can someone point me in the right direction?

I have tried reading and copying solutions from other similar cases, but they are extremely specific to the user.

What is Php's equivalent of Java's newInputStreamSupplier?

I have been trying to implement a functionality that is written in Java, for uploading a file via PUT HTTP request.

Here is my sample Java code:


public void uploadFile() {
        final makeRestRequest makeUploadRequest = makeRequestTo(upload_file_location)
                .addHeader(new HttpHeader("Accept", "application/json"))
                .addHeader(new HttpHeader("Content-Type", "application/zip"))

        final getRestResponse uploadResponse = makeUploadRequest.fetchResponse();

I am looking for a similar variant of the php code, that can make a HTTP PUT call to upload a file, but i am not sure what to use for the newInputStreamSupplier. Here is my sample php code, that makes a PUT call to upload file using CURL, but fails to get a response:

$url = upload_file_location; 
$localfile = "";

$fp = fopen ($localfile, "rb"); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_PUT, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$headers = array();
$headers[] = 'Content-Type: application/zip';
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_INFILE, $fp); 
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile)); 
$http_result = curl_exec($ch);

I get an error saying: "File content is empty". Does anyone have an idea of what i am doing wrong?

phoneGap file read/write not working

I have followed all examples I have found but none seems to work. Instead of getting the text I just get null.

I just can't figure out what I am doing wrong!

The following is a code sample I have stitched together for a couple of examples found online.

function saveSettings() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSw, fail);

function gotFSw(fileSystem) {
    fileSystem.root.getFile("tdb.settings", {create: true, exclusive: false}, gotFileEntryw, fail);

function gotFileEntryw(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);

function gotFileWriter(writer) {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
    writer.write(username + "\n" + password);

function readSettings()
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFSr, fail);
function gotFSr(fileSystem) {
    fileSystem.root.getFile("tdb.settings", null, gotFileEntryr, fail);

function gotFileEntryr(fileEntry) {
    fileEntry.file(gotFiler, fail);
function gotFiler(file){
function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as text");

function fail(evt) {

I am using saveSettings and readSettings as entry points.

Ubuntu 14.04 recursive file rename individual files appending directory name to filename

On Ubuntu 14.04 I have files that are in different sub-directories but have same filename. i.e.:

dirA/file01.jpg, dirA/file02.jpg, dirA/file03.jpg

dirB/file01.jpg, dirB/file02.jpg, dirB/file03.jpg

dirC/file01.jpg, dirC/file02.jpg, dirC/file03.jpg

I want to copy all the files (about 1000) contained in different sub-directories (about 200) recursively into a separate single directory (/home/user/temp/).

Since they have identical filenames I want to rename all 1000 individual files appending their respective directories to the filename, thus making them unique, like this:




All (1000) files should be stored in the same final directory (home/user/temp).

I tried using ls, then find, then rename, then mv, then cp with too many problems to list. If my PERL was up to scratch I would have nailed this in a minute but it's been 15 years since I've used it... sob sob... Can anyone help with something snappy and not too complicated? Your help is very much appreciated.

Reading a file in Python won't read the first line

I am reading a text file, separating the word and the number with the comma then adding them into separate lists however, the first name gets omitted. Here is my code.

for line in keywordFile:
     line = keywordFile.readline()

Why isn't a change event raised when I use jQuery in an MVC project?

I use jQuery file in my project after that change event not raise and the error raise is "$ul is not defined"

$(function () {
    function () {
      var shaId = $("#cou1 option:selected").text();

          url: "/State/GetStates",
          data: { shaId: shaId },
          success: function (value) {
            cities = JSON.parse(value);
            $("#cou2").append("<option>--- Please select ---</option>")
            $.each(cities, function (idx, city) {                          
              $("#cou2").append("<option value='" + city.Id + "'>" + + "</option>")

How to import multiple different delimited files in sas?

I have a folder with multiple files. Each in different category (say for example: 5 files are tab delimited, 5 are csv files, 5 are pipe delimited and so on). How can I import them using SAS? (I don't want to import them separately.)

Pentaho kittle - Skip files in root and only move/process the files in subfolder

I need to copy the files from User1 and user2 folder to "process" folder but I need to skip the files that may be dropped by the user directly into Root folder.

-Root + User1 + User2

Is there any way xpression can be used to skip to move those files or can we exclude the files directly under Root folder to be excluded to be processed.

Thanks, Rahul

Fileuploading not work in PHP while I select file which contains = in it's name

When i upload any image file which contains '=' in filename then server says that 404 page not found. and if i upload any other file which is not contain '=' in name then it will successfully uploaded. is there any server access issue. should i make change in .htaccess file? because i have host this code in two different host provider. godaddy and namecheap. godaddy allows us to upload any image with any name i.e it uploads image which containt '=' but same code not work on namecheap. I am sure that code doesn't have any issue. I am using below code

<script src=""></script>
<script type="text/javascript">
$(document).ready(function (e) {
    $("#uploadForm").on('submit',(function(e) {
                url: "upload.php",
                type: "POST",
                data:  new FormData(this),
                contentType: false,
                success: function(data)
                error: function(){}             
<form id="uploadForm" action="upload.php" method="post"  enctype="multipart/form-data">
  <div id="targetLayer">No Image</div>
  <div id="uploadFormLayer">
  <label>Upload Image File:</label><br/>
  <input name="userImage" type="file" class="inputFile" />
  <input type="submit" value="Submit" class="btnSubmit" />

How to efficiently allocate a file of predefined size and fill it with a non-zero value using Python?

I'm writing a program that uses dynamic programming to solve a difficult problem. The DP solution requires storing a large table. The full table occupies approximately 300 Gb. Physically it is stored in 40 ~7Gb files. I'm marking unused table entries with the byte \xFF. I'd like to allocate space for this table quickly. The program will have to run both under Windows and Linux.

In short, I want to efficiently create large files filled with a specific byte in a cross-platform manner.

Here is the code I'm currently using:

def reset_storage(self, path):
    fill = b'\xFF'

    with open(path, 'wb') as f:
        for _ in range(3715948544 * 2):

It takes it about 40 minutes to create one 7 Gb file. How do I speed it up?

I've taken a look at other questions, but none of them seem to be relevant:

PHP - open text file from another Drive

I am trying to open text file through PHP. The below code is working fine when I have text file inside the Project folder htdocs.

   $myfile = fopen("Updates/updates.txt", "r") or die("Unable to open file!");
   echo fread($myfile,filesize("HRupdates/updates.txt"));

Now I would like to open file from another drive from drive D.

I tried like this D:/Updates/updates.txt it is not working. any other ways?

Delete some text file from Sever after a period of time

I am developing a online store. There is no sign up option. So i used Ajax and PHP to keep users wishlists and carts. For that i create some text file on the server.
Is that okay? or there is better way to do that?

Second question is ,If I want to delete those text files after a certain period of time automatically, is it possible ?

Thanks Geniuses.

Load only one appender instead of all

I'm currently working on a console C# app and I have to log two type of data :

  • All steps of the app in general (AppLog)
  • All information that I get from a service (MachineLog)

MachineLog needs 2 propeties, but when I start the app I do not define them I have some work to do before. But I need to log from start whith AppLog so at le beginning I use :


And it create me the C:\DNC\Suivi\Logs.txt but also C:\DNC\Suivi\(null)\(null)-logs.txt

Is there any way to only load/configure AppLog and later MachineLog ?

I tried to add parameters to Configure() and all failed.

My App.config is :

<?xml version="1.0" encoding="utf-8" ?>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>

      <level value="DEBUG" />
      <appender-ref ref="AppLog" />
    <logger name="Machine" additivity="false">
      <level value="ALL" />
      <appender-ref ref="MachineLog" />
    <appender name="AppLog" type="log4net.Appender.RollingFileAppender">
      <file value="C:\DNC\Suivi\Logs.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

    <appender name="MachineLog" type="log4net.Appender.RollingFileAppender" >
      <file type="log4net.Util.PatternString" value="C:\DNC\Suivi\%property{Machine}\%property{ID}-logs.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
          <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

Java: Bug: JFileChooser only showing up sometimes

I have a method to open JFileChooser and allow to user to choose a file to later copy the URL of it. However, JFileChooser only shows up sometimes I run the program (?).

I do not understand what is wrong with the code. Thanks in advance.

More clearly: The UI of the JFileChooser does not show up.

    String readThisGlos = null;

    JFrame parentFrame = new JFrame();
    JFileChooser fileChooser = new JFileChooser();
    int userSelection = fileChooser.showOpenDialog(parentFrame);
    if (userSelection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = fileChooser.getSelectedFile();

        readThisGlos = fileToSave.getAbsolutePath();
    } else {
        // Error
    return readThisGlos;

Edit: I know the method is running, because when I put a System.out.println("//something"); in the beginning of the method, it works.

If I put System.out.println("//something"); between fileChooser and int userSelection, the UI shows up.

How to Upload Multilevel Files in Php? [duplicate]

This question already has an answer here:

I have a form in in that i have to upload images. below is my form.

<form method="post" action="<?php echo $this->url(array('controller'=>'practice','action'=>'save-multiple-img'),'azend');?>" enctype="multipart/form-data">
<input name="name" type="text" />
  <input name="file['f_plan'][1][]" id="file" type="file"  />
  <input name="file['f_plan'][1][]" id="file" type="file"  />
  <input name="file['f_plan'][1][]" id="file" type="file"  />
  <input name="file['f_plan'][2][]" id="file" type="file" />
  <input name="file['f_plan'][2][]" id="file" type="file"  />
  <input name="file['f_plan'][3][]" id="file" type="file"  />
  <input name="file['f_plan'][3][]" id="file" type="file"  />
  <input type="submit" name="upload_images" value="Upload Images">

in My controller

  $apt    = new Zend_File_Transfer();
    $files  = $apt->getFileInfo();
    $post = $this->getRequest()->getPost();
    //$filterChain = new Zend_Filter();//print_r($_FILES['file']);die();
    foreach($_FILES['file']['name'] as $key => $tmp_name){
        foreach($tmp_name as $k => $value) {
            $apt->addFilter('Rename', array('target' =>$post['name'],'overwrite' => true,'cropToFit'=>true));
             if ($apt->receive()) {
             echo 'not uploaded<br>';die();


While uploading files im getting Warnings like

Warning: file_exists() expects parameter 1 to be a valid path, array given in C:\xampp\htdocs\azend\library\Zend\File\Transfer\Adapter\Abstract.php on line 1283
Array to string conversion in C:\xampp\htdocs\azend\library\Zend\Validate\Abstract.php on line 233

Please Help me How to Upload these type of files!! Thanks in Advance

C++ fread reads random characters at the beginning of the file

I have an input file like;


and I read it like this;

char a[5];
fread(a, sizeof(char), 5, input);

But when I try to print

cout << a;

it writes random characters at first like


Solaris append data into binary file

The configuration is listed below: Sun C5.12 SunOS_i386 2011/11/16 Oracle Solaris Studio 12.3

We try to append data at the end of a binary file with ofstream class. Original code is here:

unsigned long uRes = 0;
std::ofstream binFile;, ios::out | ios::binary | ios::app);
    binFile.seekp(0, ios::end); // Useless regarding ios::app flag ?
    binFile.write(reinterpret_cast<char*>(&mVector[0]), mVector.size() *  sizeof(T));
    if( binFile.good())
        uRes  = static_cast<unsigned long>(binFile.tellp() / sizeof(T));
return uRes;

But under Solaris, writing pointer is always set at the beginning of the output file (data is only overridden).. So we wrote the same function in C mode:

unsigned long uRes = 0;
FILE* pFile = NULL;
pFile = fopen(filename.c_str(), "a+b");
if( pFile )
    fseek( pFile, 0, SEEK_END );  // SEEK IS MANDATORY (flag "a" isn't interpreted)
    fwrite(&mVector[0], sizeof(T)*mVector.size(), 1, pFile);
    uRes = ftell( pFile )/ sizeof(T);
    fclose ( pFile );
return uRes;

This code works only if we seek manually after opening the file ("a" flag is ignored)

Is there a logic explanation about that? I think there is a lot of problems with stream. For example stream destructor doesn't close pointed file (close should be called directly to be sure that file is correctly closed (with stream operation)) But it is another subject.

Thanks in advance for your feedback

The fastest way to read binary files by bytes in Python

I am making a program, which should be able to encode any type of file using huffman algorithm. It all works, but using it on large files is too slow (at least I think it is). When I tried to open an 120MB mp4 file to unpack it, it took me about 210s just to read the file. Not to mention that it took a large chunk of memory to do so. I thought unpacking using struct would be efficient, but it isnt. Isn't there more effiecent way to do it in python? I need to read any file by bytes and then pass it to the huffman method in string.

if __name__ == "__main__":
    start = time.time()
    with open('D:\mov.mp4', 'rb') as f:
        dataL =
    data = np.zeros(len(dataL), 'uint8')

    for i in range(0, len(dataL)):
        data[i] = struct.unpack('B', dataL[i])[0]


    end = time.time()
    print("Original file read: ")
    print end - start

    encoded, table = huffman_encode(data)

What's the use of TempFileCollection.AddExtension if it doesn't return unique names?

I need to create three temporary XML files for debugging purposes. I'm using a TempFileCollection as it fits the bill, but apparently the AddExtension method doesn't actually return unique file names.

According to the MSDN:

This method can be called only once for each file name extension, because it will return the same name if it is called with the same extension.

Apparently I just have to add my own files anyway using the AddFile method. What's the use of this method then? To work around it I'm just using

var filename = Guid.NewGuid().ToString + ".xml"
collection.AddFile(filename, false);

How to read and update(increment) a value in a file with shell commands

I have a certain file which contains many contents, including a line from the format (for example)

ABC = "x12"

What I need to do is to increment the value, so that after the command it will be

ABC = "x13"

The file itself needs to be updated, no need to create a new file or something similar.

Your help is much appreciated.

Why is the file I'm printing being cut off?

So I'm writing a primitive file browser program which is supposed to, at this point, take the contents of a file sample.txt and output: "After a few computer science courses, students may start to get the feeling that programs can always be written to solve any computational problem. Writing the program may be hard work. For example, it may involve learning a difficult technique. And many hours of debugging. But with enough time and effort, the program can be written. So it may come as a surprise that this is not the case: there are computational problems for which no program exists. And these are not ill-defined problems (Can a computer fall in love?) or uninteresting toy problems. These are precisely defined problems with important practical applications. Theoretical computer science can be briefly described as the mathematical study of computation. These notes will introduce you to this branch of computer science by focusing on computability theory and automata theory. You will learn how to precisely define what computation is and why certain computational problems cannot be solved. You will also learn several concepts and techniques that have important applications. Chapter 1 provides a more detailed introduction to this rich and beautiful area of computer science. These notes were written for the course CS345 Automata Theory and Formal Languages taught at Clarkson University. The course is also listed as MA345 and CS541. The prerequisites are CS142 (a second course in programming) and MA211 (a course on discrete mathematics in which students also gain experience writing mathematical proofs)." However the output cuts off after the word gain. Does anyone know how I could get this function to output the full file? I know it's probably something small that I'm missing. I am attaching the function I've programmed to open this file below:

bool Buffer::open(const string & new_file_name)
    std::ifstream file(new_file_name);
    if (!file) return false;

    // Note: the vector is cleared only after we know the file
    // opened successfully.

    string line;
    string word;

    while(file >> word)
        if((line.size() + word.size() + 1) > max_line_length)
            line = "";
        line.append(" " + word);
        if(file.peek() == '\n')
            word = file.get();
            if(file.peek() == '\n')
                line = "";
    file_name = new_file_name;
    ix_top_line = 0;
    return true;

What is purpose of .dtr file

I have a .dtr file. It has one input and one output.

While the output file is getting created, some values from input file are manipulated.

I want to check how these values are manipulated. I don't know how to read the code in .dtr file. Can you please help me?

How to read word from binary file

I have some character strings stored in binary file and I want to retrieve that data back in same format when stored.

For example "hello world" is stored in binary and I want to read it back. Any suggestions?

How to access the file in The rails project by gem?, 'config/global_nav_data.yml'))

The rails project where my gem got installed will have some file inside config folder. I have to get that file in the project. I tried the above but it is fetching file in the gem not in the project .

android delete old cache data programmatically

I'm using android disk cache to cache all images loaded from server.

I want to delete all those cache images that has not been used for atleast 2 weeks and keep the remaining.

Here's my code to add cache Images

public void addBitMaptoCache(String key,Bitmap bmp)
    Log.e(TAG, "Cache Creation Running");

    if(null != defaultBitmaps){
        for(Bitmap dbmp:defaultBitmaps){




                File destination = new File(directory, key + ".jpg");

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

                FileOutputStream fo;
                try {
                    fo = new FileOutputStream(destination);
                } catch (FileNotFoundException e) {
                } catch (IOException e) {

                destination = new File(directory, key + ".jpg");

                    Log.d(TAG, "Cache Created");
                    Log.e(TAG, "Cache not Created");


Any help is welcome... let me know if you need any more details...

jeudi 29 octobre 2015

how to detect when cancel upload file on mobile by javascript?

Im making upload image from mobile to website. When user click on upload button i will disable "save" button until image is uploaded. But when user cancel upload after click on upload button, i dont know how to detect that event to enable "save" button. I found this solution How to detect when cancel is clicked on file input? But It's only work on desktop. On mobile, cancel action is total different.

Will merging several files into one using command prompt from windows not affect the data inside those files?

Im trying to consolidate various rpt files into one so that I could do my data analysis quickly. The script I used through the windows cmd are as follows:

cd "d"\work files\colors\finished" 

copy *.rpt consolidated.rpt 

Since I'm dealing with figures here, I'm wondering if my data on the consolidated rpt is still accurate considering that it had undergone through that cmd thing? Like for example in the case of formatted excel files (.xlsx), the data are destroyed once I used the code above.

TypeError: expected a character buffer object in Python

I don't know why I can't write this document to file:

document=['', 'feeling frisky cool cat hits join us', 'askjoe app add music videos free today saintkittsandnevis', 'give dog flea bath midnight greeeeat smells like dawn', 'cat finds flash drive spent weeks looking', 'downside cat dude means can recognize nice smell pee second', 'louis pine apple make life brighter like star please follow me', 'gonna need nice cup coffee morning', 'gonna need nice cup coffee morning', 'iphone gives warning dies smh']

Here's the code for writing into the file:

with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:

Here's the error I get:

Traceback (most recent call last):
  File "", line 85, in <module>
TypeError: expected a character buffer object

readfile count increase issue

my code:

  while (stream.hasNext()) {
        name =;

        if (name.equals(nextName)) {
            for (int i = 1; i < 4; i++) {
                if (i == 3) {
                    if (name.charAt(0) == 2 || name.charAt(0) == 3) {

it is reading a file like this:


I am trying to keep a total of how many times each name is listed under each number, but instead it is racking up the names in the whole file under each number, and counting the total number of names 3 times for the total...?

R - split data frame and save to different files

I have a data frame with monthly temperature data for several locations:

    > df4[1:36,]
       location    variable cut month year freq
1    Adamantina temperature  10   Jan 1981 21.0
646  Adamantina temperature  10   Feb 1981 20.5
1291 Adamantina temperature  10   Mar 1981 21.5
1936 Adamantina temperature  10   Apr 1981 21.5
2581 Adamantina temperature  10   May 1981 24.0
3226 Adamantina temperature  10   Jun 1981 21.5
3871 Adamantina temperature  10   Jul 1981 22.5
4516 Adamantina temperature  10   Aug 1981 23.5
5161 Adamantina temperature  10   Sep 1981 19.5
5806 Adamantina temperature  10   Oct 1981 21.5
6451 Adamantina temperature  10   Nov 1981 23.0
7096 Adamantina temperature  10   Dec 1981 19.0
2        Adolfo temperature  10   Jan 1981 24.0
647      Adolfo temperature  10   Feb 1981 20.0
1292     Adolfo temperature  10   Mar 1981 24.0
1937     Adolfo temperature  10   Apr 1981 23.0
2582     Adolfo temperature  10   May 1981 18.0
3227     Adolfo temperature  10   Jun 1981 21.0
3872     Adolfo temperature  10   Jul 1981 22.0
4517     Adolfo temperature  10   Aug 1981 19.0
5162     Adolfo temperature  10   Sep 1981 19.0
5807     Adolfo temperature  10   Oct 1981 24.0
6452     Adolfo temperature  10   Nov 1981 24.0
7097     Adolfo temperature  10   Dec 1981 24.0
3         Aguai temperature  10   Jan 1981 24.0
648       Aguai temperature  10   Feb 1981 20.0
1293      Aguai temperature  10   Mar 1981 22.0
1938      Aguai temperature  10   Apr 1981 20.0
2583      Aguai temperature  10   May 1981 21.5
3228      Aguai temperature  10   Jun 1981 20.5
3873      Aguai temperature  10   Jul 1981 24.0
4518      Aguai temperature  10   Aug 1981 23.5
5163      Aguai temperature  10   Sep 1981 18.5
5808      Aguai temperature  10   Oct 1981 21.0
6453      Aguai temperature  10   Nov 1981 22.0
7098      Aguai temperature  10   Dec 1981 23.5

What I need to do is to programmatically split this data frame by location and create a .Rdata file for every location.

In the example above, I would have three different files - Adamantina.Rdata, Adolfo.Rdata and Aguai.Rdata - containing all the columns but only the rows corresponding to those locations.

It needs to be efficient and programmatic, because in my actual data I have about 700 different locations and about 50 years of data for every location.

Thanks in advance.

Possible oneliner for this Ruby on Rails code

I have a file object which is of type Rails ActionDispatch::Http::UploadedFile.

I need to overwrite user assigned filename with a generic name while preserving the extension of the file. This is how I have the code implemented currently. Is there are a way better and elegant way of writing this in Ruby.

extension = File.extname(file_name.original_filename)
file_name.original_filename = "hello#{extension}"

'Not a directory' error message with File::Copy::Recursive

Posting this because I spent too much time on it. I'd load like this

use File::Copy::Recursive;

and call it like this

$foo = File::Copy::Recursive->dircopy('foo', 'bar')::die($!);

and be rewarded with

Not a directory at someline.

Calling like that works great in many uses of File::Foo but not here. To make dircopy work, load it like this

use File::Copy::Recursive qw(dircopy);

and call it like this

$foo = dircopy('foo', 'bar')::die($!);

Don't blame me. I'm just showing how to make it work.

How to read Pipe delimited Line | from a File and Splitting Integers in two different ArrayList

The Program requires to interpret pipe delimited lines from a file and store it in two different ArrayLists. I have tried almost every related links on StackOverflow and came to know that | is a special operation and hence it is reserved. So I found several other ways to read the lines, but none of them actually works.

Here is my scenario:

The Text File looks like:


and so on...

The first Integer needs to go to ArrayList a1 and the second float number after the pipe delimiter need to go to ArrayList a2

I tried using scanner and them splitting the lines using split. Having saved them to a String and then doing the String conversion.I used following ways:

Method 1:

public static void readingFunc(String dirPath) throws  NumberFormatException, IOException{
    Path p = Paths.get(dirPath, "File.dat");
    for (String line: Files.readAllLines(p,StandardCharsets.US_ASCII)){
        for (String part : line.split("\\|")) {
            Integer i = Integer.valueOf(part);

Method 2:

try(BufferedReader in = new BufferedReader(new FileReader(dirPath+"/File.dat"))){
          String line;
          while((line = in.readLine())!=null){
              String[] pair = line.split("\\|",-1);

Method 3:

try(BufferedReader in = new BufferedReader(new FileReader(dirPath+"/File.dat"))){
          String line;
          while((line = in.readLine())!=null){
              String[] pair = line.split("\\|",-1);

I also used several other Methods such as Scanner and couldn't get the result. I have several files similar to the one above and I need to read them to save it in an ArrayList for their processing.

PS: one of the file is having three data like:


and so on. I guess. this would be easy and similar to the two delimiter process. PS: I am developing on Linux Eclipse IDE so paths are:


I am sending the path as dirPath from the main function and then calling it here in a function. Please suggest me how to go with it?

I have checked already following Links:

Java Null value causing issue when reading a pipe delimited file

Read a file and split lines in Java.

Java - Scanner : reading line of record separated by Pipe | as delimiter

Java - putting comma separated integers from a text file into an array

Obtain number of token in a string with java Scanner

Symfony VichUploaderBundle doesn't upload file neither write to database

I've been trying 4 times with no luck before post this issue.

I read the documentation carefully and after installing VichUploaderBundle I created my code to upload a song as follow:


namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

 * @ORM\Entity
 * @Vich\Uploadable
class Song
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
    private $id;

    // ..... other fields

     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * @Vich\UploadableField(mapping="song_track", fileNameProperty="trackName")
     * @var File
    private $trackFile;

     * @ORM\Column(type="string", length=255)
     * @var string
    private $trackName;

     * @ORM\Column(type="datetime")
     * @var \DateTime
    private $updatedAt;

     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $trackName
    public function setTrackFile(File $trackName = null)
        $this->$trackName = $trackName;
        if ($trackName) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTime('now');

     * @return File
    public function getTrackFile()
        return $this->trackFile;

     * @param string $imageName
    public function setTrackName($trackName)
        $this->trackName = $trackName;

     * @return string
    public function getTrackName()
        return $this->trackName;

     * Get id
     * @return integer
    public function getId()
        return $this->id;

     * Set updatedAt
     * @param \DateTime $updatedAt
     * @return Track
    public function setUpdatedAt($updatedAt)
        $this->updatedAt = $updatedAt;

        return $this;

     * Get updatedAt
     * @return \DateTime
    public function getUpdatedAt()
        return $this->updatedAt;


namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Song;

class UploadTrackController extends Controller
     * @Route("/uploadtrack", name="uploadtrackform")
    public function indexAction(Request $request)
      $track = new Song();
      $form = $this->createFormBuilder($track)
          ->add('trackFile', 'file')
          ->add('save', 'submit', array('label' => 'Upload File'))

        return $this->render('default/uploadtrack.html.twig', 
            'form' => $form->createView(),


{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

I can see the form, upload a file and the controller is triggered correctly. I don't get any errors but neither the file is copied in the folder or the data persisted to the database.

You can see in my Entity I have a var_dump which is actually containing an error property. Once the form has been submitted this is what I get from that var_dump:

object(Symfony\Component\HttpFoundation\File\UploadedFile)#13 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(24) "Domenico_Graziano_CV.pdf" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(15) "application/pdf" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(186992) ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0) ["pathName":"SplFileInfo":private]=> string(66) "/private/var/folders/1g/4t5n9rhj0_s_9tnstpjj6w_w5wl8pn/T/phpptwjZH" ["fileName":"SplFileInfo":private]=> string(9) "phpptwjZH" }

It seems to me that the file is stored temporally somewhere but never copied in the folder and therefore no data is persisted to the db by doctrine.

Sorry if I didn't find a way to be more concise, but this question is mainly for those who have experience with Symfony and VichUploaderBundle.

Thank you in advance

Just in case you were wondering what are the config for the bundle, here we go:

#VichUpload config
    db_driver: orm # or mongodb or propel or phpcr
            uri_prefix:         /upload/tracks
            upload_destination: %kernel.root_dir%/../web/upload/tracks

Is there a fast way to get all files names and paths using C#, like everything search app?

I'm trying to get all files paths and names to index them in my database for faster search in future. i have used multi-threading , and parallel class of C# but i'm couldn't get the performance i expected. there is an app named "Search Everything" , its amazing. it indexes all my files in less than 2 minutes, but my code takes longer A LOT. I checked the windows task manager and it was my hard drive limiting my code it was getting to 100% of usage. i know that's normal but how everything search did that? is there another way, maybe reading data from master file table or something? i'm confused.

here is my code :

void GetFiles(string dir)
            Task.Factory.StartNew(() =>
                    Task.Factory.StartNew(() => {
                        Parallel.ForEach(Directory.EnumerateDirectories(dir), single => {
                catch { }

How python file objects are managed?

I think we can work with files in two ways: directly with the kernel (as a file's descriptor) and with pointers (on high level languages as C).

So, are files managed the same way in Python (like files pointer as in C for example)? Do we create a pointer to a file when using open() function in Python?.

Upload file to share folder using application account

I am working in WPF application and I have a requirement to upload document to share folder using service/application account (application specific user credential). None of the user have access to share folder but only the service/application account can access the shared folder. Can any one help me how can I implement this functionality?

I am using Visual Studio 2013 and C#.

Thanks Selvakumar R

Read PPM files RGB values c++

I´m trying read from a PPM file. I want to read the first, second and third number from each row, in this file, but i don´t know how to read the lines.

This is what i have so far:

    for (int y = 4; y <= HEIGHT; y++) { // i think it has to start on row 4 
            for (int x = 1; x <= WIDTH; x++) { // and x from 1

            int r = CurrentR(x * y);
            int g = CurrentG(x * y);
            int b = CurrentB(x * y);

            img << r << " " << g << " " << b << endl;

int CurrentR(int xy) {
    return // the first number in row xy
int CurrentG(int xy) {
    return // the second number in row xy
int CurrentB(int xy) {
    return // the third number in row xy

Correct me if i´m wrong of course.

How to read a multiple String values from text line and store them to a String (java)

My problem is that, I want to read line by line from a text file in java, one line consist of 4 fields but one field can contain multiple words, For Ex.: I have this line: Screen Commercial Problem with product

How can I store this three fields of my line into 3 String variables in java?

var1 -> "Screen"
var2 -> "Commercial"
var3 -> "Problem with product"

Thanks in advance!!!!!!!!

Perl: merge specific columns from multiple files from a directory

I have a number of files in a directory, say dir:

dir/three.out and so on 

Each file looks like this:

Chr Pos     Ref   Depth A   T   G   C   a   t   g   c
10  1156771 C     61    0   0   0   36  0   0   0   25
10  3748402 C     68    13  0   0   26  12  0   0   17
10  7848320 T     57    0   31  0   0   0   26  0   0

I just want to get the Chr, Pos, Ref, Depth from each file and merge it like this:


Chr Pos     Ref Depth.two Depth.three
10  1156771 C   61        60        65
10  3748402 C   68        70        73

Any suggestions how to do it in perl? Thanks!

Processing two text files into a python matrix

A chocolate company has decided to offer discount on the candy products which are produced 30 days of more before the current date. I have to have a matrix as a print result where the program reads through 2 files, one being the the cost of the different candies of different sizes, and another being the threshold number of days after which the discount is offered. So in this question the two text files look something like this


31 32 19 11 15 30 35 37
12 34 39 45 66 78 12 7
76 32 8 2 3 5 18 32 48
99 102 3 46 88 22 25 21
fd zz er 23 44 56 77 99 
44 33 22 55 er ee df 22

and the second file days.txt

Discount at days = 30

It should print

      $  $  $         
$                $  $ 
      $ $ $ $  $      
       $       $  $  $ 
?  ?  ? $       
      $     ?  ?  ?   $      

So basically, everywhere the number is under 30(which is the input from days.txt) it should print a "$" sign and everywhere it is more than the number(30 in our case) it should just print spaces in their place. We also have an anomally, where we have the english alphabets in the candies.txt matrix and since we are looking for numbers to check the price and not letters, it should print a "?" sign in their place as it is not recognized.

Here is what I am trying to do.

def candyShop(candy, price):
        candyfile = open("candes.txt", "r")
        readCategory = process_file(candyfile)
        if readCategory str.isdigit():
            if readCategory > 30:

    return candyShop()

Recover Python file

My computer cut out whilst I was working on a .py file in Idle. I had saved it numerous times, but when I turned my computer back on the file was completely blank. Despite being completely empty in Idle, the file registers as 40KK, which couldn't be possible if there was nothing in it. I'm on Windows 10, and have tried "restore previous options"; nothing came up. I have no file history or backup drive setup. Is the file recoverable, and if so, how?

python - auditing lines from a file

I am trying to audit a file and store the results for each section, here is the file sample:

-------------- Task 1 -------------- Device Name: hostname_A
Status: Completed
Results: Action completed successfully...

****** Enable Mode Results ******
hostname_A#show run | in abcd
hostname_A#show ip access-list 1
Standard IP access list 1
    10 permit
    20 permit
    30 permit

-------------- Task 2 -------------- Device Name: hostname_B
Status: Completed
And so on...

And here is the Code I´ve created so far, but struggling to get it working:

with open("file_to_be_audited.txt", "r") as infile:
    with open ('audited_file.txt', "w") as outfile:
        for line in infile:
            if '--- Task' in line:           #seeting a line/section delimiter
                for each_line_in_Task_Block: #trying to check/audit each line of that section
                        device_dict = {}
                        device_dict['hostname'] ="Device Name: (.+)", each_line_in_Task_Block) # trying to store the DeviceName
                        if 'abcd' in line:
                            device_dict['community'] = 'Passed'
                            device_dict['community'] = 'Failed'

                        if '' and '' in each_line_in_Task_Block:
                            device_dict['ACL'] = 'Passed'
                            device_dict['ACL'] = 'Failed'

                    field_order = ('hostname', 'community', 'ACL')
                    for i in field_order:

There are a lot of '--- Task ---' sections, the idea is to check and store the results of each 'Device Name' in another file. I am trying to get a better and working way of doing it. Any suggestion ? Thank you !

How to write URL as a link in file

I've made a web browser in windows form now i want to save the Urls as links in my history.txt file address = txt_search.Text;// Storing Address from the Search TextBox Textbox2.goToPage(); Function created to extract html from web

          using (tw = new StreamWriter(@"History.txt", true)) //Filing to store the History, File will be made in Debug Folder

            tw.WriteLine(address);// Writing Address on text file


How to edit specific line of code in a bat file java

I wonder for a project of mine: how do i edit a specific line of code in a bat file, using java? Say the file is in the src folder, and contains the text:

cd C:\Users\User\
start example.exe

So, how can i edit the "User" in the cd, in line 1? Thnx in advance.

File upload not working online PHP

I have a question. i got an uploadingpage for files. It is working with ajax. When file is selected a php script will start. There's a problem with moving the file to the directory. This is my indexpage(sorry it is an image because my code is not properly formatted or something???)

enter image description here

enter image description here

Strange is that the upload works fine offline but on the server it doesn't. Can someone please help me.

Thank you

Javascript Drag and Drop DataTransfer Files don't have type

So I'm trying to use drag and drop with IE11 (all browsers really, but the bug is in IE). I only want certain kinds of files uploaded, and no folders.
When I get into the drop event, I scan the array to make sure that we are only processing files that are supported, and no folders.
Well I got some weirdness that is happening when I try to drag and drop a javascript file. When I check the files array, and specifically look at the type property on the FileObject in the file list, I have no type. Specifically I have a type of "" (empty string).
On every other browser, I am able to read the type and determine what it is. However, it's just on IE that I'm having this trouble.

Why does type property not exist on javascript files from a drop event? Could it just be this machine? If so, what could cause this?

Best way to chunk a large string by line

I have a large file (400+ MB) that I'm reading in from S3 using get_contents_as_string(), which means that I end up with the entire file in memory as a string. I'm running several other memory-intensive operations in parallel, so I need a memory-efficient way of splitting the resulting string into chunks by line number. Is split() efficient enough? Or is something like re.finditer() a better way to go?

How to read a matrix from text file and store it into 2D array?

I am a beginner at this. I'm trying to read a file and put it into a 2D array. Here is my code. after it outputs the file it displays the garbage in the memory and the loop never ends unless it hits 50.

include "stdafx.h"
#include <iostream> 
#include <fstream>  
using namespace std;

void main()
    char arr[50][50];
    ifstream fin;"Map.txt");

    for (int i = 0; i < 50; i++)

        for ( j = 0; j < 50; j++)

    for (int i = 0; arr[i]!=NULL; i++)
        for (int j = 0; arr[j]!=NULL; j++)
            cout<< arr[i][j];


How to Delete line from File using Java?

We should make Hospital Mangement System with Java and we have a proplem to delete a line from a File

Laravel 5 Reading and Writting Text Files

Hi am working on a Laravel 5 System. I need to open a text file let's say located on


in row.txt the only content is lets say


And I want laravel to read that and get it then increament it by 1. So I it will be 1345. I want to do it inside a controller from with sql and upload to app_data

i want to make a form for job application which save the personal details in database and a file(cv) to app_data, i can save the personal details to sql db but i can not save the file to app data,help meeeeeeeeeee model

[Required(ErrorMessage = "Required")]
public string Name { get; set; }

[Required(ErrorMessage = "Required")]
[RegularExpression(@"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$", ErrorMessage = "Must be valid email")]
public string Email { get; set; }

[Required(ErrorMessage = "Required")]
public string Comments { get; set; }

[Required(ErrorMessage = "Required")]
public HttpPostedFileBase file { get; set; }


public ActionResult SaveDataContact(ContactModel f)
            if (ModelState.IsValid)
                if (f.file != null && f.file.ContentLength > 0)
                    // extract only the filename
                    var fileName = Path.GetFileName(f.file.FileName);
                    // store the file inside ~/App_Data/uploads folder
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

                int i = D.DataInsert("INSERT INTO table_cont(Name,Email,Comments) VALUES ('" + f.Name + "','" + f.Email + "','" + f.Comments + "')");

chtml form view

@using (Html.BeginForm("SaveDataContact", "Contact", new { enctype = "multipart/form-data" }, FormMethod.Post))


@Html.LabelFor(model => model.Name)<br/>
@Html.TextBoxFor(model => model.Name)<br />

@Html.LabelFor(model => model.Email)<br />
@Html.TextBoxFor(model => model.Email)<br />

@Html.LabelFor(model => model.Comments)<br />
@Html.TextAreaFor(model => model.Comments)<br />

<label for="file">Upload your Cv:</label>
<input type="file" name="file" /><br />

The consistency of sequential file operations

The story:
A few days ago I was thinking about inter-process communication based on file exchange. Say process A creates several files during its work and process B reads these files afterwards. To ensure that all files were correctly written, it would be convenient to create a special file, which existence will signal that all operations were done.

Simple workflow:
process A creates file "file1.txt"
process A creates file "file2.txt"
process A creates file "processA.ready"

Process B is waiting until file "processA.ready" appears and then reads file1 and file2.

File operations are performed by the operating system, specifically by the file subsystem. Since implementations can differ in Unix, Windows or MacOS, I'm uncertain about the reliability of file exchange inter-process communication. Even if OS will guarantee this consistency, there are things like JIT compiler in Java, which can reorder program instructions.

1. Are there any real specifications on file operations in operating systems?
2. Is JIT really allowed to reorder file operation program instructions for a single program thread?
3. Is file exchange still a relevant option for inter-process communication nowadays or it is unconditionally better to choose TCP/HTTP/etc?

Methods to Save/Load Specific Elements of many Objects

I have a bunch of objects that contain specific variables I need to save and then later load.

The Objects all Contain Much more data then what is needed when they are loaded, but are used while program was running before (stuff that is needed over a few methods to setup all the initial data)

Here's an Example of what I am trying to save

Not valid code (Just representation of the Objects and Children of Objects)

            string entry_status
                string rating
                string date

` hashtable contains Many eh_entry (to make searching through them much faster)
details_pane is essentially just a tablelayoutpanel populated with label's. It uses custom get/set methods like the following

public string rating
    get { return rating_label.Text.Substring(8, rating_Label.Text.Length); }
    set { rating_label.Text = "Rating: " + value; }

If I should post the full classes of the custom objects I can, however They are very long and are probably not very easy to look at (I Only started up with C# about 2-3 months ago).

Essentially I need to create a file that contains parts of an object, and parts of its children objects.

PS:I need to be able to load the data back into an eh_entry and then place that eh_entry back inside a Hashtable.
Speed is a bit of an issue as well, mainly since there are so many eh_entry, the program creates about 20-25 per 1-3 seconds until it finishes scraping data, which is around 2.5million objects inside the Hashtable.

Should I create a separate class that contains Only the data I need to save, and then use it to save/load the data?

Also for something of this size, Should I be planning to use JSON, XML, binary or SQL?

Update new dba credential in batch file

how to update DB batch file in database with new dba credential and delete the previous Dba details. please help .

mercredi 28 octobre 2015

Mac: Tomcat unable to create directory folder in webapp

I have a Spring MVC web app. My Spring controller has a code to build a folder inside the web application itself. However, I am getting exception that the directory could not be created.

I understand that its some permission issue with tomcat but am not sure how to provide permission.

I am new to this. I am using Mac and tomcat-8 resides inside /Documents folder.

Please help.

How can I make a file open in my application using C#?

I would like to open a file in my application when a user clicks the file in windows file explorer. I would like to have an icon for the file also. I know how to open my file by using the open file dialog so how does it work when the user clicks the file in a file browser and how can I make my software respond to this?

The file is called a .focl. file "File Organizer Check List". What it does is stores the info of the names of the items of a check list box in text. When the file loads, the software separates the whole string in the text file between every "|" and every part of the split text becomes the name of an item item.

Processing values in each text file one at a time c++

I'm trying to processes values from two text files.One holds a set of chars and the other holds a set of integers.each in their respective places in the text file will amount to one test case.For example the first value that is read in each text file is 1 test case.The values are then used to be checked for variability then Which will then be used as variables through out my code.then in the end prints out a double. The issue is I do not know how to reach that second iteration of test cases. All my code does is read the first values of each text file and prints out the double i need but for only the first test case. As i was typing this out i thought of maybe deleting the values once they are done being used then rerunning the program by having my main in a for loop? suggestions?

#include <iostream>
#include <fstream>
using namespace std;

//function prototypes
char getPackage();
bool vaildPackage(char);
int getHours();
bool validHours(int);
double calculatePakg_A(int);
double calculatePakg_B(int);
double calculatePakg_C(int);
void showBill(double);
int main()
    char Package = getPackage();
    int Hours = getHours();
    double bill;
    switch (Package)
    case 'A':bill = calculatePakg_A(Hours);
        cout << bill << endl;
    case 'B':bill =  calculatePakg_B(Hours);
        cout << bill << endl;
    case 'C':bill = calculatePakg_C(Hours);
        cout << bill << endl;
    case 'a':bill = calculatePakg_A(Hours);
        cout << bill << endl;
    case 'b':bill = calculatePakg_B(Hours);
        cout << bill << endl;
    case 'c':bill = calculatePakg_C(Hours);
        cout << bill << endl;
    default: cout << "you did not enter a valid Service Plan. \n";

    return 0;
char getPackage()
    ifstream inputFile;
    char a;"Packages.txt");
    inputFile >> a;
  } while (! vaildPackage(a));
  return a;


 bool vaildPackage(char a)

    return a == 'a' || a == 'A'|| a == 'B' || a == 'b'|| a == 'C' || a ==      'c';
int getHours()
    ifstream inFile;
    int n;"Hours.txt");
  inFile >> n;
} while (! validHours(n));
return n;

bool validHours(int n)
    return n>=0 && n<= 720;

double calculatePakg_A(int hrs)
    if(hrs <=50)

       return 15.00;
       return (hrs-50) * 2.00 + 15;
double calculatePakg_B(int hrs)
    if(hrs <=100)
        return 20.00;
        return (hrs-100) * 1.50 + 20.00;

double calculatePakg_C(int hrs)
    if(hrs <=150)
       return 25.00;
       return (hrs-150) * 1.00 + 25.00;



A a B b C c e c


50 51 100 101 149 251 750 722

Error Creating a PDF using iText

I am relatively new to Java and Android. Having said that I am using the iText.jar file in my app to create a PDF from data entered by the user. I am starting with the basic example just to see how it works and play with it. For some reason, I either get errors, either it is read only or it does not exist. Hoping someone has run into a similar problem with a fix. My code is below that I am using. I have added the permissions in the android manifest. I didn't include every bit of code, just the relevant stuff. The GlobalVars is a class I use to store all the public variables.Also, the toast statement I am using to help debug and is where I am getting these error messages......

<public static final File location =     Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);>

<try {
    } catch (FileNotFoundException | DocumentException e) {
        errorString = e.getMessage();
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();

<public void createPdf() throws FileNotFoundException, DocumentException {
    FileOutputStream pdfFile = new FileOutputStream(location.getAbsolutePath() + "/temp.pdf");
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, pdfFile);
    // step 3;
    // step 4
    // step 5

public static PdfPTable createDataTable() {
    // a table with two columns
    PdfPTable table = new PdfPTable(4);
    // the cell object
    PdfPCell cell;
    // we add the cells with table.addCell()

    for (int x = 0; x < 40; x++) {
        cell = new PdfPCell(Phrase.getInstance(x + ": " + GlobalVars.inspectionResults[x]));
    return table;

Issue reading variables from a file

I have a file with just one line

"P00321 A 9"

I need to bring each of these in as 3 individual variables, but it seems they aren't being read correctly with the code I have.

ifstream inFile;
int hours;
string accountnum;
char servicecode;

inFile >> accountnum >> servicecode >> hours;

If I cout these accountnum comes up blank, servicecode comes up as an underlined @ symbol, and hours is a long decimal number.
What am I doing wrong?

Reading a file's ints but skipping non int strings

I'm a serious noobie here trying to learn this shit. I am in college and this is an assignment so I dont want any serious code written, just a push in the right direction.

I have an input txt file with one word per line. Some are numbers, the rest are words. I can not figure out how to record just the numbers as ints and the rest as strings!

I tried the following:

month = stream.nextInt();

The first variable in the txt file is an int and then there are like 10 lines of strings before another int. But it will only store the first value as an int and then terminates the loop, rather than eventually store the next int!

Not reading file from environment path

I have create a project in which I am trying to generate a .txt file and then calling OS specific commands (I'm using unix so using system() function to trigger application) to open it in default application.

My code works perfect.

But the problem starts when I try to run my application after setting it in environment path. I am doing that for global visibility. File gets generated correctly by while opening the .txt using system() seems like it is trying to look at it at different directory.

I want to some how convey to the system() function to look at the specific location.

How can I solve this problem?

C++ folder opening and file counting

So this is my code but I cant prevent it from printing out: . .. and it counts them as a file. I couldnt understand why. The output is: . 1files. .. 2files. course3.txt 3files. course2.txt 4files. course1.txt 5files.

But there are only 3 files... It should say 3 files instead it counts that . .. and i dont know its meaning.

int folderO(){
DIR *dir;
struct dirent *ent;
int nFiles=0;
if ((dir = opendir ("sampleFolder")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    std::cout << ent->d_name << std::endl;
    std::cout << nFiles << "files." << std::endl;
  closedir (dir);
else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;


Unable to print file contents in swift

I'm back once more with another issue. In my attempt to learn swift Ive decided that writing a bunch of small, random, playground scripts, that i can go back and use as references later on is a good place to start.


What I'm working on now, is a small script that uses 2 different ways to read the same file, printing the file contents when finished.

Using quite a few tips I found here on stack (aswell as the official docs) Ive managed to piece together a script that should do the above goal. (Please excuse the heavy commenting, as these are references)

//Import for use of NSString
import Foundation

//Set file locations
let location = NSString(string:"/Users/me/Desktop/file.txt").stringByExpandingTildeInPath
//Make fileContent = data within file
let fileContent = try? NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding)
//print content of file
print("The file contains:\n", fileContent, "\n")

//set filename
let filename = "file.txt"
//set document path
let documentsPath = "/Users/me/Desktop"
let destinationPath = documentsPath + "/" + filename
//read file
let data: NSData? = NSData(contentsOfFile: destinationPath)
print("The file contains:\n", data, "\n")


I have created the file in the given location, Yet no matter how i try to work either bit of code, I recieve 'nil' as my file contents (which is simply 'hello world')

The file is a simple text file, UTF8 made with textwrangler. There is no free space before or after my string in the file. Any ideas would be greatly appreciated.

Correct way to extract array data from binary?

There is a classic way to embed resource files as a C language array into a binary file, so that we can store some external resource files such as .jpeg or .txt files into a binary.

For example, in the header file we can define an array:

const unsigned char xd_data[] = {

which contains the contents of the resource file, and it will be compile into the final binary.

There are lots of tools and tutorials on the web about this old trick, such as:, and

However, looks like most of these pages are talking about how to embed the data into binary file using C style array.

My question is, what is the correct way to find the start address of the resource files in the final binary in order to extract them?

how to keep using malloc?

I have a file which stored a sequence of integers. The number of total integers is unknown, so I keep using malloc() to apply new memory if i read an integer from the file. I don't know if i could keep asking for memory and add them at the end of the array. The Xcode keeps warning me that 'EXC_BAD_EXCESS' in the line of malloc(). How could i do this if i keep reading integers from a file?

int main()
    // from file
    int *a = NULL;
    int size=0;
    //char ch;
    FILE *in;

    //open file
    if ( (in=fopen("/Users/NUO/Desktop/in.text","r")) == NULL){
        printf("cannot open input file\n");
        exit(0);    //if file open fail, stop the program

    while( ! feof(in) ){
        a = (int *)malloc(sizeof(int));
        fscanf(in,"%d", &a[size] );;
return 0;

How to multiply 2 ArrayLists together?

My question is, how can I multiply two ArrayList(s) together? What I am trying to do is import two separate files (which contain 2d arrays) and put them into separate arraylists. From there I am trying to multiply these two array lists together and then have my output file be a 2d array of the the product of the inputted 2d arrays. In Short, I have two input files (each file is a separate two dimensional array) and I must take these two input files, and multiply them together. My output file should be a single 2d array.

So far my code looks like:

package Matrix;

import java.util.ArrayList;
import java.util.Scanner;

public class Matrix {

public static void multiply(File input_file1, File input_file2, File output_file) {

    try {
        Scanner scanner = new Scanner(input_file1);
        PrintWriter printer = new PrintWriter(output_file);
        ArrayList<Integer> file1 = new ArrayList<Integer>();
        while (scanner.hasNextInt()){

    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block

    try {
        Scanner scanner = new Scanner(input_file1);
        PrintWriter printer = new PrintWriter(output_file);
        ArrayList<Integer> file2 = new ArrayList<Integer>();
        while (scanner.hasNextInt()){
    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block