lundi 31 août 2015

Reset iteration index after using next() Python

I am trying to edit a text file using fileinput.input(filename, inplace=1) The text file has say 5 lines:

line 0
line 1
line 2 
line 3
line 4

I wish to change data of line 1 based on info in line 2. So I use a for loop

infile = fileinput.input(filename, inplace=1)
for line in infile:
 if(line2Data):
   #do something on line1
 else:
   line1=next(infile)
   line2=next(infile) 
   #do something with line2

Now my problem is after the 1st iteration the line is set to line2 so in 2nd iteration the line is set to line3. I want line to be set to line1 in 2nd iteration. I have tried line = line but it doesn't work. Can you please let me know how I am reset the iteration index on line which gets changed due to next

PS: This is a simple example of a huge file and function I am working on.

Efficient way to read data from Console & File in C

I have the following inputs, which contains both string & integer.I need to read it from the console

Vijay   25 35 45  
Ragul   22 33 44  
Ramu    45 24 34  
Faizal  21 34 56  
Ragu    78 98 34

Please suggest the most efficient way to read data from Screen.Also please suggest efficient way to read data from File.

Lottery Program (ArrayList)

I'm currently working on a program that mimics a lottery and reads the following information from a File the file includes:

5
Durant Kevin
1 15 19 26 33 46
Schofield Michael
17 19 33 34 46 47
Black Joe
1 4 9 16 25 36
Elroy Jetson
17 19 34 46 47 48
Simone Raven
5 10 17 19 34 47

I Scan in the contents of the File and created a Ticket object to hold the name and ticket number of one person however my problem occurs when I'm trying to put that information into an ArrayList any help would be appreciated.

Here is my code:

        try
    {
        Scanner scan = new Scanner(new FileInputStream(file));
        ArrayList<Ticket> info = new ArrayList<Ticket>();
        int lim = scan.nextInt();

        for(int i = 0; i < lim; i++)
        {
            String name = scan.nextLine();
            String num = scan.nextLine();
            String[] tarr = num.split(" ");
            int[] arr = new int[tarr.length];

            for(int j = 0; j < tarr.length; j++)
            {
                arr[j] = Integer.parseInt(tarr[j]);
            }

            info.add(new Ticket(name, arr[]);
        }
        scan.close();
    }

    catch(FileNotFoundException fnfe)
    {
        System.out.println("Error! The file was not found!");
    }

}

public class Ticket
{
    public String name;
    public int[] tarray;

    public Ticket(String name, int[] tarray)
    {
        this.name = name;
        this.tarray = tarray;
    }
}

How to upload file using Volley library in android?

I already have a sub class of Request that is used for http post to the server. The problem is, I have no idea on how can I add a parameter for a file. Posting string to the server is easy. but I need to add file as a different parameter. How can I do it?

public class AddNewPetRequest extends Request<JSONObject> {

    private Response.Listener<JSONObject> listener;

    public AddNewPetRequest(String url, Map<String, String> params,
                                Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(Request.Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public AddNewPetRequest(int method, String url, Map<String, String> params,
                                Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

UPDATE QUESTION: I follow the pattern of one of the answers here in stackoverflow and I came up with this implementation:

public class MultipartRequest extends Request<String> {

private MultipartEntity entity = new MultipartEntity();

private final Response.Listener<String> mListener;
private HashMap<String, String> mParams;


public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener)
{
    super(Method.POST, url, errorListener);
    mListener = listener;

    buildMultipartEntity();
}

private void buildMultipartEntity()
{
    entity.addPart("profile_picture", new FileBody(new File("/storage/emulated/0/Pictures/VSCOCam/2015-07-31 11.55.14 1.jpg")));
    try
    {
        entity.addPart("user_id", new StringBody("15"));
        entity.addPart("name", new StringBody("Bogs"));
        entity.addPart("gender", new StringBody("Male"));
        entity.addPart("date_birth", new StringBody("1999-12-5"));
        entity.addPart("breed", new StringBody("monkey"));
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

@Override
public String getBodyContentType()
{
    return entity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        entity.writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
    return Response.success("Uploaded", getCacheEntry());
}

@Override
protected void deliverResponse(String response)
{
    mListener.onResponse(response);

}

When I add this request to my request queue, it respond a com.android.volley.TimeoutError but if a check the data base, the request executes and add items to the table but the profile picture upload has only 1 byte of size. another problem, my database item added twice.

THIS THREAD IS CLOSED I already fixed this by setting its request time. what was happened is I am not able to get the response from my server after the default timeout of volley library so set my timeout by calling and setting this method to my Request Queue:

multipartRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 60, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

How to transfere a file between two linux servers with PHP? [closed]

I have downloaded a php libraby tha enables ssh2 connection to a linux server. I have already send some commands and which works fine. Now, Im trying to move a file beetween two linux servers. I have to connect to server A and transfere "file.tar" to server B. I tried:

ssh->exec("scp -P 22 file.tar.gz user@ip:/dir/");

And it response:

    Permission denied, please try again. Permission denied, please try again. Permission denied (publickey,gssapi-with-mic,password)

How can I do that step by step?

Thanks!

Django TemplateDoesNotExist at (but file exists)

I have an issue with template rendering.

Indeed django finds my templates files but each of them uses {% extends "base.html" %} and django does not find "base.html"

Django tried this path :

/home/gi-karna/hellodjango/tfjm2/inscription/templates/base.html (File does not exist)

and my template file is in :

/home/gi-karna/hellodjango/tfjm2/inscription/templates/inscription/home.html, error at line 2

It is real weird as the file "base.html" does exist at the first path. I don't know where the problem is.

I look forward to hearing from you soon

zero length read from file

I have two processes, one of which is writing (appending) to a file, the other is reading from it. Both processes are running concurrently, but do not communicate. Another reader process may start before the writer process has finished.

This approach works, but read() often returns having read zero bytes with no error. They ratio of zero length reads to non-zero length reads is high, which is inefficient.

Is there any way around this? This is on POSIX filesystems.

Opening multiple Non-Office files through VBA

This macro is suppose to open multiple Hyperlinked CAD files in a list on an excel document. I have to use this list (using excel cells, not a drop-down) for our infrastructure.

After the first instance is met and the first file opens, the code stops. I think this is because when a non-office application is opened, the macro stops because excel is not the active application at that point.

Sub OpenCadFiles()

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False


  Dim excel As Workbook
  Set excel = ActiveWorkbook

  Dim j As Long
  For j = 32 To 133 Step 1

If ActiveSheet.Cells(j, 14).Value <> "" And Rows([j]).EntireRow.Hidden = False Then

    URL = Cells(j, 14).Text
    'ShellExecute "explorer.exe " & URL, vbNormalFocus
    ThisWorkbook.FollowHyperlink URL
    excel.Activate
Else
End If
Next j

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

Are my assumptions correct, is this not possible to do in excel VBA? If not, does anyone know of a way to do this?

Excel VBA to answer Internet Explorer 11 download prompt, in Windows 10?

I am trying to automate downloading of .csv files from http://ift.tt/1biey7p using Excel 2010 VBA and Internet Explorer.

  1. How to automate answering the download prompt with Save?

  2. Before I get to the download part the VBA code needs to click on a button with this web html code:

<div class="button showHistory floatRight">Visa historik</div>

I am using this VBA code:

Set anchorElement = Document.getElementsByClassName("button showHistory floatRight").Item(Index:=1)
anchorElement.Click

This works when I step through the code but when I run it I get an error message on the line anchorElement.Click:

Object variable or With-block variable is not specified.

Any suggestions on 1 or 2?

Corrupted linux file owner groups

I was trying to give access to /var/www for apache with this command:

chown -R apache /var/www/

I have accidently ran:

chown -R apache /

and now I can even use sudo command, connect to mysql and etc. For example when I try to connect mysql, I got this error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) Is there anyway to reset all file owner grouos?

Qt: QDirIterator bug (search for files in a directory)

I search for png files in a directory in Qt:

digest = new QStringList();
QDirIterator it("my dir", QStringList() << "*.png", QDir::Files|QDir::NoDotAndDotDot|QDir::NoSymLinks, QDirIterator::Subdirectories);
while (it.hasNext()) {
   *digest << it.next();
}

But QStringList digest contains duplicates, for example: I have dir with name and file: /Users/mydir%47%name/01.png

But in digest there are two strings: /Users/mydir%47%name/01.png and /Users/mydir/name/01.png

What can be wrong?

Cordova input file crash

I'm developing a new Cordova Project. I'm trying to implement the file-transfer plugin.

For this, the first step is to get a FileChooser and gets the FileEntry of the file i have selected.

My problem is : When i try to implement an input file type, i have the dialog window that open and when i try to select a file and then 'OK', my application simply crash. i'm not able to catch the ERROR code.

Tried on Android 4.3 with CLI command : cordova run android.

ps: No need to tell me to use cordova-file plugin, it's not the purpose. Also tried.

Thanks a lot /

Check specific file has been modified using python watchdog

i would like to know how to check change of a specific file under a folder. I found that watchdog module could check change for files in folder but i need 1 file only (with fixed name).

Please kindly help on this and thanks.

class MyHandler(FileModifiedEvent):
    def on_modified(self, event):

if __name__ == "__main__":
        integrity_file_path = DATASTORE_DIRECTORY_PATH + '/schedule.xml'
        event_handler = MyHandler()
        observer = Observer()
        observer.schedule(MyHandler(), path=integrity_file_path,recursive=True)
        observer.start()

        try:
            while True:
                time.sleep(5)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

Does MATLAB's "uigetfile()", or equivilent, exist in python? [duplicate]

This question already has an answer here:

I know in MATLAB you can interactivly search for a file name and path using "uigetfile". Is there something similar in python?

Extract files to a folder vs copy files to a folder in PHP

I am trying to create a folder and copying the content from another folder. The total size of all files exceed 100 MB which gives me headache.

I am using linux hosting.

I used the following function to copy a folder content to another folder.

function recurse_copy($src,$dst)
{
    $dir = opendir($src);
    if (!is_dir($dst))
    {
        mkdir($dst, 0755);
    }

    while(false !== ( $file = readdir($dir)) )
    {
        if (( $file != '.' ) && ( $file != '..' ))
        {
            if ( is_dir($src . '/' . $file) )
            {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else
            {
                copy($src . '/' . $file,$dst . '/' . $file);
                //echo $file." moved successfully"."<br>";
            }
        }
    }
    closedir($dir);
    return 1;
}

The above function worked fine for sometimes. But sometimes, it gives 500 Internal server error.

I used set_time_limit(6000); before recurse_copy function called.

To do this copy work faster, I create a zip file and extracted the content to the folder using the below code.

$zip = new ZipArchive;
if ($zip->open('oldfile.zip') === TRUE)
{
    $zip->extractTo($new_file_folder);
    $zip->close();
    echo 'ok';
}
else
{
    echo 'failed';
}

But this code also gives me 500 Internal server error.

How to copy this large size files without error using one of these 2 files.

I saw the error_log but it didn't show any error.

.jff File Conversion OSX

I've been scowering the internet for a good portion of the morning trying to figure this out:

Using OSX, is there a way to either 1) Open a .jff file directly using a third-party software or 2) Is there any terminal command that has proven successful in converting such a file to a type recognizable to OSX?

IOS. Cannot load file from Parse: issue "Too Many Open Files" using getDataInBackgroundWithBlock

I am trying to retrieve image data stored in Parse, however when I do so, I get an error saying "too many open files" and it doesnt work.
It worked at first, with one image, but when I added a second one, it crashed. And now doesnt work anymore at all.

  if otherUser["profilePicture"] != nil {
                self.picProf =     otherUser["profilePicture"] as! PFFile
                self.picProf.getDataInBackgroundWithBlock({ (imageData: NSData?, error) -> Void in

                 if (error == nil) {
                 if imageData != nil {
                     oneMember.profilePicFile = imageData!
                                          } }
                           else {
                              print(error)
                                   }})
                                                }

Here is the error I am getting:

BOMStorageOpenWithSys(const char *, Boolean, BomSys *): can't open: '/Users/viktor/Library/Developer/CoreSimulator/Devices/X/data/Containers/Bundle/Application/Y/http://ift.tt/1LNL6a2' Too many open files 2015-08-31 15:12:48.856 MyAPP11[1669:68206] Error: CUICommonAssetStorage -initWithPath: No storage file found at '/Users/viktor/Library/Developer/CoreSimulator/Devices/X/data/Containers/Bundle/Application/Y/http://ift.tt/1LNL6a2' errno: 'No such process'

Do you have any idea how to resolve this excess of opened files ? I do not...

Thank you infinitely,

Multi-Access to file - Web Service

I've made a dynamic PDF file creator and every time I'll click a button it generate a new PDF file (removing the older) using data on a database.

My problem is that if I try to create a new PDF and the file is opened in any client the program can't edit the file.

Is there a way to create something like "sessions" that permit every user to edit the file at the same time?

P.S. Sorry for the bad english, I've tryed my best, I hope that someone edit my question in a proper way.

How to edit a text file that belongs to another domain using php?

Below is the code that I am currently using:

    $filename = "http://ift.tt/1VrucQc";
    $content = file_get_contents($filename);
    preg_match("#\d+#", $content, $before_editing);
    $number_before = $before_editing[0];
    file_put_contents($filename, ++$number_before);

    $content = file_get_contents($filename);
    preg_match("#\d+#", $content, $after_editing);
    $number_after = $after_editing[0];

Whenever the page is refreshed, the value of number.txt (which is always a number) is taken and increased by 1. It is then saved as the new value of number.txt.

This only works with my own domain.

Is there any way to edit that same file on example.com from another domain if the user links to that PHP file from a script?

<script type="text/javascript">(function(id) {
          document.write('<script type="text/javascript" src="http://ift.tt/1EvqTU6"></script>');
        });</script>

E.g.

If the user includes the javascript on a page on example.org, then number.txt on example.com will be edited.

How to read from a text file in python line by line

I have a text file that consists of points of 4 dimensions each point.

The file is like this:

4.8 3.4 1.6 0.2 
4.8 3.0 1.4 0.1 
4.3 3.0 1.1 0.1 
5.8 4.0 1.2 0.2 
5.7 4.4 1.5 0.4 
5.4 3.9 1.3 0.4 
5.1 3.5 1.4 0.3 

I want to read the file and store each line of the file as a seperate list.For instance point1=[4,8 3,4 1,6 0,2].

What I have done so far is :

f= open('points.txt', 'r')            
    data = f.readlines()

    for line in data:
        pList= line.rstrip()
        print (pList)

I get a list of all the points.

Unitialized member variables are are initialized when creating new object in loop

I am writing a program where lines are read from a file. Each line contains data about a "student". All of the code I am going to post might seem a bit excessive, but it really is a very simple program with a very specific bug, so I just included all of it so anyone could easily try it out on their own.

I think problem is in the while-loop in the StudentList constructor. A new Student object is created, and even though the member variables id and gpa of a Student object is not initialized in its constructor, they seem to be initialized with the values provided by the previous line in the file, that is, the values assigned to the object created in the previous loop of the while statement. But this should be impossible since the object is destroyed after each loop. More explanation and code below:

Header file to Student

// Student.h

#pragma once
#include<string>
#include<sstream>

/*
   Class representing a student. 
*/
class Student
{
public:
    Student(std::string studentInformation); 
    std::string getFirstName();
    std::string getLastName();
    std::string getName();
    int getId();
    double getGPA();

private:
    std::string firstName;
    std::string lastName;
    int id;
    double gpa;

};

Source file to Student:

// Student.cpp
#include "Student.h"
#include<iostream>

using namespace std;

/*
    Purpose: Constructs a student.

    @param studentInformation Can contain first and last name, id and gpa score. 
    All separated by whitespace.
*/
Student::Student(string studentInformation)
{
    // If no information about the student was provided:
    if (studentInformation.empty()) 
        cout << "THIS STUDENT IS EMPTY!" << endl;

    // Prints the object's id and gpa values. These should be uninitialized.
    cout << "current values gpa, id : " << id << ", " << gpa << endl;

    stringstream studentStream(studentInformation);
    cout << "chars in stream: " << studentStream.rdbuf()->in_avail() << endl;

    // Precaution just to check if there are any values to assign.
    if (!studentStream.rdbuf()->in_avail() == 0)
    {
        studentStream >> firstName;
        studentStream >> lastName;
        studentStream >> id;
        studentStream >> gpa;
    }
}


string Student::getFirstName()
{
    return firstName;
}

string Student::getLastName()
{
    return lastName;
}

string Student::getName()
{
    return firstName + " " + lastName;
}


int Student::getId()
{
    return id;
}

double Student::getGPA()
{
    return gpa;
}

Header file to StudentList

#pragma once

#include<string>
#include<vector>
#include<fstream>
#include<algorithm>

#include "Student.h"

class StudentList
{
public:
    StudentList(std::string filePath);

    Student getValedictorian();  // Not used here
    std::vector<Student> getHonorRollStudents();  // Not used here
    std::vector<Student> getFailingStudents();  // Not used here

//private:
    std::vector<Student> students;

};

Source file to StudentList

#include "StudentList.h"
#include<iostream>

using namespace std;

/*
    Purpose: Initializes a member vector that holds elements of type Student.
    The values to initialize each element with are obtained from a .txt file.

    @param filePath The path to the file from which we should read the data from.
*/
StudentList::StudentList(string filePath)
{
    ifstream studentFile(filePath);

    string lineContents;  // Holds the content of each line in the file.
    int counter = 1;  // Counts the number of lines read.

    while (!studentFile.eof())
    {
        cout << "\nfile line counter: " << counter++ << endl;  
        getline(studentFile, lineContents);
        cout << "current line content in file: " << lineContents << endl;

        // Create a new student from the lines content.
        // This object should not have any initialized data about name, id or gpa.
        Student s(lineContents);

        // Check what values were added to the object.
        cout << "name: " << s.getName() << " id: " << s.getId() << " gpa: " << s.getGPA() << endl;

        // Put the object in the vector
        students.push_back(s);
    }
    studentFile.close();

    // Sort the vector based on the gpa value, in descending order
    sort(students.begin(), students.end(), [](Student &s1, Student &s2)
                                           {
                                               return s1.getGPA() > s2.getGPA();
                                           });
}

My text file that I read data from:

Shirley Temple 0235 93.8
John Appleseed 4325 89.2
Debbie Downer 9245 70.3

And finally the main function:

#include <iostream>

#include "Student.h"
#include "StudentList.h"

using namespace std;

// Practical method to write relevant info about a Student:
void printStudent(Student student)
{
    cout << "\nName: " << student.getName() << endl;
    cout << "ID: " << student.getId() << endl;
    cout << "GPA: " << student.getGPA() << endl;
}

int main() {

    // Create a new StudentList object that adds students to its vector, 
    // based on the data obtained from the file:
    StudentList list("C:/Users/UserName/Documents/students.txt");

    // Check how many students were created and added to the vector in list.
    cout << "\n students vector length: " << list.students.size() << endl;

    for (Student s : list.students)
        printStudent(s);

    //Student s2("");
    //printStudent(s2);
    system("pause");
    return 0;
}

The output looks like this:

file line counter: 1
current line content in file: Shirley Temple 0235 93.8
current values gpa, id : -858993460, -9.25596e+61  // Not already initialized, which is expected.
chars in stream: 24
name: Shirley Temple id: 235 gpa: 93.8

file line counter: 2
current line content in file: John Appleseed 4325 89.2
current values gpa, id : 235, 93.8  // Already explicitly Initialized! How come!?
chars in stream: 24
name: John Appleseed id: 4325 gpa: 89.2

file line counter: 3
current line content in file: Debbie Downer 9245 70.3
current values gpa, id : 4325, 89.2  // Already explicitly Initialized! How come!?
chars in stream: 23
name: Debbie Downer id: 9245 gpa: 70.3

file line counter: 4
current line content in file:
THIS STUDENT IS EMPTY!
current values gpa, id : 9245, 70.3  // Already explicitly Initialized! How come!?
chars in stream: 0
name:   id: 9245 gpa: 70.3

file line counter: 5
current line content in file:
THIS STUDENT IS EMPTY!
current values gpa, id : 9245, 70.3  // Already explicitly Initialized! How come!?
chars in stream: 0
name:   id: 9245 gpa: 70.3

 students vector length: 5

Name: Shirley Temple
ID: 235
GPA: 93.8

Name: John Appleseed
ID: 4325
GPA: 89.2

Name: Debbie Downer
ID: 9245
GPA: 70.3

Name:
ID: 9245
GPA: 70.3

Name:
ID: 9245
GPA: 70.3
Press any key to continue . . .

So I am absolutely very confused about how it can be possible that the id and gpa of every Student object created after the first read line in the StudentList constructor, is initialized with the values of the previously created object. As a recap, the beginning of the Student constructor looks like this:

Student::Student(string studentInformation)
    {
        // If no information about the student was provided:
        if (studentInformation.empty()) 
            cout << "THIS STUDENT IS EMPTY!" << endl;

        // Prints the object's id and gpa values. These should be uninitialized.
        cout << "current values gpa, id : " << id << ", " << gpa << endl;

as far as I know there is no way the id and gpa members can have been explicitly initialized before the cout statement. Yet, all objects created after the first one in the StudentList constructor are initialized when the cout above is executed. How can this be?

How to update $_file in this approach?

how to update the current image profile. in photos folder.

here's what I'm using in uploading image in form.

<input type="file" name="image" class="ed" id="inputFile"  required>

here's my approach I created. its working if I didnt include the image in UPDATE query.

$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
 move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
$avatar="photos/" . $_FILES["image"]["name"];
// query for cswd_records
$name = $_POST['name'];
$app = $_POST['app_id1'];
mysql_query("UPDATE cswd_records set name ='".$_POST['name']. "', age ='".$_POST['age']. "', bdate ='".$_POST['bdate']."', bplace ='".$_POST['bplace']."', educ ='".$_POST['educ']."', occu ='".$_POST['occu']."', inc ='".$_POST['inc']."', status ='".$_POST['status']."', addr ='".$_POST['addr']."', contact ='".$_POST['contact']."', photo ='$avatar',  probpres ='".$_POST['probpres']."', findings ='".$_POST['findings']."', evalreco ='".$_POST['evalreco']."', recom ='".$_POST['recom']."', lastdate =  DATE_FORMAT(NOW(),'%m-%d-%Y %h:%i %p')  WHERE app_id = '".$_POST['app_id1']."'");

but If I added I got some error.

Notice: Undefined index: image in C:\xampp\htdocs\xxx\admin\saveupdaterecord.php on line 28

Warning: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\xxx\admin\saveupdaterecord.php on line 28

Notice: Undefined index: image in C:\xampp\htdocs\xxx\admin\saveupdaterecord.php on line 29

Notice: Undefined index: image in C:\xampp\htdocs\xxx\admin\saveupdaterecord.php on line 30

Notice: Undefined index: image in C:\xampp\htdocs\xxx\admin\saveupdaterecord.php on line 30

Notice: Undefined index: image in C:\xampp\htdocs\xxx\admin\saveupdaterecord.php on line 31

File is attached but empty after form submission

I am using a jquery plugin to show images immediately after attaching. It works fine. But After form submission file input field is empty. I am using cakephp 2.6 and code for Form:

<?php echo $this->Session->flash(); ?>
                        <!-- BEGIN FORM-->
                           <?php echo $this->Form->create('Tolet', array(
                            'inputDefaults' => array(
                                'label' => false,
                                'div'   => false                                  
                                ),
                            'id'=> 'fileupload',
                            'class' => 'form-horizontal form_sample_2',
                            'novalidate' =>'novalidate',
                            'type' => 'file'
                            )
                            ); ?>
        <div class="form-group">
                                    <label class="control-label col-md-5">
                                        <span class="btn green fileinput-button">
                                            <i class="fa fa-plus"></i>
                                            <span>
                                                Add Image </span>

                                               <?php 
                                               echo $this->Form->input(
                                            'images.',

                                            array(
                                                'type' => 'file',
                                                'multiple' =>'',
                                                'class' => 'form-control'
                                                )

                                            ); 
                                            ?>
                                        </span>
                                    </label>
                                    <div class="col-md-7">

                                        <table role="presentation" class="table table-striped clearfix">
                                            <tbody class="files">
                                            </tbody>
                                        </table>
                                    </div>
                                </div>   


  <div class="form-actions">
                                <div class="row">
                                    <div class="col-md-offset-9 col-md-3">

                                         <?php 
                                                                     echo $this->Form->button(
                                                                        'Post', 
                                                                        array('class' => 'btn green', 'type' => 'submit')
                                                                        ); ?>
                                    </div>
                                </div>
                            </div>
                          <?php echo $this->Form->end(); ?>
                        <!-- END FORM-->
                    </div>

Request data:

Array
(
    [Tolet] => Array
        (
            [title] => 
            [tolet_type_id] => 
            [tolet_condition_id] => 
            [room_no] => 1
            [bath_no] => 1
            [area] => 
            [name] => 
            [cell] => 
            [email] => 
            [images] => Array
                (
                    [0] => Array
                        (
                            [name] => 
                            [type] => 
                            [tmp_name] => 
                            [error] => 4
                            [size] => 0
                        )

                )

        )

)

What am I doing wrong? Here is the live demo: http://ift.tt/1KnebZT

I am sorry if it is very basic question which should not ask in stackoverflow.

How to open a .sess file?

I have some session files of the extension *.sess. How do I open it on Linux/Windows? I tried using normal text editors but I get partial junk values and partial actual text. Thanks!

How to exclude delimiter in fscanf

My file is a text file abcdef;qwerty\n. When I run this program I get

abcedef
;qwerty

How can I get rid of the semicolon so I would be printing

abcedf
qwerty

Program:

int main(int argc, char *argv[]) {
    char str1[2000], str2[2000];
    char c; 
    FILE *fp;
    fp = fopen(argv[1],"r");
    if(fp == NULL){
        printf("File not read,errno = %d\n",errno);
        return 1;
    }

    fscanf(fp, "%[^;] %[^\n]",str1,str2);

    printf("%s\n%s\n",str1,str2);
    fclose(fp);
    return 0;

}

dimanche 30 août 2015

Angular js , not able to upload file

I am not able to upload the file to the backend, can anyone help me out

here is the html code

<form name="upload" class="form" data-ng-submit="addFile()">
             <input type="file" name="file" multiple 
                onchange="angular.element(this).scope().uploadResume(this)" />
            <button type="submit">Upload </button>
        </form>

here is the controller

$scope.uploadResume = function(element) {
    $scope.$apply(function($scope) {
    $scope.files = element.files;         
    });
}
    $scope.addFile = function() {
    UploadService.uploadfile($scope.files,
    function( msg ) // success
    {
    console.log('uploaded');
    },
        function( msg ) // error
       {
    console.log('error');
    });
}


    uploadfile : function(files,success,error){
    var url = 'C:\Users\2165\Desktop';
    for ( var i = 0; i < files.length; i++)
    {
    var fd = new FormData();
    fd.append("file", files[i]);    
    $http.post(url, fd)
    .success(function(data)
    {
    console.log(data);
    })
    .error(function(data)
    {
    console.log(data);
    });
    }
    }

here is the rest code

var uploadResume = function(req, res, next){
console.log("Inside Upload Resume");
path.join(__dirname, '../../resume/');
console.log("req");
var file=req.body.file;
console.log("file");
res.download(__dirname, '../../resume/' + file);
console.log("download");
res.status(200).end();

}

The log will print "inside upload resume" "req" "file" "download". but the file is not getting uploaded

Why compression output larger zip file

I really don't understand about python compression because whenever I am trying to compress a folder or file I end up getting a very larger file 5.5 times bigger than the original file. Why does this happen? Is there any way I can compress a folder or a file with python and get an output that's at most the size of the original file? Here is the code I am using.

import os, zipfile

def zipfiles(filename, destname):
  try:
   zf = zipfile.ZipFile(destname, 'w', zipfile.ZIP_DEFLATED)
   for dirname, subdirs, files in os.walk(filename):
      zf.write(dirname)
      for filename in files:
          zf.write(os.path.join(dirname, filename))
   zf.close()
  except Exception, e:
   print str(e)
def main():
   x = raw_input('Enter Filename:   ')
   while len(x) == 0:
       x = raw_input('Enter Filename:   ')
   y = raw_input('Enter destination name:   ')
   while len(y) == 0:
       y = raw_input('Enter destination name:   ')
   zipfiles(x, y+'.zip')
main()

How can I upload directory to FTP?

This is my code:

public void UploadIt(){
    org.apache.commons.net.ftp.FTPClient con = null;

    try
    {
        con = new FTPClient();
        con.connect("ftp server");

        if (con.login("username", "pass"))
        {
            con.enterLocalPassiveMode(); // important!
            con.setFileType(FTP.BINARY_FILE_TYPE);
            String data = baseDir + "/emre";

            FileInputStream in = new FileInputStream(new File(data));
            boolean result = con.storeFile("/", in);
            in.close();
            if (result) Log.v("upload result", "succeeded");
            con.logout();
            con.disconnect();
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Log.v(" dead","ddsd");
    }

}

I can upload file, but I can't upload directory.When I try upload dir or folder it says "... Is directory" and it doesn't upload.

I am a noobie. Thank you

Can anyone here explain to me like a 5 year old how to implement jquery file upload in php?

Play local audio file with AVAudioPlayer

I'm testing my app in simulator.

I'm downloading file and getting it's local way like this one: file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3

Now I want to play this file with AVAudioPlayer but I'm always getting this error:

file:///
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"

Code for playing:

var alertSound = NSURL(fileURLWithPath: "file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3")
        print(alertSound)

        var error:NSError?
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }

How should I make it playing?

It's possible to make a Batch programm that backup a folder files from my external hd to pc hdd, anytime I add or change a file?

I'm a graphic designer and I use my external hd frequently to move psd/jpeg/png/tiff files from my laptop at home to my Work PC and vice versa. But as a precaution before modifying or adding a file I copy it to a folder. It's possible to make it automatically? And it's easy to make on Batch?

Thanks for help!

read specific values from text file

I have the following visual basic code, which is part of a custom class. I want a simple and effective way(use little computer resources) to assign the "value1" value(100) to "_field1","value2" value(8) to "_field2" etc. Any nice ideas? thanks

Private Sub readcrnFile()
    'read files and assing values to the properties
    Dim sr As New IO.StreamReader(_fileName)

    _field1 = sr.ReadToEnd()
    _field2 = sr.ReadToEnd()
    _field3 = sr.ReadToEnd()

    sr.Close()

End Sub

where _fileName is a full path to a text file which looks like this:

value1: 100

value2: 8

value3: 80

jQuery File Upload - I do not want to automatically show all photos were up when accessing the web

I'm using the http://ift.tt/sYzQPO plugin.

We at after I download the code on installation, then encounter the case as per visit up all my photos photos will automatically show this makes my site load very slow and if my photos as much then it will load as much, for example I have up are 5000 photo next page up photo it automatically appears an external photo site at 5000 and this made my web load very slow and lag, it is not the same as the demo http://ift.tt/1LE8MuG want to look like the demo when accessing photo does not automatically show up.

Downloading file to resource directory (Swift)

I can download file with progress now. How should I save this file such way that it can be played in AVAudioPlayer using such string as

var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))

How can I download any file into resource directory or app directory?

Maybe I can find some info I need here, but I dont know obj-c :/

OI File Manager won't recognize custom file extension

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="file" />
            <data android:host="*" />
            <data android:mimeType="*/*" />
            <data android:pathPattern=".*.custom" />
            <data android:pathPattern=".*..*.custom" />
            <data android:pathPattern=".*.custom2" />
            <data android:pathPattern=".*..*.custom2" />
        </intent-filter>

Above is the XML in my manifest.

If I use File Commander, it launches into the Application right away.

I/ActivityManager(976): START u0 {act=android.intent.action.VIEW cat=[android.intent.category.DEFAULT] dat=file:///storage/emulated/0/Download/test.custom typ=application/octet-stream flg=0x3 cmp=http://ift.tt/1Vp1xvj (has extras)} from pid 1913

But when I use OI File Manager

I/ActivityManager(976): START u0 {act=android.intent.action.VIEW dat=file:///storage/emulated/0/Download/test.custom cmp=android/com.android.internal.app.ResolverActivity (has extras)} from pid 2595

I/ActivityManager(976): Start proc system:ui for activity android/com.android.internal.app.ResolverActivity: pid=2664 uid=1000 gids={41000, 2993, 3003, 1028, 1015, 3002, 3001, 2001, 3006, 1021, 3004, 3005, 1000, 3009, 1023, 1010}

I/ActivityManager(2664): Timeline: Activity_launch_request id:org.openintents.filemanager time:217470949

I/ActivityManager(976): START u0 {act=android.intent.action.VIEW dat=file:///storage/emulated/0/Download/test.custom flg=0x3000000 cmp=org.openintents.filemanager/.FileManagerActivity (has extras)} from pid 2664

Anyone have any insight as to what's causing the problem?

Get path from gallery without failing delivering Result

My application works fine on some devices. Unfortunately others reported the following bug Failure delivering result which i dont know how to solve

So i use the following code:

 @Override
         public void onActivityResult(int requestCode, int resultCode, Intent data) {

                    if (requestCode == 1 && data!=null) {

                        if (resultCode == RESULT_OK) {

                        Uri uri = data.getData();

                        String s = getPath(uri); //Null string on some devices
                     if(s!=null){
                         File f = new File(s);
                         }
                        else{
                    //????????
                          }
                        if(resultCode== RESULT_CANCELED){

                        }

                }
            }

And one method called getPath:

public String getPath(Uri uri) {
    // just some safety built in 
    if( uri == null ) {

        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if( cursor != null ){
        int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    return uri.getPath();

} Also when user click:

image = (ImageView) findViewById(R.id.imageView7);
    i.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
             Intent intent1 = new Intent();
             intent1.setType("image/*");
             intent1.setAction(Intent.ACTION_GET_CONTENT);
             startActivityForResult(Intent.createChooser(intent1,"Picture"), 1);
        }
    });

And lastly what i got from logcat

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content: flg=0x1 }} to activity {****************.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3942)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3992)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.io.File.fixSlashes(File.java:185)
at java.io.File.<init>(File.java:134)
at *************.MainActivity.onActivityResult(Unknown Source)
at android.app.Activity.dispatchActivityResult(Activity.java:5535)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3938)
... 11 more

What am i doing wrong?

file syncing from desktop to remote server

I want to develop a program which can sync file and folders from desktop to remote server like Dropbox, one drive etc. Please anyone could guide me from scratch the prerequisites and further guidance. it is not for commercial use but a semester project.

error in reading xlsx file (openpyxl)

I want to read xlsx file but i am getting error My code :

from openpyxl import load_workbook
wb = load_workbook(filename = 'F:\123.xlsx', use_iterators=True)

Error :

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    wb = load_workbook(filename = '123.xlsx', use_iterators=True)
  File "C:\Python27\lib\site-packages\openpyxl-2.3.0b1-py2.7.egg\openpyxl\reader\excel.py", line 202, in load_workbook
    parsed_styles = read_style_table(archive)
  File "C:\Python27\lib\site-packages\openpyxl-2.3.0b1-py2.7.egg\openpyxl\reader\style.py", line 181, in read_style_table
    p.parse()
  File "C:\Python27\lib\site-packages\openpyxl-2.3.0b1-py2.7.egg\openpyxl\reader\style.py", line 53, in parse
    self.parse_named_styles()
  File "C:\Python27\lib\site-packages\openpyxl-2.3.0b1-py2.7.egg\openpyxl\reader\style.py", line 109, in parse_named_styles
    names = self._parse_style_names()
  File "C:\Python27\lib\site-packages\openpyxl-2.3.0b1-py2.7.egg\openpyxl\reader\style.py", line 128, in _parse_style_names
    for _name in node:
TypeError: 'NoneType' object is not iterable

how it can be slved ? Thanks

Move file between two linux servers with PHP [on hold]

I have downloaded a php libraby tha enables ssh2 connection to a linux server. I have already send some commands and which works fine. Now, Im trying to move a file beetween two linux servers. I have to connect to server A and transfere "file.tar" to server B. I tried:

ssh->exec("scp -P 22 file.tar.gz user@ip:/dir/");

And it response:

    Permission denied, please try again. Permission denied, please try again. Permission denied (publickey,gssapi-with-mic,password)

How can I do that step by step?

Thanks!

Limit user from downloading full sized file

I am facing a problem during my website building. I built that code,

// Send the file to the user header('Content-type: application/octet-stream'); header("Content-Length: {$file->filesize}"); header(sprintf('Content-Disposition: attachment; filename="%s"', urlencode($file->realname))); header("X-Accel-Redirect: /{$file->filedir}");

I want to have 2 types of download, premium download and a regular. I want regular download users to be able to download only half of the file. Is there any way to accomplish that without saving 2 versions of the file?

HTML + JS - File name resets in text when adding a new file button

I have a add button, like this, to add more <input type="file">: enter image description here

And it does work, when I click on the button, it calls a method to add a new file chooser.

HTML:

<div class="row" id="attachments_row">
          <div class="coffee-span-4">
            <label class="label label-1">Attachments</label>
          </div>
          <div class="coffee-span-6" id="attachments">
            <div id="attachment_inner">
                <input id="file_button" type="file" name="fileUpload0" size="50" /> 
                <sf:errors path="filepath" cssClass="rfqerror"></sf:errors>
            </div>
            <input type="button" value="+" style="float: left; margin-top: 10px; margin-bottom: 10px; padding: 5px;" onclick="makeNewAttachment();"/>
          </div>

          <div class="coffee-span-2" id="file-upload-button">
          </div>

          <br>
</div>

JS:

function makeNewAttachment() {
    var ai = document.getElementById("attachment_inner").innerHTML;
    var index = document.getElementById("attachment_inner").children.length;
    var ai_new = ai + "<input id='file_button' type='file' name='fileUpload" + index + "' size='50' />";
    document.getElementById("attachment_inner").innerHTML = ai_new;
}

But when I choose a file, the file name resets back to No file chosen.

Chose a file:

enter image description here

Click add, resets?!?!?!?

enter image description here

Does anyone know why?! I made each name different, I thought that was the case, but nope!

PHP Mongodb GridFS fails to open stream when using unlink

Symfony2 REST API

Goal: Upload images, use ImageResize to re-shape them and save them to a folder. Load them up and push to Mongo GridFS and then delete saved ones in folder.

Issue: Using unlink after flushing to mongodb triggers an error as if i have used unlink before:

    Warning: file_get_contents(C:/Users/Nikola/Desktop/awesome/web\pictures\1366%20768_small.jpg): failed to open stream: No such file or directory

Note that if i don't use unlink everything goess fine.

Code:

public function uploadAction(Request $request) {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-    Type, Accept");
    header ("Content-Type: application/json; charset=utf-8");

$response = new ResponseModel();

try {

    // Did we receive any files ?
    if( $request->files->count() === 0) {
        throw new CustomErrorException("No files received");
    }

    $pathsToDelete = [];
    $names = [];

    $files = $request->files;

    foreach ($files as $file) {
        /* @var $file UploadedFile */

        // Check mime type
        if(!($file->getMimeType() == 'image/jpeg' || $file->getMimeType() == 'image/png')) {
            throw new CustomErrorException("We are only accepting jpg and png files.");
        }

        //var_dump();


        // Perform image operations and save them to a temp folder

        // Create small image
        $imageManipulator = new ImageResize($file->getRealPath());
        $imageManipulator->resizeToHeight(200);
        $imageManipulator->resizeToWidth(200);
        $array = explode(".", $file->getClientOriginalName());
        $name = $array[0];
        $ext = $array[1];
        $pathSmall = 'pictures'.DIRECTORY_SEPARATOR.$name.'_small.'.$ext;
        $imageManipulator->save($pathSmall);

        // Create medium image
        $imageManipulator = new ImageResize($file->getRealPath());
        $imageManipulator->resizeToHeight(600);
        $imageManipulator->resizeToWidth(600);
        $array = explode(".", $file->getClientOriginalName());
        $name = $array[0];
        $ext = $array[1];
        $pathMedium = 'pictures'.DIRECTORY_SEPARATOR.$name.'_medium.'.$ext;
        $imageManipulator->save($pathMedium);

        // Create Large image
        $imageManipulator = new ImageResize($file->getRealPath());
        $imageManipulator->resizeToHeight(1024);
        $imageManipulator->resizeToWidth(1024);
        $array = explode(".", $file->getClientOriginalName());
        $name = $array[0];
        $ext = $array[1];
        $pathLarge = 'pictures'.DIRECTORY_SEPARATOR.$name.'_large.'.$ext;
        $imageManipulator->save($pathLarge);



        // Get locator
        $configDirectories = array($_SERVER['DOCUMENT_ROOT']);
        $locator = new FileLocator($configDirectories);

        // Create image
        $img = new Image();
        $img->setName($file->getClientOriginalName());
        $img->setFileSmall($locator->locate($pathSmall));
        $img->setFileMedium($locator->locate($pathMedium));
        $img->setFileLarge($locator->locate($pathLarge));



        // Save files to the database
        $dm = $this->get('doctrine_mongodb')->getManager();
        $dm->persist($img);
        $dm->flush();


        array_push($pathsToDelete, $locator->locate($pathSmall));
        array_push($pathsToDelete, $locator->locate($pathMedium));
        array_push($pathsToDelete, $locator->locate($pathLarge));

        array_push($names, $file->getClientOriginalName());
    }


    // Delete files after persisting
    foreach ($pathsToDelete as $p) {
        unlink($p);
    }

    //Load files from db
    foreach ($names as $n) {
        $image = $this->get('doctrine_mongodb')->getRepository('BlueAwesomeBundle:Image')
            ->findOneBy(['name' => $n]);

        //save them for testing
        file_put_contents($n, $image->getFileSmall64());
    }


    $response->setData(['success' => true]);
}
catch(CustomErrorException $e) {
    $response->setErr($e->getMessage());
}

return new JsonResponse($response);

}

Save a class into a binary file - Python

I'm aware that saving a class into a binary file in c++ is possible using:

file.write(Class_variable, size_of_class, amount_of_saves, file_where_to_save)

or something similar, and I wanted to use that in python in order to make it easier to write and read lots of data.

I've tried to do this:

def Save_Game(player, room):
    address = 'Saves/player'

    file = open(address, 'wb')
    file.write(player)

    address = 'Saves/room'

    file = open(address, 'wb')
    file.write(room)

Room and player being class_objects. But it says:

TypeError: must be convertible to a buffer, not PlayerMarty

What can I do?

How to read/display a txt file or inf file in windows command line

Can anyone tell how to read/display a text file on windows command prompt?

I know you can use edit test.txt which open you an another editor but is there a way you can just display the content on the command prompt? like cat test.txt function, just display it on the command prompt

Thank you for your tips

Regards

FileObjectStream doesnot read previous objects stored in File after appending an Object of same class type (StreamCorruptedException)

I made a program to store objects of Product type in a File and it's append-type is set as true. So for a particular runtime, this will append object data and then after read objects of Product from the file when we choose to stop storing in the File.. It works perfectly fine for the first attempt(when no previuos File exists with any data before program is executed).

But after when I run the program again and store the object of Product in the same File by appending on the previously stored object(Product type) data, that gives me a java.io.StreamCorruptedException: invalid type code: AC after reading 2 objects from the File.

Isn't Java supposed to read all the objects stored without any complications, as all the objects that are stored in the File are of the same type: Product

My code is as below:

import java.io.*;
import java.util.*;

class Product implements Serializable {
    volatile int prodNo;
    volatile double price;

    public Product() {
        prodNo = 0;
        price = 0;
    }

    public void setValues(int no, double amt) {
        prodNo = no;
        price = amt;
    }


    public void display() {
        System.out.println("\nProduct No: " + prodNo);
        System.out.println("Price: " + price);

    }
}

class FileDemo {
    public static void main(String[] args) throws Exception {

        Scanner input = new Scanner(System.in);

    /*String fileName;
    System.out.print("\nEnter File Name: ");
    fileName = input.nextLine();    
    System.out.println();*/

        FileOutputStream fout = null;
        ObjectOutputStream oOut = null;
        try {
            fout = new FileOutputStream("MyFile", true);
            oOut = new ObjectOutputStream(fout);

            int choice;
            int prodNo;
            double prodPrice;

            Product p1;

            do {
                p1 = new Product();

                System.out.print("\nEnter Product No: ");
                prodNo = input.nextInt();
                System.out.println();

                System.out.print("Enter Product Price: ");
                prodPrice = input.nextDouble();
                System.out.println();

                p1.setValues(prodNo, prodPrice);

                oOut.writeObject(p1);
                oOut.flush();

                p1.display();

                System.out.print("\n\nPress 1 to continue adding products or press any other key to read File: ");
                choice = input.nextInt();
            } while(choice == 1);
        }

        catch(IOException e) {
            System.out.println("\nError Occured: " + e);
        }

        finally {
            oOut.close();
        }

        Product p;

        FileInputStream fin = null;
        ObjectInputStream oIn = null;
        try {

            fin = new FileInputStream("MyFile");
            oIn = new ObjectInputStream(fin);

            while(fin.available() > 0) {
                p = (Product) oIn.readObject();
                p.display();
            }
        }

        catch(IOException e) {
            System.out.println("\nError Occured: " + e);
        }
        finally {
            oIn.close();
        }

        System.out.println("\nProgram Closing");
    }
}

Matlab - Renaming files sequentially (Opposite direction)

I Have sequential files for example:

hi_0001.edf

hi_0002.edf

hi_0003.edf

hi_0004.edf

I want to rename them plus number them the opposite direction (Start from end to beginning) so that:

"hi_0001.edf" becomes "hello_0004.edf"

"hi_0002.edf" becomes "hello_0003.edf"

"hi_0003.edf" becomes "hello_0002.edf"

"hi_0004.edf" becomes "hello_0001.edf"

I have the following program that can rename the files but gives them the same numbers (From beginning to end):

%//' Directory where TIFF images are present
directory  = 'C:\Users\opd28\Desktop\folder\'; 

%//' files pattern with absolute paths
filePattern = fullfile(directory, 'hi_*.edf'); 

%// Get the filenames
old_filename = cellstr(ls(filePattern)) ;

%// Get numbers associated with each file
file_ID = strrep(strrep(old_filename,'hi_',''),'.edf','');

file_ID_doublearr = str2double(file_ID);
file_ID_doublearr = file_ID_doublearr - min(file_ID_doublearr)+1;

file_ID = strtrim(cellstr(num2str(file_ID_doublearr)));

%// Get zeros string to be pre-appended to each filename
str_zeros = arrayfun(@(t) repmat('0',1,t),         4-cellfun(@numel,file_ID),'uni',0) ;

%// Generate new filenames
new_filename = strcat('hello_',str_zeros,file_ID,'.edf') ;

%// Finally rename files with the absolute paths
cellfun(@(m1,m2)     movefile(m1,m2),fullfile(directory,old_filename),fullfile(directory,new_filename)) ;

The code above generates the following:

"hi_0001.edf" becomes "hello_0001.edf"

"hi_0002.edf" becomes "hello_0002.edf"

"hi_0003.edf" becomes "hello_0003.edf"

"hi_0004.edf" becomes "hello_0004.edf"

What do I need to add to make the new file names start from the end towards the beginning.

samedi 29 août 2015

How to count the number of matching files in Python?

I have files that are named as follows:

  • file-001-001.dat
  • file-001-002.dat
  • file-001-003.dat
  • file-001-004.dat
  • file-001-005.dat

  • file-002-001.dat

  • file-002-002.dat
  • file-002-003.dat
  • file-002-004.dat

  • file-003-001.dat

  • file-003-002.dat
  • file-003-003.dat
  • file-003-004.dat
  • file-003-005.dat
  • file-003-006.dat
  • file-003-007.dat
  • file-003-008.dat

  • file-999-010.dat

I am trying to count the number of files for the same first number, e.g. the code should give me the number of files starting with 001 as 5, 002 as 4,... 999 as 1.

I have managed to get it done using this code, that counts the files in 'file_count' folder:

from collections import Counter
import numpy as np
import os
import re
data_folders = []
data_files = []
for root, directories, files in sorted(os.walk('./file_count')):
    files = sorted([f for f in files if os.path.splitext(f)[1] in ('.dat')])
    for file in files:
        data_folders.append(root)
        data_files.append((re.findall(r"[-+]?\d*\.\d+|\d+", file)[-2].zfill(3), re.findall(r"[-+]?\d*\.\d+|\d+", \
            file)[-1].zfill(3), os.path.join(root, file)))
data_folders = np.unique(data_folders)
data_files = sorted(data_files)
a = np.array(data_files)
print a[:, 0]
c = Counter(a[:, 0])
print c['001']

Is there a much simpler and efficient code than this? Any built in function that can solve this?

reading a file and writing lines in reverese

I'm trying to read a file and write on with reverse lines. Here is my code so far:

def write_reversed_file(input_filename, output_filename):
"""Writes a reverse file"""
    with open(input_filename, 'r') as input_file:
        data = input_file.readlines()
    with open(output_filename, 'w') as output_file:
        return output_file.reversed(data)

try:
    write_reversed_file('data.txt', 'reversed.txt')
    print(open('reversed.txt').read())
except IOError:
    print ("Error: can't find file or read data"

python counting characters in a file

I'm trying to find out how to count how many characters there are in a file here is my code so far:

def file_size(filename):
num_chars = 0
open(filename, 'r')
num_chars += len(filename)

print(file_size('data.txt')) 

sorting files in R: How can I make the results consistent?

When using list.files, I get different sorting results on different computers. How can I make it so I always get the second behavior, which sorts padded numbers the way a human would?

Computer 1 (Debian)

$ uname -a
Linux work 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt9-2 (2015-04-13) x86_64 GNU/Linux
$ touch 02 10 _2
$ R -e "list.files()"

R version 3.1.1 (2014-07-10) -- "Sock it to Me"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> list.files()
[1] "02" "10" "_2"

Computer 2 (SUSE)

> uname -a
Linux efrc3 3.16.7-21-desktop #1 SMP PREEMPT Tue Apr 14 07:11:37 UTC 2015 (93c1539) x86_64 x86_64 x86_64 GNU/Linux
tug04419@efrc3:~/temp> touch 02 10 _2
tug04419@efrc3:~/temp> R -e "list.files()"
R version 3.1.1 (2014-07-10) -- "Sock it to Me"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: x86_64-suse-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> list.files()
[1] "_2" "02" "10"

Create multiple files

I have this code:

try {

                File file = new File(something+counter+".txt");

                counter++;

                if (!file.exists()) {
                    file.createNewFile();
                }

                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);
                bw.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

I need to make it like this: When they press enter, new file will be create in defined location (I made JTextField for this), but when they press it again, the file OVERWRITES. That's the problem. I need them to press enter - create new file: sample1.txt, press enter again, create new file: sample2.txt

GOlang - how to read from 10 csv files in parallel, process them in parallel and store results in 1 Hash table (key->vale)

I am pretty new with GOlang and want to try it for parallel processing of a files. Files are stored on a RamDisk in RHEL linux so there is no (or very very minimal) I/O bound since latency speed is memory speed. Let's not focus on I/O here as I saw in other posts..

There are 10 CSV files 1GB in size each and I have enough memory on computer (512GB Ram) and enough Cores (48) and I want to:

1) Read file from memory disk in parallel (all at once) 2) Split each line of a file into columns 3) Take first column and store it as a key and 3rd column as a value of a hash 4) Add all key-values to the SAME hash so once all parallel processing is done - I have 1 Hash only with all key-values from all 10 files.

Since I am very new to GoLang - I could make 2) and 3) but not sure how to do all in parallel and store results to the same hash while processing in parallel..

Goal is to execute all in 1 second or less (all 10 1GB parallel files) and have Hash ready for next processing (next is - compute Standard Deviation of all values from a hash, Average etc. etc.)..

File example (all files have same structure) - file1.csv: 123,a,1.354,c,d 531,a2,57.2,c2,d2 245,a2,21.57,c2,d2 ...

How to convert double to object?

I am writing part of my programe which read data from txt file.

I have problem when i want to set value of JSpinner by setValue(object).

My data is double so i need to convert it to object, but how?

LoadData open = new LoadData();
            data.setFz(open.giveAwayData());
            spinner_1.setValue(data.getFz()); // Fz is double

Accessing folders on wordpress (not self-hosted)

I am running a wordpress woocommerce shop, hosted on wordpress directly (not on my own server).

Now my online shop has a bug (dammit!).I've found a hotfix to resolve the issue. It needs to be installed to templates/woocommerce/single-product/add-to-cart/ or, to be more precise, I have to overwrite the file variable.php in that folder.

Is there really no way to access plugin folders when your wordpress installation is not self-hosted? Has anyone an idea, how to resolve this issue?

Thanks for your time, guys!

How to create a temp file with a specific name

I would like to create a temp file which deletes itself on script ending with a specific filename.

I know tmpfile() does the "autodelete" function but it doesn't let you name the file.

Any ideas?

perl could not OPEN DIRECTORY files

i have a problem with a script perl, as follow: i must open and analyze all the files txt in a directory, but i cannot. I could read files name that are saved and printed by @files array but i cannot open that. This is my code:

opendir my $dir, "../Sc/direct" or die "Cannot open directory: $!";
my @files = readdir $dir;
print "@files\n";
foreach my $fp (glob("$dir/(.*).txt/")) {
  ..... 

thanks in advance. Best regards

Front-end uploads wordpress

I have a wordpress webiste which allows users to upload videos and photos. instead of the upload timing out and nothing happening when the file is too big, is there anything that i can do to notify the user when the file is too big and some how automatically resize the file?

Reading data from a text file with pure javascript

I have a text file with all of the english nouns called words.txt. And my goal is to look for a word given by the user in this file. But since I'm new to javascript, I was hoping to find a way with which, in pure javascript, I can save this file into a variable in which i can later look for the word that has been input.

Android - How can i upload directory to FTP?

This is my code:

public void UploadIt(){

    org.apache.commons.net.ftp.FTPClient con = null;

    try
    {
        con = new FTPClient();

        con.connect("ftp server");

        if (con.login("username", "pass"))
        {
            con.enterLocalPassiveMode(); // important!
            con.setFileType(FTP.BINARY_FILE_TYPE);
            String data = baseDir + "/emre";

            FileInputStream in = new FileInputStream(new File(data));
            boolean result = con.storeFile("/", in);
            in.close();
            if (result) Log.v("upload result", "succeeded");
            con.logout();
            con.disconnect();
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Log.v(" dead","ddsd");
    }

}

I can upload file but i can't upload directory.When i try upload dir or folder it says "... Is directory" and it doesn't upload Please help me !

How to read data from binary file

Here I have write code that can write and read data from binary file at the same time of running a program but i have to read binary file without writing it. When try to reading a binary file its segmentation fault or the row size and column size went wrong. what should i do here for reading binary file alone(without writing it). Here column and row sizes are hardcoded by me. Please show how to find column and row sizes also for binary file. I am new to code, if i were made any mistakes sorry.

fstream fs("emp.bin",ios::binary | ios::out);
fstream fr("emp.bin",ios::binary | ios::in);
size_t rowLength=7;
size_t colLength=3;

count_t  colSize;

for (size_t j=0;j<colLength;j++)

{
    colSize.push_back(idxTbl[j].fsize);
}

cout<<rowLength<<" "<<colLength<<endl;
for(size_t i=0;i<rowLength;i++)

{

for (size_t j=0;j<colLength;j++)

    {   
    string data=mainTbl[i].at(j);           
    data.resize(colSize.at(j),' ');     
    mainTbl[i].at(j)=data;
    int len = data.length();
    fs.write(reinterpret_cast<char*> (&len),sizeof(len));
    fs.write(data.c_str(),len);

    fs.read(reinterpret_cast<char*> (&len),sizeof(len));
    data.resize(len);
    fs.read(const_cast<char*>(data.c_str()),len);
    cout<<data;
    }
fs<<endl;
cout<<endl;
}


return mainTbl; 

Managing user access to files

I'm looking for some guidance on the best way to manage user-level access to files (ideally with Perl, but any general guidance also appreciated). Here is the requirement:

  • I have users upload files which I want to keep secure so that no one can generally see them apart from the owner that uploaded them

  • I want to then be able to grant access to other specific users so that they can open the files read-only

  • All my users are managed in a MySQL database

  • I intend to hold the uploaded files in the file system, not the database. I will store metadata about the files in the database.

What's the best approach to manage secure access by user to the files? I can rename the files on upload and keep in a secure directory somewhere. I can store the required access information in the database by user. But how to manage access for any given user? Copy the files out to a temporary area while accessing them?

Display external files into Unity3d game objects

can you please tell me which external file formats, e.g. from local hard drive, can be used to load it into a game object to display that in game?

What I have tried so far:

I used image file formats like .png and .jpg and both works well with http://ift.tt/1tT76H8

I wanted to use the same with video file formats like .mp4 but it didn't work from hard drive. I used http://ift.tt/1KsFwsd. I have read that the file format should be .ogg from hard drive. So, I tried this and it works well. However, is there any other video format that is supported in this way?

I also wanted to load .pdf and .pptx files into a game object, but I read that there is no possibility to do this directly. It is only possible to write an own custom .pdf renderer to use pdfs in Unity or use something like ghostscript to convert each page into an image.

I am using Unity 5 free version and I am a beginner in Unity.

Any help would be greatly appreciated.

C# - How to write a Hashtable into the file ?

How can I write a hashtable into the file without knowing what is in it ?!

Hashtable DTVector = new Hashtable();

just store this into the file, then read it and create a hashtable again.

Python Remove Whitespace

This is my first question so forgive me if this is not a well formed question but I am trying to read the contents of a file in Python.

So far I could print the contents of the file but there are whitespaces at the beginning and end of each line and I don't want the whitespaces on the beginning. How do I do that.

with open('dump.txt','r') as f:
    print f.read()

Thanks!

How do I get certain values from a txt file?

I'm kind of noob in Android and I need help with something. I have a .txt file like this:

#nombre iron will#

#fuerza 6#
#const 6#
#habilidad 6#
#intelig 6#

#vitalidad 42#
#aguante 72#

What I want to do is to get every item in the .txt file and store it in a variable. For example, in this case I want a String variable called "nombre" with the value "Will", an int variable "fuerza" with the value "6", etc.

How can I get this? Thanks in advance, and sorry about my bad english.

My code so far:

File tarjeta = Environment.getExternalStorageDirectory();
File carpeta = new File(tarjeta.getAbsolutePath() + "/Rol/PJs/");
File archivo = new File(carpeta.getAbsolutePath(), archivoabierto); //String archivoabierto = "name.txt"
StringBuilder text = new StringBuilder();
try{
     //This is where I get lost, I don't know how to proceed
     BufferedReader br = new BufferedReader(new FileReader(archivo));
     String line;
     while ((line = br.readLine()) != null){
           text.append(line);
           text.append('\n');
     }
     br.close();
} catch (IOException e){
     Toast.makeText(Personajes.this, "No se pudo cargar "+archivo.getPath(), Toast.LENGTH_SHORT).show();
}

vendredi 28 août 2015

I wanna read data from my binary file after the writing process complete and also read data without the writing process

Here is my part of the code from binary file writing. here I'm passing a 2d vector table that contains text format data or binary data. if the main table contains binary data I wanna read and load that data into one vector table. I already done that if the data is text file I can load that data from that file, but it's a binary data I don't know how can I load. I am also using index table. That means that table contains size of the each field in main table.

For eg: emp.idx

field - Size

name - 20

age - 2

sex- 10

mainTbl - main table containing the binary data.

typedef vector <string> record_t;
typedef vector <record_t> table_t;
table_t mainTbl;

table_t fileStruct::FormatData(table_t &mainTbl)
{

fstream fs("emp.bin",ios::binary | ios::out | ios::in); 

size_t rowLength=mainTbl.size();
size_t colLength=idxTbl.size();
count_t  colSize;
    for (size_t j=0;j<colLength;j++)

    {
        colSize.push_back(idxTbl[j].fsize);
        //cout<<"colum size "<<colSize[j]<<endl;
    }


    for(size_t i=0;i<rowLength;i++)

    {

    for (size_t j=0;j<colLength;j++)

        {

        string data=mainTbl[i].at(j);

        data.resize(colSize.at(j),' ');

        mainTbl[i].at(j)=data;
        int len = data.length();
        fs.write(reinterpret_cast<char*> (&len),len);
        fs.write(const_cast<char*>(data.c_str()),len);

        //cout<<data;
        //fu<<mainTbl[i].at(j);

        }
    fs<<endl;
    //cout<<endl;
    }

    return mainTbl;

 }

How do I create default html file for each item in list?

Have a questions with file automation.

  • I want to have a default html file with code and a separate file with a list of items.
  • Each time an item is added to the list I want it to create a new html file with the default html's contents.
  • If the html file already exists then do nothing.

What would be the best language to automate this?

Change extension of files in windows batch

I am trying to rename a lot of files. I only want to change the extention from ".pdf.OCR.pdf" to ".pdf" So far I got the following code

rem for /r myPDFfolder %%i in (*.pdf.OCR.pdf) do ren "%%i" "%%~ni.pdf"

But it does not appear to work with the extension that has multiple dots -- what am I doing wrong?

How to Use a Browsed File in Allegro 5?

I need to create a very simple program that will let the user browse an image, which will then be used for a bitmap that will be displayed in the screen.

I know how to create a simple native file dialog with Allegro 5, but I don't know how to use the selected file for my bitmap.

This is my code:

ALLEGRO_FILECHOOSER *filechooser;
    filechooser = al_create_native_file_dialog("C:", "Choose a file.", "*.*;*.jpg;", 1);
    al_show_native_file_dialog(display, filechooser);

When I click on the files, the native file dialog disappears and nothing happens at all. I searched a lot for this matter, but I could not find an answer to my problem.

How do I create a bitmap with the selected image?

Issues reading a text file in the same folder as the JAR program

I have a text file in the same location as my .jar program:

Main Folder:

|_ myJar.jar

|_ myText.txt

When I run the .jar file I would like it to read the contents of myText.txt, however with the path set as String fileName = "./Paths.txt"; it still doesn't read the file. I believe it's trying to read the Paths.txt file from inside the jar.

I tried other solutions, none seem to tell the program to read the Paths.txt file from outside of the jar file, so any help would be greatly appreciated.

Code:

public static void readFile() { 

    String fileName = "./Paths.txt"; 
    BufferedReader br; 
    String line; 
    //Attempts to read fileName
    try { 
        br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        try { 
            // Starts reading the file and adding values to linked hashmap
            while ((line = br.readLine()) != null) { 
                String[] lineSplit1 = line.split("#"); 
                String lineKey = lineSplit1[0]; 
                String lineValue = lineSplit1[1]; 
                hm.put(lineKey, lineValue);
            }
        } catch(Exception e3) { 
            errorMessage("Error when trying to read the file and add "
                    + "the values to a hashmap"); 
        }
        //Attempts to close fileName
        try {
            br.close();
        } catch(IOException e1 ) { 
            System.out.println("Messed up while trying to close buffered reader"); 
            System.out.println(e1); 
        }
    } catch (FileNotFoundException e1) { 
        errorMessage("The file " + fileName + " does not exist" 
                 + "\nI have created the file for you."); 
        try {  
            PrintWriter writer = new PrintWriter(fileName, "UTF-8");
            writer.println("");
            writer.close();
        } catch(Exception e2) { 
            errorMessage("Error while trying to create " + fileName);
        }
    }
}

SVN - Automatically generate unique ID for every versioned file

Is there an unique identifier for every versioned file in an SVN repository? If yes, can it be read using some svn command? If no, is it possible to generate one on every svn add call?

For example, if I have a GUID generator application, can I call it on every svn add, and somehow bind its output (the new GUID) tightly to the added file? Storing it locally is not enough: the unique ID must be stored on the SVN server, because we must be able to download it during every svn checkout and svn update.

Find out the software used for creating an image file [on hold]

Is there any way to check if an image file (png, jpg...) file have been created with Adobe Photoshop or other softwares?

Access html form element from javascript

Can a file type input element of an html form be updated using Javascript? As in my case I generate an image object which I want to assign to the input field of type file. Just like we assign the text fields of an input form from Javascript can we also update file input from Javascript? My image object of type png is stored in a variable that I want to assign to the input field.

Issue when reading a matrix from a PGM file C

I want to read a PGM file (without # comments) and export just the image data(matrix) to a new text file.So far I did managed to write the code,but not very well I think. My issue is that when I fprintf the matrix from memory to a text file it give me some lines of zeros.Same when i want to printf the matrix from memory.

Any ideas?

Play local audio file with AVAudioPlayer

I'm testing my app in simulator.

I'm downloading file and getting it's local way like this one: file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3

Now I want to play this file with AVAudioPlayer but I'm always getting this error:

file:///
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"

Code for playing:

var alertSound = NSURL(fileURLWithPath: "file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3")
        print(alertSound)

        var error:NSError?
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }

How should I make it playing?

what is the right way to write to a temp file which can be read from other app

It needs to generates a temp file and do share through other possible apps:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));
startActivity(Intent.createChooser(intent, "share file");

But when share with other app the file seems not access able. It is because the file is saved to the app internal dir.

So it needs to saved to a dir belongs to this app (so it will be removed when uninstall, best to be in a temp dir so OS could clean it is needed), and other app could also access it.

Saw getExternalCacheDir(), getExternalFilesDir(), getExternalStorageDirectory(), getExternalStoragePublicDirectory(), not sure which one is right one to use for this case. Anyone has suggestion? Thanks!

cant send file over socket C

so i try to send a file over a socket but after the file is send , it differs from the original after the first chunck of FILE_DOWNLOAD_SIZE is send. after that chunck it places one chunck off FILE_DOWNLOAD_SIZE zeroes and then the original bytes.

Server:

while (1)
    {
        ZeroMemory(buff, FILE_DOWNLOAD_SIZE);
        nread = fread(buff, 1, FILE_DOWNLOAD_SIZE, f);
        if (nread != FILE_DOWNLOAD_SIZE) {
            // LAST CHUNCK
            send(s, buff, nread, 0);
            break;
        }
        else {
            // CHUNCK OFF SIZE FILE_DOWNLOAD_SIZE
            send(s, buff, nread, 0);
        }
    }

Client:

while (1) {
        n = 0;
        ZeroMemory(r_buf, BUFSIZE - 1);
        bytesReceived = recv(sock, r_buf, FILE_DOWNLOAD_SIZE, 0);

        if (bytesReceived < 0) {
            // ERROR
            puts("[!] recv failed");
            return;
        }
        else if (bytesReceived < FILE_DOWNLOAD_SIZE) {
            // LAST CHUNCK
            if (WriteFile(out, r_buf, bytesReceived, &n, NULL) == FALSE) {
                printf("WriteFile() error %d\n", GetLastError());
            }
            SetFilePointer(out, n, NULL, FILE_CURRENT);
            break;
        }
        else {
            // CHUNCK OFF SIZE FILE_DOWNLOAD_SIZE
            if (WriteFile(out, r_buf, bytesReceived, &n, NULL) == FALSE) {
                printf("WriteFile() error %d\n", GetLastError());
            }
            SetFilePointer(out, n, NULL, FILE_CURRENT);
        }
    }

Pls tell me whats wrong

Android Studio - Android Device Monitor's File explorer not working

I have just learnt using preferences in Android. For debugging purpose I need to access the preferences files. I googled and found the default location of the preference file and also how to access it via Android Device Monitor.

Somehow I am not able to open any folders under the File explorer tab of the Android device monitor. They just aren't responding. I tried waiting for ADM to load and tried again but no success. (Double click on folder is not working, STRANGE!)

Do we need to configure before using it? I am using Android studio. Any help would be appreciated. Attaching image Android Device Monitor screenshot

Python regex on multiple src to destination

I have been reading through thousands of posts trying to find best solution. I apologize if the nature of this question has been asked multiple times before.

I have a file that I put placeholders in. The file is 200 lines and in this file there is a section where I have propertyNames and corresponding propertyValues. The propertyValues are placeholders that I want to find and substitute actual values with. I think I will use fileinput and re modules to do this, but I do not want to have to parse line by line multiple times to fill in multiple propertyValues. Instead I was thinking it would be more efficient to have multiple strings I search for and its corresponding replacement text and while its scanning through lines if it finds any instance it replaces with its corresponding replacement. What would be the best way to do this? Can it be done in a simple way with fileinput and re?

what is the right way to write to a temp file which can be read from other app

It needs to generates a temp file and do share through other possible apps:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath)));
startActivity(Intent.createChooser(intent, "share file");

But when share with other app the file seems not access able. It is because the file is saved to the app internal dir.

So it needs to saved to a dir belongs to this app (so it will be removed when uninstall, best to be in a temp dir so OS could clean it is needed), and other app could also access it.

Saw getExternalCacheDir(), getExternalFilesDir(), getExternalStorageDirectory(), getExternalStoragePublicDirectory(), not sure which one is right one to use for this case. Anyone has suggestion? Thanks!

writefile only writes 4 bytes instead of more

So I want to upload a file from server to client, the bytes are received correctly through the socket, but when it comes to writing the received bytes to the file writefile, it only writes 4 bytes of every chunk received.

Server:

while (1)
    {
        /* First read file in chunks of 1000 bytes */
        ZeroMemory(buff, FILE_DOWNLOAD_SIZE);
        nread = fread(buff, 1, FILE_DOWNLOAD_SIZE, f);
        printf("Bytes read %d \n", nread);

        if (nread > 0 && nread == FILE_DOWNLOAD_SIZE)
        {
            printf("Sending \n");
            send(s, buff, nread, 0);
        }

        if (nread < FILE_DOWNLOAD_SIZE)
        {
            printf("Sending Last Chunk (%s)\n\n\n", buff);
            send(s, buff, nread, 0);

            if (feof(f))
                printf("End of file\n");
            if (ferror(f))
                printf("Error reading\n");
            break;
        }
    }
    fclose(f);

Client:

while (1) {
        n = 0;
        memset(r_buf, 0, BUFSIZE - 1);
        bytesReceived = recv(sock, r_buf, FILE_DOWNLOAD_SIZE, 0);
        printf("Bytes received %d\n", bytesReceived);
        if (bytesReceived < 0) {
            puts("[!] recv failed");
            return;
        }
        else if (bytesReceived < FILE_DOWNLOAD_SIZE) {
            printf("Recieving Last Chunk (%s)\n\n\n", r_buf);
            if (WriteFile(out, r_buf, recv_size, &n, NULL) == FALSE) {
                printf("WriteFile() error %d\n", GetLastError());
            }
            SetFilePointer(out, n, NULL, FILE_CURRENT);
            //bytes_written = fwrite(r_buf, 1, recv_size, out);
            printf("Recieved Buff Len = (%d) Bytes written %d, should be smaller 1000\n ", strlen(r_buf), n);
            //fseek(out, bytes_written, SEEK_CUR);
            //SetFilePointer(out, n, NULL, FILE_CURRENT);
            break;
        }
        else {
            //printf("%s", r_buf);
            //bytes_written = fwrite(r_buf, 1, recv_size, out);
            if (WriteFile(out, r_buf, recv_size, &n, NULL) == FALSE) {
                printf("WriteFile() error %d\n", GetLastError());
            }
            SetFilePointer(out, n, NULL, FILE_CURRENT);
            printf("Buff Len = (%d) Bytes written %d, should be 1000\n ", strlen(r_buf), n);
            //fseek(out, bytes_written, SEEK_CUR);
        }
    }
    //fclose(out);
    CloseHandle(out);

Pls tell me what's wrong.

Find out the software used for creating an image file

Is there any way to check if an image file (png, jpg...) file have been created with Adobe Photoshop or other softwares?

SVN - Automatically generate unique ID for every versioned file

Is there an unique identifier for every versioned file in an SVN repository? If yes, can it be read using some svn command? If no, is it possible to generate one on every svn add call?

For example, if I have a GUID generator application, can I call it on every svn add, and somehow bind its output (the new GUID) tightly to the added file? Storing it locally is not enough: the unique ID must be stored on the SVN server, because we must be able to download it during every svn checkout and svn update.

How can I read and replace Strings line by line in a Text File?

I have a text file that reads this:

INSERT INTO `shops` VALUES ('', '3', '1000000', '0');
INSERT INTO `shops` VALUES ('', '3', '1000010', '0');
INSERT INTO `shops` VALUES ('', '3', '1000020', '0');
INSERT INTO `shops` VALUES ('', '3', '1000030', '0');
INSERT INTO `shops` VALUES ('', '3', '1001000', '0');

Notice for each line the first key is ''. For each line, I want to find that '', and replace it with a number (starting with 1), then add 1 to it as it goes to the next line, Like so:

INSERT INTO `shops` VALUES ('1', '3', '1000000', '0');
INSERT INTO `shops` VALUES ('2', '3', '1000010', '0');
INSERT INTO `shops` VALUES ('3', '3', '1000020', '0');
INSERT INTO `shops` VALUES ('4', '3', '1000030', '0');
INSERT INTO `shops` VALUES ('5', '3', '1001000', '0');

I've been trying to do this for a couple of hours but I'm failing.

Here is what I've been thinking of (I know this is far from right, but I'm not that savvy in c#, so maybe one of you can help me come up with the right code):

string text = File.ReadAllText("C:\\Users\\Donavon\\Desktop\\old.sql");

int i = 0;
text = text.Replace("('',", "('" + i + "',");
i++;
File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);

Thanks for any help, It's greatly appreciated

Scrapy IOError: [Errno 22] invalid mode ('wb') or filename

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import HtmlXPathSelector
import os
from Erowid.items import ErowidItem
import codecs

class ExperiencesSpider(CrawlSpider):
    name = "experiences"
    allowed_domains = ["www.erowid.org"]
    start_urls = ['http://ift.tt/1czoMRA']
    rules = [ 
        Rule(LinkExtractor(allow =('subs/exp_[a-zA-Z]+.shtml')), follow = True), 
        Rule(LinkExtractor(allow=r'/experiences/exp\.php\?ID=\d+$'),callback='parse_item', follow = True)
    ]
    def parse_item(self, response):
        selectors = response.css('div')
        for selector in selectors:
            experience = ErowidItem()
            experience['Author'] = selector.xpath('//div[@class="author"]/a/text()').extract()
            experience['Title'] = selector.xpath('//div[@class="title"]/text()').extract()
            experience['Substance'] = selector.xpath('//div[@class="substance"]/text()').extract()
            experience['Text'] = selector.xpath("//div[@class = 'report-text-surround']/text()").extract()
            experience['Title'] =  str(experience['Title']).replace('\\' , "")
            experience['Title'] =  str(experience['Title']).replace('?' , "")

            directory = os.path.join('Erowid/archive/',experience['Substance'][0].strip().lower())
            filename = os.path.join(directory,experience['Title'][0]+'.txt')

            if not os.path.exists(directory):
                os.makedirs(directory)

            with codecs.open(filename, encoding = 'utf-8', mode= 'wb') as fid:
                for symbols in experience['Text']:
                    fid.write(symbols) 
        yield experience

I am trying to scrape Erowid and so far this code is made so that I will create a directory and write a file primarily based on the name of an experience and the text. (By experience, I am referring to the information I am scrapping off Erowid.)

The problem is that some of the experiences have in their names characters that can't be written as a file because they contain reserved characters that can't be used in windows filenames.

I am trying to remove all of these reserved characters which are

  • The following reserved characters:

    • < (less than)
    • > (greater than)
    • : (colon)
    • " (double quote)
    • / (forward slash)
    • \ (backslash)
    • | (vertical bar or pipe)
    • ? (question mark)
    • * (asterisk)

I tried to do something with the lines

 experience['Title'] =  str(experience['Title']).replace('\\' , "")
 experience['Title'] =  str(experience['Title']).replace('?' , "")

(a majority of the errors come from "\" and"?") but I still receive the error

IOError: [Errno 22] invalid mode ('wb') or filename: u'Erowid/archive/syrian rue\\Meditative Help?.txt'

or some other filename that I know is wrong because there isn't supposed to be a question mark or backslashes.

What am I doing wrong that triggers these errors?

How can I copy a dat file to my home directory?

I have a dat file on my desktop called test.dat and want to copy or move it to the home directory which is called tom.

Print pdf file with Javascript [using a

I have a question. In this topic ( Can a PDF file's print dialog be opened with Javascript? ) the second answer say something about an iframe with a pdf file inside, in the 'src' attribute. The url passed into src attribute, can be a local file? Or must be a online file?

Thanks!!