dimanche 31 mai 2015

destination ID in a .cc file from traffic file / tcl file

my problem is ---

in lar.cc command () argc == 5 "sendData"  there is a line  nsaddr_t destID = (nsaddr_t)atoi(argv[2]);

Basically this line is taking the argument_2 from box.tcl 

$ns_ at $k "$g(0) sendData 49 64 B" [ # the format now for the lar send is # # "$nodeId sendData <dest ID> <size> <method>" ]

But i want destID should be taken automatically from traffic file as we do in our other routing protocols like GPSR or AODV etc. 

traffic file --- some lines are as 

# 1 connecting to 2 at time 2.5568388786897245 set udp_(0) [new Agent/UDP] $ns_ attach-agent $node_(1) $udp_(0) set null_(0) [new Agent/Null] $ns_ attach-agent $node_(2) $null_(0) set cbr_(0) [new Application/Traffic/CBR] $cbr_(0) set packetSize_ 512 $cbr_(0) set interval_ 0.25 $cbr_(0) set random_ 1 $cbr_(0) set maxpkts_ 10000 $cbr_(0) attach-agent $udp_(0) $ns_ connect $udp_(0) $null_(0) $ns_ at 2.5568388786897245 "$cbr_(0) start"

like here node2 is the destination , so destID value should be 2 , for next agent might be some different value ..............

How can i do this .........  or if possible plz tell me how this value is automatically goes in AODV or GPSR or any other routing protocol.

kindly advise further. My work is stucked ............... therefore plz help ........

Create file on internal storage MODE_WORLD_WRITEABLE,

My phone doesn't have any external storage, only internal. I want to create a file that i could access from my computer after created.

do i need to root my phone? for example i got a lot of applications that made a folder and saved their files there like Whatsapp

thanks

fwrite() not working to write integer in binary file

Can someone tell my why won't this function work? I just can't get it...

void writeRegister(FILE *arq, Book *L){ //writes in actual file position
  char c = '|';
  int sizeRegWrite = reglen(L); //reglen() returns the size of Book
  fwrite(&sizeRegWrite, sizeof(int), 1, arq);

  fwrite(L->TITLE, sizeof(char), strlen(L->TITLE), arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter

  fwrite(L->AUTHOR, sizeof(char), strlen(L->AUTHOR), arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter

  fwrite(L->PUBLISHER, sizeof(char), strlen(L->PUBLISHER), arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter

  fwrite(L->YEAR, sizeof(int), 1, arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter

  fwrite(L->LANGUAGE, sizeof(char), strlen(L->LANGUAGE), arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter

  fwrite(L->PAGES, sizeof(int), 1, arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter

  fwrite(L->PRICE, sizeof(float), 1, arq);
  fwrite(&c, sizeof(char), 1, arq); //writing delimiter
        return;
}  

The struct Book is declared like this:

typedef struct {
    char *TITLE;
    char *AUTHOR;
    char *PUBLISHER;
    int YEAR;
    char *LANGUAGE;
    int PAGES;
float PRICE;
} Book;

Main

int main() {
FILE *arq = fopen("BD_books2.bin", "rb+");
if(arq == NULL)
    printf("Error while opening file!!!");

Book L;
readData(&L); //Reads all fields from keyboard and places in Book. Working properly
writeRegister(arq, &L);

system("pause");
return 0;

}

I have to use those pointers inside the struct, so I can't remove them. By the way, my problem is only with those integers and the float.

This fuction is only working properly if I write all the integers and floats (YEAR, PAGES and PRICE) with fprintf(), but I'm writing it in a binary file, and of course I want to write it in binary, so I'm trying to use fwrite().

Another thing is: the compiler is pointing incompatible type for argument 1 of 'fwrite' at this line: fwrite(L->PRICE, sizeof(float), 1, arq);

Can someone explain me what is happening? My program crashes when it tries to write in the file...

Combining Folder Contents In Windows Explorer

This is a little unusual request and not exactly what it sounds like. Take my music folder, in this instance. I have multiple folders dedicated to each artist that composed the song. So, for example, a song by Group 1 will be in a different file location than a song by Group 2.

My goal is to, in any way possible, find some way to view all of these files in Windows Explorer without having to keep them all in the same folder (file location). I'm trying to do this because, sometimes, I want to organize all of my music by a certain tag (such as Rating, Bitrate, Genre or Mood). However, I don't want to put them all into one folder (thus changing their file location) because then, whenever I need to reference specific songs for an application or just when I'm looking for a specific song rather than trying to organize them by a certain tag, keeping them all in one folder becomes miserable (since I have THOUSANDS of songs).

I tried using a library file, but I obtained the following result: This is a snapshot of using a Library File to organize a few of my songs

However, as you'll notice, they're separated by folder. No matter what tag I decide to organize them by (as you can see "Contributing Artists" and "Album" tags to the side) they'll still stay confined to their respective folders. I just want some way to view all of my files in one list and be able to organize them all by various tags without having to keep them all in the same folder (in Windows 8.1 Explorer). That's all there is to it, and I don't know how. If you can provide any way to help, I would be very grateful.

Mac 1000 File Per Folder Limit

I've written a java program recently that scrapes various files from a site using Selenium and stores the files in a folder that is created in the user directory. I know the program is functioning correctly because it works fine on windows, but I'm also trying to get it working on mac and I'm running into a problem there. The program still functions, but as soon as I download over 1000 files the oldest files begin disappearing. I'm fairly unfamiliar with mac os so I tried looking online for some setting or reason for why this would be occurring but I can't seem to find anything. Can anyone help me?

Additional Information: I'm using the java file and filewriter classes to do my writes. Each file has a unique name so none of them should overwrite another.

Cannot replace default icon in android studio

The image I am trying to replace the default icon with is 512x512px .png. To change the icon I go app/res [new; image asset;...]. It won't let me replace or create new icon set in the @drawable. My most recent thought are that I might not have unlocked some priveges but I am able edit contents of drawable by directly accessing it's location

Any ideas?

Python read text file as binary?

I was trying to build an encryption program in python 2.7. It would read the binary from a file and then use a key to encrypt it. However, I quickly ran into a problem. Files like image files and executables read as hex values. However, text files do not using open(). Even if i run

file=open("myfile.txt", "rb")

out=file.read()

it still comes out as just text. I'm on windows 7, not linux which i think may make a difference. Is there any way i could read the binary from ANY file (including text files), not just image and executable files?

Node webkit native file drag events from nw app (dragout)

I am trying to let a user do a system-like drag event of a file from my NW.js application.

I looked at all kinds of stuff, and I have gotten quite close with the followling approach, but the issue is that it duplicates the file, and it also does not handle correctly when trying to drag into things like gmail.

Current code:

<div draggable="true" 
  ondragstart="file = new File('file:///path/to/file.docx', '' );
    event.dataTransfer.setData('DownloadURL', file.type + ':' + file.name + ':' + file.path);"
>
  Some file
</div>

Is it possible to get native/native like file drag events from a nwjs application?

I found this node-webkit-dragout, but I don't understand how I can make it work :(

I have been looking through this mozilla document as well, but no more luck there.

Concatenating strings with wildcard - Matlab

I am trying to search for file names containing the user-input string desiredfile and stored as .dat.

My code:

selectedfiles = dir(fullfile(path-to-desiredfile,['*' desiredfile '*.dat']));

However, this line returns

path-to-desiredfile/*desiredfile*.dat

rather than

path-to-desiredfile/____desiredfile___.dat*

where the underscores indicate the remainder of the file name. Thanks in advance!

How to allow wordpress website browsing but no file write or create

I would like to know how can i setup a website in a way i can browse the website normally, but deny create or write any file except from the ftp access. Just to give more explanations, I have a wordpress website who get hacked over and over. I know i have to find the exact vulnerability, but as a quick temporary fix, i would like to deny the website to create new php pages or modify existing one but still allow update to be done by ftp

For now all folder are 755 and files 644 and from what i can find, all files/folder are owned by the account user. I am on a dedicated hosting using whm/cpanel. From what i read, that must be doable using the file ownership, but i hardly get how to know what group or user to put files/folder to achieve what i asked

Thanks in advance

File Size Calculated but File Not Found

I am trying to install the "Waiting time file download script using php and jquery" script found at http://ift.tt/1I2wijd

I have downloaded the demo scripts and installed them in my server at /var/www/test/. When I try to call the demo files it recognizes the file size but says the file is not found. [url]http://ift.tt/1ADwMN3] Any ideas?

how to create .bin file on external storage

I used a lot of examples trying to understand why it doesnt create my file but i didn't and i need some help.

File myFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "FFFFFFFFF.bin");
try {
    myFile.createNewFile();
    setOutputStream(new FileOutputStream(myFile));
        for (short i = 1; i <= this.array.length; i++) {
            this.array[i-1] = new myobject(i);
        }
        get_objOutputStream().writeObject(this.array);
        getOutputStream().close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

the getters/setters are regular, it worked when i wrote it to internal file before i changed it a little so the problem is not an error or related to the array of my objects

thanks for any help

Error writing binary file in Python

I have a Python program that receives a binary file via parameter and writes this file in a directory. But when it writes the file, some characters the program replaces it with a series of numbers. Below the original file the program receives as a parameter:

**ÐT_Ö/¤Ð樮kMµûÀz”Ô(Î,“+œd¼Es¥**

But when the program writes, look at the result:

**ÐT_Ö/¤Ð樮kMµûÀz &#148 ; Ô(Î, &#147 ; &#156 ;d¼Es¥**

You can see that the character between characters z and Ô was replaced by sequence &#148 ;. Also the caracter "+" between characters Î, and œd was replaced by sequence &#147

Below the Python program code that do the leitiura and recording binary file

import subprocess
from subprocess import Popen, PIPE, STDOUT
def chamaProg(arquivo): 
   var_file = open("C:\\Nitgen\\arquivo.rec","wb")
   conteudo_texto = var_file.write(arquivo)
   var_file.close() 

Why is it happening? What should I do to read and write all the characters correctly?

Universal Resource Locator - Finding its resource location in server file system

How does the web server know the path of the resource(index.html)?, when I type http://www.example.com, It displays the home page. The home page is at "Protocol://IP address or DNS/index.html. How does just the IP address locates the path of index.html in the server file system?.

Ftp file download edit?

Hi I try to download resumeable ftp

I found http download class and work nice on http but I need ftp. can any body help me for add ftp support?

I try some code but not work ::S

not need http I need only ftp

Imports System.IO
Imports System.Net
Imports System.Threading
 
'// This is the main download class.
Public Class DownloadFileAsyncExtended
 
#Region "Methods"
 
    Private _URL As String = String.Empty
    Private _LocalFilePath As String = String.Empty
    Private _userToken As Object = Nothing
    Private _ContentLenght As Long = 0
    Private _TotalBytesReceived As Integer = 0
 
    '// Start the asynchronous download.
    Public Sub DowloadFileAsync(ByVal URL As String, ByVal LocalFilePath As String, ByVal userToken As Object)
        Dim Request As HttpWebRequest
        Dim fileURI As New Uri(URL) '// Will throw exception if empty or random string.

        '// Make sure it's a valid http:// or https:// url.
        If fileURI.Scheme <> Uri.UriSchemeHttp And fileURI.Scheme <> Uri.UriSchemeHttps Then
            Throw New Exception("Invalid URL. Must be http:// or https://")
        End If
 
        '// Save this to private variables in case we need to resume.
        _URL = URL
        _LocalFilePath = LocalFilePath
        _userToken = userToken
 
        '// Create the request.
        Request = CType(HttpWebRequest.Create(New Uri(URL)), HttpWebRequest)
        Request.Credentials = Credentials
        Request.AllowAutoRedirect = True
        Request.ReadWriteTimeout = 30000
        Request.Proxy = Proxy
        Request.KeepAlive = False
        Request.Headers = _Headers '// NOTE: Will throw exception if wrong headers supplied.

        '// If we're resuming, then add the AddRange header.
        If _ResumeAsync Then
            Dim FileInfo As New FileInfo(LocalFilePath)
            If FileInfo.Exists Then
                Request.AddRange(FileInfo.Length)
            End If
        End If
 
        '// Signal we're busy downloading
        _isbusy = True
 
        '// Make sure this is set to False or the download will stop immediately.
        _CancelAsync = False
 
        '// This is the data we're sending to the GetResponse Callback.
        Dim State As New HttpWebRequestState(LocalFilePath, Request, _ResumeAsync, userToken)
 
        '// Begin to get a response from the server.
        Dim result As IAsyncResult = Request.BeginGetResponse(AddressOf GetResponse_Callback, State)
 
        '// Add custom 30 second timeout for connecting.
        '// The Timeout property is ignored when using the asynchronous BeginGetResponse.
        ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf TimeoutCallback), State, 30000, True)
    End Sub
 
    '// Here we receive the response from the server. We do not check for the "Accept-Ranges"
    '// response header, in order to find out if the server supports resuming, because it MAY
    '// send the "Accept-Ranges" response header, but is not required to do so. This is
    '// unreliable, so we'll just continue and catch the exception that will occur if not
    '// supported and send it the DownloadCompleted event. We also don't check if the
    '// Content-Length is '-1', because some servers return '-1', eventhough the file/webpage
    '// you're trying to download is valid. e.ProgressPercentage returns '-1' in that case.
    Private Sub GetResponse_Callback(ByVal result As IAsyncResult)
        Dim State As HttpWebRequestState = CType(result.AsyncState, HttpWebRequestState)
        Dim DestinationStream As FileStream = Nothing
        Dim Response As HttpWebResponse = Nothing
        Dim Duration As New Stopwatch
        Dim Buffer(8191) As Byte
        Dim BytesRead As Integer = 0
        Dim ElapsedSeconds As Integer = 0
        Dim DownloadSpeed As Integer = 0
        Dim DownloadProgress As Integer = 0
        Dim BytesReceivedThisSession As Integer = 0
 
        Try
            ''// Get response
            Response = CType(State.Request.EndGetResponse(result), HttpWebResponse)
 
            '// Asign Response headers to ReadOnly ResponseHeaders property.
            _ResponseHeaders = Response.Headers
 
            '// If the server does not reply with an 'OK (200)' message when starting
            '// the download or a 'PartialContent (206)' message when resuming.
            If Response.StatusCode <> HttpStatusCode.OK And Response.StatusCode <> HttpStatusCode.PartialContent Then
                '// Send error message to anyone who is listening.
                OnDownloadCompleted(New FileDownloadCompletedEventArgs(New Exception(Response.StatusCode), False, State.userToken))
                Return
            End If
 
            '// Create/open the file to write to.
            If State.ResumeDownload Then
                '// If resumed, then create or open the file.
                DestinationStream = New FileStream(State.LocalFilePath, FileMode.OpenOrCreate, FileAccess.Write)
            Else
                '// If not resumed, then create the file, which will delete the existing file if it already exists.
                DestinationStream = New FileStream(State.LocalFilePath, FileMode.Create, FileAccess.Write)
                '// Get the ContentLength only when we're starting the download. Not when resuming.
                _ContentLenght = Response.ContentLength
            End If
 
            '// Moves stream position to beginning of the file when starting the download.
            '// Moves stream position to end of the file when resuming the download.
            DestinationStream.Seek(0, SeekOrigin.End)
 
            '// Start timer to get download duration / download speed, etc.
            Duration.Start()
 
            '// Get the Response Stream.
            Using responseStream As Stream = Response.GetResponseStream()
                Do
                    '// Read some bytes.
                    BytesRead = responseStream.Read(Buffer, 0, Buffer.Length)
                    If BytesRead > 0 Then
                        '// Write incoming data to the file.
                        DestinationStream.Write(Buffer, 0, BytesRead)
                        '// Count the total number of bytes downloaded.
                        _TotalBytesReceived += BytesRead
                        '// Count the number of bytes downloaded this session (Resume).
                        BytesReceivedThisSession += BytesRead
                        '// Get number of elapsed seconds (need round number to prevent 'division by zero' error).
                        ElapsedSeconds = CInt(Duration.Elapsed.TotalSeconds)
 
                        '// Update frequency: No Delay, every Half a Second or every Second.
                        Select Case ProgressUpdateFrequency
                            Case UpdateFrequency.NoDelay
                                '// Calculate download speed in bytes per second.
                                If ElapsedSeconds > 0 Then
                                    DownloadSpeed = (BytesReceivedThisSession \ ElapsedSeconds)
                                End If
                                '// Send download progress to anyone who is listening.
                                OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, ElapsedSeconds, DownloadSpeed, State.userToken))
                            Case UpdateFrequency.HalfSecond
                                If (Duration.ElapsedMilliseconds - DownloadProgress) >= 500 Then
                                    DownloadProgress = Duration.ElapsedMilliseconds
                                    '// Calculate download speed in bytes per second.
                                    If ElapsedSeconds > 0 Then
                                        DownloadSpeed = (BytesReceivedThisSession \ ElapsedSeconds)
                                    End If
                                    '// Send download progress to anyone who is listening.
                                    OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, ElapsedSeconds, DownloadSpeed, State.userToken))
                                End If
                            Case UpdateFrequency.Second
                                If (Duration.ElapsedMilliseconds - DownloadProgress) >= 1000 Then
                                    DownloadProgress = Duration.ElapsedMilliseconds
                                    '// Calculate download speed in bytes per second.
                                    If ElapsedSeconds > 0 Then
                                        DownloadSpeed = (BytesReceivedThisSession \ ElapsedSeconds)
                                    End If
                                    '// Send download progress to anyone who is listening.
                                    OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, ElapsedSeconds, DownloadSpeed, State.userToken))
                                End If
                        End Select
 
                        '// Exit loop when paused.
                        If _CancelAsync Then Exit Do
 
                    End If
                Loop Until BytesRead = 0
            End Using
 
            '// Send download progress once more. If the UpdateFrequency has been set to
            '// HalfSecond or Second, then the last percentage returned might be 98% or 99%.
            '// This makes sure it's 100%.
            OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, Duration.Elapsed.TotalSeconds, DownloadSpeed, State.userToken))
 
            If _CancelAsync Then
                '// Send completed message (Paused) to anyone who is listening.
                OnDownloadCompleted(New FileDownloadCompletedEventArgs(Nothing, True, State.userToken))
            Else
                '// Send completed message (Finished) to anyone who is listening.
                OnDownloadCompleted(New FileDownloadCompletedEventArgs(Nothing, False, State.userToken))
            End If
        Catch ex As Exception
            '// Send completed message (Error) to anyone who is listening.
            OnDownloadCompleted(New FileDownloadCompletedEventArgs(ex, False, State.userToken))
        Finally
            '// Close the file.
            If DestinationStream IsNot Nothing Then
                DestinationStream.Flush()
                DestinationStream.Close()
                DestinationStream = Nothing
            End If
            '// Stop and reset the duration timer.
            Duration.Reset()
            Duration = Nothing
            '// Signal we're not downloading anymore.
            _isbusy = False
        End Try
    End Sub
 
    '// Here we will abort the download if it takes more than 30 seconds to connect, because
    '// the Timeout property is ignored when using the asynchronous BeginGetResponse.
    Private Sub TimeoutCallback(ByVal State As Object, ByVal TimedOut As Boolean)
        If TimedOut Then
            Dim RequestState As HttpWebRequestState = CType(State, HttpWebRequestState)
            If RequestState IsNot Nothing Then
                RequestState.Request.Abort()
            End If
        End If
    End Sub
 
    '// Cancel the asynchronous download.
    Private _CancelAsync As Boolean = False
    Public Sub CancelAsync()
        _CancelAsync = True
    End Sub
 
    '// Resume the asynchronous download.
    Private _ResumeAsync As Boolean = False
    Public Sub ResumeAsync()
        '// Throw exception if download is already in progress.
        If _isbusy Then
            Throw New Exception("Download is still busy. Use IsBusy property to check if download is already busy.")
        End If
 
        '// Throw exception if URL or LocalFilePath is empty, which means
        '// the download wasn't even started yet with DowloadFileAsync.
        If String.IsNullOrEmpty(_URL) AndAlso String.IsNullOrEmpty(_LocalFilePath) Then
            Throw New Exception("Cannot resume a download which hasn't been started yet. Call DowloadFileAsync first.")
        Else
            '// Set _ResumeDownload to True, so we know we need to add
            '// the Range header in order to resume the download.
            _ResumeAsync = True
            '// Restart (Resume) the download.
            DowloadFileAsync(_URL, _LocalFilePath, _userToken)
        End If
    End Sub
 
#End Region
 
#Region "Properties"
 
    Public Enum UpdateFrequency
        NoDelay = 0
        HalfSecond = 1
        Second = 2
    End Enum
 
    '// Progress Update Frequency.
    Public Property ProgressUpdateFrequency() As UpdateFrequency
 
    '// Proxy.
    Public Property Proxy() As IWebProxy
 
    '// Credentials.
    Public Property Credentials() As ICredentials
 
    '// Headers.
    Public Property Headers() As New WebHeaderCollection
 
    '// Is download busy.
    Private _isbusy As Boolean = False
    Public ReadOnly Property IsBusy() As Boolean
        Get
            Return _isbusy
        End Get
    End Property
 
    '// ResponseHeaders.
    Private _ResponseHeaders As WebHeaderCollection = Nothing
    Public ReadOnly Property ResponseHeaders() As WebHeaderCollection
        Get
            Return _ResponseHeaders
        End Get
    End Property
 
    '// SynchronizingObject property to marshal events back to the UI thread.
    Private _synchronizingObject As System.ComponentModel.ISynchronizeInvoke
    Public Property SynchronizingObject() As System.ComponentModel.ISynchronizeInvoke
        Get
            Return Me._synchronizingObject
        End Get
        Set(ByVal value As System.ComponentModel.ISynchronizeInvoke)
            Me._synchronizingObject = value
        End Set
    End Property
 
#End Region
 
#Region "Events"
 
    Public Event DownloadProgressChanged As EventHandler(Of FileDownloadProgressChangedEventArgs)
    Private Delegate Sub DownloadProgressChangedEventInvoker(ByVal e As FileDownloadProgressChangedEventArgs)
    Protected Overridable Sub OnDownloadProgressChanged(ByVal e As FileDownloadProgressChangedEventArgs)
        If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
            'Marshal the call to the thread that owns the synchronizing object.
            Me.SynchronizingObject.Invoke(New DownloadProgressChangedEventInvoker(AddressOf OnDownloadProgressChanged), _
                                          New Object() {e})
        Else
            RaiseEvent DownloadProgressChanged(Me, e)
        End If
    End Sub
 
    Public Event DownloadCompleted As EventHandler(Of FileDownloadCompletedEventArgs)
    Private Delegate Sub DownloadCompletedEventInvoker(ByVal e As FileDownloadCompletedEventArgs)
    Protected Overridable Sub OnDownloadCompleted(ByVal e As FileDownloadCompletedEventArgs)
        If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
            'Marshal the call to the thread that owns the synchronizing object.
            Me.SynchronizingObject.Invoke(New DownloadCompletedEventInvoker(AddressOf OnDownloadCompleted), _
                                          New Object() {e})
        Else
            RaiseEvent DownloadCompleted(Me, e)
        End If
    End Sub
 
#End Region
 
End Class
 

'// This class is passed as a parameter to the GetResponse Callback,
'// so we can work with the data in the Response Callback.
Public Class HttpWebRequestState
    Private _LocalFilePath As String
    Private _Request As HttpWebRequest
    Private _ResumeDownload As Boolean
    Private _userToken As Object
 
    Public Sub New(ByVal LocalFilePath As String, ByVal Request As HttpWebRequest, ByVal ResumeDownload As Boolean, ByVal userToken As Object)
        _LocalFilePath = LocalFilePath
        _Request = Request
        _ResumeDownload = ResumeDownload
        _userToken = userToken
    End Sub
 
    Public ReadOnly Property LocalFilePath() As String
        Get
            Return _LocalFilePath
        End Get
    End Property
 
    Public ReadOnly Property Request() As HttpWebRequest
        Get
            Return _Request
        End Get
    End Property
 
    Public ReadOnly Property ResumeDownload() As Boolean
        Get
            Return _ResumeDownload
        End Get
    End Property
 
    Public ReadOnly Property userToken() As Object
        Get
            Return _userToken
        End Get
    End Property
End Class
 

'// This is the data returned to the user for each download in the
'// Progress Changed event, so you can update controls with the progress.
Public Class FileDownloadProgressChangedEventArgs
    Inherits System.EventArgs
 
    Private _BytesReceived As Integer
    Private _TotalBytesToReceive As Integer
    Private _DownloadTime As Integer
    Private _DownloadSpeed As Long
    Private _userToken As Object
 
    Public Sub New(ByVal BytesReceived As Integer, ByVal TotalBytesToReceive As Integer, ByVal DownloadTime As Integer, ByVal DownloadSpeed As Long, ByVal userToken As Object)
        _BytesReceived = BytesReceived
        _TotalBytesToReceive = TotalBytesToReceive
        _DownloadTime = DownloadTime
        _DownloadSpeed = DownloadSpeed
        _userToken = userToken
    End Sub
 
    Public ReadOnly Property BytesReceived() As Integer
        Get
            Return _BytesReceived
        End Get
    End Property
 
    Public ReadOnly Property TotalBytesToReceive() As Integer
        Get
            Return _TotalBytesToReceive
        End Get
    End Property
 
    Public ReadOnly Property ProgressPercentage() As Integer
        Get
            If _TotalBytesToReceive > 0 Then
                Return Math.Ceiling((_BytesReceived / _TotalBytesToReceive) * 100)
            Else
                Return -1
            End If
        End Get
    End Property
 
    Public ReadOnly Property DownloadTimeSeconds() As Integer
        Get
            Return _DownloadTime
        End Get
    End Property
 
    Public ReadOnly Property RemainingTimeSeconds() As Integer
        Get
            If DownloadSpeedBytesPerSec > 0 Then
                Return Math.Ceiling((_TotalBytesToReceive - _BytesReceived) / DownloadSpeedBytesPerSec)
            Else
                Return 0
            End If
        End Get
    End Property
 
    Public ReadOnly Property DownloadSpeedBytesPerSec() As Long
        Get
            Return _DownloadSpeed
        End Get
    End Property
 
    Public ReadOnly Property userToken() As Object
        Get
            Return _userToken
        End Get
    End Property
End Class
 

'// This is the data returned to the user for each download in the
'// Download Completed event, so you can update controls with the result.
Public Class FileDownloadCompletedEventArgs
    Inherits System.EventArgs
 
    Private _ErrorMessage As Exception
    Private _Cancelled As Boolean
    Private _userToken As Object
 
    Public Sub New(ByVal ErrorMessage As Exception, ByVal Cancelled As Boolean, ByVal userToken As Object)
        _ErrorMessage = ErrorMessage
        _Cancelled = Cancelled
        _userToken = userToken
    End Sub
 
    Public ReadOnly Property ErrorMessage() As Exception
        Get
            Return _ErrorMessage
        End Get
    End Property
 
    Public ReadOnly Property Cancelled() As Boolean
        Get
            Return _Cancelled
        End Get
    End Property
 
    Public ReadOnly Property userToken() As Object
        Get
            Return _userToken
        End Get
    End Property
End Class

can anybody help me?

Alternative JAVA WAR/ZIP/JAR reader/manipulator library

I am struggling to find some alternative library which would make browsing some.war file.

Problem is I need to parse WAR file then find specific JAR by name and some of the contents inside JAR file. Then I must parse those contents e.g. pom.xml from those jars to create a separate maven project module with only certain dependencies and configuration appended from other resources. I found java.util.zip package a bit inconvenient and cluttering.

Is there some alternative to java.util.zip that could make parsing/reading war without such headaches like switching between ZipFile/ZipEntry -> JarFile/JarEntry ? Something that could treat zip/war/jar and jar files inside war archive just like a directory ? Or one must craft his/her own solution ?

Thank you,

Split big shinydashboard app into pieces

I'm quite new to shiny and shinydashboard. My first application has grown to a size that I would like to refactor it into pieces as hinted http://ift.tt/1HEoFg8 here

dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody()
)

It should be a fairly simple task. However I could not find any examples on how to split my app into multiple files. And I am not sure what is the best way to do this.

I could not get it to work so far: I tried calling source("myBody.R") within each part.

Saving custom object to sdcard (Android)

I'm exploring saving internally versus saving on the sdcard. Currently, I'm trying to save a custom object (DummyTwice) on the sdcard, like so:

            String root = (Environment.getExternalStorageDirectory().toString());
            File dir = new File(root + PUB_EXT_DIR);
            dir.mkdirs();
            File file = new File(dir,FILE_NAME);

            try {

                DummyTwice dt = new DummyTwice(textEnter.getText().toString());
                FileOutputStream os = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(os);
                oos.writeObject(dt);
                oos.close();
                os.close();

                Toast.makeText(v.getContext(),"Object Saved",Toast.LENGTH_SHORT).show();
                Toast.makeText(v.getContext(),file.getAbsolutePath(), Toast.LENGTH_LONG).show();

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

Execution stops at:

FileOutputStream os = new FileOutputStream(file);

Catching the exception:

FileNotFoundException e

What am I doing wrong? Relevant constants:

private final static String PUB_EXT_DIR = /data
private final static String FILE_NAME = /obj.dat 

Java FileReader: How to assign every line in the text file to a variable

I want every line in my textdoc to be assigned to a variable.

import java.io.*;
import static java.lang.System.*;

class readfile {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("filename");
            BufferedReader br = new Buffered(fr);
            String str;
            while ((str = br.readLine()) != null) {}
            br.close();
        } catch (IOException e) {
            out.println("file not found");
        }
    }
}

Can't delete or change specific file

I have one particular file that, even it's been written by my own process, can't be deleted:

Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(destination);

No matter what I try, I always get:

java.nio.file.AccessDeniedException: C:\ProgramData\FAForever\bin\BsSndRpt.exe
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) ~[na:1.8.0_45]
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.8.0_45]
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.8.0_45]
    at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source) ~[na:1.8.0_45]
    at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(Unknown Source) ~[na:1.8.0_45]
    at java.nio.file.Files.deleteIfExists(Unknown Source) ~[na:1.8.0_45]

All other files, with EXACTLY the same user/group permission and owner, don't have this problem. And no, the file isn't opened, since I just copied it there.

How can this possibly be? How could I find out? (ProcMon only gave "BUFFER OVERFLOW" but no access violation or so) How can I fix it?

I am trying to do small encrypting by changing each char in txt file by -- each char. Can anyone help me debug?

//I am trying to do small encrypting by changing each char in txt file by --it, and save it to another file //Can anyone help me debug?

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

public class writer {

public static void main(String args[]) {        
 try {
    File input = new File("input.txt");
    File output = new File("output.txt");
    Scanner sc = new Scanner(input);
    PrintWriter printer = new PrintWriter(output);
    while(sc.hasNextLine()) {
        String s = sc.nextLine();
for (int i = 0; i < s.length(); i++){  //processing each line`
            char c = s.charAt(i);        
         //Process each char in each new lined String
        c--; 
        s.charAt(i)=c;//<< error appears here
        }
        printer.write(s);
    printer.write("\n");//new line 



    }
printer.flush();//close writer
}
catch(FileNotFoundException e) {
    System.err.println("File not found. Please scan in new file.");//exception
}
}

}

How to group array of the same name using Python?

I have over a thousand array categories in a text file, for example:

Category A1 and Cateogry A2: (array in matlab code)

A1={[2,1,2]};
A1={[4,2,1,2,3]};
A2={[3,3,2,1]};
A2={[4,4,2,2]};
A2={[2,2,1,1,1]};

I would like to use Python to help me read the file and group them into:

A1=[{[2,1,2]} {[4,2,1,2,3]}];  
A2=[{[3,3,2,1]} {[4,4,2,2]} {[2,2,1,1,1]}];

File with string in JSON format , how to read filecontent into NSDictionary

I have a file-"xyz.txt" in my applicaion bundle with just JSON formatted text. I want to open the filepath of the text file and read the content to NSDictionary. How to do that.

{
"ABC": [
    {
      "id": "01",
      "score": "0.2"
    },
    {
      "id": "02",
      "score": "0.2"
    }
  ],
  "XYZ": [
    {
      "id": "01",
      "score": "0.9"
    },
    {
      "id": "02",
      "score": "0.9"
    }
   ],
  "PQR": [
    {
      "id": "01",
      "score": "0.9"
    },
    {
      "id": "02",
      "score": "0.3"
    },
    {
      "id": "03",
      "score": "0.2"
    }
   ]
}

how can i use ruby and twitter tweet from text file

I'm trying to tweet from a text file without getting the extra symbols.

My tweets looks like: ["This is a sample of my tweet on twitter"\n] << it includes the symbols and the extra "n".

What I'm trying to get is: This is a sample of what I want my tweet to look like. << no extra symbols.

My code:

def tweet
  file = File.open("tweets_from.txt","r")
  read = file.readlines.sample(1)
  client.update("#{read}").text
end

tweet

Thanks in advance for your help :)

2 files with same data being computed the same way producing different output

Firstly, I apologise for the vague question but I am at my wits end. I have made a compiler than converts Assembly code into Binary.

I have two files called "test.asm" and "MaxL.asm" that both have the same information in them:

// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/06/max/MaxL.asm

// Symbol-less version of the Max.asm program.

@0
D=AMD
@1
D=D-M
@10
D;JGT
@1
D=M
@12
0;JMP
@0
D=M
@2
M=D
@14
0;JMP

When I call my program, a .hack extended file is generated (eg. test.hack)

When I call my program, MaxL.hack and test.hack should have the same output, however they don't!

Any point in the right direction would be incredibly appreciated.

Here is my code for context:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int tempVarInst;
int tempVarDest;
int tempVarJmp = 0;


bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

bool isComment(string line){
    string comment = "/";
    if((line.find(comment)) != string::npos){
        return true;
    }else{
        return false;
    }
}

string ConvertToBinary(unsigned int val)
{

    string tempStore;

   unsigned int mask = 1 << (sizeof(int) * 4 - 1);

   for(int i = 0; i < sizeof(int) * 4; i++)
   {
      if( (val & mask) == 0 )
         tempStore+='0';
      else
         tempStore+='1';


      mask  >>= 1;
   }
   return tempStore;
}

bool isMemLoc(string line){
    string symbol = "@";
    if(line.find(symbol) != string::npos ){
        return true;
    }else{
        return false;
    }

}


int destConstants(string line){

    if(line== "A")
        return 2;
    if(line== "M")
        return 8;
    if(line== "D")
        return 16;
    if(line== "AM")
        return 40;
    if(line== "AD")
        return 48;
    if(line== "MD")
        return 24;
    if(line== "AMD")
        return 56;  
}

int isInst(string line){

    if(line=="0")
        return 60032;
    if(line=="1")
        return 61376;
    if(line=="-1")
        return 61056;
    if(line=="D")
        return 58112;
    if(line=="!D")
        return 58176;
    if(line=="M")
        return 64512;
    if(line=="A")
        return 60416;
    if(line=="!M")
        return 64576;
    if(line=="!A")
        return 60480;
    if(line=="-D")
        return 58304;
    if(line=="-M")
        return 64704;
    if(line=="-A")
        return 60608;
    if(line=="D+1")
        return 59328;
    if(line== "M+1")
        return 64960;
    if(line== "A+1")
        return 60864;
    if(line== "D-1")
        return 58240;
    if(line== "M-1")
        return 64640;
    if(line== "A-1")
        return 60544;
    if(line== "D+M")
        return 61568;
    if(line== "D+A")
        return 57472;
    if(line== "D-M")
        return 62656;
    if(line== "D-A")
        return 58560;
    if(line== "M-D")
        return 61888;
    if(line== "A-D")
        return 57792;
    if(line== "D&M")
        return 61440;
    if(line== "D&A")
        return 57344;
    if(line== "D|M")
        return 62784;
    if(line== "D|A")
        return 58688;   
}


int jmpConstants(string line){

    if(line== "JGT")
        return 1;
    if(line== "JEQ")
        return 2;
    if(line== "JGE")
        return 3;
    if(line== "JLT")
        return 4;
    if(line== "JNE")
        return 5;
    if(line== "JLE")
        return 6;
    if(line== "JMP")
        return 7;
}

bool isJumpInstruction(string line){

    string symbol = ";";
    if(line.find(symbol) != string::npos ){
        return true;
    }else{
        return false;
    }

}

int main( int argc, const char* argv[] )
{
    string outLine = "testa output";
    string file1 = argv[1];
    replace(file1, "asm", "hack");

    //input
    //WHILE READ LINE()
    ifstream infile(argv[1]);
    string tempLine;

    ofstream outfile(file1.c_str());
    tempVarJmp=0;
    tempVarDest=0;
    tempVarInst=0;
    while (getline(infile, tempLine)){
        //Blank check
        cout << "The tempLine is: " << tempLine << endl;
        if(tempLine.length()<=1){
            continue;
        }
        //Comment Check
        else if(isComment(tempLine))
            continue;
        //@ Check
        else if(isMemLoc(tempLine)){
            tempLine.erase(0,1);
            int number = (atoi(tempLine.c_str()));
            cout << ConvertToBinary(number) << endl;
            outfile << ConvertToBinary(number) << std::endl;
            continue;
            }

            //tempLine=tempLine(isInst).c_str+tempLine(destConstants)+tempLine(jmpConstants);
            //outfile << ConvertToBinary(tempLine) << endl;

        else if(isJumpInstruction(tempLine)){

                cout << "Jump Instruction" << endl;
                tempVarJmp = jmpConstants(tempLine.substr(tempLine.find(';')+1));
                cout << "TempVarInst: " << tempLine.substr(tempLine.find(';')+1) << endl;
                cout << "tempVarJmp: " << tempVarJmp << endl;
                tempVarDest = isInst(tempLine.substr(0,tempLine.find(';')));
                cout << "tempvarDest = " << tempVarDest << endl;

                int finalVal=tempVarDest+tempVarJmp;
                outfile << ConvertToBinary(finalVal) << std::endl;
                cout << ConvertToBinary(finalVal) << endl;
            }else{

                cout << "Right TempLineInst is: " << tempLine.substr(tempLine.find('=')+1,tempLine.length()) << endl;
                cout << "Right TempLineDest is: " << tempLine.substr(0,tempLine.find('=')) << endl;

                tempVarInst = isInst(tempLine.substr(tempLine.find('=')+1,tempLine.length()));
                tempVarDest = destConstants(tempLine.substr(0,tempLine.find('=')));
                tempVarJmp = 0;
                if(tempLine.substr(1,2) == ";J"){
                    tempVarJmp = jmpConstants(tempLine.substr(2,4));
                    cout << "TempLineDest is: " << tempLine.substr(2,4) << endl;

                }
                cout << "tempvarInst = " << tempVarInst << endl;
                cout << "tempvarDest = " << tempVarDest << endl;
                cout << "tempvarJmp = " << tempVarJmp << endl;
                int totalSum = tempVarInst+tempVarDest+tempVarJmp;
                cout << "totalSum: " << ConvertToBinary(totalSum) << endl;

                outfile << ConvertToBinary(totalSum) << std::endl;
            }


        //print to terminal and pass to file
        //outfile << tempLine << std::endl;
    }

    outfile.close();
    //BINARY CONVERSION, feed conversion into 'line' variable
    //output
}

Write a program to count the number of times a character appears in the File. (Case insensitive... 'a' and 'A' are considered to be the same)

Write a program to count the number of times a character appears in the File. (Case insensitive... 'a' and 'A' are considered to be the same)

Input and Output Format:

Refer sample input and output for formatting specifications.

All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output:

Enter the file name

test.txt

Enter the character to be counted

r

File 'test.txt' has 99 instances of letter 'r'.

samedi 30 mai 2015

Write a .txt file in c

i'm trying to write in a file in a certain format, but when i open the file in notepad, it's not as i want. if I decrease the size of the window(notepad) became as i want, but if I maximize a little bit the format change. My code to generate the file is:

#include <stdio.h>
#include <stdlib.h>

void main(){
FILE *fp,*fp2;
int i=0;
int num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12;
fp=fopen("treino01.bin","r");
fp2=fopen("treino02.txt","w");

fprintf(fp2,"ESTC\tNDEP\tRENDA\tTIPOR\tVBEM\tNPARC\tVPARC\tTEL\tIDADE\tRESMS\tENTRADA\tCLASSE\n",num1,num2,num3,num4,num5,
                num6,num7,num8,num9,num10,num11,num12);
while( (fscanf(fp, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", &num1, &num2, &num3, &num4, &num5, 
        &num6, &num7, &num8, &num9, &num10, &num11, &num12))!= EOF ){

    printf("%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\n",num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12);
    fprintf(fp2,"%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\t%d,\n",num1,num2,num3,num4,num5,num6,num7,num8,num9,num10,num11,num12);


}

fclose(fp);
fclose(fp2);
}

the first file file is like:

12 fields and each field is represented as a numbers, it's a table.

The second file is just read the first file and insert the comma after each number.(1,)

what I need to do is just insert a comma after each number. I don't know if u guys got my point. I cannot put the files here because the system don't allow. Thanks!

How to show only non-hidden folders programmatically

So I have this simple method that helps list all of the files in a directory (hidden and non-hidden) and I wish to edit it to display only non hidden files.

 public ArrayList<String> GetFiles(String DirectoryPath) {
        ArrayList<String> MyFiles = new ArrayList<String>();
        File file = new File(DirectoryPath);

        //You create an array list
        //The public final field length, which contains the number of components of the array
        file.mkdirs();
        File[] files = file.listFiles();
        //list all of the files in the array
        if (files.length == 0)
            //if there are no files, return null
            return null;
        else {
            //if the number of files is greater than 0, add the files and their names
            for (int i = 0; i < files.length; i++)
                MyFiles.add(files[i].getName());
        }

        return MyFiles;

How can I modify the above code to only display non hidden files?

By the way, inserting a . in front of a file name hides the file.

Thank you.

Is It Possibly to Access Firefox Save As Command Using JS?

I'm trying to figure out how to call the File Save As Command in Firefox (the one you get when you right click an image and save it) to save an image using JS (or if there is something else I can use, I would be grateful if you pointed me in that direction). I am looking for an example of how to open the Save As menu and pre-fill the file name field ... I've been searching furiously and have come up with zip. In my search I saw that you cannot directly save a file to disk, but is it impossible to call the save as function? Any suggestions would be greatly appreciated!

-Will

Write a file within another file

Like the title says I'm trying to write a file within another binary file, the thing is that the way I do it, it seems that it saves a reference to the original file, not the file itself, anyone knows how can I do save the whole file not just a reference? here's the code I used:

File archivo = new File(name + ".compressing");
BitOS fop = new BitOS(
        new FileOutputStream(archivo));
for (int i = 0; i < secuenciaFinal.length(); i++) {
    if (secuenciaFinal.charAt(i) == '1') {
        fop.write(1);//lee la cadena y si contiene 1 escribe 1 bit en mi archivo
    } else if (secuenciaFinal.charAt(i) == '0') {
        fop.write(0);//si la cadena contiene 0 escribe 0 bits
    }
}
fop.close();
// guardar el árbol y el archivo con la secuencia como binario.
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try {
    fout = new FileOutputStream(name + ".DABCZIP");
    oos = new ObjectOutputStream(fout);
    oos.writeObject(archivo);           
    oos.writeObject(root);
    oos.writeObject(extension);

} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (oos != null) {
        oos.close();
    }
}

I want to be able to save "archivo" in the new file. Thanks in advance.

Why is my text file always empty?

I have created a game that saves your high score in a text file called highscores.txt. When I open the game, the correct high score is displayed. But when I open the text file, it is always empty. Why is this? Here is my code for writing and reading the text file.

FileInputStream fin = new FileInputStream("highscores.txt");
DataInputStream din = new DataInputStream(fin);

highScore = din.readInt();
highSScore.setText("High Score: " + highScore);
din.close();

FileOutputStream fos = new FileOutputStream("highscores.txt");
DataOutputStream dos = new DataOutputStream(fos);

dos.writeInt(highScore);
dos.close();

Write a file into another binary file

Like the title says I'm trying to write a file within another binary file, the thing is that the way I do it, it seems that it saves a reference to the original file, not the file itself, anyone knows how can I do save the whole file not just a reference? here's the code I used:

File archivo = new File(name + ".compressing");
    BitOS fop = new BitOS(
            new FileOutputStream(archivo));
    for (int i = 0; i < secuenciaFinal.length(); i++) {
        if (secuenciaFinal.charAt(i) == '1') {
            fop.write(1);//lee la cadena y si contiene 1 escribe 1 bit en mi archivo
        } else if (secuenciaFinal.charAt(i) == '0') {
            fop.write(0);//si la cadena contiene 0 escribe 0 bits
        }
    }
    fop.close();
    // guardar el árbol y el archivo con la secuencia como binario.
    ObjectOutputStream oos = null;
    FileOutputStream fout = null;
    try {
        fout = new FileOutputStream(name + ".DABCZIP");
        oos = new ObjectOutputStream(fout);
        oos.writeObject(archivo);           
        oos.writeObject(root);
        oos.writeObject(extension);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (oos != null) {
            oos.close();
        }
    }

I want to be able to save "archivo" in the new file. Thanks in advance.

How to sort file output?

I have a program that takes user input and creates Records with several fields that the user enters. The user is asked to enter the first and last name of the person, address, city, state, zipcode, and phone #. I'm trying to sort the records in alphabetical order in relation to the city of each record. How would I go about this, I'm pretty stumped on how I could sort based on one variable and then print the entire record properly.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct Record Record;

struct Record
    {
        char fname[51];
        char lname[51];
        char address[51];
        char city[51];
        char state[51];
        char zipcode[51];
        char phoneNumber[51];

        Record *next;
    };


int main()
{
    FILE *fileWriter;
    const char filename[] = "data.txt";
    char answer = '\0';
    Record *records = NULL;
    Record *records_first = NULL;
    Record *records_previous = NULL;

    fileWriter = fopen(filename,"wt");

    if(fileWriter != NULL) {

        for( ; ; ) {
            records = (Record*) malloc(sizeof(Record));  

            if(records_first == NULL)
                records_first = records;

            if(records_previous != NULL)
                records_previous->next = records;

            records = records_first;
            printf("First Name: \n");
            scanf("%s", records->fname);
            fprintf(fileWriter,"%s\t",records->fname);

            printf("Last Name: \n");
            scanf("%s", records->lname);
            fprintf(fileWriter,"%s\t",records->lname);

            printf("Address: \n");
            scanf(" %[^\n]", records->address);
            fprintf(fileWriter,"%s\t",records->address);

            printf("City: \n");
            scanf("%s", records->city);
            fprintf(fileWriter,"%s\t",records->city);

            printf("State: \n");
            scanf("%s", records->state);
            fprintf(fileWriter,"%s\t",records->state);

            printf("Zipcode: \n");
            scanf("%s", records->zipcode);
            fprintf(fileWriter,"%s\t",records->zipcode);

            printf("Phone Number: \n");
            scanf("%s", records->phoneNumber);
            fprintf(fileWriter,"%s\t\n",records->phoneNumber);

            records->next = NULL;
            records_previous = records;

            printf("Are there anymore records? [y/n] ");
            scanf(" %c", &answer);

            if(tolower(answer) != 'y') {
                free(records);
                fclose(fileWriter);
                break;
            }
        }

    } else
        printf("Error opening file.");

    return 0;
}

C# redirect a file generate by a process

im making an asp.net app and in the app im running a process that generate a pdf file, but the file is generated in IIS Express folder and only admin has access to the file, so, i need to redirect that file when the process end, i want to redirect to an especific folder, What can i do?

Reading a file in C and passing the contents to main()

I'm new to C. I'm having an issue accessing the data read in from a file. The idea behind what I'm trying to do is get a text file, read it in, create an array and set the contents of that array equal to the contents of the file (the characters).

Now, here is where I get confused. To manipulate tStr in the main method, I need to be able to access its contents set in the read method. If I try to access the tStr array in the main class, from my understanding, you wont be able to considering you have only set the size of it but passed no values into it.

If I want to edit the array tStr that should contain the contents of the text file how do i get that data from readFile() to main()

#include <stdio.h>
    #include <stdlib.h>

    #define size 1000

    int readFile(char fn[], char tStr[]);

    int main(int argc, char* argv[]){

        char tStr[size];
        return 0;
    }

    int readFile(char fn[], char tStr[])
    {
        FILE *fptr;
        char c;
        int i = 0;

        if ((fptr=fopen(fn, "r")) == NULL){
            printf("Error: unknown file %s\n", fn);
            exit(1);
        }

        while ((c = fgetc(fptr)) != EOF)
            tStr[i++] = c;

        tStr[i] = '\0';

        return i;   
    }

I need assistance with my IP Logger

I need help with my IP logger.

at my index.php file, I use this code:

----> $line = date('Y-m-d H:i:s') . " - $_SERVER[REMOTE_ADDR]"; file_put_contents('cpanel/iphenter.log', $line . PHP_EOL, FILE_APPEND);

And in my cpanel directory, I have a home.php file. In this home.php file I use the following code to implement the .log file in a DIV:

---> include 'iphenter.log' ;

At this point, everything works. But, every IP mashes 'crashes' together(Not sure how to explain this properly).

So, here is my question: How do I make a IP go on their own line. doesnt work in a PHP code, so how do I make it 'press enter' after every log?

I hope you understood my issue. Thanks!

Bluestacks 0.9.27 (latest version) Facebook package file is invalid?

I have been struggling with Facebook while using Bluestacks for more than 50 days and even before the latest update I could not install the latest version of the Facebook and I only installed one version accidentally out of 200 versions and I was required to get the latest version of FB which I failed to do so and I was hoping with the new version of BS I could solve this issue but it seems I was wrong and I think I am missing something here and I hope you guys and gals help me solve it. Now I have the latest version of BS and no matter what method I use or what I do and rest assured I have studied and tested 90% of the methods proposed anywhere on the web yet no success! No matter what I do, install it from play store or getting the countless versions of Facebook and installing them manually (Getting invalid file or old SDK in this way) I cannot install the Facebook on Bluestacks and I swear on God on heaven and Earth this issue has made me go crazy nuts angry and very upset as there is no tomorrow and it is essential that I get the latest version of the Facebook installed on the latest version of the Bluestacks. I implore you to help me this hellish issue I am having. Bluestacks version: 0.9.27.5408 Cell: Samsung GT-I9500 (installed with BS) Android version on setting of the BS: 4.4.2 KitKat

You will have my eternal gratitude and respect I thank you all in advance for you time and apologize if this matter has been solved before and I have missed the solution.

Kind Regards Neo

How do I get python to read only every other line from a file that contains a poem.

I know the code for reading every line is f=open ('poem.txt','r') for line in f: print line how do you have python read only even-numbered lines from the original file. Assuming 1-based numbering of lines.

Read INI file section with separator to array

I'm trying to convert my C++ code to Visual C#. My goal is to be able to read a INI file (not a XML file !) with some sections. Each line is assigned to a button and each button launch a command. Each INI line has 4 value, separated by a ";".

For example :

[Button_section1]

Button1=Button Scenario;open;notepad;/a;scenario.txt

Means :

  • List item
  • Button1 : real name of the button
  • Button Scenario : the text (dipslayed name) of the button
  • open : initial command (can be print or explore too...
  • notepad : executable (can be any file or CMD for another example)
  • /a : first argument
  • scenario.txt : 2nd argument

So, in my previous code, I had 25 methods ReadSection and StringSepare, which was able to read each section of my INI file then put in array with the StringSepare method

When loading the form, the Button Text can be displayed from the INI file with following

Button bt = (Button)this.Controls.Find(i, true)[0];

Then clicking on the button allow to launch the following command : (open in this case) -> notepad /a scenario.txt

NOTES : I don't want to use any XML file, because I have a link with my SQL BD, which is interpretated as a CSV file. In fact, it is a CSV file with sections.,..

Creating executable file

I'm creating a program which will encrypt executable file, here are the steps

 1.Open the file
 2. Write the file into array of unsigned chars
 3. Encrypt the data
 4. Output the file

I'm stuck at the 4th step, how can I create an executable file in Linux, I'm using C++, I want to create the executable with C++ in the source code.

ifstream operator >> uint16_t sets failbit

i'm trying to ready a binary-file into a set of variables using the c++ std::ifstream class.

The following example works:

std::ifstream inFile;
inFile.open("example.bin");
uint8_t temp8;
uint16_t temp16;
inFile >> temp8;
inFile >> temp8;

But if i replace the last two lines with one line

inFile >> temp16;

nothing is read and inFile.fail() returns true.

Can anyone explain, why I can't read into a 16 bit variable?

How to download files (pdf, doc etc...) into sdcard and open the file using volley in android?

In my android app i need to download a file into my SD card and view it through intents, I'm using volley library for all network calls in my application. Ideas.

android: listening to the server that immediately send any file

hi my C# server immediately send any file to the client and my android client must automatically save the same file to the desktop or any directory in to the sdCard. how this happen ? my android code is :

public class main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);

    GetServerData.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            // Server Request URL
            String serverURL = "10.0.2.2:8889";

            // Create Object and call AsyncTask execute Method
            new LongOperation().execute(serverURL);

        }
    });

}

// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {

    // private final HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    private final ProgressDialog Dialog = new ProgressDialog(
            AsyncronoustaskAndroidExample.this);
    TextView uiUpdate = (TextView) findViewById(R.id.output);

    @Override
    protected void onPreExecute() {
        // NOTE: You can call UI Element here.

        // UI Element
        uiUpdate.setText("Output : ");
        Dialog.setMessage("Downloading source..");
        Dialog.show();
    }

    // Call after onPreExecute method
    @Override
    protected Void doInBackground(String... urls) {
        try {

            // Call long running operations here (perform background
            // computation)
            // NOTE: Don't call UI Element here.

            // Server url call by GET method
            MyHttpClient Client = new MyHttpClient(getApplicationContext());
            Log.i("h", "1");
            HttpGet httpget = new HttpGet(urls[0]);
            Log.i("h", "2");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Log.i("h", "3");
            Content = Client.execute(httpget, responseHandler);
            Log.i("h", "4");
        } catch (ClientProtocolException e) {
            Error = e.getMessage();
            cancel(true);
        } catch (IOException e) {
            Error = e.getMessage();
            cancel(true);
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void unused) {
        // NOTE: You can call UI Element here.

        // Close progress dialog
        Dialog.dismiss();

        if (Error != null) {

            uiUpdate.setText("Output : " + Error);

        } else {

            uiUpdate.setText("Output : " + Content);

        }
    }

}

}

C++ Erase(0,1); in string, removing all instances of character in file

I have a program that checks for "@" in the 'isMemLoc()' function, and if it finds one it should remove it. (this symbol will always be the first character on the line, hence the erase(0,1) call

#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;


bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

bool isComment(string line){
    string comment = "/";
    if(line.find(comment) != string::npos){
        return true;
    }else{
        return false;
    }
}

bool isMemLoc(string line){
    string symbol = "@";
    if(line.find(symbol) != string::npos){
        cout << "CONSTANT FOUND" << endl;
        //ConvertToBinary(atoi(line.c_str));
        return true;
    }else{
        return false;
    }

}



 int main( int argc, const char* argv[] )
{
    string outLine = "test output";
    string file1 = argv[1];
    cout << "before: " << file1 << endl;
    replace(file1, "asm", "hack");
    cout << "after: " << file1 << endl;

    //input
    //WHILE READ LINE()
    ifstream infile(argv[1]);
    string tempLine;

    ofstream outfile(file1.c_str());

    while (getline(infile, tempLine)){
        if(isComment(tempLine))
            continue;
        if(isMemLoc(tempLine)){
            tempLine.erase(0);
            cout << tempLine << endl;
            outfile << tempLine << std::endl;
            continue;
        }

        //print to terminal and pass to file
        cout << tempLine << endl;   
        outfile << tempLine << std::endl;
    }

    outfile.close();
}

However, when it finds this character, my program is also deleting all of the lines where this value is found eg:

1
2
3
13 
@12
@12
@13
2

turns into

1
2
3
13 
2

This is undesired. What am I doing wrong?

How can I run a command line command from within a ruby file?

I have a gem installed that displays a ascii image of a train moving across the terminal screen when someone types "ls". I also have a file called runner.rb.

If it's possible, how can I input the "ls" command to the terminal from within the ruby file?

C++ while read line (iterate over all lines in file)

I am trying to write a compiler that reads a file in an assembly-style language, and convert it into binary. Here is my code:

    int main( int argc, const char* argv[] )
{
    string line = "test output";
    string file1 = argv[1];

    //input
    //WHILE READ FILE LINE BY LINE()   
    //BINARY CONVERSION(), pass output into 'line' variable

    //output
    ofstream outfile(file1.c_str());
    outfile << line << std::endl;
    outfile.close();
}

how do I implement "WHILE_READ_FILE_LINE_BY_LINE()"

File check in C Language

I need to ask you about a better way to check if a file exists or not, because I really do not know which is the right way. I have a program which works just fine, but the problem appears when i have to deal with different kind of files, not just, lets say txt files.

I am a Linux user and I tried to see how the program works if I try to use it on a Library file.

Here is the problem, the program cannot read that file because I use READ MODE "r", and the library file is not a txt file.

How can I check if that file exist ?

Here is the whole program:

#include <stdio.h>
#include <stdlib.h>

int main (){
    FILE * fp;
    char *fileNAme = "secret.txt";
    long fileLong;
    char * buffer;
    size_t result;

    /*Check if the file exists, if not Exit*/
    fp = fopen (fileNAme , "r");
    if (fp==NULL){
        printf("\n\n\t\t\tThe file %s does not Exists\n\n\n\n\n", fileNAme);
        exit(1);
    }

    /* Read the Number of Chars present and store them in FileLong*/
    fseek (fp , 0 , SEEK_END);
    fileLong = ftell (fp);

    /* Print the size of the FileLong */
    if(fileLong == 0){
        printf("The Size of the File is \t= %ld\n",fileLong);
    }else{
        printf("The Size of the File is \t= %ld\n",fileLong-1);
    }


    /* Moving the pointer back to the begining of the file */
    rewind (fp);

    /* allocate memory to the buffer to which is needed for holding the whole File content */
    buffer = (char*) malloc (sizeof(char)*fileLong);

    /* Check if the memory was aloccated, if not print the Error and Exit */
    if (buffer == NULL){
        fputs ("Memory error",stderr);
        exit (1);
    }

    /* copy the file into the buffer:*/
    result = fread (buffer,1,fileLong,fp);

    /*Print the size of the Buffer*/
    if(result == 0){
        printf("The size of the Buffer is \t= %ld\n",result);
    }else{
        printf("The size of the Buffer is \t= %ld\n",result-1);
    }


    /* Check if the Buffer have the same size as lsize */
    if (result != fileLong){
        fputs ("Reading error",stderr);
        exit (1);
    }else{
        printf("\nThe Content of the File(%ld)\tis the same as the content of the Buffer(%ld)\n", fileLong-1, result-1);
    }

    /* Now we can print the Content of the File */
    printf("\n\n\n\n\t\tThe Content of the File is:\n");

    /* Compare result with FileLong to see if there are some information inside that File or not */
    if(result != 0 && fileLong != 0){
        printf("%s", buffer);
    }else{
        printf("\n\n\nThe File is empty\n\n\n");
    }

    /* Close that File */
    fclose (fp);

    /* Free the needed memory*/
    free (buffer);

    return 0;
}

Read in 2D array

I'd like to read in the following format from a file into a 2D array:

      -1.2545186e-01   6.1235522e-01
      -3.3039316e+00  -5.7215697e+00
      -4.3039316e+00  -7.7215697e+00

Is there any (builtin-) function to it?

Why isn't java.io.File deprecated?

Since Java 7 there the java.nio.file package. So why is java.io.Filestill not deprecated in Java 8?

C++ using ofstream to write to file

I am trying to use ofstream() to write to a file (I am writing an assembler that converts .asm file into .hack file and converts assembly commands into binary for the NANDTOTETRIS course)

I am having trouble with the ofstream function, here is my code:

#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;


bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

int main( int argc, const char* argv[] )
{
    string file1 = "hello.asm";
    cout << "before: " << file1 << endl;
    replace(file1, "asm", "hack");
    cout << "after: " << file1 << endl;

    ofstream outfile(file1);
    outfile << "my text here!" << std::endl;
    outfile.close();

}

And this is my error:

g++ assembler.cpp
assembler.cpp: In function ‘int main(int, const char**)’:
assembler.cpp:23: error: no matching function for call to ‘std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)’
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/fstream:623: note: candidates are: std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/fstream:608: note:                 std::basic_ofstream<_CharT, _Traits>::basic_ofstream() [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iosfwd:84: note:                 std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(const std::basic_ofstream<char, std::char_traits<char> >&)
[a1649446@ingb16w013 projects]$ 

Java - File save does not work

I would like to save an ArrayList's content to file (the user should choose the .txt's location) but my method can not reach the "stage" however I am trying to give the stage to it.

Do you have any idea how to do that?

package vizsgaquiz;

import java.io.File;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.FileChooser;
import javafx.stage.Stage;


public class VizsgaQuiz extends Application {

    ArrayList<String> kerdeslista = new ArrayList<String>();
    String a ="a";


    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Foablak.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.setTitle("Quiz Játék");
        stage.show();
        save();
    }

    public void save(){
                kerdeslista.add(a);

                FileChooser fileChooser = new FileChooser();

              //Set extension filter
              FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
              fileChooser.getExtensionFilters().add(extFilter);

              //Show save file dialog
              File file = fileChooser.showSaveDialog(stage);

              if(file != null){
                  SaveFile(kerdeslista, file);
              }
    }



    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

Broken Pipe exception (sendto failed: EPIPE (Broken pipe)) in retrofit

I am using retrofit for file uploading in android i'm using the following service interface

public interface FileUploadService {


    public static final String BASE_URL = "server url";

    @Multipart
    @POST("/upload")
    void upload(@Part("file") TypedFile file,
                @Part("path") String path,
                Callback<Pk_Response> cb);
}

This is my service generator class

public class ServiceGenerator {

    // No need to instantiate this class.
    private ServiceGenerator() {
    }


    public static <S> S createService(Class<S> serviceClass, String baseUrl) {

        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(baseUrl)
                .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade request) {
                        request.addHeader("accesstoken", "token");                            request.addHeader("Content-Type", "multipart/form-data");
                    }
                })
                .setClient(new OkClient(new OkHttpClient()));

        RestAdapter adapter = builder.build();

        return adapter.create(serviceClass);
    }
}

This is how i am calling the service in my activity

FileUploadService service = ServiceGenerator.createService(FileUploadService.class, FileUploadService.BASE_URL); TypedFile typedFile = new TypedFile("image/jpeg", new File(outputFileUri.getPath())); String path = "directory11";

service.upload(typedFile, path, new Callback<Pk_Response>() {

    @Override
    public void success(Pk_Response pk_response, retrofit.client.Response response) {
        Toast.makeText(getApplicationContext(),"requestsuccess",Toast.LENGTH_LONG).show();
    }

    @Override
    public void failure(RetrofitError error) {
        Log.e("Upload", "error");
        error.toString();
    }
});

I'm getting the following error:

java.net.SocketException: sendto failed: EPIPE (Broken pipe)
sendto failed: EPIPE (Broken pipe)

Please help me on how to solve this issue

Display all men from a file on the screen in C

I'm a newbie in C. Could you help me please. There is a structure First name, Last Name, gender, age. Entries must be entered from the keyboard. I need to save this information in a file and then show on the screen all entries with gender == Male and save them in a separate file. Thank you!

There is a code for reading a structure from file, but I can't understand how to check gender == Male.

#include "stdafx.h"
#include <cstdio>


int _tmain(int argc, _TCHAR* argv[])
{
    FILE *file;
    struct food {
        char name[20]; 
        unsigned qty; 
        float price; 
    };
    struct food shop[10];
    char i=0;

    file = fopen("e:\\Test\\tst.txt", "r");

    while (fscanf (file, "%s%u%f", shop[i].name, &(shop[i].qty), &(shop[i].price)) != EOF) {
        printf("%s %u %.2f\n", shop[i].name, shop[i].qty, shop[i].price); 
        i++;
    }

    file = fopen("e:\\Test\\fprintf.txt", "w");

    while (scanf ("%s%u%f", shop[i].name, &(shop[i].qty), &(shop[i].price)) != EOF) {
        fprintf(file, "%s %u %.2f\n", shop[i].name, shop[i].qty, shop[i].price); 
        i++;
    }
    fread;

    return 0;
}

Make a replay file with java

I am coding a very simple RTS in java and here is my problem, I need to code a replay file which save every actions made by the player and must be able to be read to watch a game (Only the actions need to be saved, the mouse movement are not important and the time between every action does not need to be saved, I will put the same delay between every actions). How could I do that knowing that I need to save the x and y position of the implicit element, the action(attack, move, porduct ...) and the x and y position of the unit in my program parameters. For exemple : archer.attack(beast), so in this exemple I need to save the x and y of the archer, it's action so here attack and the x an the y of the beast. Thank you very much to every answer, it would help me a lot !

It stoppes working after adding the records for the first student and it doesnt saves the data on the file

//Whenever I try to add student information it lets me enter the details for the first student and then stops working after pressing enter. Please help, I have a presentation in two days

#include #include #include #include

#define NAME 50
#define LNAME 50
#define AGE 2
#define SUBJECT 200
#define ID 50


void Students();
void Subjects();


struct student{
    int ID_no;
    char name[20];
    char lname[20];
    int age[2] ;
    int id_grupi;
}; struct student stu;

struct subject
{
    char subject[20];  
    int mark[2];

};
 struct subject sub;
//initializing the files used in the program

  FILE *fp;
int main()
{
  int choice=0;
 system("cls");
           printf("\n\t\t    ======================================");
            printf("\n\t\t    |            Options:                |");
           printf("\n\t\t    |                                    |");
          printf("\n\t\t   |  [1] Add a student                 |");
           printf("\n\t\t   |  [2] Add subject                   |");
             printf("\n\t\t   ======================================");
            printf("\n");
    scanf(" %i", &choice);
    switch (choice)
    { 
    case 1:
      Students(); 
    break;
    case 2:
      Subjects();

    default: printf("**Invalid Input.**\n");
 }
 return (0);
 }

void Students() //problem when pressing enter after giving the details
{
  int select;
  char choice1;          
                            while (select!=2){
                             system("cls");
   printf("\n\t\t              ======================================");
   printf("\n\t\t    |                MENU:               |");
   printf("\n\t\t    |                                    |");
   printf("\n\t\t    |  [1] Add a student              |");
   printf("\n\t\t    |  [2] Go back to main menu                |");
   printf("\n\t\t    ======================================");
                             printf("\n\t\t\tSelect:\n ");
                                scanf("%d", &select);
                                switch(select)
                              {
      case 1: 
    system("cls");
  printf("\n\t\t\t\t-ADD A STUDENT-\n");
    printf("NAME: ");
    scanf("%s",stu.name);
    printf("LAST NAME: ");
    scanf("%s",stu.lname);
    printf("AGE: ");
    scanf("%d",stu.age);
    printf("ID: ");
    scanf("%d",stu.ID_no); 
     fp=fopen("studentfile.txt","a+");
          fprintf(fp,"\n%s    \n",stu.name);
    fprintf(fp,"\n%s    \n",stu.lname);
    fprintf(fp,"\n%d    \n",stu.age);
    fprintf(fp,"\n%s    \n",stu.ID_no);

     fclose(fp);

                            }
                        }
  select=1;
  main();
}




void Subjects() //runs succesfully
{
  char choice2;
  int select2;
                                                                                               /* Choice2 */

                while(select2!=2){
      printf("\n\t\t    ======================================");
      printf("\n\t\t    |                MENU:               |");
      printf("\n\t\t    |                                    |");
      printf("\n\t\t    |  [1] Add subjects per student       |");
      printf("\n\t\t    |  [2] Main menu                 |");
      printf("\n\t\t    ======================================");
                             printf("\n\t\t\tSelect: ");

                                scanf("%d", &select2);
                                switch (select2)
                              {
                                case 1:
                                        system("cls");
                                        printf("\n\t\t\t\t-Add subjects-");
                                        printf("\n\t\tID : ");
                                        scanf("%d", &stu.ID_no);
                          fp=fopen("studentfile.txt","a+");  
                       fprintf(fp,"\n ID no:    %d\n",stu.ID_no); 
                                         int i=0,l;
                                         printf("Add number of subjects: ");
                                         scanf("%d",&l);
                                         for(i=0;i<l; i++)
                                         {
                                              printf("Subject %d: ",i+1);
                                            scanf("%s",sub.subject);
                                              scanf("%s",sub.mark);


                           fprintf(fp,"Subject:   %s\n",sub.subject);
                   fprintf(fp,"Mark**strong text**:    %s\n",sub.nota);
                                          }



                                        fclose(fp);

                            }
                        }
  select2=1;
  main();**strong text** //runs the main function again
}`

how to calculate i-node blocks?

I have an example about i-node but I can't understand how it is calculated.

c) I thought it can be -> 600/512 = 1,17.. so it needs two blocks.

d) I don't understand it, how can we get 10 + 1 ?

enter image description here

Opencart 2.0.1.1 - Option file in product page - success messasge

at OpenCart 2.0.1.1. I use products with the option of adding two images to customers (option file). Uploading pictures works well, but after uploading is never shown that the image is successfully uploaded.

So I need to do something like that button to upload a images after the button has changed to inactive and that it was show - the file uploaded. I tried to apply the procedure of this: http://ift.tt/1QheNxI ... but it's not working.

The system uses a different theme as the base.

Thank you for helping.

My .py python file is null after PC crash? [on hold]

Yesterday my PC crashed and i had a opened .py Python file.My PC crashed and now it is showing NULL file but the file size is still 44 kb how to get back my data?

Why does when scanning files at c it doesn't ignore files?

Here is a piece of C code that seems very peculiar. For some strange reason, the DT_DIR should ignore folders but it doesn't:

char** getFiles(char* pathToScan, int size)
{
    DIR *d;
    struct dirent *dir;
    char** filesName;
    int i=0;
    filesName = malloc(sizeof(char*)*size);
    d = opendir(pathToScan);

    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            if (dir->d_type != DT_DIR)
            {
                *(filesName + i-2) = malloc(sizeof(char)*strlen(pathToScan) + sizeof(char)*strlen(dir->d_name));
                strcpy(*(filesName + i-2), pathToScan);
                strcat(*(filesName + i-2), "\\");
                strcat(*(filesName + i-2), dir->d_name);
            }
            i++;
        }
        closedir(d);
    }
    return filesName;
    }

  • If i add to the file that i scan a folder, the program crash.
  • If there are no folders at the file that i scan, it works perfectly.

My first thought was that there is a problem with the DT_DIR (read about DT_DIR),

but i don't know what to do about it.

What is going on?

Why is the DT_DIR doesn't ignore folders?

Need inc vs cil14 file format explanation

When I have using .inc file for db configurations in my PHP website, some hackers hacked website, for that I got some suggestions that use .cil14 format instead of .inc. I could not get .cil14 format explanation.

Can anyone help me.

saving photo/video and Uri logic?

I am following a tutorial for using intents to use an existing camera app to take photo/video or choose one of those. My question is when I am passing the Uri as an extra to the Intent to take photo/video, does the camera app replace the created file (using the Uri) with the newly created photo/video and keeps the same name or something else? I am just trying to understand the logic here. I have a method called "getOutputMediaFileUrl" that returns the Uri (from a file that is created).

Here is my code:

public static final int MEDIA_TYPE_IMAGE = 4;
public static final int MEDIA_TYPE_VIDEO = 5;

protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
            case 0:  //Take picture
                Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                mMediaUri = getOutputMediaFileUrl(MEDIA_TYPE_IMAGE);
                if(mMediaUri == null){
                    // display an error
                    Toast.makeText(MainActivity.this,getString(R.string.error_external_storage),Toast.LENGTH_LONG).show();
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mMediaUri);
                startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
                break;
            case 1: //Take video
                    Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    mMediaUri = getOutputMediaFileUrl(MEDIA_TYPE_VIDEO);
                if(mMediaUri == null){
                    // display an error
                    Toast.makeText(MainActivity.this,getString(R.string.error_external_storage),Toast.LENGTH_LONG).show();
                }
                videoIntent.putExtra(MediaStore.EXTRA_OUTPUT,mMediaUri);
                videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,10);
                videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,0);
                startActivityForResult(videoIntent,TAKE_VIDEO_REQUEST);
                break;
            case 2://Choose picture
                Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                choosePhotoIntent.setType("image/*");
                startActivityForResult(choosePhotoIntent,PICK_PHOTO_REQUEST);

                break;
            case 3:   //Choose video
                Intent chooseVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                chooseVideoIntent.setType("video/*");
                Toast.makeText(MainActivity.this,getString(R.string.video_size_warning),Toast.LENGTH_LONG).show();
                startActivityForResult(chooseVideoIntent, PICK_VIDEO_REQUEST);
                break;
        }
    }

and this is the method that returns the Uri:

private Uri getOutputMediaFileUrl(int mediaType) {
        if(isExternalStoreageAvailable()){
            //get URI

            // 1. Get the external storage directory
            String appName = MainActivity.this.getString(R.string.app_name);
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                        appName);
            Log.d(TAG,mediaStorageDir + "");
            // 2. Create our subdirectory
            if(! mediaStorageDir.exists()){
                //creates directory. IF it fails returns false otherwise it creates the directory and returns true
                if(! mediaStorageDir.mkdirs()){
                    Log.e(TAG,"Failer to create directory");
                    return null;
                };
            }
            // 3. Create a file name
            // 4. Create the file
            File mediaFile;
            Date now = new Date();
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.UK).format(now);
            String path = mediaStorageDir.getPath() + File.separator;
            if(mediaType == MEDIA_TYPE_IMAGE){
                mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
            }else if (mediaType == MEDIA_TYPE_VIDEO){
                mediaFile = new File(path + "VID_" + timestamp + ".mp4");
            }else{
                return null;
            }

            // 5. Return the file's uri
            Log.d(TAG,"File: " + Uri.fromFile(mediaFile));
            return Uri.fromFile(mediaFile);
        }else{
            return null;
        }

    }

From binary to text

How do I make this following code to write and read in a text file instead of a binary one. The functions must work so that the data I put in is written and of course read in a text file.

void save (void)
{
    FILE *fp;
    list *node=head;
    fp=fopen("Gallery.dat", "wb");
    if (fp!=NULL)
    {
        while (node!=NULL)
        {
            fwrite(&node->val, sizeof (p),1,fp);
            node=node->next;

        }
    fclose(fp);
    }
}
void readFile (void)
{
    FILE *fp;
    list *node;
    fp=fopen("Gallery.dat", "rb");
    if (fp!=NULL)
    {
        while (1)
        {
            node = (list*) malloc (sizeof (list));
            if (!fread(&node->val, sizeof (p),1,fp)) break;
            node->next=head;
            head=node;
        }
    fclose(fp);
    }
}

I need help, formidabble doesnt install on node

Guys please i need your help urgently, i recently went through the node begineer book and i was asked to install formidable for handling file uploads..and i got an error like this![formidable install][1] i need your advice as i cannot go on learning it without fixing this error

1 error Windows_NT 6.2.9200

2 error argv "C:\Program Files\nodejs\\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "formidable"

3 error node v0.12.4

4 error npm v2.10.1

5 error code EACCES

6 error errno EACCES

7 error syscall connect

8 error Error: connect EACCES

9 error at exports._errnoException (util.js:746:11)

10 error at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)

11 error { [Error: connect EACCES] code: 'EACCES', errno: 'EACCES', syscall: 'connect' } 12 error Please try running this command again as root/Administrator.

13 verbose exit [ 1, true ]

Copy file with tcp connection

I am using io.copy to copy from one file to another, as shown below.

package main

import (
  "io"
  "fmt"
  "os"
)

func main () {
  // open files r and w
  r, err := os.Open("input.txt")
  if err != nil {
      panic(err)
  }
  defer r.Close()

  w, err := os.Create("output.txt")
  if err != nil {
      panic(err)
  }
  defer w.Close()

  // do the actual work
  n, err := io.Copy(w, r) 
  if err != nil {
      panic(err)
  }

 fmt.Printf("Copied %v bytes\n", n)
}

How can I use this to copy file from server to client with help of tcp connection.

Multiple Files upload in spring mvc

I am trying to upload multiple files using spring mvc and commons-fileupload*.jar. I am using HttpServletRequest for getting the request object and then request.getPart() to get file part. But when I run the code I found below error.

java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided

the code is as below:

public ModelAndView(@RequestParam Map<String,String> map, HttpServletRequest request)
{
Part part1=request.getPart("wallpaper0");
Part part2=request.getPart("wallpaperx");
//then write these files 

}

}

Java: Confused with these file I/O methods not functioning

I'm trying to implement a method to write an array of Song() objects to a file for an assignment. I've become fairly lost on how to achieve this. I want to be able to call the function in the main method but it doesn't appear to do anything. At this stage it is a test where I want it to print on the command line upon running main(). Here's my code:

    public static void main (String[] args)
    { //run the main program.
        Interface songUI = new Interface();
        songUI.run();

        try{
        PrintWriter outputTest = null;
        outputTest = write("testfile");
        read();
    }
    catch(IOException e){
        System.out.println("Caught!");
    }

    }


      public static PrintWriter write (String fileName) throws IOException{

      Scanner console = new Scanner(System.in);


      PrintWriter outFile = new PrintWriter(fileName);

      outFile.println ("Random numbers"); 

      for(int i=0; i<10; i++)
      {
          outFile.println ((int)( 1 + Math.random()*10) + " "); 
      }

      outFile.close();
      return outFile;
}

I also have a method for reading from the file i'm trying to get working here:

public static void read() throws IOException{

        String fileName = "test1";
        System.out.println ("The file " + fileName + "\ncontains the following lines:\n");
        Scanner inputStream = new Scanner (new File (fileName));

        while (inputStream.hasNextLine ())
        {
            String line = inputStream.nextLine ();
            System.out.println (line);
        }
        inputStream.close ();
}

As you can tell i'm confused, and any help would be amazing. Thank you.

vendredi 29 mai 2015

Reading a Text file with arrays in it - to display in table

I am hoping someone can point in the right direction here, been surfing the internet for hours and haven't found a solution.

First, I am an "OKAY" php coder .. so this might be obvi but I am lost.

I have a txt file with array() in from a pull in an api transaction list.

    Array
    (
        [orderid] => 00000000
        [type] => rebill
        [paystatus] => cancelled
    )

    Array
    (
        [orderid] => 000000
        [type] => rebill
        [paystatus] => cancelled
    )
Array
(
    [orderid] => 000000
    [type] => refund
    [paystatus] => cancelled
    [productid] => 939399393
    [firstName] => XXXXXX
    [lastName] => XXXX
    [customeremail] => XXXX
    [amount] => XX.XX
    [refunddate] => 2015-01-01
    [refundstatus] => ok
)

There is thousands of these array()'s ... I am use to dealing with json etc to pull for each, but right now I am lost completely.

I am able to replicate the file with

$f = fopen("merged.txt", "r");

// Read line by line until end of file
while(!feof($f)) { 
    echo fgets($f) . "<br />";
}

fclose($f);

... that's it

I have played around with all kinds of foreach while etc and can't get it to work. If someone could point in the right direction, I would appreciate it so much.

Thanks!

Not able to insert data in file using append mode in c++

my code is this:

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

int main()
{
fstream file;
file.open("abc.txt",ios::app);
file<<"hello";
file.close();
return 0;
}

The above code is creating an empty file.

Please can anyone point it out where i'm going wrong.

I have a arrays of apk files, what I need is to do write the apk files of ArrayList into cache storage and read it back again as same ArrayList. I know how to insert a single file and retrieve back again from the cache. But whereas ArrayList objects as concern I completely stuck up with the solutions and methodology. Please help me. I am using following code for read and write into cache memory. Any modification or slight changes in my code will be more helpful to me. Thanks in advance

Actual code for Read and write single File

//Write to cache dir

FileWriter writer = null;
try {
    writer = new FileWriter(tmpFile);
    writer.write(text.toString());
    writer.close();

    // path to file
    // tmpFile.getPath() 

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

//Read to cache directory
String TMP_FILE_NAME = "base.apk";
File tmpFile;

File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;

String line="";
StringBuilder text = new StringBuilder();

try {
    FileReader fReader = new FileReader(tmpFile);
    BufferedReader bReader = new BufferedReader(fReader);

    while( (line=bReader.readLine()) != null  ){
        text.append(line+"\n");
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}catch(IOException e){
    e.printStackTrace();
}

Modified code for my requirement to insert ArrayList<File>

String tempFile = null;
public void writeFile(ArrayList<File> files(){

 for(File file: files) {
            FileWriter writer = null;
            try {
                writer = new FileWriter(file);
                tempFile = file.getName().toString();
                writer.write(file.getName().toString());
                writer.close();

                // path to file
                // tmpFile.getPath()

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

        }
}

This is where I stuck completely to read as ArrayList

What i tried is

String line="";
        StringBuilder text = new StringBuilder();

        try {
            FileReader fReader = new FileReader(tempFile);
            BufferedReader bReader = new BufferedReader(fReader);

            while( (line=bReader.readLine()) != null  ){
                text.append(line+"\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }