I think your program is failing because you need to change: _getAvailableID(i) to return _getAvailableID(i) (At the moment the recursive function finds the correct answer which is discarded.) However, it would probably be better to simply put all the ids you have seen into a set to make the program...
The issue is in the code - curr_file = open('myfile',w) curr_file.write('hello world') curr_file.close() The second argument should be a string, which indicates the mode in which the file should be openned, you should use a which indicates append . curr_file = open('myfile','a') curr_file.write('hello world') curr_file.close() w mode indicates write ,...
EDIT: After explaining your logic, it looks like you need to keep track of which of the 4 special Strings appeared in the current record, and to add whichever of them didn't when the record ends. You can do it with 4 boolean variables. boolean osi = false; boolean posi...
The problem is the way you are treating the result of strtok: you are setting its value right into the node, instead of copying it. Make a copy of name when adding a node: void push(node ** head, int uid ,char* uname) { node * new_node; new_node = malloc(sizeof(node)); new_node->uid...
android,file,uri,contacts,android-contacts
The idea to check if the file exists led me to this post where it was answered detect if contact has photo .getDrawable() == null gets the correct result. thanks for all comments...
I would like to have a loop read first header store in variable then read details and everytime it hits 'I' it uploads that line to MYSQL. There are multiple ways to parse your file. The following approach makes use of explode() for H and I. So you have...
It SOUNDS like what you need is (replace 6 and 2 with whatever numbers you want): awk '{for (i=2;i<=6;i+=2) if (!(NR%i)) print > ("file"i)}' file e.g. run in an empty directory: $ seq 1 20 | awk '{for (i=2;i<=6;i+=2) if (!(NR%i)) print > ("file"i)}' $ lf file2 file4 file6 $...
php,file,encryption,aes,php-openssl
You could use CBC encryption using Mcrypt and then encrypt a segment of data at a time. Make sure that the segment is x times the block size of the used cipher (e.g. 16 bytes for AES). Encrypt the segment and take the last block of the generated ciphertext and...
.gitignore is just like any other file under version control, so yes, you can delete it. However, keep in mind that it probably has entries in it that should be kept, so instead of deleting it, I would just modify it so that your jar files are no longer ignored.
java,file,javafx,line,bufferedreader
As it turned out in the discussion, the problem is that with readLine() the following files will behave the same way: File A: "Hello\n" File B: "Hello" 1st readLine() --> "Hello" 2nd readLine() --> null ==> we cannot know if there was a '\n' after the last line or not...
As soon you read an empty line you need to output your orange and melon line. And additional when you reach the end of the file. Find a snippet where you could start with. create an new file with the addtional llines String newLine; try (PrintStream output = new PrintStream("fruits.out");...
With this AJAX form submission approach, you will not be able to upload file using ajax. If you don't like using a third-party plugin like dropzone.js or Jquery file upload, you can use XMLHttpRequest. An example below: $('#newcatform').on('submit', function(ev){ ev.preventDefault(); var forms = document.querySelector('form#newcatform'); var request = new XMLHttpRequest(); var...
java,file,file-io,bufferedreader
If you care about the memory wasted in the intermediate StringBuffer, you can try the following implementation: public static void skipLine(BufferedReader br) throws IOException { while(true) { int c = br.read(); if(c == -1 || c == '\n') return; if(c == '\r') { br.mark(1); c = br.read(); if(c != '\n')...
Because you will have to read the line to know where is ending and also you have to write at the end of the each line. In conclusion you have to read everything and write at the end of each line just appending won't save to much performance it only...
I believe the problem is with Dir.foreach, not CSV.open. You need to supply a directory to foreach as an argument. That's why you are getting the missing argument error. Try: Dir.foreach('/path/to_my/directory') do |current_file| I think the open that is referenced in the error message is when Dir is trying to...
According to your loop, once you get line that doesn't equals input, then you stop everything - what is logically incorrect. You have to compare lines, until one of them equals input or end of file. ... bool valid = false; using (WebClient client = new WebClient()) { using (Stream...
php,image,file,properties,file-attributes
I don't believe that PHP natively contains a function to edit the EXIF data in a JPEG file, however there is a PEAR extension that can read and write EXIF data. pear channel-discover pearhub.org pear install pearhub/PEL Website for the module is at http://lsolesen.github.io/pel/ and an example for setting the...
I solved my problem by inserting my files in a folder named like this: ".my_folder" and it's worked!
android,file,exception,filenotfoundexception
Android is case sensitive. Replace ANDROID.PERMISSION with android.permission: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> Also, you should only need one of those permissions. If you are planning on writing to external storage, you should not also need READ_EXTERNAL_STORAGE....
You have to call DirectoryStream<Path> files = Files.newDirectoryStream(dir); each time you iterate over the files. Pls check this question... java.lang.IllegalStateException: Iterator already obtained...
Extract from http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature The first two bytes distinguish PNG files on systems that expect the first two bytes to identify the file type uniquely. The first byte is chosen as a non-ASCII value to reduce the probability that a text file may be misrecognized as a PNG file; also, it...
python,image,list,file,python-imaging-library
Quick fix First, you need to have your pixel tuples in a single un-nested list: pixels_out = [] for row in pixels: for tup in row: pixels_out.append(tup) Next, make a new image object, using properties of the input image, and put the data into it: image_out = Image.new(image.mode,image.size) image_out.putdata(pixels_out) Finally,...
Simplest options is always thebest option, go with shared preferences Here is simple tutorial from google http://developer.android.com/training/basics/data-storage/shared-preferences.html It will store your data in application local file. Take a note of that there are different shared preferences in example getPreferences() will return file specific for activity you used this method. While...
java,file,constructor,static-analysis,hardcoded
As a general rule of thumb, hardcoding absolute paths makes your program less flexible. Consider a configuration file located at /usr/share/myapp/myapp.conf - what if the end user wants to install your application somewhere else than /usr/share? Using such an absolute path will break the application. And as always, no general...
Since the next thing we plan to do is create something at that location, and since we want to treat it as an error if something already exists there, then let's not bother checking. Just attempt the create and exit with an error if it fails. The create step uses...
You could do: size = Hash[arr.zip(arr_s)] To give you a better idea, in irb, I typed: a = (1..5).to_a => [1, 2, 3, 4, 5] b = ('a'..'e').to_a => ["a", "b", "c", "d", "e"] Then, typing size=Hash[a.zip(b)] Returns {1=>"a", 2=>"b", 3=>"c", 4=>"d", 5=>"e"} So you could do: puts size[1] which...
dict() does not parse Python dictionary literal syntax; it won't take a string and interpret its contents. It can only take another dictionary or a sequence of key-value pairs, your line doesn't match those criteria. You'll need to use the ast.literal_eval() function instead here: from ast import literal_eval if line.startswith(self.kind):...
There's no tab entity defined in ISO-8859-1 HTML, so I think you can replace tab characters with some characters: if (File.Exists(path)) { using (TextReader tr = new StreamReader(path)) { while (tr.Peek() != -1) { var htmlLine = tr.ReadLine().Replace("\t", " ") + "<br/>"; Response.Write(htmlLine); } } } ...
I tried to make this a bit more generic. To show how this can be helpful, I also created another command that you can call as "add 1 2" and it will print the sum of adding the two integers. If you are serious into making a CLI interactive application,...
To read files I recommend to you to use an ArrayList: Scanner s = new Scanner(new File(//Here the path of your file)); ArrayList<String> list = new ArrayList<String>(); while (s.hasNext()) { list.add(s.nextLine()); } Now in your ArrayList you will have all the lines of your file. So, now, you can go...
java,file,sorting,distinct-values
You can leverage: NIO (Non-blocking I/O) API (available since Java 7) Streams API (available since Java 8) …to solve the problem elegantly: public static void main(String... args) { Path input = Paths.get("/Users/yourUser/yourInputFile.txt"); Path output = Paths.get("/Users/yourUser/yourOutputFile.txt"); try { List<String> words = getDistinctSortedWords(input); Files.write(output, words, UTF_8); } catch (IOException e) {...
Is it possible to use a variable in the AssignFile command? Yes. The second parameter of AssignFile has type string. The expression cFileDir + '\' + sFile has type string. FWIW, AssignFile is known as a function rather than a command. Getting on top of terminology like this will...
The string bound to "s" will be deallocated once the function ends ("s" goes out of scope), so you cannot return a reference to its contents outside the function. The best way is to return the string itself: fn read_shader_code(string_path: &str) -> String { let path = Path::new(string_path); let display...
Filename isn't a base64 encoded string. It is encoded as defined by RFC 2047. Don't try to decode such strings by hand. Use solid libraries like Apache Mime4j for encoding/decoding mime messages. Add Mime4j to your project (here Maven): <dependency> <groupId>org.apache.james</groupId> <artifactId>apache-mime4j-core</artifactId> <version>0.7.2</version> </dependency> Use org.apache.james.mime4j.codec.DecoderUtil for decoding quoted-printable strings:...
You need to change your $target_file variable to the name you want, since this is what gets passed into move_uploaded_file(). I don't see anywhere in your code where you actually set this variable to their username (right now it's still using the name they selected when they uploaded it). Without...
Probably your csv don't have a header, where the specification of the key is done, since you didn't define the key names. The DictReader requires the parameter fieldnames so it can map accordingly it as keys (header) to values. So you should do something like to read your csv file:...
This is the start of what you want. Because this is an assignment I have left you with some reading, and the remainder of the assignment. I have also translated much of the code to read in Portuguese. #include <iostream> #include <fstream> // seu códe // Faça isso para ler...
Here's a function that returns whether a filename matches your YY-MM-DD.csv pattern or not. from datetime import datetime def is_dated_csv(filename): """ Return True if filename matches format YY-MM-DD.csv, otherwise False. """ date_format = '%y-%m-%d.csv' try: datetime.strptime(filename, date_format) return True except ValueError: # filename did not match pattern pass return False...
As long as the text file isn't that large, you should be able to just read in the text file into an array, insert an element into the specific line index, and then output the array back to the file. I've put some sample code below - make sure you...
So to encrypt an aspect of the file you may want to gather it's bytes in an array*, That can either be done using the class Files from java or a stream to do it manually. For now lets say you got the byte array obtained using Files.readAllBytes(Path file); So...
First of all, the code you wrote here is not working, because when you open an outputStream to the exact file you try read from, it will empty the source file and the statement in.readLine() always returns null. So if this is your real code maybe this is the problem....
file,asp.net-mvc-4,button,upload,submit
@using(Html.BeginForm("Upload","Home",new {@id="frm"})) { <input type="file" id="upld" /> <input type="button" value="upload" id="btn" /> } <script> $('#btn').click(function(){ var has_selected_file = $('#upld').filter(function(){ return $.trim(this.value) != '' }).length > 0 ; if(has_selected_file){ $('#frm').submit(); } else{ alert('No file selected'); } }); I hope this is your requirement ...
The path you have mentioned in the FileReader is wrong... If file is in the same folder in which your java program is present then the path would be.... And also tell me y are you using the input stream its not necessary... BufferedReader br = new BufferedReader(new FileReader("LerDaqui.txt"));
python,string,file,integer,logic
By conversion to string, you hide the error. Always try repr(value) instead of str(value) for debugging purposes. You should also know, that it is better to compare integers instead of strings -- e.g. " 1" != "1". Edit: From your output, it is clear that you have an extra '\n'...
java,file,while-loop,bufferedreader,readline
It would be much easier to do with a Scanner, where you can just set the delimiter: Scanner scan = new Scanner(new File("/path/to/file.txt")); scan.useDelimiter(Pattern.compile(";")); while (scan.hasNext()) { String logicalLine = scan.next(); // rest of your logic } ...
Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...
This solution is a modified solution from BalusC File Servlet blog. The reason I use this solution is because it reset() the HttpServletResponse response before writing data. @WebServlet(urlPatterns = { "/Routing/*" }) @MultipartConfig(location = "/tmp", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024...
This is exactly what you need. It will check all files dynamically, you don't need to give number of files. for example, if you have any number of files and various number of rows in each file, not to worry. it will read it correctly. import java.io.*; import java.util.*; import...
/*Everything looks find in your code. in my machine it is working fine . I have only added a if condition to print the contents same as the file thats it .. */ #include<stdio.h> int main(void) { FILE *fp; int c; fp = fopen("rabi.txt","r"); if(fp == NULL) { perror("Error in...
That's normal, you didn't allocate string. C needs you to allocate it in memory before you use it. Also you will have to know its size. In your code, string points to nowhere into memory so it doesn't exist (to be exact it points to somewhere you have a lot...
While I don't know of a method to make File.exists() perform faster (likely there is no way as it's more of an OS issue), you can at least mitigate the issue by using asynchronous operations instead - thus avoiding locking the UI. You can skip the exists operation, and just...
You could split the text and have a list of lists, where each sub list is a row, then pluck whatever you need from the list using rows[row - 1][column - 1]. f = open('test.txt', 'r') lines = f.readlines() f.close() rows = [] for line in lines: rows.append(line.split(' ')) print...
When a process opean a file for Read/Write with FileShare.None any subsequent access by any process on this same file will result in Acess Denied Exception. To answer your question, Second user will get exception. MSDN: FileShare.None - Declines sharing of the current file. Any request to open the file...
OP's code problems include: 1) Passing a variable, rather than an address of a variable in fscanf(read_from, " ch=1 n=%d v=%d", array[u][2], array[u][3]); 2) Insufficient space reading "Off" with char status[3]; ... ctrl = fscanf(read_from, " %s", &status); The better approach is to not use fscanf(). Read the line using...
You can read the input from user and append .txt char fileName[30]; // ... scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29) strcat(fileName, ".txt"); // append .txt extension // ... FILE *f = fopen(fileName, "a"); ...
Speaking as someone who's had to do exactly what you're talking about a number of time, rr got it basically right, but I would change the emphasis a little. For file versioning, text is basically the winner. Since you're using an hdf5 library, I assume both serializing and parsing are...
I don't know if you can write to a specific line in a file, but if you need to you can write your lines to a List then write the list to a file 'Declare your list Dim lines As New List(Of String) For Each lineToWrite In YourLines If toInsert...
You're not actually opening the file in Excel so you can't count how many cells there are. Try reading how many lines instead: Open FilePath & file For Input As #1 While Not EOF(1): Line Input #1, trashLine: Wend i = i + 1 Close #1 Alternatively, open the file...
javascript,jquery,ajax,file,csv
I would recommend you create the CSV at server side PHP program and set Content-Type as "application/vnd.ms-excel" (or) "text/csv" and set "Content-Disposition: attachment; [yourfilename] " Refer this Create a CSV File for a user in PHP Refer this Force Download CSV File Simply put hyperlink as <a class="areaSummaryExport" href="admin_ajax.php" value="1">...</a>...
If you know the extensions that can show up you can use the following solution with a regex: //regex for file name with known extensions Regex r = new Regex("^.*\\.(ext|doc|PUT_OTHER_EXTENSIONS_HERE)$"); var lines = File.ReadAllLines(FILE_PATH); var res = lines.Where(x => !string.IsNullOrWhiteSpace(x) && r.Match(GetFirstEntry(x)).Success) .Select(x => GetFirstEntry(x)); where GetFirstEntry : /// <summary>...
String line; PrintStream out = null; BufferedReader br = null; try { out = new PrintStream(new FileOutputStream(outputFile)); br = new BufferedReader(new FileReader(inputFile)); while((line=br.readLine())!=null){ if(line.trim().isEmpty()) { out.println("proc_online_system_id"); //print what you want here, BEFORE printing the current line } out.println(line); //always print the current line } } catch (IOException e) { System.err.println(e);...
You can use: gf to edit the file name under the cursor in the current window (requires 'nomodified' on the existing buffer in the current window). ^wf to edit the file name under the cursor in a new window. (Note: conveniently, ^w^f also works.) ^wgf to edit the file name...
java,file,filepath,javax.imageio
you have to create the missing directories yourself If you don't want to use a 3rd party library you can use File.mkdirs() on the parent directory of the output file File outputFile = new File(nameAndPath); outputFile.getParentFile().mkdirs(); ImageIO.write(image, "png", outputFile); Warning that getParentFile() may return null if the output file is...
java,file,sftp,apache-commons-vfs
Use FileObject.exists() method. See https://commons.apache.org/proper/commons-vfs/apidocs/org/apache/commons/vfs2/FileObject.html#exists%28%29...
arrays,string,algorithm,file,data-structures
For instance a single string matching is the z-algorithm. It's the fastest matcher.
Remove the if not len(key) != len(aDict) and the break. What you probably wanted to do is stopping the loop after iterating all the keys. However key is one of 'OG_1', 'OG_2', 'OG_XX', it's not a counter or something like that. Replace open("key", "w") with open(key + ".txt", "w")....
The problem may be related with the order of execution. In your for loop you are reading all files with reader.readAsArrayBuffer(file). This code will run before any onload is run for a reader. Depending on the browser implementation of FileReader this can mean the browser loads the entire file (or...
python,file,python-3.x,rename,file-rename
You don't need all the lists, just rename all files on the fly. import sys, os, glob newnames = ["North", "South", "East", "West"] for folder_name in glob.glob(sys.argv[1]): for new_name, old_name in zip(newnames, sorted(os.listdir(folder_name))): os.rename(os.path.join(folder_name, old_name), os.path.join(folder_name, new_name)) ...
Use file -. The hyphen means "take input from standard input".
You can always use the String#contains() method to search for substrings. Here, we will read each line in the file one by one, and check for a string match. If a match is found, we will stop reading the file and print Match is found! package com.adi.search.string; import java.io.*; import...
java,file,url,apache-commons,fileutils
The code 302 refers to a relocation. The correct url will be transmitted in the location header. Your browser then fetches the file form there. See https://en.wikipedia.org/wiki/HTTP_302 Try https://repo1.maven.org/maven2/com/cedarsoftware/json-io/4.0.0/json-io-4.0.0.jar For FileUtils see How to use FileUtils IO correctly?...
c,arrays,string,file,dynamic-memory-allocation
The problem with strtok is that the token it returns you becomes invalid as soon as you make the next call of strtok. You could either copy it into a separate string, or use it right away, and discard, but you must use it before calling strtok again. for (i...
One needs to use ftype and assoc commands as follows (and note that sequence matters): ftype txtfile="C:\Program Files (x86)\PSPad editor\PSPad.exe" "%1" assoc .log=txtfile assoc .txt=txtfile assoc .wtx=txtfile or ftype TIFImage.Document="C:\Program Files\MSPVIEW.exe" "%1" assoc .tif=TIFImage.Document assoc .tiff=TIFImage.Document Note that I haven't MSPVIEW.exe installed so I can't approve your ftype assignment rightness....
That is the proper way of deleting it. You can check the Migration example in the RealmExample project that come with the SDK and see that that's exactly how they do it, so I assume the recommended way. let defaultPath = Realm.defaultPath NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil) ...
read() will read the entire file. Try with readline(). with open('keys', 'r') as f: key = f.readline().rstrip() secret = f.readline().rstrip() print(key) print(secret) # ewjewej2j020e2 # dw8d8d8ddh8h8hfehf0fh or splitting read: with open('keys', 'r') as f: key, secret = f.read().split() print(key) print(secret) # ewjewej2j020e2 # dw8d8d8ddh8h8hfehf0fh with open('keys', 'r') as f: key,...
Example code: #!/bin/bash declare -a textarr numarr while read -r text num;do textarr+=("$text") numarr+=("$num") done <file echo ${textarr[1]} ${numarr[1]} #will print Toy 85 data are stored into two array variables: textarr numarr. You can access each one of them using index ${textarr[$index]} or all of them at once with ${textarr[@]}...
I usually use the fgets() function to a file on a line-per-line basis (provided it is a text file). #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #define LINELEN 200 #define NAMELEN 40 struct PRICELIST { char item[NAMELEN]; float price; unsigned int order_no; struct PRICELIST *next; struct PRICELIST *prev; };...
file,fonts,true-type-fonts,legal,fees
You did not do your homework in looking up how fonts actually work before asking your question. Next time, please do. Now, while there exists a "ttf format", it has nothing to do with the font format itself, instead only specifying how to encode glyph outlines in a binary block...
No. Websites cannot access arbitrary files on the computer the browser is running on. That would be a terrible security risk. It sounds like you would be better off cutting the browser out entirely. Possibly using Node.js or WSH if you want to use JavaScript to perform your updates....
You can use Path to separate FileName into a file name and an extension, insert the date in the middle, and combine them back, like this: var fn = Path.GetFileNameWithoutExtension(FileUpload1.FileName); var ext = Path.GetExtension(FileUpload1.FileName); var fileName = string.Format("{0}{1:yyyy-MM-dd}.{2}", fn, DateTime.Now, ext); ...
You first need to detect whether you are inside a "Bar" block. Then, while you are, print/accumulate those lines that start with * [x]. Here's one way to do it: def get_selected_block_entries(lines, block_name, block_prefix='#####', selected_entry_prefix='* [x]'): selected_lines = [] block_marker = '{} {}'.format(block_prefix, block_name) for line in lines: if line.startswith(block_prefix):...
java,swing,file,path,joptionpane
JOptionPane.showMessageDialog(null,"your file path,remember to use double slahses instead of single ones"); ...
1. Since you use fgets(), yes this is the expected behaviour, since you grab the full line, which includes the new line character at the end. 2. You can just use fgetcsv() and specify the delimiter as tab, e.g. $handle = fopen("test.csv", "r"); if ($handle) { while (($data = fgetcsv($handle,...
Removed error from your version In your recursion you never ask for null values. Do it and it should run like this: public static List<File> listf(String directoryName) throws IOException { File directory = new File(directoryName); List<File> resultList = new ArrayList<>(); // get all the files from a directory File[] fList...
c++,arrays,string,file,large-data
part 2 If you are reading the file back onto the same type of system (endianness) then use a binary blittable format. Ie store a straight binary dump of the 200 * 200 array. I would also multiply by 1000 and store as ints since they are typically slightly faster...
There are actually 3 ways: Write a signature and properties into PDF file and then read back. This requires to use specialized 3rd party PDF library to write, read, add signature to PDF; Maintain a separate XML file with detailed information like last updated, version, CRC or MD5 value to...
Interesting question. I'm not aware of the size on disk value being a property of any scriptable object. You could calculate it by getting filesize modulo bytes-per-cluster, subtracting that modulo from the file size, then adding the cluster size. (Edit: or use Aacini's more efficient calculation, which I'm still trying...
There is one new line, which is to be expected. The echo command prints all its arguments on a single line separated by spaces, which is the output you see. You need to execute the result of: echo "$(ls %s)" to preserve the newlines in the ls output. See Capturing...
I see you have called the bindParameters() method after calling execute(). It should be the other way round. i.e. $stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl); $stmt->execute(); ......
A pretty portable way of doing it would be this: for i in *.text*; do mv "$i" "$(echo "$i" | sed 's/([0-9]\{1,\})$//')"; done Loop through all files which end in .text followed by anything. Use sed to remove any parentheses containing one or more digits from the end of each...