Search Results

Search found 3977 results on 160 pages for 'filename'.

Page 21/160 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • File Format DOS/Unix/MAC code sample

    - by mac
    I have written the following method to detemine whether file in question is formatted with DOS/ MAC, or UNIX line endings. I see at least 1 obvious issue: 1. i am hoping that i will get the EOL on the first run, say within first 1000 bytes. This may or may not happen. I ask you to review this and suggest improvements which will lead to hardening the code and making it more generic. THANK YOU. new FileFormat().discover(fileName, 0, 1000); and then public void discover(String fileName, int offset, int depth) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName)); FileReader a = new FileReader(new File(fileName)); byte[] bytes = new byte[(int) depth]; in.read(bytes, offset, depth); a.close(); in.close(); int thisByte; int nextByte; boolean isDos = false; boolean isUnix = false; boolean isMac = false; for (int i = 0; i < (bytes.length - 1); i++) { thisByte = bytes[i]; nextByte = bytes[i + 1]; if (thisByte == 10 && nextByte != 13) { isDos = true; break; } else if (thisByte == 13) { isUnix = true; break; } else if (thisByte == 10) { isMac = true; break; } } if (!(isDos || isMac || isUnix)) { discover(fileName, offset + depth, depth + 1000); } else { // do something clever } }

    Read the article

  • ASP.NET MVC Image refreshing

    - by user295541
    Hi, I have an Employee object which has an image property. Image class contains image metadata as image caption, and image file name. If I upload a new image for an employee on async way without full post back the new image is not appeared on the page. I use GUID to name the image file to avoid the page caching. I do the image modifying the following way: ctrEmployee employee = Repository.Get(PassedItemID); if (employee.ctrImage != null) { string fullFileName = serverFolder + employee.ctrImage.FileName; FileInfo TheFile = new FileInfo(fullFileName); if (TheFile.Exists) { TheFile.Delete(); } fileName = Guid.NewGuid() + ".jpg"; employee.ctrImage.FileName = fileName; } resizedBmp.Save(string.Format("{0}{1}", serverFolder, fileName), System.Drawing.Imaging.ImageFormat.Jpeg); Repository.Edit<ctrEmployee>(employee); ImageID = employee.Image.Value; return PartialView(UserControlPaths.Thumbnail, new ThumbnailDataModel(employee.Image.Value, 150, 150)); The partial view has an image tag which gets the saved image url string which is a GUID. Anybody has an idea what I do wrong?

    Read the article

  • «HTTP::Message content must be bytes» error when trying to post

    - by ZyX
    I have the following code: ... sub setImage { my $self=shift; my $filename=shift; unless(-r $filename) { warn "File $filename not found"; return; } my $imgn=shift; my $operation=&URI::Escape::uri_escape_utf8( (shift) ? "???????! (Delete)" : "?????????! (Store)"); my $FH=&::File::open($filename, 0, 0); my $image; # &utf8::downgrade($image); sysread($FH, $image, 102400, 0); close $FH; my $imginfo=eval{&Image::Info::image_info(\$image)}; if($@ or $imginfo->{"error"}) { warn "Invalid image: ".($@ || $imginfo->{"error"}); return undef; } my $fields=[ DIR => $self->url("fl"), OPERATION => $operation, FILE_NAME => ".photo$imgn", # FILE => [$filename], FILE => [undef, "image.".$imginfo->{"file_ext"}, # Content_Type => $imginfo->{"file_media_type"}, # Content_Type => 'application/octet-stream', Content => $image, ], ]; my $response=&ZLR::UA::post( &ZLR::UA::absURL("/cgi-bin/file_manager")."", $fields, Content_Type => "form-data", ); print $response->decoded_content; } ... When I try to use function setImage it fails with error HTTP::Message content must be bytes at /usr/lib64/perl5/vendor_perl/5.8.8/HTTP/Request/Common.pm line 91. Worse that I can't reproduce this error without using all of my code and upgrading libwww-perl does nothing. What can cause it?

    Read the article

  • How to create a route that catch all pdf file?

    - by VinnyG
    I want to have my pdf files sent this way to my users : public ActionResult GetPDF( string filename ) { return File( filename, "application/pdf", Server.HtmlEncode( filename ) ); } But I don't know how to create a route that will catch all the different pdf file in my site? Thanks a lot for the help!

    Read the article

  • loading multiple .mat files in MATLAB

    - by smilingbuddha
    I have 110 files named time1.mat, time2.mat ..., time110.mat. I want to load these matrices into the MATLAB workspace. I have always used load -'ASCII' matrix.mat to load an ASCII matrix file in the current folder. So I tried doing for i=1:10 filename=strcat('time',int2str(i),'.mat'); load -'ASCII' filename end But I am getting a MATLAB error as ??? Error using ==> load Unable to read file filename: No such file or directory. ? Of course the string filename seems to be evaluated correctly by MATLAB as time1.mat. in the first iteration where it crashes at the load line. Any suggestions how I should do this?

    Read the article

  • There's a black hole in my server (TcpClient, TcpListener)

    - by Matías
    Hi, I'm trying to build a server that will receive files sent by clients over a network. If the client decides to send one file at a time, there's no problem, I get the file as I expected, but if it tries to send more than one I only get the first one. Here's the server code: I'm using one Thread per connected client public void ProcessClients() { while (IsListening) { ClientHandler clientHandler = new ClientHandler(listener.AcceptTcpClient()); Thread thread = new Thread(new ThreadStart(clientHandler.Process)); thread.Start(); } } The following code is part of ClientHandler class public void Process() { while (client.Connected) { using (MemoryStream memStream = new MemoryStream()) { int read; while ((read = client.GetStream().Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, read); } if (memStream.Length > 0) { Packet receivedPacket = (Packet)Tools.Deserialize(memStream.ToArray()); File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Guid.NewGuid() + receivedPacket.Filename), receivedPacket.Content); } } } } On the first iteration I get the first file sent, but after it I don't get anything. I've tried using a Thread.Sleep(1000) at the end of every iteration without any luck. On the other side I have this code (for clients) . . client.Connect(); foreach (var oneFilename in fileList) client.Upload(oneFilename); client.Disconnect(); . . The method Upload: public void Upload(string filename) { FileInfo fileInfo = new FileInfo(filename); Packet packet = new Packet() { Filename = fileInfo.Name, Content = File.ReadAllBytes(filename) }; byte[] serializedPacket = Tools.Serialize(packet); netStream.Write(serializedPacket, 0, serializedPacket.Length); netStream.Flush(); } netStream (NetworkStream) is opened on Connect method, and closed on Disconnect. Where's the black hole? Can I send multiple objects as I'm trying to do? Thanks for your time.

    Read the article

  • Cache SHA1 digest result?

    - by johnathan
    I'm storing several versions of a file based on a digest of the original filename and its version, like this: $filename = sha1($original . ':' . $version); Would it be worth it to cache the digest ($filename) in memcache as a key/value pair (the key being the original + version and value the sha1 hash), or is generating the digest quick enough (for a high traffic php web app)? Thanks, Johnathan

    Read the article

  • How to pass variable value to gpg commands

    - by trainee
    $importkey = system('gpg --import newkey.asc . $username'); need to pass the file name as a variable.so that file name with its contents can be import in gnupg keyring. $gpg = system('gpg --recipient userid --output filename --armor --encrypt filename to encrypt', $retvalue); how can i pass the recipient email id(userid) and the filename as variable to gpg commands thanks!

    Read the article

  • Quick Java question about variables

    - by Spencer
    I'm declaring a variable: private static final String filename = "filename.txt"; First, does the order of private static final matter? If not, is there a standard excepted sequence or convention? Second, the filename in my application is fixed. Is this the best was to store it's value? Thanks, Spencer

    Read the article

  • store/load numpy array from binary files

    - by Javier
    Dear all, I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix. def saveArrayToFile(data, fileName): with open(fileName, 'w') as file: a = array.array('f') nSamples, ndim = data.shape a.extend([nSamples, ndim]) # write number of elements and dimensions a.fromstring(data.tostring()) a.tofile(file) def readArrayFromFile(fileName): _featDesc = np.fromfile(fileName, 'f') _ndesc = int(_featDesc[0]) _ndim = int(_featDesc[1]) _featDesc = _featDesc[2:] _featDesc = _featDesc.reshape([_ndesc, _ndim]) return _featDesc, _ndesc, _ndim An example on how to use the functions is: myarr=np.array([[7, 4],[3, 9],[1, 3]]) saveArrayToFile(myarr,'myfile.txt') _featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt') However, an error message of 'ValueError: total size of new array must be unchanged' is shown. My arrays can be of size MxN and MxM. Any suggestions are more than welcomed. I think the problem might be in the saveArrayToFile function. Best wishes, Javier

    Read the article

  • Filestream in Sql Server 2008 Express

    - by Xaitec
    i tried to get it to work but i never seem to have to luck, i go a code snippet for a blog and still no dice. This is the code. EXEC sp_configure filestream_access_level, 1 GO RECONFIGURE GO CREATE DATABASE NorthPole ON PRIMARY ( NAME = NorthPoleDB, FILENAME = 'C:\Temp\NP\NorthPoleDB.mdf' ), FILEGROUP NorthPoleFS CONTAINS FILESTREAM( NAME = NorthPoleFS, FILENAME = 'C:\Temp\NP\NorthPoleFS') LOG ON ( NAME = NorthPoleLOG, FILENAME = 'C:\Temp\NP\NorthPoleLOG.ldf') GO

    Read the article

  • PyML 0.7.2 - How to prevent accuracy from dropping after storing/loading a classifier?

    - by Michael Aaron Safyan
    This is a followup from "Save PyML.classifiers.multi.OneAgainstRest(SVM()) object?". The solution to that question was close, but not quite right, (the SparseDataSet is broken, so attempting to save/load with that dataset container type will fail, no matter what. Also, PyML is inconsistent in terms of whether labels should be numbers or strings... it turns out that the oneAgainstRest function is actually not good enough, because the labels need to be strings and simultaneously convertible to floats, because there are places where it is assumed to be a string and elsewhere converted to float) and so after a great deal of hacking and such I was finally able to figure out a way to save and load my multi-class classifier without it blowing up with an error.... however, although it is no longer giving me an error message, it is still not quite right as the accuracy of the classifier drops significantly when it is saved and then reloaded (so I'm still missing a piece of the puzzle). I am currently using the following custom mutli-class classifier for training, saving, and loading: class SVM(object): def __init__(self,features_or_filename,labels=None,kernel=None): if isinstance(features_or_filename,str): filename=features_or_filename; if labels!=None: raise ValueError,"Labels must be None if loading from a file."; with open(os.path.join(filename,"uniquelabels.list"),"rb") as uniquelabelsfile: self.uniquelabels=sorted(list(set(pickle.load(uniquelabelsfile)))); self.labeltoindex={}; for idx,label in enumerate(self.uniquelabels): self.labeltoindex[label]=idx; self.classifiers=[]; for classidx, classname in enumerate(self.uniquelabels): self.classifiers.append(PyML.classifiers.svm.loadSVM(os.path.join(filename,str(classname)+".pyml.svm"),datasetClass = PyML.VectorDataSet)); else: features=features_or_filename; if labels==None: raise ValueError,"Labels must not be None when training."; self.uniquelabels=sorted(list(set(labels))); self.labeltoindex={}; for idx,label in enumerate(self.uniquelabels): self.labeltoindex[label]=idx; points = [[float(xij) for xij in xi] for xi in features]; self.classifiers=[PyML.SVM(kernel) for label in self.uniquelabels]; for i in xrange(len(self.uniquelabels)): currentlabel=self.uniquelabels[i]; currentlabels=['+1' if k==currentlabel else '-1' for k in labels]; currentdataset=PyML.VectorDataSet(points,L=currentlabels,positiveClass='+1'); self.classifiers[i].train(currentdataset,saveSpace=False); def accuracy(self,pts,labels): logger=logging.getLogger("ml"); correct=0; total=0; classindexes=[self.labeltoindex[label] for label in labels]; h=self.hypotheses(pts); for idx in xrange(len(pts)): if h[idx]==classindexes[idx]: logger.info("RIGHT: Actual \"%s\" == Predicted \"%s\"" %(self.uniquelabels[ classindexes[idx] ], self.uniquelabels[ h[idx] ])); correct+=1; else: logger.info("WRONG: Actual \"%s\" != Predicted \"%s\"" %(self.uniquelabels[ classindexes[idx] ], self.uniquelabels[ h[idx] ])) total+=1; return float(correct)/float(total); def prediction(self,pt): h=self.hypothesis(pt); if h!=None: return self.uniquelabels[h]; return h; def predictions(self,pts): h=self.hypotheses(self,pts); return [self.uniquelabels[x] if x!=None else None for x in h]; def hypothesis(self,pt): bestvalue=None; bestclass=None; dataset=PyML.VectorDataSet([pt]); for classidx, classifier in enumerate(self.classifiers): val=classifier.decisionFunc(dataset,0); if (bestvalue==None) or (val>bestvalue): bestvalue=val; bestclass=classidx; return bestclass; def hypotheses(self,pts): bestvalues=[None for pt in pts]; bestclasses=[None for pt in pts]; dataset=PyML.VectorDataSet(pts); for classidx, classifier in enumerate(self.classifiers): for ptidx in xrange(len(pts)): val=classifier.decisionFunc(dataset,ptidx); if (bestvalues[ptidx]==None) or (val>bestvalues[ptidx]): bestvalues[ptidx]=val; bestclasses[ptidx]=classidx; return bestclasses; def save(self,filename): if not os.path.exists(filename): os.makedirs(filename); with open(os.path.join(filename,"uniquelabels.list"),"wb") as uniquelabelsfile: pickle.dump(self.uniquelabels,uniquelabelsfile,pickle.HIGHEST_PROTOCOL); for classidx, classname in enumerate(self.uniquelabels): self.classifiers[classidx].save(os.path.join(filename,str(classname)+".pyml.svm")); I am using the latest version of PyML (0.7.2, although PyML.__version__ is 0.7.0). When I construct the classifier with a training dataset, the reported accuracy is ~0.87. When I then save it and reload it, the accuracy is less than 0.001. So, there is something here that I am clearly not persisting correctly, although what that may be is completely non-obvious to me. Would you happen to know what that is?

    Read the article

  • How to list directory hierarchy in PyGTK treeview widget?

    - by lyrae
    I am trying to generate a hierarchical directory listing in pyGTK. Currently, I have this following directory tree: /root folderA - subdirA - subA.py - a.py folderB - b.py I have written a function that -almost- seem to work: def go(root, piter = None): for filename in os.listdir(root): isdir = os.path.isdir(os.path.join(root, filename)) piter = self.treestore.append(piter, [filename]) if isdir == True: go(os.path.join(root, filename), piter) This is what i get when i run the app: I also think my function is inefficient and that i should be using os.walk(), since it already exists for such purpose. How can I, and what is the proper/most efficient way of generating a directory tree with pyGTK?

    Read the article

  • php resize image

    - by haohan
    I have a class to read and output the image content, if $width is set, it will resize the image, and then output it. If I call the function like this $image-readImage('123.jpg'); , it can output the image file correctly, but when I call $image-readImage('123.jpg'); , it just display a black image with resized width & height. And I tried to replace the code from @imagejpeg($thumb, null, 100); to @imagejpeg($image, null, 100); will works~ - protected function readImage($fileName, $width = 0) { if ($width <= 0) { return @file_get_contents($this-destination . '/' . $fileName); } else { $imageSize = @getimagesize($this-destination . '/' . $fileName); $actualWidth = $imageSize[0]; $actualHeigth = $imageSize[1]; if ($actualWidth <= $width) { return @file_get_contents($this-destination . '/' . $fileName); } $height = (100 / ($actualWidth / $width)) * .01; $height = @round($actualHeigth * $height); $image = @imagecreatefromjpeg($this-destination . '/' . $fileName); $thumb = @imagecreatetruecolor($width, $height); @imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $actualWidth, $actualHeight); ob_start(); @imagejpeg($thumb, null, 100); $bits = ob_get_contents(); ob_end_clean(); return $bits; } } Any experts know what happened and help me to solve it ? Thanks.

    Read the article

  • Get remote image using cURL then resample.

    - by Chris
    I want to be able to retrieve a remote image from a webserver, resample it, and then serve it up to the browser AND save it to a file. Here is what I have so far: $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "$rURL"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // grab URL and pass it to the browser $out = curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); $imgRes = imagecreatefromstring($out); imagejpeg($imgRes, $filename, 70); header("Content-Type: image/jpg"); header("Content-length: ".filesize($filename)); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); readfile("$filename"); exit(); Update Updated code to include imjpeg step to save the image as lower quality. But how do I then, efficiently, serve this up to the browser. I currently, later in the code, do this readfile("$filename"); along with some header information but that means I'm reading the file back in again which seems inefficient.

    Read the article

  • how to get linkbutton id that is genrated dynamically from code behind in the eventhandler

    - by Ranjana
    i have create two linkbuttons dynamically: for (int i = 0; i < 2; i++) { LinkButton lb = new LinkButton(); lb.ID = "lnk" + FileName; lb.Text = FileName; Session["file"] = FileName; lb.CommandArgument = FileName; lb.Click += new EventHandler(Lb_Click); Panel1.Controls.Add(lb); Panel1.Controls.Add(new LiteralControl("<br />")); } i have got two links namely: File11 File22 void Lb_Click(object sender, EventArgs e) { string id=lb.ID; i.e //--Here how to get link button id which is clicked (either File11 id or File22 id)-------------------- }

    Read the article

  • PyML 0.7.2 - How to prevent accuracy from dropping after stroing/loading a classifier?

    - by Michael Aaron Safyan
    This is a followup from "Save PyML.classifiers.multi.OneAgainstRest(SVM()) object?". The solution to that question was close, but not quite right, (the SparseDataSet is broken, so attempting to save/load with that dataset container type will fail, no matter what. Also, PyML is inconsistent in terms of whether labels should be numbers or strings... it turns out that the oneAgainstRest function is actually not good enough, because the labels need to be strings and simultaneously convertible to floats, because there are places where it is assumed to be a string and elsewhere converted to float) and so after a great deal of hacking and such I was finally able to figure out a way to save and load my multi-class classifier without it blowing up with an error.... however, although it is no longer giving me an error message, it is still not quite right as the accuracy of the classifier drops significantly when it is saved and then reloaded (so I'm still missing a piece of the puzzle). I am currently using the following custom mutli-class classifier for training, saving, and loading: class SVM(object): def __init__(self,features_or_filename,labels=None,kernel=None): if isinstance(features_or_filename,str): filename=features_or_filename; if labels!=None: raise ValueError,"Labels must be None if loading from a file."; with open(os.path.join(filename,"uniquelabels.list"),"rb") as uniquelabelsfile: self.uniquelabels=sorted(list(set(pickle.load(uniquelabelsfile)))); self.labeltoindex={}; for idx,label in enumerate(self.uniquelabels): self.labeltoindex[label]=idx; self.classifiers=[]; for classidx, classname in enumerate(self.uniquelabels): self.classifiers.append(PyML.classifiers.svm.loadSVM(os.path.join(filename,str(classname)+".pyml.svm"),datasetClass = PyML.VectorDataSet)); else: features=features_or_filename; if labels==None: raise ValueError,"Labels must not be None when training."; self.uniquelabels=sorted(list(set(labels))); self.labeltoindex={}; for idx,label in enumerate(self.uniquelabels): self.labeltoindex[label]=idx; points = [[float(xij) for xij in xi] for xi in features]; self.classifiers=[PyML.SVM(kernel) for label in self.uniquelabels]; for i in xrange(len(self.uniquelabels)): currentlabel=self.uniquelabels[i]; currentlabels=['+1' if k==currentlabel else '-1' for k in labels]; currentdataset=PyML.VectorDataSet(points,L=currentlabels,positiveClass='+1'); self.classifiers[i].train(currentdataset,saveSpace=False); def accuracy(self,pts,labels): logger=logging.getLogger("ml"); correct=0; total=0; classindexes=[self.labeltoindex[label] for label in labels]; h=self.hypotheses(pts); for idx in xrange(len(pts)): if h[idx]==classindexes[idx]: logger.info("RIGHT: Actual \"%s\" == Predicted \"%s\"" %(self.uniquelabels[ classindexes[idx] ], self.uniquelabels[ h[idx] ])); correct+=1; else: logger.info("WRONG: Actual \"%s\" != Predicted \"%s\"" %(self.uniquelabels[ classindexes[idx] ], self.uniquelabels[ h[idx] ])) total+=1; return float(correct)/float(total); def prediction(self,pt): h=self.hypothesis(pt); if h!=None: return self.uniquelabels[h]; return h; def predictions(self,pts): h=self.hypotheses(self,pts); return [self.uniquelabels[x] if x!=None else None for x in h]; def hypothesis(self,pt): bestvalue=None; bestclass=None; dataset=PyML.VectorDataSet([pt]); for classidx, classifier in enumerate(self.classifiers): val=classifier.decisionFunc(dataset,0); if (bestvalue==None) or (val>bestvalue): bestvalue=val; bestclass=classidx; return bestclass; def hypotheses(self,pts): bestvalues=[None for pt in pts]; bestclasses=[None for pt in pts]; dataset=PyML.VectorDataSet(pts); for classidx, classifier in enumerate(self.classifiers): for ptidx in xrange(len(pts)): val=classifier.decisionFunc(dataset,ptidx); if (bestvalues[ptidx]==None) or (val>bestvalues[ptidx]): bestvalues[ptidx]=val; bestclasses[ptidx]=classidx; return bestclasses; def save(self,filename): if not os.path.exists(filename): os.makedirs(filename); with open(os.path.join(filename,"uniquelabels.list"),"wb") as uniquelabelsfile: pickle.dump(self.uniquelabels,uniquelabelsfile,pickle.HIGHEST_PROTOCOL); for classidx, classname in enumerate(self.uniquelabels): self.classifiers[classidx].save(os.path.join(filename,str(classname)+".pyml.svm")); I am using the latest version of PyML (0.7.2, although PyML.__version__ is 0.7.0). When I construct the classifier with a training dataset, the reported accuracy is ~0.87. When I then save it and reload it, the accuracy is less than 0.001. So, there is something here that I am clearly not persisting correctly, although what that may be is completely non-obvious to me. Would you happen to know what that is?

    Read the article

  • vb.net one dimensional string array manipulation difficulty

    - by Luay
    Hi, I am having some problems with manipulating a one dimensional string array in vb.net and would like your assistance please. My objective is to get 4 variables (if possible) from a file path. these variables are: myCountry, myCity, myStreet, Filename. All declared as string. The file location is also declared as string. so I have: Dim filePath As String to illustrate my problem and what I am trying to do I have the following examples: 1- C:\my\location\is\UK\Birmingham\Summer Road\this house.txt. In this example myCountry would be= UK. myCity= Birmingham. myStreet=Summer Road. Filename=this house.txt 2- C:\my Location\is\France\Lyon\that house.txt. here myCountry=France. myCity=Lyon. There is no street. Filename=that house.txt 3- C:\my Location is\Germany\the other house.txt Here myCountry=Germany. No city. No street. Filename=the other house.txt What I am trying to say is I have no idea before hand about the lenght of the string or the position of the variables I want. I also don't know if I am going to find/get a city or street name in the path. However I do now that i will get myCountry and it will be one of 5 options: UK, France, Germany, Spain, Italy. To tackle my problem, the first thing I did was Dim pathArr() As String = filePath.Split("\") to get the FileName I did: FileName = pathArr.Last To get myCountry I did: If filePath.Contains("UK") Then myCountry = "UK" ElseIf filePath.Contains("France") Then myCountry = "France" ElseIf filePath.Contains("Germany") Then myCountry = "Germany" ElseIf filePath.Contains("Spain") Then myCountry = "Spain" ElseIf filePath.Contains("Italy") Then myCountry = "Italy" End If in trying to figure out myCity and myStreet (and whether they exist in the string in the first place) I started with: Dim ind As Integer = Array.IndexOf(pathArr, myCountry) to get the index of the myCountry string. I thought I could make my way from there but I am stuck and don't know what to do next. Any help will be appreciated. Thanks

    Read the article

  • File transfer eating alot of CPU

    - by Dan C.
    I'm trying to transfer a file over a IHttpHandler, the code is pretty simple. However when i start a single transfer it uses about 20% of the CPU. If i were to scale this to 20 simultaneous transfers the CPU is very high. Is there a better way I can be doing this to keep the CPU lower? the client code just sends over chunks of the file 64KB at a time. public void ProcessRequest(HttpContext context) { if (context.Request.Params["secretKey"] == null) { } else { accessCode = context.Request.Params["secretKey"].ToString(); } if (accessCode == "test") { string fileName = context.Request.Params["fileName"].ToString(); byte[] buffer = Convert.FromBase64String(context.Request.Form["data"]); string fileGuid = context.Request.Params["smGuid"].ToString(); string user = context.Request.Params["user"].ToString(); SaveFile(fileName, buffer, user); } } public void SaveFile(string fileName, byte[] buffer, string user) { string DirPath = @"E:\Filestorage\" + user + @"\"; if (!Directory.Exists(DirPath)) { Directory.CreateDirectory(DirPath); } string FilePath = @"E:\Filestorage\" + user + @"\" + fileName; FileStream writer = new FileStream(FilePath, File.Exists(FilePath) ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.ReadWrite); writer.Write(buffer, 0, buffer.Length); writer.Close(); }

    Read the article

  • How to trigger binding source update from code in WPF?

    - by Benny
    In My ViewModel class I have a property: class ViewModel { public string FileName {get;set;} } and in my View I bind a label's content to ViewModel's FileName. now When I do drag-drop a file to my View, How can I update the label's Content property, so that the ViewMode's FileName also get updated via binding? Directly set the label's Content property won't work, it just simply clear the binding.

    Read the article

  • document directory problem?

    - by senthilmuthu
    When i write Data(53MB ) to Document directory ,the data is not written when i check directly through application support path.i coded like this, - (BOOL)writeApplicationData:(NSData *)data toFile:(NSString *)fileName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; if (!documentsDirectory) { NSLog(@"Documents directory not found!"); return NO; } NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName]; return ([data writeToFile:appFile atomically:YES]); } it works fine, but when i read the data using follwing code, the data is null, anyhelp pls? - (NSData *)applicationDataFromFile:(NSString *)fileName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName]; NSData *myData = [[[NSData alloc] initWithContentsOfFile:appFile] autorelease]; return myData; }

    Read the article

  • Best style for Python programs: what do you suggest?

    - by Noctis Skytower
    A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements). #! /usr/bin/env python ################################################################################ """\ CLASS INFORMATION ----------------- Program Name: Program 11 Programmer: Stephen Chappell Instructor: Stephen Chappell for CS 999-0, Python Due Date: 17 May 2010 DOCUMENTATION ------------- This is a simple encryption program that can encode and decode messages.""" ################################################################################ import sys KEY_FILE = 'Key.txt' BACKUP = '''\ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO\ PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ _@/6-UC'GzaV0%5Mo9g+yNh8b">Bi=<Lx [sQn#^R.D2Xc(\ Jm!4e${lAEWud&t7]H\`}pvPw)FY,Z~?qK|3SOfk*:1;jTrI''' ################################################################################ def main(): "Run the program: loads key, runs processing loop, and saves key." encode_map, decode_map = load_key(KEY_FILE) try: run_interface_loop(encode_map, decode_map) except SystemExit: pass save_key(KEY_FILE, encode_map) def run_interface_loop(encode_map, decode_map): "Shows the menu and runs the appropriate command." print('This program handles encryption via a customizable key.') while True: print('''\ MENU ==== (1) Encode (2) Decode (3) Custom (4) Finish''') switch = get_character('Select: ', tuple('1234')) FUNC[switch](encode_map, decode_map) def get_character(prompt, choices): "Gets a valid menu option and returns it." while True: sys.stdout.write(prompt) sys.stdout.flush() line = sys.stdin.readline()[:-1] if not line: sys.exit() if line in choices: return line print(repr(line), 'is not a valid choice.') ################################################################################ def load_key(filename): "Gets the key file data and returns encoding/decoding dictionaries." plain, cypher = open_file(filename) return dict(zip(plain, cypher)), dict(zip(cypher, plain)) def open_file(filename): "Load the keys and tries to create it when not available." while True: try: with open(filename) as file: plain, cypher = file.read().split('\n') return plain, cypher except: with open(filename, 'w') as file: file.write(BACKUP) def save_key(filename, encode_map): "Dumps the map into two buffers and saves them to the key file." plain = cypher = str() for p, c in encode_map.items(): plain += p cypher += c with open(filename, 'w') as file: file.write(plain + '\n' + cypher) ################################################################################ def encode(encode_map, decode_map): "Encodes message for the user." print('Enter your message to encode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(encode_map[char] if char in encode_map else char) def decode(encode_map, decode_map): "Decodes message for the user." print('Enter your message to decode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(decode_map[char] if char in decode_map else char) def custom(encode_map, decode_map): "Allows user to edit the encoding/decoding dictionaries." plain, cypher = get_new_mapping() for p, c in zip(plain, cypher): encode_map[p] = c decode_map[c] = p ################################################################################ def get_message(): "Gets and returns text entered by the user (until EOF)." buffer = [] while True: line = sys.stdin.readline() if line: buffer.append(line) else: return ''.join(buffer) def get_new_mapping(): "Prompts for strings to edit encoding/decoding maps." while True: plain = get_unique_chars('What do you want to encode from?') cypher = get_unique_chars('What do you want to encode to?') if len(plain) == len(cypher): return plain, cypher print('Both lines should have the same length.') def get_unique_chars(prompt): "Gets strings that only contain unique characters." print(prompt) while True: line = input() if len(line) == len(set(line)): return line print('There were duplicate characters: please try again.') ################################################################################ # This map is used for dispatching commands in the interface loop. FUNC = {'1': encode, '2': decode, '3': custom, '4': lambda a, b: sys.exit()} ################################################################################ if __name__ == '__main__': main() For all those Python programmers out there, your help is being requested. How should the formatting (not necessarily the coding by altered to fit Python's style guide? My friend does not need to be learning things that are not correct. If you have suggestions on the code, feel free to post them to this wiki as well.

    Read the article

  • Please help debug this ASP.Net [VB] code. Trying to write to text file from SQL Server DB.

    - by NJTechGuy
    I am a PHP programmer. I have no .Net coding experience (last seen it 4 years ago). Not interested in code-behind model since this is a quick temporary hack. What I am trying to do is generate an output.txt file whenever the user submits new data. So an output.txt file if exists should be replaced with the new one. I want to write data in this format : 123|Java Programmer|2010-01-01|2010-02-03 124|VB Programmer|2010-01-01|2010-02-03 125|.Net Programmer|2010-01-01|2010-02-03 I don't know VB, so not sure about string manipulations. Hope a kind soul can help me with this. I will be grateful to you. Thank you :) <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <script language="vb" runat="server"> sub Page_Load(sender as Object, e as EventArgs) Dim sqlConn As New SqlConnection("Data Source=winsqlus04.1and1.com;Initial Catalog=db28765269;User Id=dbo2765469;Password=ByhgstfH;") Dim myCommand As SqlCommand Dim dr As SqlDataReader Dim FILENAME as String = Server.MapPath("Output4.txt") Dim objStreamWriter as StreamWriter ' If Len(Dir$(FILENAME)) > 0 Then Kill(FILENAME) objStreamWriter = File.AppendText(FILENAME) Try sqlConn.Open() 'opening the connection myCommand = New SqlCommand("SELECT id, title, CONVERT(varchar(10), expirydate, 120) AS [expirydate],CONVERT(varchar(10), creationdate, 120) AS [createdate] from tblContact where flag = 0 AND ACTIVE = 1", sqlConn) 'executing the command and assigning it to connection dr = myCommand.ExecuteReader() While dr.Read() objStreamWriter.WriteLine("JobID: " & dr(0).ToString()) objStreamWriter.WriteLine("JobID: " & dr(2).ToString()) objStreamWriter.WriteLine("JobID: " & dr(3).ToString()) End While dr.Close() sqlConn.Close() Catch x As Exception End Try objStreamWriter.Close() Dim objStreamReader as StreamReader objStreamReader = File.OpenText(FILENAME) Dim contents as String = objStreamReader.ReadToEnd() lblNicerOutput.Text = contents.Replace(vbCrLf, "<br>") objStreamReader.Close() end sub </script> <asp:label runat="server" id="lblNicerOutput" Font-Name="Verdana" />

    Read the article

  • asp.net mvc outputting json with backslashes ( escape) despite many attemps to filter

    - by minus4
    i have an asp.net controller that output Json as the results a section of it is here returnString += string.Format(@"{{""filename"":""{0}"",""line"":[", file.Filename); what i get returned is this: "{\"DPI\":\"66.8213457076566\",\"width\":\"563.341067\",\"editable\":\"True\",\"pricecat\":\"6\",\"numpages\":\"2\",\"height\":\"400\",\"page\":[{\"filename\":\"999_9_1.jpg\",\"line\":[]},{\"filename\":\"999_9_2.jpg\",\"line\":[]}]]" i have tried to return with the following methods: return Json(returnString); return Json(returnString.Replace("\\",""); return Json will serialize my string to a jSon string, this i know but it likes to escape for some reason, how can i get rid of it ???? for info this is how i call it with jQuery: $.ajax({ url:"/Products/LoadArtworkToJSon", type:"POST", dataType: "json", async: false, data:{prodid: prodid }, success: function(data){ sessvars.myData = data; measurements = sessvars.myData; $("#loading").remove(); //empty the canvas and create a new one with correct data, always start on page 0; $("#movements").remove(); $("#canvas").append("<div id=\"movements\" style=\"width:" + measurements.width + "px; height:" + Math.round(measurements.height) + "px; display:block; border:1px solid black; background:url(/Content/products/" + measurements.page[0].filename + ") no-repeat;\"></div>"); your help is much appreciated thanks

    Read the article

  • How can I download all files of a specific type from a website using PHP?

    - by CheeseConQueso
    I want to get all midi (*.mid) files from a site that's set up pretty simple in terms of directory tree structure. I wish we had wget installed here, but that's another party.... The site is VGMusic.com and the path containing all of the midi files is: http://www.vgmusic.com/music/console/nintendo/nes/ I tried glob'ing it out, but I suppose that glob only works locally? Here is what I wrote to try to make it happen (doesn't work.. obviously..): <?php echo 'not a blizzard<br>'; foreach(glob('http://www.vgmusic.com/music/console/nintendo/nes/*.mid') as $filename) { echo $filename.'<br>'; //$newfile = 'http://www.mydomain.com/nes/'.$filename; //copy($filename, $newfile) } ?> I tried it also without the http:// in there with no luck.

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >