Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Does sombebody know a C++ library for accessing different operating system APIs? I'm thinking about a wrapper to access OS specific functions. Something like: > osAPI.MessageBox(); // calls MessageBox() in Win32, equivalent in Mac > OS Linux etc... Since I think it's hard to realize this for different OSes for now it would be also ok to have a nice C++ wrapper class for WinAPI.
Boost offers libraries for networking (Boost.Asio), threads (Boost.Thread), time, dates, file system traversal, shared memory, memory mapped files, etc. ACE also has abstractions for networking, threads, time, file system stuff, shared memory, etc. AFAIK, neither has GUI abstractions or DB abstractions either. Others have mentioned Qt, wxWidgets and so forth.
I think you're looking for [Trolltech's Qt](http://en.wikipedia.org/wiki/Qt_toolkit) C++ framework. It's a cross platform C++ library for GUI and just about everything else cross platform. And as of the latest version it is free to use for commercial use.
Is there an operating system API wrapper library for c++?
[ "", "c++", "cross-platform", "operating-system", "" ]
if I run this C# code ``` int realInt = 3; string foo = "bar"; Int32.TryParse(foo, out realInt); Console.WriteLine(realInt); Console.Read(); ``` I get 0. And I would like to know why! Cause I cannot find any reason why it would. This forces me to make temp variables for every parsing. So please! Great coders of the universe, enlighten me!
It is "out", not "ref". Inside the method it **has** to assign it (without reading it first) to satisfy the meaning of "out". Actually, "out" is a *language* concern (not a framework one) - so a managed C++ implementation could probably ignore this... but it is more consistent to follow it. In reality; if the method returns false you simply shouldn't look at the value; treat it as garbage until it is next assigned. It is stated to return 0, but that is rarely useful. --- Also - if it didn't do this (i.e. if it preserved the value); what would this print: ``` int i; int.TryParse("gibber", out i); Console.WriteLine(i); ``` That is perfectly valid C#... so what does it print?
[The Int32.TryParse Method (String, Int32) doc](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) says: > Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. > > result > > Type: System.Int32 > > When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, **or zero if the conversion failed**. The conversion fails if the s parameter is null reference (Nothing in Visual Basic), is not of the correct format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.
Why does Int32.TryParse reset the out parameter when not able to convert?
[ "", "c#", "" ]
I'm using the following code to grab a wmv file through a WebResponse. I'm using a thread to call this function: ``` static void GetPage(object data) { // Cast the object to a ThreadInfo ThreadInfo ti = (ThreadInfo)data; // Request the URL WebResponse wr = WebRequest.Create(ti.url).GetResponse(); // Display the value for the Content-Length header Console.WriteLine(ti.url + ": " + wr.Headers["Content-Length"]); string toBeSaved = @"C:\Users\Kevin\Downloads\TempFiles" + wr.ResponseUri.PathAndQuery; StreamWriter streamWriter = new StreamWriter(toBeSaved); MemoryStream m = new MemoryStream(); Stream receiveStream = wr.GetResponseStream(); using (StreamReader sr = new StreamReader(receiveStream)) { while (sr.Peek() >= 0) { m.WriteByte((byte)sr.Read()); } streamWriter.Write(sr.ReadToEnd()); sr.Close(); wr.Close(); } streamWriter.Flush(); streamWriter.Close(); // streamReader.Close(); // Let the parent thread know the process is done ti.are.Set(); wr.Close(); } ``` The file seems to download just fine, but Windows Media Viewer cannot open the file properly. Some silly error about not being able to support the file type. What incredibly easy thing am I missing?
You just need to download it as binary instead of text. Here's a method that should do the trick for you. ``` public void DownloadFile(string url, string toLocalPath) { byte[] result = null; byte[] buffer = new byte[4097]; WebRequest wr = WebRequest.Create(url); WebResponse response = wr.GetResponse(); Stream responseStream = response.GetResponseStream; MemoryStream memoryStream = new MemoryStream(); int count = 0; do { count = responseStream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, count); if (count == 0) { break; } } while (true); result = memoryStream.ToArray; FileStream fs = new FileStream(toLocalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); fs.Write(result, 0, result.Length); fs.Close(); memoryStream.Close(); responseStream.Close(); } ```
I do not understand why you are filling MemoryStream **m** one byte at a time, but then writing the **sr** to the file. At that point, I believe the **sr** is empty, and MemoryStream **m** is never used. Below is some code I wrote to do a similar task. It gets a WebResponse in 32K chunks at a time, and dumps it directly to a file. ``` public void GetStream() { // ASSUME: String URL is set to a valid URL. // ASSUME: String Storage is set to valid filename. Stream response = WebRequest.Create(URL).GetResponse().GetResponseStream(); using (FileStream fs = File.Create(Storage)) { Byte[] buffer = new Byte[32*1024]; int read = response.Read(buffer,0,buffer.Length); while (read > 0) { fs.Write(buffer,0,read); read = response.Read(buffer,0,buffer.Length); } } // NOTE: Various Flush and Close of streams and storage not shown here. } ```
How to use WebResponse to Download .wmv file
[ "", "c#", ".net", "windows-media-player", "" ]
While running my program I get this error: ``` terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create Abort trap ``` I know that you can't do much without the code but I think that this error is too deep in the code to copy all of it. Maybe I can figure it out if I understand what this error means. Is this a sign for an issue with reading or writing at the wrong memory address? Is there something I can do to get more information about the problem from my program?
It means you tried to create a string bigger than std::string::max\_size(). <http://msdn.microsoft.com/en-us/library/as4axahk(VS.80).aspx> > An exception of type length\_error Class > is thrown when an operation produces a > string with a length greater than the > maximum size.
I know this is a old question but I just ran into the same issue. Using Linux with gcc. Disassembling the function showed a lot of jumps in the code, where the exception was thrown, which shouldn't be there. In the end, a Clean Build resolved the issue for me.
What is the meaning of this C++ Error std::length_error
[ "", "c++", "string", "runtime-error", "" ]
I need some help on creating a user profile system. I want it to be like Facebook or [Myspace](http://en.wikipedia.org/wiki/Myspace) where it has only the username after the address, no question marks or anything, for example, `www.mysite.com/username`. I have all the register, logging scripts, etc. all done, but how do I go to profiles using the URL example above, "/username"?
You would need to create a mod rewrite that took the first directory and passed it as a $\_GET parameter. Try this: ``` RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^(.*)/$ index.php?user=$1 ``` That should rewrite anything after '/' as index.php?user=directory
Here's the abridged version of my answer, in case anyone a tldr moment: 1. Create a directory called "users". 2. Inside that directory, make an .htaccess file with the following mod\_rewrite: `REQUEST_URIRewriteEngine on` `RewriteRule !\.(gif|jpg|png|css)$ /your_web_root/users/index.php'REQUEST_URI` Now all page requests for any extensions not in the parenthesis made to the users directory will go to index.php index.php takes the URL that the user put in, and grabs the bit at the end. There are tons of ways of doing this, here's a simple on if you know the last part will always be a user name and not, maybe, username/pics/ : ``` $url_request = $_SERVER['REQUEST_URI']; //Returns path requested, like "/users/foo/" $user_request = str_replace("/users/", "", $url_request); //this leaves only 'foo/' $user_name = str_replace("/", "", $user_request); //this leaves 'foo' ``` Now, just do a query to the DB for that username. If it exists, index.php outputs the profile, if it doesn't have the script redirect to: /users/404.php But if the user does exist, all your visitor will see is that they put in ``` www.example.org/users/foo/ ``` and they got to foo's user page. No get variables for a hacker to exploit, and a pretty, easy to put on another blog or business card URL. --- Actually, it is possible to get rid of the "?" and have a nice simple www.example.org/users/someusername. I learned about this is on Till Quack's article "[How to Succeed with URLs](http://www.alistapart.com/articles/succeed/)" on [A List Apart](http://www.alistapart.com/). So you will need to understand Apache, .htaccess, and mod\_rewrite, and this method does require you to understand the security risks and account for them. Here's the basic idea: You create a directory called "users" (you don't have to, but this will simplify the whole thing), and in that directory, you put your .htaccess file which contains a mod\_rewite that effectively says "all file or directory requests that aren't of a certain kind (images, pdfs) should be sent to this script, which will handle where to send the user." The mod\_rewrite from the article looks like this: ``` RewriteEngine on RewriteRule !\.(gif|jpg|png|css)$ /your_web_root/index.php ``` In my example it would be "/your\_web\_root/users/index.php", the reason why it's more simple is because instead of this script handling ALL requests on your page, it's just dealing with the ones in the user directory. Then, you have a php script that says "okay, what was the URL given?" and it basically grabs the part after the last trailing slash (or two, if there is another one at the very end), and SANITIZES what it finds (that's really crucial) and says "does this username exist in my DB?" If yes, it sends the requester to the user's profile, but with a pretty URL (we'll get to that in a second), if not, it sends them to a "User Not Found" page, or whatever you want. So if it does find your user, the PHP script will output the user profile (Again, make sure to sanitize it. Any jerk user you may have can --if you give them the opportunity--embed malicious code into their own profile, knowing the browsers that views the profile will execute that code). Since the page requested was: ``` www.example.org/users/example_user ``` and since you are using mod\_rewrite instead of a redirect, the URL stays the same and the script that the .htaccess file pulls up just dumps the user profile. To the visitor, they just see that they put in the above url, and the user profile showed up. You also want to the PHP script that checks for the user to do a redirect to a "user not found" page, instead of simply having it output a "user\_not\_found" page. This is so anyone who puts in: ``` www.example.org/users/blabhaboehbohe ``` Will see the URL change to ``` www.example.org/users/notfound/ ``` instead of seeing the URL stay the same. If a hacker sees that the URL doesn't change, they now know that you are using a mod\_rewrite and thus there must be a script handling the actual output. If they know that, they can start going crazy looking for every security hole you may have left open. cheers.
How to create user profiles with PHP and MySQL
[ "", "php", "mysql", "membership", "profile", "" ]
I want to list the methods of the class files in the jar using the javap tool. How do I do it so that it lists the methods and members of all the class files in the jar. Right now I am able to do it for just one class at a time. I am expecting something like if I say ``` javap java.lang.* ``` it should enlist the methods and members of all the classes in java.lang package. If javap is not capable of that, are there any such tools available?
``` #!/bin/bash # Set the JAR name jar=<JAR NAME> # Loop through the classes (everything ending in .class) for class in $(jar -tf $jar | grep '.class'); do # Replace /'s with .'s class=${class//\//.}; # javap javap -classpath $jar ${class//.class/}; done ```
Even easier would be ``` JAR=<path to jarfile> \ javap -classpath $JAR $(jar -tf $JAR | grep "class$" | sed s/\.class$//) ```
How do I print the class structures in a jar file using the javap tool?
[ "", "java", "command-line", "javap", "" ]
I have a combo box where I am displaying some entries like: ``` Equals Not Equals Less Than Greater Than ``` Notice that these strings contain spaces. I have a enum defined which matches to these entries like: ``` enum Operation{Equals, Not_Equals, Less_Than, Greater_Than}; ``` Since space is not allowed, I have used \_ character. Now, is there any way to convert given string automatically to an enum element without writing a loop or a set of if conditions my self in C#?
I suggest building a `Dictionary<string, Operation>` to map friendly names to enum constants and use normal naming conventions in the elements themselves. ``` enum Operation{ Equals, NotEquals, LessThan, GreaterThan }; var dict = new Dictionary<string, Operation> { { "Equals", Operation.Equals }, { "Not Equals", Operation.NotEquals }, { "Less Than", Operation.LessThan }, { "Greater Than", Operation.GreaterThan } }; var op = dict[str]; ``` Alternatively, if you want to stick to your current method, you can do (which I recommend against doing): ``` var op = (Operation)Enum.Parse(typeof(Operation), str.Replace(' ', '_')); ```
``` Operation enumVal = (Operation)Enum.Parse(typeof(Operation), "Equals") ``` For "Not Equals", you obv need to replace spaces with underscores in the above statement EDIT: The following version replaces the spaces with underscores before attempting the parsing: ``` string someInputText; var operation = (Operation)Enum.Parse(typeof(Operation), someInputText.Replace(" ", "_")); ```
String to enum conversion in C#
[ "", "c#", "enums", "" ]
Can I serialize a generic list of serializable objects without having to specify their type. Something like the intention behind the broken code below: ``` List<ISerializable> serializableList = new List<ISerializable>(); XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType()); serializableList.Add((ISerializable)PersonList); using (StreamWriter streamWriter = System.IO.File.CreateText(fileName)) { xmlSerializer.Serialize(streamWriter, serializableList); } ``` Edit: For those who wanted to know detail: when I try to run this code, it errors on the XMLSerializer[...] line with: Cannot serialize interface System.Runtime.Serialization.ISerializable. If I change to `List<object>` I get `"There was an error generating the XML document."`. The InnerException detail is `"{"The type System.Collections.Generic.List1[[Project1.Person, ConsoleFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context."}"` The person object is defined as follows: ``` [XmlRoot("Person")] public class Person { string _firstName = String.Empty; string _lastName = String.Empty; private Person() { } public Person(string lastName, string firstName) { _lastName = lastName; _firstName = firstName; } [XmlAttribute(DataType = "string", AttributeName = "LastName")] public string LastName { get { return _lastName; } set { _lastName = value; } } [XmlAttribute(DataType = "string", AttributeName = "FirstName")] public string FirstName { get { return _firstName; } set { _firstName = value; } } } ``` The PersonList is just a `List<Person>` . This is just for testing though, so didn't feel the details were too important. The key is I have one or more different objects, all of which are serializable. I want to serialize them all to one file. I thought the easiest way to do that would be to put them in a generic list and serialize the list in one go. But this doesn't work. I tried with `List<IXmlSerializable>` as well, but that fails with `System.Xml.Serialization.IXmlSerializable cannot be serialized because it does not have a parameterless constructor.` Sorry for the lack of detail, but I am a beginner at this and don't know what detail is required. It would be helpful if people asking for more detail tried to respond in a way that would leave me understanding what details are required, or a basic answer outlining possible directions. Also **thanks** to the two answers I've got so far - I could have spent a lot more time reading without getting these ideas. It's amazing how helpful people are on this site.
I have an solution for a generic List<> with dynamic binded items. class PersonalList it's the root element ``` [XmlRoot("PersonenListe")] [XmlInclude(typeof(Person))] // include type class Person public class PersonalList { [XmlArray("PersonenArray")] [XmlArrayItem("PersonObjekt")] public List<Person> Persons = new List<Person>(); [XmlElement("Listname")] public string Listname { get; set; } // Konstruktoren public PersonalList() { } public PersonalList(string name) { this.Listname = name; } public void AddPerson(Person person) { Persons.Add(person); } } ``` class Person it's an single list element ``` [XmlType("Person")] // define Type [XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))] // include type class SpecialPerson and class SuperPerson public class Person { [XmlAttribute("PersID", DataType = "string")] public string ID { get; set; } [XmlElement("Name")] public string Name { get; set; } [XmlElement("City")] public string City { get; set; } [XmlElement("Age")] public int Age { get; set; } // Konstruktoren public Person() { } public Person(string name, string city, int age, string id) { this.Name = name; this.City = city; this.Age = age; this.ID = id; } } ``` class SpecialPerson inherits Person ``` [XmlType("SpecialPerson")] // define Type public class SpecialPerson : Person { [XmlElement("SpecialInterests")] public string Interests { get; set; } public SpecialPerson() { } public SpecialPerson(string name, string city, int age, string id, string interests) { this.Name = name; this.City = city; this.Age = age; this.ID = id; this.Interests = interests; } } ``` class SuperPerson inherits Person ``` [XmlType("SuperPerson")] // define Type public class SuperPerson : Person { [XmlArray("Skills")] [XmlArrayItem("Skill")] public List<String> Skills { get; set; } [XmlElement("Alias")] public string Alias { get; set; } public SuperPerson() { Skills = new List<String>(); } public SuperPerson(string name, string city, int age, string id, string[] skills, string alias) { Skills = new List<String>(); this.Name = name; this.City = city; this.Age = age; this.ID = id; foreach (string item in skills) { this.Skills.Add(item); } this.Alias = alias; } } ``` and the main test Source ``` static void Main(string[] args) { PersonalList personen = new PersonalList(); personen.Listname = "Friends"; // normal person Person normPerson = new Person(); normPerson.ID = "0"; normPerson.Name = "Max Man"; normPerson.City = "Capitol City"; normPerson.Age = 33; // special person SpecialPerson specPerson = new SpecialPerson(); specPerson.ID = "1"; specPerson.Name = "Albert Einstein"; specPerson.City = "Ulm"; specPerson.Age = 36; specPerson.Interests = "Physics"; // super person SuperPerson supPerson = new SuperPerson(); supPerson.ID = "2"; supPerson.Name = "Superman"; supPerson.Alias = "Clark Kent"; supPerson.City = "Metropolis"; supPerson.Age = int.MaxValue; supPerson.Skills.Add("fly"); supPerson.Skills.Add("strong"); // Add Persons personen.AddPerson(normPerson); personen.AddPerson(specPerson); personen.AddPerson(supPerson); // Serialize Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) }; XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes); FileStream fs = new FileStream("Personenliste.xml", FileMode.Create); serializer.Serialize(fs, personen); fs.Close(); personen = null; // Deserialize fs = new FileStream("Personenliste.xml", FileMode.Open); personen = (PersonalList)serializer.Deserialize(fs); serializer.Serialize(Console.Out, personen); Console.ReadLine(); } ``` Important is the definition and includes of the diffrent types.
See [Introducing XML Serialization](http://msdn.microsoft.com/en-us/library/182eeyhh.aspx): > ## Items That Can Be Serialized > > The following items can be serialized using the **XmlSerializer** > class: > > * Public read/write properties and fields of public classes > * Classes that implement **`ICollection`** or **`IEnumerable`** > * **`XmlElement`** objects > * **`XmlNode`** objects > * **`DataSet`** objects --- In particular, `ISerializable` or the `[Serializable]` attribute does not matter. --- Now that you've told us what your problem is ("it doesn't work" is not a problem statement), you can get answers to your actual problem, instead of guesses. When you serialize a collection of a type, but will actually be serializing a collection of instances of derived types, you need to let the serializer know which types you will actually be serializing. This is also true for collections of `object`. You need to use the [XmlSerializer(Type,Type[])](http://msdn.microsoft.com/en-us/library/e5aakyae.aspx) constructor to give the list of possible types.
XML Serialize generic list of serializable objects
[ "", "c#", "list", "generics", "xml-serialization", "" ]
I have a thread and I need to wait for its result, like this: ``` t1.start(); while (variableModifiedByMyThread == null) { /* do nothing */ } // "t1" set the value of "variableModifiedByMyThread" ``` The code above is working, but not a very nice solution... Is this code doing the same thing (is it waiting for the "t1" thread)? ``` t1.start(); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } // "t1" thread finished ```
The former is waiting for a variable to be set, the latter is waiting for the thread to die. If the variable is set just before the thread dies there is little difference except: * The former "spins" - the waiting thread is doing something (checking the variable) all the time - very wasteful! * The latter can be interrupted by another thread.
Consider [Future](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html)s. The idea is that you have some computation that will be completed "some time in the future" and you can then check if it has completed, or wait for it. From the javadoc: ``` FutureTask<String> future = new FutureTask<String>(new Callable<String>() { public String call() { return searcher.search(target); }}); executor.execute(future); ```
Java Wait-For-Thread Question
[ "", "java", "multithreading", "" ]
I have learned a good deal of XNA in 2D and have created a good number of the classic games using XNA (Breakout, pong, a platformer, tetris) and feel quite confident about using it. I managed this using guesswork and Microsoft's meager 2D XNA tutorials. However, now I want to begin to learn how to code games in 3D and it seems there is much, much more to learn; I have not coded in 3D before (except a failed attempt to learn the old "Managed DirectX" a few years ago) so will probably need to learn a significant amount. I have found this website, <http://www.ziggyware.com/> but the I cannot find or decide which tutorial to start on (something tells me I shouldn't be learning to build HLSL shaders just yet...). Can you recommend any good tutorials to begin with?
I've always though that <http://www.riemers.net/> has great tutorials for XNA, especially, that some series have MDX version, so you can see the different way of doing something in XNA/MDX. //Edit: Aso for the HLSL, nowaday everything runs on shaders, XNA gives you a basic shader that enabled you to render some basic scenes, but learning hlsl and writing own shaders is the only way to achieve something better, so you shouldn't be afraid of them. Again, what I like in riemers tutorials was that introduction to shaders, rendering to textures was pretty smooth, although I had an expierience with 3D before I started using XNA, so you might have a bit different point of view.
A free tutorial with videos by Microsoft: <http://creators.xna.com/en-US/education/gettingstarted/bg3d/chapter1> I recommend getting a copy of Learning XNA 3.0 published by O'Reilly as well.
Recommended XNA tutorials to start to learn 3D (for the first time)
[ "", "c#", ".net", "3d", "xna", "" ]
We're refactoring a long method; it contains a long `for` loop with many `continue` statements. I'd like to just use the **Extract Method** refactoring, but Eclipse's automated one doesn't know how to handle the conditional branching. I don't, either. Our current strategy is to introduce a `keepGoing` flag (an instance variable since we're going to want to **extract method**), set it to false at the top of the loop, and replace every continue with setting the flag to true, then wrapping all the following stuff (at different nesting levels) inside an `if (keepGoing)` clause. Then perform the various extractions, then replace the `keepGoing` assignments with early returns from the extracted methods, then get rid of the flag. Is there a better way? **Update**: In response to comments - I can't share the code, but here's an anonymized excerpt: ``` private static void foo(C1 a, C2 b, C3 c, List<C2> list, boolean flag1) throws Exception { for (int i = 0; i < 1; i++) { C4 d = null; Integer e = null; boolean flag2 = false; boolean flag3 = findFlag3(a, c); blahblahblah(); if (e == null) { if (flag1) { if (test1(c)) { if (test2(a, c)) { Integer f = getF1(b, c); if (f != null) e = getE1(a, f); if (e == null) { if (d == null) { list.add(b); continue; } e = findE(d); } } else { Integer f = getF2(b, c); if (f != null) e = getE2(a, f); if (e == null) { if (d == null) { list.add(b); continue; } e = findE(d); } flag2 = true; } } else { if (test3(a, c)) { Integer f = getF2(b, c); if (f != null) e = getE2(a, f); if (e == null) { if (d == null) { list.add(b); continue; } e = findE(d); } flag2 = true; } else { if (d == null) { list.add(b); continue; } e = findE(d); flag2 = true; } } } if (!flag1) { if (d == null) { list.add(b); continue; } e = findE(d); } } if (e == null) { list.add(b); continue; } List<C2> list2 = blahblahblah(b, list, flag1); if (list2.size() != 0 && flag1) { blahblahblah(); if (!otherTest()) { if (yetAnotherTest()) { list.add(b); continue; } blahblahblah(); } } } } ```
This is one of those fun ones where no single pattern will get you there. I would work at it iteratively. First I'd try to see if I couldn't use an early continue to remove one of those levels of ifs. It's much clearer code to check for a condition and return early (or in your case continue) than to have deeply nested ifs. Next I think I'd take some of the inner chunks and see if they couldn't be extracted into a separate method. It looks like the first two big blocks (within the "if (test2(a, c)) {" and its else statement) are very similar. There is cut and paste logic that should be the same. Finally after that stuff is cleared up, you can start looking at your actual problem--you need more classes. This entire statement is probably a three line polymorphic method in 3-5 sibling classes. It's very close to throw-away and rewrite code, once you identify your actual classes, this entire method will vanish and be replaced with something so simple it hurts. Just the fact that it's a static utility method should be telling you something--you don't want one of those in this type of code. Edit (After looking a little more): There is so much here it would be really fun to go through. Remember that when you are done you want no code duplication--and I'm pretty sure this entire thing could be written without a single if--I think all your ifs are cases that could/should easily be handled by polymorphism. Oh, and as an answer to your question of eclipse not wanting to do it--don't even TRY automatic refactoring with this one, just do it by hand. The stuff inside that first if() needs to be pulled out into a method because it's virtually identical to the clause in its else()! When I do something like this, I usually create a new method, move the code from the if into the new method (leaving just a call to the new method inside the if), then run a test and make sure you didn't break anything. then go line by line and check to ensure there is no difference between the if and its else code. If there is, compensate for it by passing the difference as a new variable to the method. After you're sure everything is identical, replace the else clause with a call. Test again. Chances are at this point a few additional optimizations will become obvious, you'll most likely lose the entire if by combining it's logic with the variable you passed to differentiate the two calls. Just keep doing stuff like that and iterating. The trick with refactoring is to use Very Small Steps and test between each step to ensure nothing changed.
`continue` is basically an analogue of an early return, right? ``` for (...) { doSomething(...); } private void doSomething(...) { ... if (...) return; // was "continue;" ... if (!doSomethingElse(...)) return; ... } private boolean doSomethingElse(...) { ... if (...) return false; // was a continue from a nested operation ... return true; } ``` Now I must admit that I didn't quite follow your current strategy, so I might have just repeated what you said. If so, then my answer is that I can't think of a better way.
Extract Method with continue
[ "", "java", "refactoring", "" ]
In C#/.NET, is there any way to get a notification before the object pointed to by a weak reference is destructed? Basically, I want to allow an object to be collected, but do something right before the object is destroyed, without modifying code to add destructors (since I won't know exactly what types of objects will be sued with my code). Thanks, Robert
.Net 4.0 has the solution you need: [ConditionalWeakTable](http://msdn.microsoft.com/en-us/library/dd287757.aspx). Here is a short program that demonstrates the idea. (discussed [here](http://www.facebook.com/note.php?note_id=327114446573) as well) ``` using System; using System.Runtime.CompilerServices; namespace GCCollectNotification { class ObjectToWatch { } class Notifier { public object ObjectToWatch { get; set; } ~Notifier() { Console.WriteLine("object is collected"); } } class Program { private ConditionalWeakTable<object, Notifier> map = new ConditionalWeakTable<object, Notifier>(); public void Test() { var obj = new ObjectToWatch(); var notifier = map.GetOrCreateValue(obj); notifier.ObjectToWatch = obj; } static void Main(string[] args) { new Program().Test(); GC.Collect(); GC.WaitForPendingFinalizers(); // "object is collected" should have been printed by now Console.WriteLine("end of program"); } } } ```
No there is no way to achieve this functionality. After a bit of speculation, I don't believe it's possible to implement a feature in the manner you are describing. Consider that at the point the object held by a WeakReference is collected, there are no more references (hence it's collectable). For an event to have any use to you it would need to provide the object as part of the event. This means that the reference has gone from collectable to not-collectable. There is nothing stopping the handling code from retaking a reference on that object. Hence the object can no longer be considered collectable. The CLR would need to make a second pass on the object to re-ensure it was collectable. You can see how the second time around the event could not be raised because it would lead to uncollectable objects. It would be a misuse of naming to claim this event was raised just before an object was collected. Simply because any handler could prevent this from being collected by establishing a new reference to the object. Instead it would have to be "ObjectMaybeAboutToBeCollected". This probably won't give you the behavior you're looking for.
C#: Notification before WeakReference is collected?
[ "", "c#", ".net", "events", "garbage-collection", "weak-references", "" ]
I need help converting this string **-->** `20090727 10:16:36:643` ***to*** **-->** `07/27/2009 10:16:36` The original date and time are being returned by the `SynchronizationAgent.LastUpdated()` function, which returns a String in the above format. --- ## Original question:preserved for reference I have this **-->** ``` HUD.LastSyncDate = mergeSubscription.SynchronizationAgent.LastUpdatedTime; ``` Which is setting a property that looks like this **-->** ``` public static string LastSyncDate { get { return _lastSyncDate; } set { _lastSyncDate = String.Format(CultureInfo.InvariantCulture,"{0:G}", value); } } ``` Unfortunately, with or without the `String.Format` the date that is displayed looks like this **-->** `20090727 10:16:36:643` I have tried multiple variations to Format it the way I want. What am I missing? Based on the below suggestions(*Mostly Joel's*), I implemented the suggested changes but I am still getting a `"String is not a valid DateTime error"` I also tried implementing this --> ``` HUD.LastSyncDate = DateTime.ParseExact(mergeSubscription.SynchronizationAgent.LastUpdatedTime,"yyyyMMdd HH:mm:ss:fff",CultureInfo.InvariantCulture); ``` but still nothing.
It appears to me that LastUpdatedTime is actually a string (since you can do the assignment) not a DateTime. In that case, the format applied won't do anything. You'll want to parse the LastUpdatedTime into a DateTime then reformat into the format that you want before assigning it to your string. ``` DateTime lastUpdated = DateTime.Parse( mergeSubscription.SynchronizationAgent.LastUpdatedTime ); HUD.LastSyncDate = string.Format( "{0:G}", lastUpdated ); public static string LastSyncDate { get; set; } ``` Note that you may need to use ParseExact instead. ``` DateTime lastUpdated = DateTime.ParseExact( "yyyyMMdd HH:mm:ss:fff", ..., CultureInfo.InvariantCulture ); ```
``` HUD.LastSyncDate = DateTime.Parse(mergeSubscription.SynchronizationAgent.LastUpdatedTime).ToString("MM/dd/yyyy") ``` You can put any [format string](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) you want there. But it sounds like what you really want is something more like this: ``` private static DateTime _lastSyncDate; public static DateTime LastSyncDate { get { return _lastSyncDate; } set { _lastSyncDate = value;} } public static string LastSyncDateString { get { return LastSyncDate.ToString("MM/dd/yyyy"); } } ``` Keep it as a datetime in the background and just use the string property for display.
Format a string to display the Date correctly
[ "", "c#", "datetime", "string", "formatting", "iformatprovider", "" ]
A question that's lurking in my head for a while now. What's the importance of Path.DirectorySeperatorChar ? I mean can't we just put '\' instead - which i think is faster than calling a property especially if you're constructing a huge number of paths in your application? Is there a reason for it? could there be another Char for folder/file path seperation other than '\' ? maybe in another operating system?
Yes, use the property. It will be more future-proof. You will be compatible with Mono (Linux) but MS.NET may also move to other platforms (like Compact and Micro Framework). But the best method is to use `Path.Combine()` and `Path.GetFileName()` et al, and then you won't be needing the separator char at all.
Use `Path.Combine()` for combining paths. Unfortunately, it's not as fast as it could be since the `Path` class' methods operate on `string` instead of a special struct (`Path` as a non-static class, perhaps?). Why is this a problem you ask? This gem: > **Exceptions:** > `ArgumentException` *path1* or *path2* contain one or more of the invalid characters defined in `GetInvalidPathChars`.
should we use Path.DirectorySeperatorChar C#
[ "", "c#", ".net", "string", "" ]
According to Brian Goetz's Java Concurrency in Practice *JVM can't exit until all the (nondaemon) threads have terminated, so failing to shut down an Executor could prevent the JVM from exiting.* I.e. System.exit(0) doesn't necessarily work as expected if there are Executors around. It would seem necessary to put some kind of ``` public void stop() { exec.shutdown() } ``` methods to all classes that contain Executors, and then call them when the application is about to terminate. Is this the only way, or is there some kind of shortcut to shut down all the Executors?
There's no shortcut to do them all, no. Also, you should probably call `shutdownNow()` rather than `shutdown()`, otherwise you could be waiting a while. What you could do, I suppose, is when you create the Executor, register it in a central place. Then, when shutting down, just call `shutdown()` on that central object, which in turn could terminate each of the registered executors. If you use Spring, then you can take advantage of its factory beans which create and manage the Executors for you. That includes shutting them down gracefully when the application quits, and saves you having to manage them yourself.
By default, an Executor will create only non-daemon threads. You can override that by supplying the Executor with your own ThreadFactory. Here's an example: ``` class DaemonThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } } ``` Be cautious, though, because the JVM will exit *right away* even if these threads are busy doing useful work!
How to shut down all Executors when quitting an application?
[ "", "java", "concurrency", "" ]
I am using PHP for a website. I have to get users upload their pics. Now, the pics can be in jpeg or png or gif format. My problem is that i identify a user by a unique userid, so I want to save the pics as: userid.jpg or userid.png etc. Now, how do i find out the extension of the file selected by the user using php?
I wouldn't rely on the file extension provided by the visitor. Instead, ask the file itself what it is (this can still be spoofed, but its less likely; also you don't have to wonder if the extension is 3 or 4 characters (jpeg, jpg for example)). Try: ``` if ($_FILES['avatar']['type'] == "image/gif") if ($_FILES['avatar']['type'] == "image/jpeg") if ($_FILES['avatar']['type'] == "image/png") ``` They're much more reliable.
Instead of relying on the extension sent by the client, you can also determine the type of the file, using [fileinfo](http://php.net/manual/en/function.finfo-file.php) (PHP >= 5.3), or if you're using an older version of PHP, something like `mime_content_type` Once you have the mime-type of the file, it's just a matter of mapping (like 'image/png' => 'png') (Should actually be better for security reasons ; if I remember correctly, $\_FILES['...']['type'] is sent by the client, and can be faked)
finding extension of the file being uploaded using php
[ "", "php", "file-upload", "" ]
I'm wondering how to parse values in XML that appear to have : in their name. I've been using: ``` $response = file_get_contents($url); $data = simplexml_load_string($response); ``` then doing a: ``` foreach($data->item as $key => $current){ ``` However, one of the latest feeds that I've been given has colons in the name of the feed as seen in the example below: ``` <item> <title>foo</title> <description>foo</description> <ccc:fid>10</ccc:fid> <ccc:bid>6</ccc:bid> </item> ``` When i try to create a $current->ccc:bid php does not get to happy (rightfully so). Is there any way to get around this?
the usage of ccc:fid is an extension of the namespace which needs to be declared in xml in order to be able to use it in libraries like simplexml. Here are some examples of descriptions of usin a namespace: * <http://www.w3.org/TR/1999/REC-xml-names-19990114/> * <http://www.w3.org/TR/xml-names/> Hope that helps, albeit it is a little complicated.
The elements with colons are using [namespace prefixes](http://www.w3schools.com/XML/xml_namespaces.asp), and it is perfectly valid XML. When using multiple schemas together, namespaces help differentiate elements which have the same name. The way SimpleXMLElement objects in PHP handle it, you can essentially ignore the part before the colon: ``` $current->fid; ``` If you do want to find out the namespace portion of the element name, you can do: ``` $current->fid->getNamespaces(); ```
How do I parse XML containing custom namespaces using SimpleXML?
[ "", "php", "xml", "namespaces", "" ]
m\_MAX and ask() are used by run() but should otherwise not be public. How can/should this be done? ``` #include <vector> class Q { public: static int const m_MAX=17; int ask(){return 4;} }; class UI { private: std::vector<Q*> m_list; public: void add(Q* a_q){m_list.push_back(a_q);} int run(){return Q::m_MAX==m_list[0]->ask();} }; int main() { UI ui; ui.add(new Q); ui.add(new Q); int status = ui.run(); } ```
You could define both m\_MAX and ask() within the private section of class Q. Then in Q add: "friend class UI". This will allow UI to access the private members of Q, but no one else. Also note that UI must be defined before the "friend class UI" statement. A forward declaration will work.
A simple solution - make m\_MAX and ask() private and make UI a friend of Q.
How can/should C++ static member variable and function be hidden?
[ "", "c++", "c++11", "encapsulation", "" ]
How can I add a css class to an updatepanel in the c# code behind file of asp.net
As you've seen the update panel doesn't have a css class property. So since it can't be done directly you need a work around; there are two (Grabbed from [UpdatePanel and CSS](http://weblogs.asp.net/rajbk/archive/2007/01/14/updatepanel-and-css.aspx)) that can get the behavior you desire. One is to surround the update panel with a div: ``` <div id="foo" style="visibility: hidden; position: absolute"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> </asp:UpdatePanel> </div> ``` The other is to apply a css selector based on the update panel's id: ``` <style type="text/css"> #<%=UpdatePanel1.ClientID%> { visibility: hidden; position: absolute; } </style> ``` Yet another way not mentioned in the article is surround the panel in a div and style the update panel based on it rendering as a div: ``` <style type="text/css"> #foo div { visibility: hidden; position: absolute; } </style> <div id="foo"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> </asp:UpdatePanel> </div> ```
you can use single class html attribute ``` <asp:UpdatePanel ID="UpdatePanel1" runat="server" class="MyCssClass"> </asp:UpdatePanel> ```
How can I add a css class to an updatepanel in ASP.Net?
[ "", "c#", "asp.net", "css", "" ]
I have a program that listens on a port waiting for a small amount of data to tell it what to do. I run 5 instances of that program, one on each port from 5000 to 5004 inclusively. I have a second program written in Python that creates a socket "s", writes the data to port 5000, then closes. It then increments the port number and creates a new socket connected to 5001. It does this until it reaches 5004. The first three socket connections work just fine. The programs on ports 5000 to 5002 receive the data just fine and off they go! However, the fourth socket connection results in a "Connection Refused" error message. Meanwhile, the fourth listening program still reports that it is waiting on port 5003 -- I know that it's listening properly because I am able to connect to it using Telnet. I've tried changing the port numbers, and each time it's the fourth connection that fails. Is there some limit in the system I should check on? I only have one socket open at any time on the sending side, and the fact that I can get 3 of the 5 through eliminates a lot of the basic troubleshooting steps I can think of. Any thoughts? Thanks! --- EDIT --- I'm on CentOS Linux with Python version 2.6. Here's some example code: ``` try: portno = 5000 for index, data in enumerate(data_list): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('myhostname', portno)) s.sendall(data) s.close() portno = portno + 1 except socket.error, (value,message): print 'Error: Send could not be performed.\nPort: ' + str(portno) + '\nMessage: ' + message sys.exit(2) ```
This sounds a lot like the anti-portscan measure of your firewall kicking in.
I don't know that much about sockets, so this may be really bad style... use at own risk. This code: ``` #!/usr/bin/python import threading, time from socket import * portrange = range(10000,10005) class Sock(threading.Thread): def __init__(self, port): self.port = port threading.Thread.__init__ ( self ) def start(self): self.s = socket(AF_INET, SOCK_STREAM) self.s.bind(("localhost", self.port)) self.s.listen(1) print "listening on port %i"%self.port threading.Thread.start(self) def run(self): # wait for client to connect connection, address = self.s.accept() data = True while data: data = connection.recv(1024) if data: connection.send('echo %s'%(data)) connection.close() socketHandles = [Sock(port) for port in portrange] for sock in socketHandles: sock.start() # time.sleep(0.5) for port in portrange: print 'sending "ping" to port %i'%port s = socket(AF_INET, SOCK_STREAM) s.connect(("localhost", port)) s.send('ping') data = s.recv(1024) print 'reply was: %s'%data s.close() ``` should output: ``` listening on port 10000 listening on port 10001 listening on port 10002 listening on port 10003 listening on port 10004 sending "ping" to port 10000 reply was: echo ping sending "ping" to port 10001 reply was: echo ping sending "ping" to port 10002 reply was: echo ping sending "ping" to port 10003 reply was: echo ping sending "ping" to port 10004 reply was: echo ping ``` perhaps this will help you see if it's your firewall causing troubles. I suppose you could try splitting this into client and server as well.
Connection refused when trying to open, write and close a socket a few times (Python)
[ "", "python", "sockets", "limit", "max", "" ]
I want to generate a list of all methods in a class or in a directory of classes. I also need their return types. Outputting it to a textfile will do...Does anyone know of a tool, lug-in for VS or something which will do the task? Im using C# codes by the way and Visual Studio 2008 as IDE
Sure - use Type.GetMethods(). You'll want to specify different binding flags to get non-public methods etc. This is a pretty crude but workable starting point: ``` using System; using System.Linq; class Test { static void Main() { ShowMethods(typeof(DateTime)); } static void ShowMethods(Type type) { foreach (var method in type.GetMethods()) { var parameters = method.GetParameters(); var parameterDescriptions = string.Join (", ", method.GetParameters() .Select(x => x.ParameterType + " " + x.Name) .ToArray()); Console.WriteLine("{0} {1} ({2})", method.ReturnType, method.Name, parameterDescriptions); } } } ``` Output: ``` System.DateTime Add (System.TimeSpan value) System.DateTime AddDays (System.Double value) System.DateTime AddHours (System.Double value) System.DateTime AddMilliseconds (System.Double value) System.DateTime AddMinutes (System.Double value) System.DateTime AddMonths (System.Int32 months) System.DateTime AddSeconds (System.Double value) System.DateTime AddTicks (System.Int64 value) System.DateTime AddYears (System.Int32 value) System.Int32 Compare (System.DateTime t1, System.DateTime t2) System.Int32 CompareTo (System.Object value) System.Int32 CompareTo (System.DateTime value) System.Int32 DaysInMonth (System.Int32 year, System.Int32 month) ``` (etc)
``` using (StreamWriter sw = new StreamWriter("C:/methods.txt")) { foreach (MethodInfo item in typeof(MyType).GetMethods()) { sw.WriteLine(item.Name); } } ```
Generate List of methods of a class with method types
[ "", "c#", "class", "methods", "" ]
I'm coding a web site and I have a php fonction called site\_nav.php which first define a $list array and than echos it in a json form. This way, I can get my web site map with ajax. My problem is that now, I would like to get the $list object in php, without echoing the json object. My question: Is there a way to include my php file without activation of the echo call which is in it? Thanks a lot!
Yes, just use output buffering. See the documentation on [`ob_start`](https://www.php.net/manual/en/function.ob-start.php) and [`ob_end_clean`](https://www.php.net/manual/en/function.ob-end-clean.php). ``` ob_start(); include("file.php"); ob_end_clean(); ```
You could use an output buffer to catch the output in a string. ``` ob_start(); include_once('file.php'); var $output = ob_get_contents(); ob_end_clean(); ```
PHP include w/o echo
[ "", "php", "" ]
I've got a collection of javascript files from a 3rd party, and I'd like to remove all the unused methods to get size down to a more reasonable level. Does anyone know of a tool that does this for Javascript? At the very least give a list of unused/used methods, so I could do the manually trimming? This would be in addition to running something like the YUI Javascript compressor tool... Otherwise my thought is to write a perl script to attempt to help me do this.
No. Because you can "use" methods in insanely dynamic ways like this. ``` obj[prompt("Gimme a method name.")](); ```
Check out [JSCoverage](http://siliconforks.com/jscoverage/) . Generates code coverage statistics that show which lines of a program have been executed (and which have been missed).
Is there a tool to remove unused methods in javascript?
[ "", "javascript", "" ]
Here's Eric Lippert's comment from [this post](https://stackoverflow.com/questions/1141502/why-does-this-finally-execute/1141513): > Now that you know the answer, you can > solve this puzzle: write me a program > in which there is a reachable goto > which goes to an unreachable label. – > Eric Lippert Jul 17 at 7:17 I am not able to create a code which will have reachable goto pointing to an unreachable label. Is that even possible? If yes, what would the C# code look like? Note: Let's not get into discussion about how 'goto' is bad etc. This is a theoretical exercise.
My original answer: ``` try { goto ILikeCheese; } finally { throw new InvalidOperationException("You only have cottage cheese."); } ILikeCheese: Console.WriteLine("MMM. Cheese is yummy."); ``` Here is without the compiler warning. ``` bool jumping = false; try { if (DateTime.Now < DateTime.MaxValue) { jumping = (Environment.NewLine != "\t"); goto ILikeCheese; } return; } finally { if (jumping) throw new InvalidOperationException("You only have cottage cheese."); } ILikeCheese: Console.WriteLine("MMM. Cheese is yummy."); ```
By the way if you use goto the csharp compiler for example for this case without finally block changes the code to a version without goto. ``` using System; public class InternalTesting { public static void Main(string[] args) { bool jumping = false; try { if (DateTime.Now < DateTime.MaxValue) { jumping = (Environment.NewLine != "\t"); goto ILikeCheese; } else{ return; } } finally { if (jumping) { //throw new InvalidOperationException("You only have cottage cheese."); Console.WriteLine("Test Me Deeply"); } } ILikeCheese: Console.WriteLine("MMM. Cheese is yummy."); } } ``` Turns To: ``` public static void Main(string[] args) { bool flag = false; try { if (DateTime.Now < DateTime.MaxValue) { flag = Environment.NewLine != "\t"; } else { return; } } finally { if (flag) { Console.WriteLine("Test Me Deeply"); } } Console.WriteLine("MMM. Cheese is yummy."); } ```
C# Puzzle : Reachable goto pointing to an unreachable label
[ "", "c#", "goto", "" ]
I have an engine that executes powershell scripts, and when they execute, need to feed back in some xml to the caller. The engine only takes i/o as an idmef xml message. So the script needs to return a similarly formatted xml message. I have a class which does my formatting for me and it would like the script writers to use it. So question is I want to wrap a c# class to enable it to be used by powershell. I saw something some where you can refer to c# class using the square bracket mob, eg. How to you make the c# available to be used like this. I reckon it needs to be made into class lib and somehow loaded into the powershell runtime but how. Also as I'm running the powershell from c#, how do I add it into the environment at that point. Any help would be appreciated. Bob.
If have an assembly (exe or dll) with the class in it, PowerShell can load it via `[System.Reflection.Assembly]::LoadFile("PathToYourAssembly")` or in V2 ``` Add-Type -Path "PathToYourAsembly" ``` If you are creating a runspace in your application and would like to make an assembly available, you can do that with a [RunspaceConfiguration](http://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.runspaceconfiguration(VS.85).aspx). ``` RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(); AssemblyConfigurationEntry myAssembly = new AssemblyConfigurationEntry("strong name for my assembly", "optional path to my assembly"); rsConfig.Assemblies.Append(myAssembly); Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig); myRunSpace.Open(); ```
I don't think anything is necessary. You can access pretty much the entire .NET Framework from PowerShell. I'm sure they didn't create any wrappers to do it.
Whats the best way to wrap a c# class for use by powershell script
[ "", "c#", "powershell", "powershell-2.0", "" ]
``` typedef vector<double>::size_type vec_sz; vec_sz size = homework.size(); ```
The first line [creates an alias](http://en.wikipedia.org/wiki/Typedef) of the `vector<double>::size_type` type. The `typedef` keyword is often used to make "new" data types names that are often shorter than the original, or have a clearer name for the given application. The second line should be pretty self-explanatory after that.
typedef **def**ines a **type** so you can use this new name instead of the longer old one, at least in this example. Then a variable size is defined, and it's type is of the just defined kind. At last the value of this size variable is set the the size of the homework object, probably also a vector.
Please explain two lines to me
[ "", "c++", "" ]
In PowerShell 1.0, if I have a cmdlet parameter of an enum type, what is the recommended method for testing whether the user specified that parameter on the cmdlet command line? For example: ``` MyEnum : int { No = 0, Yes = 1, MaybeSo = 2 } class DoSomethingCommand : PSCmdlet ... private MyEnum isEnabled; [Parameter(Mandatory = false)] public MyEnum IsEnabled { get { return isEnabled; } set { isEnabled = value; } } protected override void ProcessRecord() { // How do I know if the user passed -IsEnabled <value> to the cmdlet? } ``` Is there any way to do this without having to seed isEnabled with a dummy value? By default it will equal 0, and I don't want to have to seed every parameter or add a dummy value to my enum. I've potentially got **many** cmdlets with 100's of parameters, there's got to be a better way. This is related to [this question](https://stackoverflow.com/questions/727912/how-can-i-know-that-powershell-function-parameter-is-omitted) but I was looking for a cleaner way of doing this. Thanks.
In this case, I would use a nullable wrapper around the enum type e.g. ``` [Parameter(Mandatory = false)] public MyEnum? IsEnabled { get; set; } ``` Note the ? modifier on MyEnum. Then you can test if it is set like so: ``` if (this.IsEnabled.HasValue) { ... } ```
PowerShell aside, it's never good style to use 0 in that way. You should always use 0 for the most appropriate default. In this case, the most appropriate default should be something like "Unset." Ultimately, this is nothing to do with PowerShell and everything to do with good coding practices for .NET. * Oisin
How do I determine if a PowerShell Cmdlet parameter value was specified?
[ "", "c#", "powershell", "parameters", "powershell-cmdlet", "" ]
I swear... i hope this is the last question I have to ask like this, but I'm about to go crazy. I've got a JTable using a custom TableCellRenderer which uses a JEditorPane to display html in the individual cells of the JTable. How do I process clicking on the links displayed in the JEditorPane? I know about HyperlinkListener but no mouse events get through the JTable to the EditorPane for any HyperlinkEvents to be processed. How do I process Hyperlinks in a JEditorPane within a JTable?
The EditorPane isn't receiving any events because the component returned from the TableCellRenderer is only allowed to display, and not intercept events, making it pretty much the same as an image, with no behaviour allowed on it. Hence even when listeners are registered, the returned component is never 'aware' of any events. The work-around for this is to register a MouseListener on the JTable, and intercept all relevant events from there. Here's some classes I created in the past for allowing JButton roll-over to work in a JTable, but you should be able to re-use most of this for your problem too. I had a separate JButton for every cell requiring it. With that, this ActiveJComponentTableMouseListener works out in which cell the mouse event occurs in, and dispatches an event to the corresponding component. It's the job of the ActiveJComponentTableCellRenderer to keep track of the components via a Map. It's smart enough to know when it's already fired events, so you don't get a backlog of redundant events. Implementing this for hypertext shouldn't be that different, and you may still want roll-over too. Here are the classes ``` public class ActiveJComponentTableMouseListener extends MouseAdapter implements MouseMotionListener { private JTable table; private JComponent oldComponent = null; private TableCell oldTableCell = new TableCell(); public ActiveJComponentTableMouseListener(JTable table) { this.table = table; } @Override public void mouseMoved(MouseEvent e) { TableCell cell = new TableCell(getRow(e), getColumn(e)); if (alreadyVisited(cell)) { return; } save(cell); if (oldComponent != null) { dispatchEvent(createMouseEvent(e, MouseEvent.MOUSE_EXITED), oldComponent); oldComponent = null; } JComponent component = getComponent(cell); if (component == null) { return; } dispatchEvent(createMouseEvent(e, MouseEvent.MOUSE_ENTERED), component); saveComponent(component); save(cell); } @Override public void mouseExited(MouseEvent e) { TableCell cell = new TableCell(getRow(e), getColumn(e)); if (alreadyVisited(cell)) { return; } if (oldComponent != null) { dispatchEvent(createMouseEvent(e, MouseEvent.MOUSE_EXITED), oldComponent); oldComponent = null; } } @Override public void mouseEntered(MouseEvent e) { forwardEventToComponent(e); } private void forwardEventToComponent(MouseEvent e) { TableCell cell = new TableCell(getRow(e), getColumn(e)); save(cell); JComponent component = getComponent(cell); if (component == null) { return; } dispatchEvent(e, component); saveComponent(component); } private void dispatchEvent(MouseEvent componentEvent, JComponent component) { MouseEvent convertedEvent = (MouseEvent) SwingUtilities.convertMouseEvent(table, componentEvent, component); component.dispatchEvent(convertedEvent); // This is necessary so that when a button is pressed and released // it gets rendered properly. Otherwise, the button may still appear // pressed down when it has been released. table.repaint(); } private JComponent getComponent(TableCell cell) { if (rowOrColumnInvalid(cell)) { return null; } TableCellRenderer renderer = table.getCellRenderer(cell.row, cell.column); if (!(renderer instanceof ActiveJComponentTableCellRenderer)) { return null; } ActiveJComponentTableCellRenderer activeComponentRenderer = (ActiveJComponentTableCellRenderer) renderer; return activeComponentRenderer.getComponent(cell); } private int getColumn(MouseEvent e) { TableColumnModel columnModel = table.getColumnModel(); int column = columnModel.getColumnIndexAtX(e.getX()); return column; } private int getRow(MouseEvent e) { int row = e.getY() / table.getRowHeight(); return row; } private boolean rowInvalid(int row) { return row >= table.getRowCount() || row < 0; } private boolean rowOrColumnInvalid(TableCell cell) { return rowInvalid(cell.row) || columnInvalid(cell.column); } private boolean alreadyVisited(TableCell cell) { return oldTableCell.equals(cell); } private boolean columnInvalid(int column) { return column >= table.getColumnCount() || column < 0; } private MouseEvent createMouseEvent(MouseEvent e, int eventID) { return new MouseEvent((Component) e.getSource(), eventID, e.getWhen(), e.getModifiers(), e.getX(), e.getY(), e.getClickCount(), e.isPopupTrigger(), e.getButton()); } private void save(TableCell cell) { oldTableCell = cell; } private void saveComponent(JComponent component) { oldComponent = component; }} public class TableCell { public int row; public int column; public TableCell() { } public TableCell(int row, int column) { this.row = row; this.column = column; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TableCell other = (TableCell) obj; if (this.row != other.row) { return false; } if (this.column != other.column) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + this.row; hash = 67 * hash + this.column; return hash; }} public class ActiveJComponentTableCellRenderer<T extends JComponent> extends AbstractCellEditor implements TableCellEditor, TableCellRenderer { private Map<TableCell, T> components; private JComponentFactory<T> factory; public ActiveJComponentTableCellRenderer() { this.components = new HashMap<TableCell, T>(); } public ActiveJComponentTableCellRenderer(JComponentFactory<T> factory) { this(); this.factory = factory; } public T getComponent(TableCell key) { T component = components.get(key); if (component == null && factory != null) { // lazy-load component component = factory.build(); initialiseComponent(component); components.put(key, component); } return component; } /** * Override this method to provide custom component initialisation code * @param component passed in component from getComponent(cell) */ protected void initialiseComponent(T component) { } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return getComponent(new TableCell(row, column)); } @Override public Object getCellEditorValue() { return null; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { return getComponent(new TableCell(row, column)); } public void setComponentFactory(JComponentFactory factory) { this.factory = factory; }} public interface JComponentFactory<T extends JComponent> { T build(); } ``` To use it, you want to register the listener to as mouse and motion listener on the table, and register the renderer on the appropriate cells. If you want to intercept actionPerformed type events, override ActiveJComponentTableCellRenderer.initialiseComponent() like so: ``` protected void initialiseComponent(T component) { component.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopCellEditing(); } }); } ```
If you register a `MouseListener` on the JTable, you could easily get the text at the mouse click point. This would be done by generating a `Point` object from the `MouseEvent`, using `event.getX()` and `event.getY()`. You then pass that `Point` into `JTable`'s `rowAtPoint(pt)` and `columnAtPoint(pt)`. From there, you can get the text via `JTable.getValueAt(row, column)`. Now you have the value of your cell, so you can determine whether it is a link or not and do what you'd like with the result.
hyperlinks in JEditorPane in a JTable
[ "", "java", "html", "swing", "jtable", "jeditorpane", "" ]
I have a 48x48 image which is rotated using a transformation matrix. For some reason, the rotated image in design-time differs from the rotated image in run-time as you can see from [~~this screenshot (link dead)~~](http://img210.yfrog.com/img210/8058/render.jpg) (design-time on the left, run-time on the right): It might be a little bit difficult to spot, but if you look closely at the right edge of the blue circle, it is about a pixel wider in the image to the right. Note that the image is layered - the white glow in the foreground is the part that's being rotated, while the blue ball in the background is static. It seems like the image is offset 1 pixel in run-time, when rotating exactly 90 degrees (as in the screenshot), 180 degrees and probably also 270 degrees. The image looks the same with any other rotation angle, as far as I can see. Here's a snippet: ``` protected static Image RotateImage(Image pImage, Single pAngle) { Matrix lMatrix = new Matrix(); lMatrix.RotateAt(pAngle, new PointF(pImage.Width / 2, pImage.Height / 2)); Bitmap lNewBitmap = new Bitmap(pImage.Width, pImage.Height); lNewBitmap.SetResolution(pImage.HorizontalResolution, pImage.VerticalResolution); Graphics lGraphics = Graphics.FromImage(lNewBitmap); lGraphics.Transform = lMatrix; lGraphics.DrawImage(pImage, 0, 0); lGraphics.Dispose(); lMatrix.Dispose(); return lNewBitmap; } void SomeMethod() { // Same results in design-time and run-time: PictureBox1.Image = RotateImage(PictureBox2.Image, 18) // Different results in design-time and run-time. PictureBox1.Image = RotateImage(PictureBox2.Image, 90) } ``` Can anyone explain the reason for this behaviour? Or better yet, a solution to make run-time results look like design-time results? It's important for me because this image is part of an animation which is generated from code based on a single image which is then rotated in small steps. In design-time, the animation looks smooth and nice. In run-time it looks like it's jumping around :/ I'm using Visual Studio 2005 on Windows Vista Business SP2.
It might have something to do with differences in the Graphics object used at design time versus run time like the PixelOffsetMode.
How are you specifying your angle of rotation? in Degrees or in Radians? Sometimes I get results like those you describe when I've accidentally specified my angle in degrees when it should've been radians (and as a result the object has been rotated several hundred degrees instead of a few) I don't know for sure given your specific example, but its worth suggesting.
Transformation (rotation) of image using matrix - design-time vs. run-time rendering results
[ "", "c#", "graphics", "matrix", "rotation", "transformation", "" ]
I am searching how to format time including microseconds. I'm using class DateTime, it allowes (using properties) to get data till miliseconds, which is not enougth. I tried using Ticks, but I didn't know how to translate it to microseconds.
You can use `"ffffff"` in a format string to represent microseconds: ``` Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.ffffff")); ``` To convert a number of ticks to microseconds, just use: ``` long microseconds = ticks / (TimeSpan.TicksPerMillisecond / 1000); ``` If these don't help you, please provide more information about exactly what you're trying to do. EDIT: I originally multiplied `ticks` by 1000 to avoid losing accuracy when dividing `TimeSpan.TicksPerMillisecond` by 1000. However, It turns out that the `TicksPerMillisecond` is actually a constant value of 10,000 - so you can divide by 1000 with no problem, and in fact we could just use: ``` const long TicksPerMicrosecond = 10; ... long microseconds = ticks / TicksPerMicrosecond; ```
I was unable to get Johns tick to micorosecond conversion to work. Here is how I was able to measure Microsecond and Nanosecond resolution by using ticks and the Stopwatch: ``` Stopwatch sw = new Stopwatch(); sw.Start(); // Do something you want to time sw.Stop(); long microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L)); long nanoseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L*1000L)); Console.WriteLine("Operation completed in: " + microseconds + " (us)"); Console.WriteLine("Operation completed in: " + nanoseconds + " (ns)"); ```
C# time in microseconds
[ "", "c#", "" ]
In a lot online judge problems, the format for the input is as follows: first line is the number of test cases. Let's say X. Then X lines after that are the conditions for each test case. In the example below, there are two test cases. Each test case specify the upper and lower bound for which primes should be shown in the output. ``` Input: 2 1 10 3 5 Output: 2 3 5 7 3 5 ``` Now for my question. Right now, my program can handle one test case like so: ``` int main() { TestCase t; t.setRange(); t.compute(); t.print(); } ``` How can I create X amount of TestCases without naming them all 't'? X is specified at rumtime.
You can make a `std::vector<TestCase> allofem;` and `allofem.push_back(TestCase())` `X` times; remember to `#include <vector>` of course. Then you can loop on `allofem` and compute and then print on each item.
``` for (int i = 0; i < numOfTestCases; ++i) { TestCase t; t.setRange(); t.compute(); t.print(); } ```
Creating X Number of Nameless Objects
[ "", "c++", "object", "" ]
I've got a search input which sends data from an input to a php file as I type. The php file does a search on my database and shows up a list of search options. You know, the ajax style live searching. My problem is, if you type something really fast, it might just conduct a search off of the first 1 or 2 letters even though another 10 have been typed. This causes a few problems. My jQuery looks a bit like this: ``` $(document).ready(function(){ $('#searchMe').keyup(function(){ lookup(this.value); }); }); ``` and ``` function lookup(searchinput) { if(searchinput.length == 0) { // Hide the suggestion box. $("#suggestions").hide(); } else { $('#loading').fadeIn(); $.post("/RPCsearch.php", {queryString: ""+searchinput+""}, function(data){ if(data.length > 0) { $("#suggestions").html(data).show(); $('#loading').fadeOut(); } }); } } // lookup ``` So I'm just curious, how can I make it so that my script waits until I've finished typing before running the function? My logic says something like if a key hasn't been pressed for 200 micro seconds, run the function, otherwise hold up a bit. How is this done?
Easy, using [`setTimeout`](https://developer.mozilla.org/en/DOM:window.setTimeout). Of course you only want one timer going at once, so it's important to use [`clearTimeout`](https://developer.mozilla.org/en/DOM:window.clearTimeout) at the beginning of the function... ``` $(function() { var timer; $("#searchMe").keyup(function() { clearTimeout(timer); var ms = 200; // milliseconds var val = this.value; timer = setTimeout(function() { lookup(val); }, ms); }); }); ```
You may be interested in my [`bindDelayed`](http://phrogz.net/jquery-bind-delayed-get) jQuery mini-plugin. It: * Allows you to specify a delay before kicking off the request * Automatically cancels any previous requests that were scheduled to go off * Automatically cancels any in-air XHR requests that were in progress when you make your request * Only invokes your callback for the latest request + *If the user types "s", waits long enough for the request to go out, and then types "a", and the response for "s" comes back before the response for "sa" you won't have to deal with it.* The answer to the original question using `bindDelayed` would look like so: ``` // Wait 200ms before sending a request, // avoiding, cancelling, or ignoring previous requests $('#searchMe').bindDelayed('keyup',200,'/RPCsearch.php',function(){ // Construct the data to send with the search each time return {queryString:this.value}; },function(html){ // Use the response, secure in the knowledge that this is the right response $("#suggestions").html(html).show(); },'html','post'); ``` In case my site is down, here's the plugin code for Stack Overflow posterity: ``` (function($){ // Instructions: http://phrogz.net/jquery-bind-delayed-get // Copyright: Gavin Kistner, !@phrogz.net // License: http://phrogz.net/js/_ReuseLicense.txt $.fn.bindDelayed = function(event,delay,url,dataCallback,callback,dataType,action){ var xhr, timer, ct=0; return this.on(event,function(){ clearTimeout(timer); if (xhr) xhr.abort(); timer = setTimeout(function(){ var id = ++ct; xhr = $.ajax({ type:action||'get', url:url, data:dataCallback && dataCallback(), dataType:dataType||'json', success:function(data){ xhr = null; if (id==ct) callback.call(this,data); } }); },delay); }); }; })(jQuery); ```
How do I make my live jQuery search wait a second before performing the search?
[ "", "javascript", "jquery", "ajax", "" ]
I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.
Consider using [Django's json lib](http://docs.djangoproject.com/en/dev/topics/serialization/), which is included with GAE. ``` from django.utils import simplejson as json # load the object from a string obj = json.loads( string ) ``` The link above has examples of Django's serializer, and here's the link for [simplejson's documentation](http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html). If you're looking at storing Python class instances or objects (as opposed to compositions of lists, strings, numbers, and dictionaries), you probably want to look at [pickle](http://docs.python.org/library/pickle.html). Incidentally, to get Django 1.0 (instead of Django 0.96) running on GAE, you can use the following call in your main.py, per [this article](http://code.google.com/appengine/docs/python/tools/libraries.html#Django): ``` from google.appengine.dist import use_library use_library('django', '1.0') ``` --- ## Edit: Native JSON support in Google App Engine 1.6.0 with Python 2.7 As of Google App Engine 1.6.0, you can [use the Python 2.7 runtime](http://code.google.com/appengine/docs/python/python27/using27.html) by adding `runtime: python27` in `app.yaml`, and then you can import the native JSON library with `import json`.
Google App Engine now supports python 2.7. If using python 2.7, you can do the following: ``` import json structured_dictionary = json.loads(string_received) ```
How can I parse JSON in Google App Engine?
[ "", "python", "json", "google-app-engine", "" ]
In TagBuilder and other classes I can write something like: ``` var tr = new TagBuilder("HeaderStyle"){InnerHtml = html, [IDictionary Attributes]} ``` but I don't know how to pass the IDictionary parameter. How can I do that *on the fly*? Without creating a Dictionary variable. TagBuilder is an example, there are other classes that accept a parameter `IDictionary`as well. The question is about the generic case.
The following blog post has a helper method that can create Dictionary objects from anonymous types. <http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx> ``` void CreateADictionaryFromAnonymousType() { var dictionary = MakeDictionary(new {Name="Roy",Country="Israel"}); Console.WriteLine(dictionary["Name"]); } private IDictionary MakeDictionary(object withProperties) { IDictionary dic = new Dictionary<string, object>(); var properties = System.ComponentModel.TypeDescriptor.GetProperties(withProperties); foreach (PropertyDescriptor property in properties) { dic.Add(property.Name,property.GetValue(withProperties)); } return dic; } ```
Another way to create Dictionaries from Anonymous types: ``` new Dictionary<int, StudentName>() { { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}}, { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}}, { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}} }; ``` <http://msdn.microsoft.com/en-us/library/bb531208.aspx>
How to initialize IDictionary in constructor?
[ "", "c#", "asp.net-mvc", "" ]
Any suggestions on how I should approach this? Thanks.
I have to do this often - and my biggest hang-up is the semi-colon. Never fails that my first few days of writing VB after a longer stint of C# coding, the VB compiler is always barking at me for putting a semi-colon on every line of VB code. Other than that, it shouldn't be too painful. If you're fluent in C#, moving to VB might be stressful for the first few days, but after that you should be smooth sailing. Code converter tools come in handy to help you remember/learn/re-learn all of those odd syntax differences that you forget easily. The one I normally turn to first is <http://converter.telerik.com/> - and if that won't do the trick, a quick google search for code converters will turn up a handful of other good ones. Another pain point that I've had in the past too is Snippets. Snippets in C# rock - but in VB rock a bit less. Get to know the differences between those and life will be much easier. (Come on VB team - get that enter key working like the C# snippet team has it...)
Take a look at this [VB to C# Comparison](http://www.harding.edu/fmccown/vbnet_csharp_comparison.html) chart for some of the syntax and keyword differences.
Transitioning from C# to VB.NET
[ "", "c#", "vb.net", "" ]
Quick question: It's kind of tough to describe so let me just show an example. Is there anyway to do this: (I'm using jQuery but this is a general javascript question) $('div.element').offset().x; $('div.element').offset() by itself will return {'x' : 30, 'y' : 180}, so I'm just wondering if there is any compact way of doing this without creating an extra variable. Thanks! Matt
As you said, you can absolutely use this: ``` $('div.element').offset().left ``` OR ``` $('div.element').offset().top ``` Please note that jQuery's [`offset()`](http://docs.jquery.com/CSS/offset) returns `{ left: 30, top: 180 }` not an x/y pair like you said.
It will always create the object. I think you mean .top or .left instead of x/y? ``` >>> $('#jq-header').offset().left // 177.5 var coords = $('#jq-header').offset() coords.left // 177.5 coords.top // 0 alert($('body').offset().left) // 0 ``` <http://docs.jquery.com/CSS/offset>
Call a Javascript function within an inline statement
[ "", "javascript", "jquery", "" ]
I want to output some braces in a java MessageFormat. For example I know the following does not work: ``` MessageFormat.format(" public {0} get{1}() {return {2};}\n\n", type, upperCamel, lowerCamel); ``` Is there a way of escaping the braces surrounding "return {2}"?
You can put them inside single quotes e.g. ``` '{'return {2};'}' ``` See [here](https://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html) for more details.
The documentation for [MessageFormat](http://java.sun.com/javase/6/docs/api/java/text/MessageFormat.html) knows the answer: > Within a *String*, `"''"` represents a > single quote. A *QuotedString* can > contain arbitrary characters except > single quotes; the surrounding single > quotes are removed. An *UnquotedString* > can contain arbitrary characters > except single quotes and left curly > brackets. Thus, a string that should > result in the formatted message > `"'{0}'"` can be written as `"'''{'0}''"` > or `"'''{0}'''"`.
Can I escape braces in a java MessageFormat?
[ "", "java", "escaping", "messageformat", "" ]
How would I do so that the page I'm on won't be clickable? ``` $page = (isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1); $limit = ($page - 1) * 15; $sql = mysql_query("SELECT * FROM log LIMIT $limit, 15"); $totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM log"),0); $totalpages = ceil($totalres / 15); for ($i = 1; $i <= $totalpages; $i++) { $pagination .= "<a href=\"$_SERVER[PHP_SELF]?page=$i\">$i</a> "; } <p><?php echo $pagination ?></p> ```
``` if ($i == $page) $pagination .= "$i "; else $pagination .= "<a href=\"$_SERVER[PHP_SELF]?page=$i\">$i</a> "; ```
With an `if` inside the `for`, ``` if ( $i != $page) { //Your code. } else { //Same page. $pagination .= "&nbsp;" . $page . "&nbsp;" } ```
PHP question pagination
[ "", "php", "pagination", "" ]
How can I write gadgets for the Windows 7 desktop using C# and Visual Studio 2008? I'm looking for tutorials and resources on that topic.
Try [Authoring Sidebar Gadgets in C#](http://web.archive.org/web/20101218165848/http://nikhilk.net/SidebarGadgets.aspx). C# is not the only option. This [detailed tutorial](http://www.odetocode.com/articles/463.aspx) explains how to develop gadgets without C#. (Orginally gadgets were authored in a mix of XML, HTML, CSS, and some IE scripting language.) [How to get started with Windows 7 gadgets](https://stackoverflow.com/questions/902818/how-to-get-started-with-windows-7-gadgets) is a related Stack Overflow question that may also provide additional information.
I have not tried it myself, but this might help: <http://www.codeproject.com/KB/gadgets/RunVistaGadget2.aspx>
C# tutorial to write gadgets
[ "", "c#", ".net", "visual-studio", "windows-desktop-gadgets", "" ]
I have application that produces files. I would like to connect those files with application so that double-click on file launches my application. Everything works properly except for annoyance that icon looks same like icon of my application. I would like to have one icon for application and one icon for it's documents. DefaultIcon value in registry requires "app.exe,1" syntax where 1 is icon index. It seems that .NET resources are not Win32 resources. I tried following but without success: 1. Selecting "Embedded Resource" as file's build action. 2. Adding icon to resource file. Only thing that worked is having icon file separated from executable and pointing to it. However, that seems to me like surrender. Any ideas how to solve this?
Have you tried setting 2 as the icon index? EDIT: I found a way but you have to do it again for every new build. 1. Open the .exe file in Visual Studio (File -> Open File) 2. Right click the icon folder and select Add resource 3. Click the button Import 4. Select your .ico file 5. You might have to mess with the icon numbers, I think the lowest number (example 101) will be the application's icon 6. Remember the new icon number and set it as the index EDIT 2: Try this article: <http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx>
If you are using the Wix toolset (<http://www.wixtoolset.org>) to install your application, you can get Wix to take care of the file type and document icon registration Here is my magic Wix incantation: ``` <!-- Your executable --> <File Id="MaAppExe" Name="MyApp.exe" Source="MyApp.exe" KeyPath="yes" > </File> <!-- your document icon --> <File Id='IconMyAppDoc.ico' Name='IconMyAppDoc.ico' Source='$(var.MyApp.ProjectDir)\Resources\Images\Icons\docicon.ico' /> <-- File Extension and associated document icon --> <ProgId Id='MyApp.MyAppExtension' Description='My App Data File' Icon='IconMyAppDoc.ico'> <Extension Id='MyApp' ContentType='text/plain'> <Verb Id='open' Command='Open' TargetFile="MyAppExe" Argument='"%1"' /> </Extension> </ProgId> </Component> ```
Registering file type and custom document icon in .NET
[ "", "c#", ".net", "icons", "file-type", "" ]
I have a basic programming question. I would like to know if every non-void function should have an "return" statement in PHP script. Take the following two example functions. Which one would be the better way to program? They both do the same thing (to my understanding) but which is the "better practice" and why? ``` function displayApple1($str){ if($str == 'apple') echo $str; } function displayApple2($str){ if($str == 'apple') echo $str; else return; } ```
Overuse of `return` is a bad thing. Your execution paths should be simple and straightforward; overuse of the `return` keyword can imply (improper) complexity.
Your second example hurts my head. It should probably read: ``` funciton displayApple2($str){ if($str == 'apple') echo $str; return; } ``` Personally, I don't use return statements if I am not specifically returning something.
Is it good programming practice to have a return statement in all functions?
[ "", "php", "function", "" ]
I have a public static property in a class. The class has some custom attributes applied to it. I want to access the Attribute in a static property. In a non-static member I can get the type of current class using this.GetType() but how do I do this in a static member of the class ? **Please note that..** * I do not want to use **typeof(typename)** due to inheritance issues. [I will have this property inherited to derived classes.]. * I also do not want to use **Generics** as well. ## EDIT **Here's my objective.** I have an abstract base class called EntityBase. All my entities derive from this class. Each entity also carries a custom attribute called TableMappingAttribute that lets me know the table it refers/maps to, during runtime. I already have a property in EntityBase that returns me the mapped TableName for the entity. I will always need an instance of entity to access the TableName property. I wish to access this property statically sometime, like MyEntity.TableName. I have large amount entities in my project. I want this static property to be added in EntityBase class itself. So I must discover the type at runtime. How do I do this in EntityBase class itself ?? Thnaks.
You can't, basically. typeof(...) *is* what you need to use. Bear in mind that if you try to use: ``` Type type = MyDerivedType.SomeStaticProperty; ``` which is *declared* in `MyBaseType`, that will actually end up being compiled to ``` Type type = MyBaseType.SomeStaticProperty; ``` anyway. Static members basically aren't polymorphic. If you try to use them polymorphically, you'll run into problems like this. EDIT: So from your edit, it looks like you're trying to do exactly the above type of thing, with ``` MyEntity.TableName ``` instead of ``` EntityBase.TableName ``` It just won't work. The compiler will emit code to fetch EntityBase.TableName. The runtime has no concept of "the current class". There's no context here. Basically you need to change your design. If you want to use inheritance, you may want to have a parallel hierarchy - one for the metadata (things like table names) and one for the actual objects. So you'd have something like: ``` public class MyEntity : EntityBase<MyEntityType> ``` where MyEntityType derives from EntityType in the parallel hierarchy. Then you *can* use inheritance within the metadata hierarchy. Alternatively, just making EntityBase generic anyway will let you get at the type of entity you're talking about: ``` public class MyEntity : EntityBase<MyEntity> ``` I know you said you didn't want to use generics, but as what you want to do just won't work, you should at least consider it...
> I do not want to use typeof(typename) due to inheritance issues. static properties **aren't inherited** in the normal sense. Sure, they are in-scope, but that isn't the same. The only way to get what you want would be to look at the stack-frame, but that is ugly and hacky (and risky if optimisations are enabled). I'd refactor for a solution that uses the instace... instance have a `Type`.
How to get System.Type instance of a class-type in Static Member?
[ "", "c#", "reflection", "static-members", "" ]
Are there no "high-level" HTTP libraries for native C/C++ in Win32 or am I just looking in the wrong places? By "high-level" I mean an API that lets me do HTTP web requests/responses in C++ with "about the same" abstraction level as the .NET framework (but note that using C++/CLI is not an option for me). How to do something like this (with about the same amount of code) in C/C++ in Win32 without using .NET? As a reference, I include a code sample to show how I'd do it in C#. ``` byte[] fileBytes = null; bool successfulDownload = false; using (WebClient client = new WebClient()) { WebProxy proxy = WebProxy.GetDefaultProxy(); client.Proxy = proxy; tryAgain: try { fileBytes = client.DownloadData(fileUrl); successfulDownload = true; } catch (WebException wEx) { if (wEx.Response != null && wEx.Response is HttpWebResponse) { string username = null, password = null; bool userCanceled = false; HttpStatusCode statusCode = ((HttpWebResponse)wEx.Response).StatusCode; switch (statusCode) { case HttpStatusCode.ProxyAuthenticationRequired: // This is just a convenience function defined elsewhere GetAuthenticationCredentials(fileUrl, true, out username, out password, out userCanceled); if (!userCanceled) { client.Proxy.Credentials = new NetworkCredential(username, password); goto tryAgain; } break; case HttpStatusCode.Unauthorized: // This is just a convenience function defined elsewhere GetAuthenticationCredentials(fileUrl, false, out username, out password, out userCanceled); if (!userCanceled) { client.Credentials = new NetworkCredential(username, password); goto tryAgain; } break; } } } } ```
Win32 provides the `Internet*` functions. <http://msdn.microsoft.com/en-us/library/aa385473(VS.85).aspx> You'll need to do an (IIRC, I haven't touched these APIs in over 10 years) `InternetOpenURL` and `InternetReadFile`.
Apart from libcurl/curlpp (which is flexible and powerful but I find very...clunky) there are two C++ libraries I'm keeping my eye on. Both are quite new and based on Boost::ASIO. However *neither* support proxies (as best I can tell). [cpp-netlib](http://cpp-netlib.wiki.sourceforge.net/) ([blog](http://cpp-netlib.blogspot.com/)) is perhaps more mature (I know it's had some real-world testing) but is currently lacking timeouts (I'm working on it!). Example: ``` network::http::request request("http://google.com"); network::http::client client; network::http::response response; response = client.get(request); if (response.status() == 200) { std::cout << body(response)); } ``` [Urdl](http://sourceforge.net/projects/urdl/) ([documentation](http://www.think-async.com/Urdl/doc/html/index.html)) is written by the ASIO creator and has timeouts (but was only announced *last month*). It uses a different model, opting to work with streams: ``` urdl::istream is("http://google.com"); std::string line; while (std::getline(is, line)) { std::cout << line << std::endl; } ``` I agree that C++ doesn't have great support for HTTP but both of these libraries show a lot of promise.
High-level HTTP client library for native C/C++ in Win32
[ "", "c++", "http", "winapi", "client", "" ]
I'm trying to read from files created outside of the program, but am having some trouble. The program has the user create a file. Then it reads words from two .txt files created outside of the program, and then writes the words to the created file. ``` #include "std_lib_facilities.h" int main() { string word; cout << "Create file.\n"; char name[20]; cin >> name; ofstream ost(name, ios::out); cout << "Open first file.\n"; char filename[20]; cin >> filename; ifstream ist(filename); while(ist >> word) ost << word << " "; ist.close(); cout << "Open second file.\n"; cin >> filename; ifstream isttwo(filename); while(isttwo >> word) ost << word << " "; isttwo.close(); ost.close(); keep_window_open(); } ``` However, when I open the created file in notepad, it comes out blank. Is this because reading into a string is impossible because the files being read were created separately? I'm not really sure. Any help is appreciated.
The code is correct. Just make sure when you write the name of the first file and the second one you write their extensions as well. For example : ``` first.txt second.txt ```
A potential problem is your use of cin instead of getline. Imagine this input: ``` Open second file. >>file one.txt ``` This obviously won't open the file you want, since cin stops reading once you hit a space. Try explicitly opening name, such as: ``` ost.open(name); ``` I also don't like your implicit use of the >> operator in the while loops. Try this: ``` while (!ist.eof()) { getline(ist, word); ost << word; } ```
Reading data from file created from outside
[ "", "c++", "" ]
I used NetBeans to create a Metro Web service and to be deployed on GlassFish. I get an error when I try to build but *only* if one of the operations in the web service returns an Object instead of a primitive type or String. The error: ``` Deploying application in domain failed; Deployment Error -- Exception occured in the wsgen process javax.xml.ws.WebServiceException: Unable to create JAXBContext build-impl.xml:569: The module has not been deployed. BUILD FAILED (total time: 2 seconds) ``` The containing code: ``` <target if="netbeans.home" name="-run-deploy-nb"> <nbdeploy clientUrlPart="${client.urlPart}" debugmode="false" forceRedeploy="${forceRedeploy}"/> </target> ``` Any help is appreciated!
[This thread](http://www.manning-sandbox.com/message.jspa?messageID=79093) is also a good illustration of your problem: > The problem is that the custom class has public access for the properties and also it has getter/setter methods. > I discover because you can use Netbeans to generate the `WSDL` files for the `Webservice` to inspect them. Doing so it returned the detailed error. > If you want to use it, write your Web Service, then go to "`Web Services`" node, select your Web Service, right click it and select "Generate and Copy `WSDL`". You can find some practical advices here on the [definition of your object](http://www.jseduite.org/doku/cookbook/build-ws#business_object). And of course you still have the [Java Web Service Tutorial](http://java.sun.com/webservices/docs/2.0/tutorial/doc/) exposing the [Requirements of a JAX-WS Endpoint](http://java.sun.com/webservices/docs/2.0/tutorial/doc/JAXWS3.html#wp144873).
I found the Solution.. The class I am returning has a public value also, set and get so delete them and worked fine
Unable to create JAXBContext in Java Web service
[ "", "java", "web-services", "jakarta-ee", "glassfish", "" ]
I'm looking for a dijit widget which works like a normal html select (combobox). all dijit widgets i found until now, have an editable text box. I prefer to have a drop down box only and no editable textbox. ``` <select name="aCombobox"> <option value="1" selected="selected">Hund</option> <option value="2">Katze</option> <option value="3">Maus</option> <option value="4">Waldelfe</option> </select> ``` Also important for me is, that the upper code is working with the widget and the widget have to use the "Value" values and not the display text. I checked this dijit widgets: combobutton, combobox, filteringselect, dropdownbutton. Maybe there is an attribute i forgot to set. Is there a widget which meet my requirements?
I think you need to use dijit.form.FilteringSelect: ``` <select name="aCombobox" dojotype="dijit.form.FilteringSelect"> <option value="1" selected="selected">Hund</option> <option value="2">Katze</option> <option value="3">Maus</option> <option value="4">Waldelfe</option> <script type="dojo/connect" event="onChange"> console.log( 'picked ' + this.attr('value') + ' = ' + this.attr('displayedValue') ); </script> </select> ``` Hope this helps. If you are feeling adventurous, you can try out dijit.form.DropDownSelect. It just got added on 7/21 to trunk. [Here's the test.](http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/tests/form/test_DropDownSelect.html)
I'm new so can't leave comments yet, but seth mentions dijit.form.DropDownSelect being in trunk - this is for 1.4 I believe; 1.3 has it in dojox as [dojox.form.DropDownSelect](http://docs.dojocampus.org/dojox/form/DropDownSelect)
Looking for a Dijit Widget which works like a default html select
[ "", "javascript", "dojo", "" ]
I have a CheckedListBox (WinForms) control (which inherits from ListBox; googling shows that the problem is with ListBox) that is anchored to all four sides of its form. When the form is resized, the ListBox has an ugly flicker. I tried inheriting CheckedListBox and setting `DoubleBuffered` to `true` in the ctor (this technique works with other controls, including ListView and DataGridView), but it had no effect. I tried adding the [`WS_EX_COMPOSITED`](http://msdn.microsoft.com/en-us/library/ms632680.aspx) style to `CreateParams`, and this helped, but makes the form resize mush more slowly. Is there any other way to prevent this flickering?
I was having similar issues albeit with an owner drawn listbox. My solution was to use BufferedGraphics objects. Your mileage may vary with this solution if your list isn't owner drawn, but maybe it will give you some inspiration. I found that TextRenderer had difficulties rendering to the correct location unless I suppled TextFormatFlags.PreserveGraphicsTranslateTransform. The alternative to this was to use P/Invoke to call BitBlt to directly copy pixels between the graphics contexts. I chose this as the lesser of two evils. ``` /// <summary> /// This class is a double-buffered ListBox for owner drawing. /// The double-buffering is accomplished by creating a custom, /// off-screen buffer during painting. /// </summary> public sealed class DoubleBufferedListBox : ListBox { #region Method Overrides /// <summary> /// Override OnTemplateListDrawItem to supply an off-screen buffer to event /// handlers. /// </summary> protected override void OnDrawItem(DrawItemEventArgs e) { BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current; Rectangle newBounds = new Rectangle(0, 0, e.Bounds.Width, e.Bounds.Height); using (BufferedGraphics bufferedGraphics = currentContext.Allocate(e.Graphics, newBounds)) { DrawItemEventArgs newArgs = new DrawItemEventArgs( bufferedGraphics.Graphics, e.Font, newBounds, e.Index, e.State, e.ForeColor, e.BackColor); // Supply the real OnTemplateListDrawItem with the off-screen graphics context base.OnDrawItem(newArgs); // Wrapper around BitBlt GDI.CopyGraphics(e.Graphics, e.Bounds, bufferedGraphics.Graphics, new Point(0, 0)); } } #endregion } ``` --- The `GDI` class (suggested by **frenchtoast**). ``` public static class GDI { private const UInt32 SRCCOPY = 0x00CC0020; [DllImport("gdi32.dll", CallingConvention = CallingConvention.StdCall)] private static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, UInt32 dwRop); public static void CopyGraphics(Graphics g, Rectangle bounds, Graphics bufferedGraphics, Point p) { IntPtr hdc1 = g.GetHdc(); IntPtr hdc2 = bufferedGraphics.GetHdc(); BitBlt(hdc1, bounds.X, bounds.Y, bounds.Width, bounds.Height, hdc2, p.X, p.Y, SRCCOPY); g.ReleaseHdc(hdc1); bufferedGraphics.ReleaseHdc(hdc2); } } ```
You could check if switching to a ListView Control with checkboxes improves matters. It's not as easy to deal with (but hey, the WinForms ListBox isn't a stroke of genius either), I found that it's resize behavior with `DoubleBuffered=true` is bearable. Alternatively, you could try to reduce flicker by overriding the parent forms background drawing - either providing a hollow brush, or overriding `WM_ERASEBKND` by doing nothing and returning `TRUE`. (that's ok if your control covers the entire client area of the parent form, otherwise you'd need a more complex background drawing method. I've used this successfully in Win32 applications, but I don't know if the Forms control adds some of it's own magic that renders this nonfunctional.
Double buffered ListBox
[ "", "c#", ".net", "winforms", "listbox", "doublebuffered", "" ]
I'm trying to determine how to specify null as a parameter value in an OracleCommand using the following C# code. I've excerpted the relevant bits, but basically the point is if sal\_id comes in with the value 0 it should be stored as null. I've tried Null, "Null", and a couple other things but so far no luck. ``` cmd.CommandText = "INSERT INTO tcustomer(cust_id, salutation_id) VALUES(ORADBA.SEQCUST.NEXTVAL, :salid) RETURNING cust_id INTO :newcid" ; if (sal_id==0) { cmd.Parameters.Add("salid", Null) ; } else { cmd.Parameters.Add("salid", sal_id) ; } cmd.Parameters.Add("newcid", OracleDbType.Int32).Direction = ParameterDirection.ReturnValue ; cmd.ExecuteNonQuery() ; String newcidval = cmd.Parameters["newcid"].Value.ToString() ; cmd.Dispose() ; ```
Try [`System.DBNull`](http://msdn.microsoft.com/en-us/library/system.dbnull.aspx) insead of `null`. > The DBNull class represents a > nonexistent value. In a database, for > example, a column in a row of a table > might not contain any data whatsoever. > That is, the column is considered to > not exist at all instead of merely not > having a value. A DBNull object > represents the nonexistent column
DBNull can not be assigned to any other data type so have to implicit convert it to object. ``` cmd.Parameters.Add(new OracleParameter(":number_column", OracleType.Number)).Value = (s.Class.HasValue) ? s.Class.Value : (object)DBNull.Value; ``` where s.Class is int? and parameter value is set as `(object)DBNull.Value` in case it is null
Handling null values in OracleCommand parameters
[ "", "c#", "odp.net", "" ]
I am trying to parse my URL into different parts using this RegExp: ``` ([\w\\.-]*) ``` Given an example URL <http://www.foo.com/bar/baz> I get those results from preg\_match\_all(): ``` Array ( [0] => Array ( [0] => http [1] => [2] => [3] => [4] => www.foo.com [5] => [6] => bar [7] => [8] => baz [9] => ) ) ``` It seems that it parses any invalid character into an empty item. How do I solve this?
By using `*` you're capturing empty groups - use `+` instead: ``` ([\w\.-]+) ``` I assume the extra \ in your RE is because you have it inside a quoted string.
You sure you want `\\.` ? In other words, from what you've posted, it looks like you've escaped a backslash instead of the period as you've likely intended to. EDIT: For tidiness, no harm to remove redundant escaping, but this isnt the actual problem [as pointed out by blixt -- thanks]. Highly recommend The Regulator as a regex debugging tool [Though its based on .NET regexes so isnt ideal for PHP work - but the general point that there are tools that will let you identify the basis on which matching is operating] Still don't understand what you want with the backslashes in the range. Can you post the final regex you use in the question please? And sorry for the distractions that this answer has been! EDIT: As blixt pointed out, period doesnt act as a metachar as I suggested.
Why am I getting empty results in my RegExp?
[ "", "php", "regex", "preg-match-all", "" ]
Looking for a regexp sequence of matches and replaces (preferably PHP but doesn't matter) to change this (the start and end is just random text that needs to be preserved). IN: ``` fkdshfks khh fdsfsk <!--g1--> <div class='codetop'>CODE: AutoIt</div> <div class='geshimain'> <!--eg1--> <div class="autoit" style="font-family:monospace;"> <span class="kw3">msgbox</span> </div> <!--gc2--> <!--bXNnYm94--> <!--egc2--> <!--g2--> </div> <!--eg2--> fdsfdskh ``` to this OUT: ``` fkdshfks khh fdsfsk <div class='codetop'>CODE: AutoIt</div> <div class='geshimain'> <div class="autoit" style="font-family:monospace;"> <span class="kw3">msgbox</span> </div> </div> fdsfdskh ``` Thanks.
Are you just trying to remove the comments? How about ``` s/<!--[^>]*-->//g ``` or the slightly better (suggested by the questioner himself): ``` <!--(.*?)--> ``` But remember, HTML is *not* regular, so using regular expressions to parse it will lead you into a world of hurt when somebody throws bizarre edge cases at it.
``` preg_replace('/<!--(.*)-->/Uis', '', $html) ``` This PHP code will remove all html comment tags from the $html string.
RegExp to strip HTML comments
[ "", "php", "html", "regex", "" ]
I'm considering writing my own tool for tracking visitors/sales as Google Analytics and others are just not comprehensive enough in the data dept. They have nice GUIs but if you have SQL skills those GUIs are unnecessary. I'm wondering what the best approach is to do this. I could simply just log the IP, etc to a text file and then have an async service run in the background to dump it into the DB. Or, maybe that's overkill and I can just put it straight in the DB. But one DB WRITE per web request seems like a poor choice where scalability is concerned. Thoughts? As a sidenote, it is possible to capture the referring URL or any incoming traffic, right? So if they came from a forum post or something, you can track that actual URL, is that right? It just seems that this is a very standard requirement and I don't want to go reinventing the wheel. As always, thanks for the insight SOF.
The answer to [this question](https://stackoverflow.com/questions/1146986/library-for-an-interative-stats-website/) mentions the open-source GAnalytics alternative [Piwik](http://piwik.org/) - it's not C# but you might get some ideas looking at the implementation. For a .NET solution I would recommend reading Matt Berseth's [Visit/PageView Analysis Services Cube](https://web.archive.org/web/20090302052528/http://mattberseth.com/blog/2008/09/v01_of_my_visitpageview_analys.html) blog posts (and [earlier](https://web.archive.org/web/20090314220815/http://mattberseth.com/blog/2008/09/maintaining_my_own_pageviewvis.html) and [example](https://web.archive.org/web/20150213153015/http://mattberseth.com/blog/2008/10/v02_of_my_visitpageview_cube_c.html) and another [example](https://web.archive.org/web/20090315042300/http://mattberseth.com/blog/2008/10/creating_a_live_traffic_page_f.html), since they aren't easy to find on his site). I'm not sure if he ever posted the server-side code (although you will find his [`openurchin.js`](http://mattberseth2.com/ou/openurchin.js) linked in his html), but you will find most of the concepts explained. You could probably get something working pretty quickly by following his instructions. I don't think you'd want to write to a text file - locking issues might arise; I'd go for INSERTs into a database table. If the table grows too big you can always 'roll up' the results periodically and purge old records. As for the REFERER Url, you can definitely grab that info from the HTTP HEADERS (assuming it has been sent by the client and not stripped off by proxies or strict AV s/w settings). BTW, keep in mind that Google Analytics adds a lot of value to stats - it geocodes IP addresses to show results by location (country/city) and also by ISP/IP owner. Their javascript does Flash detection and segments the User-Agent into useful 'browser catagories', and also detects other user-settings like operating system and screen resolution. That's some non-trivial coding that you will have to do if you want to achieve the same level of reporting - not to mention the data and calculations to get entry & exit page info, returning visits, unique visitors, returning visitors, time spent on site, etc. There is a [Google Analytics API](http://analytics.blogspot.com/2009/04/attention-developers-google-analytics.html) that you might want to check out, too.
I wouldn't have though writing to a text file would be more efficient than writing to a database - quite the opposite, in fact. You would have to lock the text file while writing, to avoid concurrency problems, and this would probably have more of an impact than writing to a database (which is designed for exactly that kind of scenario). I'd also be wary of re-inventing the wheel. I'm not at all clear what you think a bespoke hits logger could do better than Google Analytics, which is extremely comprehensive. Believe me, I've been down the road and written my own, and Analytics made it quite redundant.
Google Analytics LIKE Tool
[ "", "c#", "statistics", "google-analytics", "web-traffic", "" ]
I have a string I am writing to the outputstream of the response. After I save this document and open it in Notepad++ or WordPad I get nicely formatted line breaks where they are intended, but when I open this document with the regular old Windows Notepad, I get one long text string with □ (square like symbols) where the line breaks should be. Has anyone had any experience with this?
Yes - it means you're using `\n` as the line break instead of `\r\n`. Notepad only understands the latter. (Note that `Environment.NewLine` suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want `\r\n`, you should specify it explicitly.)
Use [Environment.NewLine](http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx) for line breaks.
C# Encoding a text string with line breaks
[ "", "c#", "encoding", "response", "" ]
The [JAI setup](http://download.java.net/media/jai-imageio/builds/release/1.1/INSTALL-jai_imageio.html#Manual) is quite tedious, involving multiple jars and environment variables. It would aid the project's portability quite a lot if I could add it as a regular Maven dependency. The POM snippet I'm using is ``` <dependency> <groupId>com.sun.media</groupId> <artifactId>jai_imageio</artifactId> <version>1.1</version> </dependency> ``` and the errors are ``` [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Failed to resolve artifact. Missing: ---------- 1) com.sun.media:jai_imageio:jar:1.1 2) javax.media:jai_core:jar:1.1.3 ``` I can, of course, download and install those jars. The problem is twofold: * jai\_imageio requires two jars; * jai\_imageio requires a native library to be installed and two environment variables to be set. I have not found a way to make this work with Maven. --- See [Reading JCS\_YCCK images using ImageIO](https://stackoverflow.com/questions/1196721/reading-jcsycck-images-using-imageio) for the reason I'm using JAI.
What I failed to see was that the JAI dependency needed to be satisfied only at runtime, and therefore I made sure the production environment has access to JAI, by configuring it for Tomcat.
To avoid donwloading the jars and installing them you can add a dependency on the spring repo. So change the normal dependency slightly: ``` <dependency> <groupId>javax.media.jai</groupId> <artifactId>com.springsource.javax.media.jai.core</artifactId> <version>1.1.3</version> </dependency> ``` and add a repository declaration: ``` <repository> <id>com.springsource.repository.bundles.external</id> <name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name> <url>http://repository.springsource.com/maven/bundles/external</url> </repository> ``` And it should now work (it makes all the sun classes available javax.media.jai.\*). See here: <http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.javax.media.jai.core&version=1.1.3> You can also add the codec dependency if necessary... <http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.javax.media.jai.codec&version=1.1.3>
Using Java Advanced Imaging with Maven
[ "", "java", "maven-2", "jai", "" ]
**Problem:** I have a form in TurboGears 2 that has a text field for a list of e-mails. Is there a simple way using ToscaWidgets or FormEncode to chain form validators for Set and Email or will I have to write my own validator for this?
I think it should be more like the below. It has the advantage of trying each email instead of just stopping at the first invalid. It will also add the errors to the state so you could tell which ones had failed. ``` from formencode import FancyValidator, Invalid from formencode.validators import Email class EmailList(FancyValidator): """ Takes a delimited (default is comma) string and returns a list of validated e-mails Set the delimiter by passing delimiter="A_DELIMITER" to the constructor. Also takes all arguments a FancyValidator does. The e-mails will always be stripped of whitespace. """ def _to_python(self, value, state): try: values = str(value).split(self.delimiter) except AttributeError: values = str(value).split(',') validator = formencode.ForEach(validators.Email()) validator.to_python(values, state) return [value.strip() for value in values] ```
from <http://formencode.org/Validator.html> Another notable validator is formencode.compound.All – this is a compound validator – that is, it’s a validator that takes validators as input. Schemas are one example; in this case All takes a list of validators and applies each of them in turn. formencode.compound.Any is its compliment, that uses the first passing validator in its list.
Chain FormEncode Validators
[ "", "python", "widget", "turbogears", "formencode", "toscawidgets", "" ]
Say I have an array like this: ``` <?php $colors=array(); $colors[0]['id']=1; $colors[0]['color']='blue'; $colors[1]['id']=2; $colors[1]['color']='green'; ...... ?> ``` What's the easiest way to have the entire array converted to XML?
> *Some working Example for the Data in Question that is on-site:* <https://stackoverflow.com/a/14143759/367456> > > Original answer follows: Take a look at these pre-defined implementations: <http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/> <http://vantulder.net/f2o/notities/arraytoxml/>
If you also want attribute support for converting array to XML, you can use this implementation: <http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/> For attribute support it requires you to construct your array in a particular way. For xml without attributes you can directly pass any array to the function and get an XML
Converting a PHP array to XML?
[ "", "php", "xml", "" ]
I do not want to display all the slashes when displaying the html What I have is ``` echo "<input type=\"text\" name=\"myname\" value=\"myvalue\""; ``` What I want to do is: ``` echo '<input type="text" name="myname" value="myvalue">'; ``` I am looking to save myself from typing all the slashes. Is there a way around that?
Your second example works (although it is ugly), I assume you want a way to be able to print variables while printing the HTML with double quotes. If that's the case, you could use [Heredoc](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc) syntax: ``` echo <<<DOC <input type="text" name="myname" value="myvalue"> DOC; ``` Or, better, yet, you could use a templating system (which PHP kind of is) or a MVC framework to separate your business and presentational logic so you don't have to go around printing stuff like input fields in the first place. :)
You probably don't want to echo stuff really, and Paolo explained that quite well, but in general the best practice regarding apostrophes and quotation marks is as follows: When you have apostrophes ' in the text, enclose it in double quotes " ``` echo "foo bar 'baz'"; ``` When you have double quotes, enclose in apostrophes ``` echo 'foo bar "baz"'; ``` This way you don't have to clutter it with backslashes. If you have both kinds, consider heredoc as per Paolo's example, or just stick to the style the rest of the code usually uses. As to what comes to using apostrophes in HTML instead of double quotes.. While swapping them might be useful when you want to include variables, it would be more beneficial to always keep the same style - always apostrophes, or always double quotes. You can also use printf (or sprintf), a function which often seems to be forgotten by PHP programmers: ``` printf('<input type="text" name="myname" value="%s" />', $value); ```
Slashes within echo of input type html
[ "", "php", "html", "" ]
Anyone know of any controls that you can add to your application to allow the user to check out the content of an object? I'm thinking of something like QuickWatch in Visual Studio, just list all properties of an object and its values and allow the user to drill down. I started writing one using reflection but it turned out be a lot of work to handle different kind of collections. This functionality would be used for debugging purposes mostly and not by regular users. I prefer WPF but Winforms would work as well.
try [this](http://www.sliver.com/dotnet/statebrowser/)
[Snoop](http://blois.us/Snoop/) is amazing. Also check out [Crack.NET](http://www.codeplex.com/cracknetproject).
Object viewer control needed (like QuickWatch in VS)
[ "", "c#", "wpf", "" ]
I know that there is a library called [FreeMarker](http://freemarker.sourceforge.net/) to create Email templates for Java. Do you think this library is suitable to use in enterprise projects? Is there any other libraries to create email template for java?
Freemarker works well, and is very powerful. [Velocity](http://velocity.apache.org/) has a simpler syntax, is somewhat less powerful, and is a lot more forgiving wrt. nulls (variables not being populated). I've used both, and Velocity is very easy to get started with. Freemarker (despite its stricter implementation) offers a lot more in terms of 'correctness' and facilities.
A number of years ago I've written an application for sending invoice notifications. I used Velocity to create the actual contents of the e-mails. The transport was provided by James, the e-mail server by Apache. This application sends out 10s of thousands of personalised e-mails each day. Velocity did not give me any problems, but having had some experience with FreeMarker, I would probably pick FreeMarker now.
Email Template Library in Java
[ "", "java", "email", "email-templates", "" ]
How is ThreadLocal implemented? Is it implemented in Java (using some concurrent map from ThreadID to object), or does it use some JVM hook to do it more efficiently?
All of the answers here are correct, but a little disappointing as they somewhat gloss over how clever `ThreadLocal`'s implementation is. I was just looking at the [source code for `ThreadLocal`](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/ThreadLocal.java) and was pleasantly impressed by how it's implemented. **The Naive Implementation** If I asked you to implement a `ThreadLocal<T>` class given the API described in the javadoc, what would you do? An initial implementation would likely be a `ConcurrentHashMap<Thread,T>` using `Thread.currentThread()` as its key. This will would work reasonably well but does have some disadvantages. * Thread contention - `ConcurrentHashMap` is a pretty smart class, but it ultimately still has to deal with preventing multiple threads from mucking with it in any way, and if different threads hit it regularly, there will be slowdowns. * Permanently keeps a pointer to both the Thread and the object, even after the Thread has finished and could be GC'ed. **The GC-friendly Implementation** Ok try again, lets deal with the garbage collection issue by using [weak references](http://en.wikipedia.org/wiki/Weak_reference). Dealing with WeakReferences can be confusing, but it should be sufficient to use a map built like so: ``` Collections.synchronizedMap(new WeakHashMap<Thread, T>()) ``` Or if we're using [Guava](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/MapMaker.html) (and we should be!): ``` new MapMaker().weakKeys().makeMap() ``` This means once no one else is holding onto the Thread (implying it's finished) the key/value can be garbage collected, which is an improvement, but still doesn't address the thread contention issue, meaning so far our `ThreadLocal` isn't all that amazing of a class. Furthermore, if someone decided to hold onto `Thread` objects after they'd finished, they'd never be GC'ed, and therefore neither would our objects, even though they're technically unreachable now. **The Clever Implementation** We've been thinking about `ThreadLocal` as a mapping of threads to values, but maybe that's not actually the right way to think about it. Instead of thinking of it as a mapping from Threads to values in each ThreadLocal object, what if we thought about it as a mapping of ThreadLocal objects to values *in each Thread*? If each thread stores the mapping, and ThreadLocal merely provides a nice interface into that mapping, we can avoid all of the issues of the previous implementations. An implementation would look something like this: ``` // called for each thread, and updated by the ThreadLocal instance new WeakHashMap<ThreadLocal,T>() ``` There's no need to worry about concurrency here, because only one thread will ever be accessing this map. The Java devs have a major advantage over us here - they can directly develop the Thread class and add fields and operations to it, and that's exactly what they've done. In [`java.lang.Thread`](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/lang/Thread.java) there's the following lines: > ``` > /* ThreadLocal values pertaining to this thread. This map is maintained > * by the ThreadLocal class. */ > ThreadLocal.ThreadLocalMap threadLocals = null; > ``` Which as the comment suggests is indeed a package-private mapping of all values being tracked by `ThreadLocal` objects for this `Thread`. The implementation of `ThreadLocalMap` is not a `WeakHashMap`, but it follows the same basic contract, including holding its keys by weak reference. `ThreadLocal.get()` is then implemented like so: > ``` > public T get() { > Thread t = Thread.currentThread(); > ThreadLocalMap map = getMap(t); > if (map != null) { > ThreadLocalMap.Entry e = map.getEntry(this); > if (e != null) { > @SuppressWarnings("unchecked") > T result = (T)e.value; > return result; > } > } > return setInitialValue(); > } > ``` And `ThreadLocal.setInitialValue()` like so: > ``` > private T setInitialValue() { > T value = initialValue(); > Thread t = Thread.currentThread(); > ThreadLocalMap map = getMap(t); > if (map != null) > map.set(this, value); > else > createMap(t, value); > return value; > } > ``` Essentially, use a map *in this Thread* to hold all our `ThreadLocal` objects. This way, we never need to worry about the values in other Threads (`ThreadLocal` literally can only access the values in the current Thread) and therefore have no concurrency issues. Furthermore, once the `Thread` is done, its map will automatically be GC'ed and all the local objects will be cleaned up. Even if the `Thread` is held onto, the `ThreadLocal` objects are held by weak reference, and can be cleaned up as soon as the `ThreadLocal` object goes out of scope. --- Needless to say, I was rather impressed by this implementation, it quite elegantly gets around a lot of concurrency issues (admittedly by taking advantage of being part of core Java, but that's forgivable them since it's such a clever class) and allows for fast and thread-safe access to objects that only need to be accessed by one thread at a time. **tl;dr** `ThreadLocal`'s implementation is pretty cool, and much faster/smarter than you might think at first glance. If you liked this answer you might also appreciate my (less detailed) [discussion of `ThreadLocalRandom`](https://stackoverflow.com/a/41760223/113632). `Thread`/`ThreadLocal` code snippets taken from [Oracle/OpenJDK's implementation of Java 8](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/jdk8-b132).
You mean `java.lang.ThreadLocal`. It's quite simple, really, it's just a Map of name-value pairs stored inside each `Thread` object (see the `Thread.threadLocals` field). The API hides that implementation detail, but that's more or less all there is to it.
How is Java's ThreadLocal implemented under the hood?
[ "", "java", "multithreading", "thread-local", "thread-static", "" ]
I want to make a collection that stores groups of users. A user can be a member of multiple groups, groups can be nested, a selection of groups should return a distinct IEnumerable`<user`> . I could write this from scratch of course using the standard List`<T`>,Dictionary<`T,`U> etc collections, but is there a built-in collection that already exposes a lot of this behaviour? Thanks!
I would do something like this: ``` using System; using System.Collections.Generic; class Program { static void Main() { List<User> users = new List<User> { // use a List<T> to hold the users themselves }; } } class Group { public Group NestedGroup { get; set; } } class User { // Store the groups in a HashSet<T> to keep // a distinct list. HashSet<Group> groups; public IEnumerable<Group> Groups { get { return groups; } } } ``` Using a [`List<T>`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) to hold the users themselves should be fine. Notice that the `Groups` property of the `User` type is exposed as an `IEnumerable<Group>` but is implemented internally as a [`HashSet<Group>`](http://msdn.microsoft.com/en-us/library/bb359438.aspx) to allow you to keep a distinct list as you wanted.
I would have a thought a generic `List<T>` would work (where T is the class that holds your user).
Which collection(s) to store groups of users?
[ "", "c#", ".net", "collections", "" ]
I currently have the following tables for a private messaging forum: [alt text http://img159.imageshack.us/img159/45/pmdata.jpg](http://img159.imageshack.us/img159/45/pmdata.jpg) [alt text http://img504.yfrog.com/img504/3968/pminfo.jpg](http://img504.yfrog.com/img504/3968/pminfo.jpg) What I'm trying to do is output an "inbox" that displays the most recent thread at the top and group by thread (meaning, you don't see the same thread twice in your inbox), no matter who the sender is. What I have right now works fine for simple messages between 2 uesrs. However, once a third user replies to the same thread, it doesn't display correctly. My current query is this: ``` SELECT pm_info.is_read, sender.usrFirst as sender_name, pm_data.date_sent, pm_data.title, pm_data.thread_id, pm_data.id as dataid, thread_max_date_sent FROM pm_info INNER JOIN pm_data ON pm_info.message_id = pm_data.id INNER JOIN tblUsers AS sender ON pm_data.sender_id = sender.usrID INNER JOIN (SELECT thread_id, sender_id, MAX(date_sent) AS thread_max_date_sent FROM pm_data GROUP BY thread_id, sender_id) deriv1 ON pm_data.thread_id = deriv1.thread_id AND pm_data.date_sent = deriv1.thread_max_date_sent AND pm_data.sender_id = deriv1.sender_id WHERE pm_info.receiver_id = '$usrID' ORDER BY deriv1.thread_max_date_sent DESC ``` Assuming that $usrID = 68 (hence, receiver\_id = 68), it outputs this: ``` From: Kyle (pm_data.id = 18) RE: single message (thread_id= 13587) From: Ed (pm_data.id = 12) RE: single message (thread_id= 13587) From: Ed (pm_data.id = 8) RE: Test Number 2 (thread_id= 16256) ``` Notice how the thread\_id (13587) shows up twice because there are 2 different senders. How could I have it *just* display the most recent thread\_id, no matter who the sender is? Many thanks!!
It actually seems like the query in the original question only requires a very small change for getting the actual most recent record for each thread. 1. drop the sender\_id in the subquery's GROUP BY fields 2. drop the *pm\_data.sender\_id = deriv1.sender\_id* in the ON clause ``` SELECT pm_info.is_read, sender.usrFirst as sender_name, pm_data.date_sent, pm_data.title, pm_data.thread_id, pm_data.id as dataid, thread_max_date_sent FROM pm_info INNER JOIN pm_data ON pm_info.message_id = pm_data.id INNER JOIN tblUsers AS sender ON pm_data.sender_id = sender.usrID INNER JOIN (SELECT thread_id, /*sender_id,*/ MAX(date_sent) AS thread_max_date_sent FROM pm_data GROUP BY thread_id /*, sender_id*/) deriv1 ON pm_data.thread_id = deriv1.thread_id AND pm_data.date_sent = deriv1.thread_max_date_sent /*AND pm_data.sender_id = deriv1.sender_id*/ WHERE pm_info.receiver_id = '$usrID' ORDER BY deriv1.thread_max_date_sent DESC ``` As a side note: if possible, look for the max messageID in that subquery instead of max(date\_sent)
Try ``` SELECT pm_info.is_read, sender.usrFirst as sender_name, pm_data.date_sent, pm_data.title, pm_data.thread_id, pm_data.id as dataid FROM pm_data, pm_info, tblUsers as sender WHERE pm_info.message_id = pm_data.id AND pm_data.sender_id = sender.usrID AND pm_info.receiver_id = '$usrID' GROUP BY thread_id ORDER BY date_sent DESC LIMIT 0,1 ```
MySQL Select Statement - For Messages
[ "", "php", "mysql", "select", "" ]
I remember eclipse and idea have this template to automatically create an object's hashCode based on its attributes. One of the strategies if a number and a string is used is something like this. ``` return stringValue.hashCode() + intValue * 32; ``` Ooor something like that. I don't have nor eclipse or idea at hand and I would like to create such function. **EDIT** Based on the answers I create this mini-class ``` class StringInt { private final String s; private final int i; static StringInt valueOf( String string , int value ) { return new StringInt( string, value ); } private StringInt( String string, int value ) { this.s = string; this.i = value; } public boolean equals( Object o ) { if( o != null && o instanceof StringInt ){ StringInt other = ( StringInt ) o; return this.s == other.s && this.i == other.i; } return false; } public int hashCode() { return s != null ? s.hashCode() * 37 + i : i; } } ``` This class is to be used as key for a large memory map ( > 10k elements ) I don't want to iterate them each time to find if the String and the int are the same. Thank you. ps.. mmh probably it should be names StringIntKey.
Use the Apache Commons HashcodeBuilder: ``` public int hashCode() { new HashCodeBuilder(17, 37). append(myString). append(myInt); } ``` Link here: <http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/builder/HashCodeBuilder.html> And here: <http://www.koders.com/java/fidCE4E86F23847AE93909CE105394B668DDB0F491A.aspx>
Eclipse always does roughly the same hashing function, here's an example for a class with an in and String as fields ``` public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.interger; result = prime * result + ((this.string == null) ? 0 : this.string.hashCode()); return result; } ``` They always pick 31 as the prime, and then multiple by build in hash functions or the value if its a primitive. Something like this wouldn't be hard to create as a method. ``` public int hashCode(Object ... things) { final int prime = 31; int result = 1; for(Object thing : things) { result = prime * result + thing.hashCode(); } return result; } ```
Create hash from string and int
[ "", "java", "eclipse", "hash", "code-generation", "intellij-idea", "" ]
I am trying to create a utility in C# using the MVC framework where a user uploads a picture which is used to crop pieces out of to be used as thumbnail icons (only one user at a time will be doing this at any given time). The user can then upload a different picture and continue cropping. I have a controller action that handles the file upload taking the picture, converting it from whatever format it's in to a jpeg and saving it as "temp.jpg" (I know it's not a thin controller, but this is just for testing purposes). When they upload the next picture I want to replace that temp.jpg with this new image. This controller works fine in development on my machine, but in production after the user uploads the first image and tries to replace it with another image they get the following error: "the process cannot access the file because it is being used by another process" It seems to me the the "temp.jpg" file is being locked after the first upload and I can't figure out how to avoid this. Any suggestions or alternative ideas are welcome. Break down of what my code does: * Checks if the picture to be uploaded exists on the server and deletes it if found * Saves the picture as is with it's original file name and extension * Checks for the "temp.jpg" file and deletes it if found * Opens the original image in a System.Drawing.Image object to convert to jpeg * Save it as a new "temp.jpg" to replace the deleted file. My Code: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult PicUpload(DateTime sd, FormCollection collection) { foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0) continue; string savedFileName = Path.Combine( AppDomain.CurrentDomain.BaseDirectory + "Content\\AdContent\\", Path.GetFileName(hpf.FileName)); FileInfo temp = new FileInfo(savedFileName); if (temp.Exists) temp.Delete(); hpf.SaveAs(savedFileName); string tempFileName = AppDomain.CurrentDomain.BaseDirectory + "Content\\AdContent\\temp.jpg"; temp = new FileInfo(tempFileName); if (temp.Exists) temp.Delete(); EncoderParameters codecParams = new EncoderParameters(1); codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L); ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); Image newPic = Image.FromFile(savedFileName); newPic.Save(tempFileName, encoders[1], codecParams); newPic.Dispose(); FileInfo tmp = new FileInfo(savedFileName); if (tmp.Exists) tmp.Delete(); return RedirectToAction("Create", new { startdate = String.Format("{0:MM-dd-yyyy}", sd) }); } return RedirectToAction("Create", new { startdate = String.Format("{0:MM-dd-yyyy}", sd) }); } ```
It turns out I was not freeing the resources of the image properly in another section of my code that was returning width and height properties of the image. Also instead using the `Dispose();` method, I put the code into a "using block" instead like so: ``` using (Image newPic = Image.FromFile(savedFileName)) { newPic.Save(tempFileName, encoders[1], codecParams); } ``` This worked like a charm and I can now delete the temp.jpg file with impunity.
System.Drawing.Image.Save() cannot save to the same location the file was opened from: From [the docs](http://msdn.microsoft.com/en-us/library/ktx83wah.aspx): "Saving the image to the same file it was constructed from is not allowed and throws an exception."
Unable to overwrite uploaded images in C# using the Image object
[ "", "c#", ".net", "asp.net-mvc", "image", "file-io", "" ]
What's the right way to control timeouts, from the client, when running against a MySQL database, using SQLAlchemy? The `connect_timeout` URL parameter seems to be insufficient. I'm more interested in what happens when the machine that the database is running on, e.g., disappears from the network unexpectedly. I'm not worried about the queries themselves taking too long. The following script does what you'd expect (i.e., time out after approximately one second) if *somehost* is unavailable **before** the `while` loop is ever reached. But if *somehost* goes down **during** the `while` loop (e.g., try yanking out its network cable after the loop has started), then the timeout seems to take at least 18 seconds. Is there some additional setting or parameter I'm missing? It's not surprising that the `wait_timeout` session variable doesn't work, as I think that's a server-side variable. But I threw it in there just to make sure. ``` from sqlalchemy import * from sqlalchemy.exc import * import time import sys engine = create_engine("mysql://user:password@somehost/test?connect_timeout=1") try: engine.execute("set session wait_timeout = 1;") while True: t = time.time() print t engine.execute("show tables;") except DBAPIError: pass finally: print time.time() - t, "seconds to time out" ```
this isn't possible due to the way TCP works. if the other computer drops off the network, it will simply stop responding to incoming packets. the "18 seconds" you're seeing is something on your TCP stack timing out due to no response. the only way you can get your desired behavior is to have the computer generate a "i'm dying" message immediately before it dies. which, if the death is unexpected, is completely impossible. have you ever heard of hearbeats? these are packets that high-availability systems send to each other every second or less to let the other one know they still exist. if you want your application to know "immediately" that the server is gone, you first have to decide how long "immediate" is (1 second, 200 ms, etc.) and then designed a system (such as heartbeats) to detect when the other system is no longer there.
I believe you are reaching a totally different error, this is a dreaded "mysql has gone away" error, If I'm right the solution is to update to a newer mysqldb driver as the bug has been patches in the driver. If for some reason you can't/won't update you should try the SA fix for this ``` db= create_engine('mysql://root@localhost/test', pool_recycle=True) ```
How do you control MySQL timeouts from SQLAlchemy?
[ "", "python", "mysql", "sqlalchemy", "" ]
I have two different PHP files that both write to the same file. Each PHP script is called by a user action of two different HTML pages. I know it will be possible for the two PHP files to be called, but will both PHP files attempt to write to the file at the same time? If yes, what will happen? Also, it is possible to make one of the PHP fail gracefully (file write will just fail, and the other PHP can write to the file) as one PHP function is less important that the other.
The usual way of addressing this is to have both scripts use [`flock()`](http://www.php.net/flock) for locking: ``` $f = fopen('some_file', 'a'); flock($f, LOCK_EX); fwrite($f, "some_line\n"); flock($f, LOCK_UN); fclose($f); ``` This will cause the scripts to wait for each other to get done with the file before writing to it. If you like, the "less important" script can do: ``` $f = fopen('some_file', 'a'); if(flock($f, LOCK_EX | LOCK_NB)) { fwrite($f, "some_line\n"); flock($f, LOCK_UN); } fclose($f); ``` so that it will just not do anything if it finds that something is busy with the file.
Please note posix states atomic access if files are opened as **append**. This means you can just append to the file with several threads and they lines will not get corrupted. I did test this with a dozen threads and few hundred thousand lines. None of the lines were corrupted. This might not work with strings over 1kB as buffersize might exceed. This might also not work on windows which is not posix compliant.
PHP Simultaneous File Writes
[ "", "php", "file", "file-io", "" ]
Is the standard MySQL JDBC driver thread-safe? Specifically I want to use a single connection across all threads, but each statement will only be used in a single thread. Are there certain scenarios that are safe and others that aren't? What's your experience here?
Transactions are started / committed per connection. Unless you're doing some very specific stuff (I can't really think of an example where that would be justified to be honest), you're better off with a connection pool and connection per thread.
If autocommit = 1, then it is very feasible to have multiple threads share the same connection, provided the access to the connection is synchronized. If autocommit = 0, you will have to control access to the connection via some sort of mutex until the commit happens. Unless you absolutely are limited in the amount of connections your application can have, a connection pool may be a more viable alternative.
Is MySQL Connector/JDBC thread safe?
[ "", "java", "mysql", "jdbc", "concurrency", "thread-safety", "" ]
I have the following code: ``` try { fi.MoveTo(getHistoryFileName()); } finally { Debug.Write("Move complete"); } ``` I thought that using this would make sure that I'd never have exceptions thrown, but I am getting IOExceptions sometimes. What is the reason?
**finally** does not catch thrown exceptions; it guarantees that code in it will execute regardless of whether an exception is thrown in the try block. You are going to want to catch the exceptions and then handle them appropriately. A Catch block would be between the Try and Finally blocks and start with something like this: ``` catch(Exception ex) { //error handling } ``` You could replace Exception with a more specific exception to just handle that exception.
The try/finally combination doesn't handle exceptions like you think it does. All it does is ensure, as much as possible, that the code in the finally block will run, even in cases when an exception is thrown in the code in the try block. To avoid specific exceptions, handle them, like this: ``` try { fi.MoveTo(getHistoryFileName()); } catch (IOException ex) { // swallow this one } finally { Debug.Write("Move complete"); } ```
Exception handling issue
[ "", "c#", ".net", "vb.net", "io", "" ]
my application shows contact information (from approx. 2000 contact records with various detail information (names, phone numbers etc.) that form the base of a contact grid) which typically rarely changes. A good number of users have the authority to edit this information though, and if it is edited, it is required that the change be visible immediately to everybody. At the same time I'd like to limit refetching this information from the database every time anybody views this information, especially because days might go by without any change happening. I could refetch the entire list every time a minute change is made, but that doesn't seem the right way either. So I'm looking for a way to cache everything, invalidate & refetch only a part that is changed (say, one record) while keeping everything else cached. The page would primarily feed off the cache then every time it is viewed, and fetching data becomes an exception. How could I go about this design & code wise? Your help is very much appreciated.
> On each insert and edit operation, you should replace your cache entry, then write to the database I wouldn't do it this way. If there are multiple concurrent updates, you won't be sure that the cache replacements are done in the same order as the database updates (unless the cache update is part of the same transaction as the database update, which seems overkill). Instead I would: * Store items in the cache with a cache key derived from the primary key. * On each update operation, simply remove the cache entry **after** the database update. In this way the cache will be refreshed with up-to-date data next time it's accessed.
On each insert and edit operation, you should replace your cache entry, then write to the database. Prior to sending an edit to the db, you should also check to ensure that the entry hasn't been invalidated (i.e. you got a dirty read), leading to data loss. If you are really concerned about data integrity, you could keep a transaction log of the cache & db operations so you have a way of knowing what was in progress at the time of an outage.
ASP.NET C#: Caching Database Results, When/How Invalidate (on per-record basis)
[ "", "c#", ".net", "asp.net", "caching", "" ]
I have seen many different naming schemes and extensions used for PHP files that are basically just classes. Some examples: 1. myClass.php 2. myClass.class.php 3. myClass.class What is the difference, and which is better?
There is no difference beyond what you see. The ones with `.class` are helpful if you use [autoloading](http://www.php.net/manual/en/language.oop5.autoload.php) and don't have a specific directory where your class files live. Otherwise, it's entirely arbitrary. (I used to use `ClassName.class.php`.)
What are your coding standards? It’s common to start class names with a capital letter (for example: `class MyClass`). If you do this, then it follows that you would name the file `MyClass.php`. And `MyClass.class.php` works too. `MyClass.class` is a bad idea that could allow someone to view your source code if they request that file by name. Using the `.php` extension ensures that the the user will only see the output after the file is processed by the PHP interpreter which—for a file that contains nothing but a class—is a blank page. Finally, look into [`autoload()`](http://us.php.net/manual/en/language.oop5.autoload.php), which saves you the trouble of calling `require_once` in order to load your class. --- **Update:** With PHP coding standard [PSR-4](http://www.php-fig.org/psr/psr-4/), there is now a semi-official way to name your class files. The previous advice—to name your class file the same as the class with the `.php` extension—still stands. But now you are expected to place that class file in a subdirectory named after your class namespace; PSR-4 requires that all of your classes be contained in a namespace defined by you. What do you get for this? Autoloading for free! If you’re using [Composer](http://getcomposer.org/), you can [specify the top-level directory for your classes](https://getcomposer.org/doc/01-basic-usage.md#autoloading) and Composer will autoload them. No more `require` statements to load your classes. If you don’t want to do this, you don’t have to: PSR-4 is a *recommendation*, not a requirement.
What should I name my PHP class file?
[ "", "php", "class", "naming-conventions", "" ]
Is it possible to use Javascript to emulate the Add to Home Screen option in Mobile Safari's bookmark menu? Something similar to IE's `window.external.AddFavorite(location.href, document.title);` possibly?
TLDR: @Craig has a better answer above. Below is my original answer, but I do not believe it answers the question adequately. Today I would say you'd have to try a library to emulate this effect, as A2HS is not supported in WebViews (PWAs). @Kerrick I would like to delete my answer, but cannot as it has been accepted. Old answer: Yes. The majority of modern browsers support the Add to Home screen (or A2HS) feature for Progressive Web Apps. To quote the [Mozilla Web Docs article](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Add_to_home_screen): > Add to Home screen is a feature available in > modern browsers that allows a user to "install" a web app, ie. add a > shortcut to their Home screen. See also: [A2HS browser support at caniuse.com](https://caniuse.com/?search=A2HS)
Until Safari implements Service Worker and follows the direction set by Chrome and Firefox, there is no way to add your app programatically to the home screen, or to have the browser prompt the user However, there is a small library that prompts the user to do it and even points to the right spot. Works a treat. <https://github.com/cubiq/add-to-homescreen>
Javascript for "Add to Home Screen" on iPhone?
[ "", "javascript", "iphone", "mobile-safari", "bookmarks", "homescreen", "" ]
> **Possible Duplicate:** > [Javascript === vs == : Does it matter which “equal” operator I use?](https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use) What are the differences between `===` vs `==` and `!==` vs `!=`? When should you use each one?
=== is the Identity operator, and is used to test that value and type are equal. so.. ``` "3" == 3 // true "3" === 3 // false 1 == true // true 1 === true // false "1" == true // true "1" === true // false ``` so when you care that value and type are equal, or not equal use Identity operators === or !==
The "normal" `==` operators in javascript perform type coercion, and try their best to do things like treat a string as number or an object as a string where required. The longer === operators will *not* do type coercion, but rather a strict comparison within the type.
When should you use === vs ==, !== vs !=, etc.. in javascript?
[ "", "javascript", "equals", "literals", "" ]
I am trying to override malloc by doing this. ``` #define malloc(X) my_malloc((X)) void* my_malloc(size_t size) { void *p = malloc(size); printf ("Allocated = %s, %s, %s, %x\n",__FILE__, __LINE__, __FUNCTION__, p); return p; } ``` However, this is indefinitely calling my\_malloc recursively (because of malloc call inside my\_malloc). I wanted to call C malloc function inside my\_malloc and not the macro implementation. Could you please let me know how to do that? Thanks.
Problem solved: ``` void* my_malloc(size_t size, const char *file, int line, const char *func) { void *p = malloc(size); printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size); return p; } #define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__) ```
With [Glibc](http://www.gnu.org/software/libc/), there exists [`malloc_hook(3)`](http://linux.die.net/man/3/malloc_hook) as the *proper* way to globally interpose your own `malloc` function. ``` #include <stdio.h> #include <malloc.h> static void *(*old_malloc_hook)(size_t, const void *); static void *new_malloc_hook(size_t size, const void *caller) { void *mem; __malloc_hook = old_malloc_hook; mem = malloc(size); fprintf(stderr, "%p: malloc(%zu) = %p\n", caller, size, mem); __malloc_hook = new_malloc_hook; return mem; } static void init_my_hooks(void) { old_malloc_hook = __malloc_hook; __malloc_hook = new_malloc_hook; } void (*__malloc_initialize_hook)(void) = init_my_hooks; ``` ``` $ cat >mem.c <<'EOF' (the code above) EOF $ cat >main.c <<'EOF' #include <stdio.h> #include <stdlib.h> int main() { char *buf = malloc(50); sprintf(buf, "Hello, world!"); puts(buf); free(buf); return 0; } EOF $ cc mem.c main.c $ ./a.out 0x40077e: malloc(50) = 0x22f7010 Hello, world! ``` (We could use [`__attribute__((constructor))`](http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Function-Attributes.html#index-g_t_0040code_007bconstructor_007d-function-attribute-2200), but that trick isn't necessary: Glibc handily provides `__malloc_initialize_hook` as another way to load run code before `main`.)
Problem in overriding malloc
[ "", "c++", "c", "" ]
I have to send and receive dynamic data using a SysV message queue for a university project. The length of the data is transmitted in a separate message, `size` is therefor already known. And this is how I try to receive the data. I have to admit that I'm not a C++ specialist, especially when it comes to memory allocation. ``` struct { long mtype; char *mdata; } msg; msg.mdata = (char *)malloc(size * sizeof(char)); msgrcv(MSGQ_ID, &msg, size, MSG_ID, 0); ``` The problem seems to be the `malloc` call, but I don't know how to do this right. **EDIT** What I try is to have a some sort of *read* method in a OO wrapper around the message queues. I'd like to read the data in the message queue into a `char[]` or a `std::string`. What I have now looks (simplified) like this. ``` bool Wrapper::read(char *data, int length) { struct Message { long mtype; std::string mdata; }; Message msg; msg.mdata = std::string(size, '\0'); if(msgrcv(MSGQ_ID, &msg, size, MSG_ID, 0) < 0) { return false; } memcpy(data, msg.mdata.c_str(), msg.mdata.size()); return true; } ``` All I get is segmentation faults or completely corrupt data (although this data sometimes contains what I want).
You can't pass a pointer to a structure that contains a `std::string` member to `msgrcv`, this violates the interface contract. The second parameter passed to `msgrcv` needs to point to a buffer with sufficient space to store a 'plain' C struct of the form `struct { long mtype; char mdata[size]; };` where size is the third parameter to `msgrcv`. Unfortunately, determining the size of this buffer might depend on `size` due to possible alignment issues but you have to assume that it doesn't on a system that provides this sort of interface. You can use the standard `offsetof` macro to help determine this size. As a `vector` stores its components contiguously, once you know the size of the buffer, you can resize a `vector` of `char` and use this to hold the buffer. Using a `vector` relieves you of the obligation to `free` or `delete[]` a buffer manually. You need to do something like this. ``` std::string RecvMessage() { extern size_t size; // maximum size, should be a parameter?? extern int MSGQ_ID; // message queue id, should be a parameter?? extern long MSG_ID; // message type, should be a parameter?? // ugly struct hack required by msgrcv struct RawMessage { long mtype; char mdata[1]; }; size_t data_offset = offsetof(RawMessage, mdata); // Allocate a buffer of the correct size for message std::vector<char> msgbuf(size + data_offset); ssize_t bytes_read; // Read raw message if((bytes_read = msgrcv(MSGQ_ID, &msgbuf[0], size, MSG_ID, 0)) < 0) { throw MsgRecvFailedException(); } // a string encapsulates the data and the size, why not just return one return std::string(msgbuf.begin() + data_offset, msgbuf.begin() + data_offset + bytes_read); } ``` To go the other way, you just have to pack the data into a `struct` hack compatible data array as required by the msgsnd interface. As others have pointer out, it's not a good interface, but glossing over the implementation defined behaviour and alignment concerns, something like this should work. e.g. ``` void SendMessage(const std::string& data) { extern int MSGQ_ID; // message queue id, should be a parameter?? extern long MSG_ID; // message type, should be a parameter?? // ugly struct hack required by msgsnd struct RawMessage { long mtype; char mdata[1]; }; size_t data_offset = offsetof(RawMessage, mdata); // Allocate a buffer of the required size for message std::vector<char> msgbuf(data.size() + data_offset); long mtype = MSG_ID; const char* mtypeptr = reinterpret_cast<char*>(&mtype); std::copy(mtypeptr, mtypeptr + sizeof mtype, &msgbuf[0]); std::copy(data.begin(), data.end(), &msgbuf[data_offset]); int result = msgsnd(MSGQ_ID, &msgbuf[0], msgbuf.size(), 0); if (result != 0) { throw MsgSendFailedException(); } } ```
Here is [an example for SyS](http://www.ecst.csuchico.edu/~beej/guide/ipc/mq.html). I hope it will help. The way you are using malloc seems to be correct but you should be very careful when making memory allocations for IPC. You should check how the other process is managing memory (byte alignment, size, platform...) In your code, What is the purpose of the mtype? Does the size you receive takes this mtype into account? Or is it only the size of mdata? Update: Is mtype part of the message? If so: msgsize = size \* sizeof(char) + sizeof(long) pmsg = malloc(msgsize); msgrcv(MSGQ\_ID, pmsg, msgsize, MSQ\_ID, 0); if not msg.data = (char \*)malloc(size \* sizeof(char)); msgrcv(MSGQ\_ID, msg.data, size, MSQ\_ID, 0); The mtype is alocated on the stack while the data is allocated on the heap. If the msgreceive makes a kind of memcpy on the given pointer, it will cause some troubles.
How to receive dynamic length data from a message queue?
[ "", "c++", "malloc", "message-queue", "" ]
I can't find an answer on their website. Do you have any idea if [HtmlCleaner](http://htmlcleaner.sourceforge.net/) is thread safe or not? I have a multiple threads that need to use it but I don't know if I can safetly reuse an instance of the HtmlCleaner object. Have you ever used it? any idea?
Looking at the source code, no - an HtmlCleaner object is not thread safe. Use one object per thread.
Now HTMLCleaner is thread safe, look example <http://htmlcleaner.sourceforge.net/javause.php>
Is HtmlCleaner thread safe?
[ "", "java", "html", "xml", "parsing", "" ]
I have tried using the method drawOval with equal height and width but as the diameter increases the circle becomes worse looking. What can I do to have a decent looking circle no matter the size. How would I implement anti-aliasing in java or some other method.
As it turns out, Java2D (which I'm assuming is what you're using) is already pretty good at this! There's a decent tutorial here: <http://www.javaworld.com/javaworld/jw-08-1998/jw-08-media.html> The important line is: ``` graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ```
you can set rendering hints: ``` Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ```
How to draw a decent looking Circle in Java
[ "", "java", "graphics", "antialiasing", "geometry", "" ]
I'm jumping into unit-testing the Visual-Studio 2008 way, and I'm wondering what's the best way to accomplish cross-assembly `class` access for testing purposes. Basically, I have two projects in one solution: 1. MyProject (C#) 2. MyProjectTests (C# Test Project) Everything in MyProject currently has default accessibility, which if I recall correctly means everything is effectively `internal`. I'm mostly looking to test at the `class` level, but there are a few `delegates` involved. There will probably be an external API sometime in the future, but I'm about 20% of the way to feature complete (at least on paper) and I'm getting pretty leery of layering more code on top of this untested core. Accordingly I'd like to get some testing done now, before the app is complete enough for traditional (read: bad and/or lazy) functional testing and definitely before the version n+1 external API is up. In addition to a straight answer, an example of the solution would be greatly appreciated.
You can use assembly-level attribute [InternalsVisibleToAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) to achieve this. Add ``` [assembly:InternalsVisibleTo("MyProjectTests")] ``` to AssemblyInfo.cs in your MyProject assembly.
You need to add ``` [assembly:InternalsVisibleTo("Unit.Tests.Assembly")] ``` to AssemblyInfo.cs of your "MyProject (C#)". That then allows your tests to access the internal methods for testing.
How to access classes in another assembly for unit-testing purposes?
[ "", "c#", "unit-testing", ".net-assembly", "" ]
What is the difference between the onFocus and onMouseEnter event?
onFocus, when applied to form elements, is triggered when the field is given focus by either tabbing to the field or clicking on it so you can enter a value. Most HTML elements are not given focus through onMouseEnter in any case, so the two events are completely different.
The `onfocus` event fires when the user clicks on an element, usually `<input>` or `<textarea>` elements, and the `mousover` event fires when the pointer mouses over any element on the page. The `mouseenter` event, however, is a non-standard event used by IE and [implemented by some javascript libraries](http://demos.mootools.net/Mouseenter).
What is the difference between the onFocus and onMouseEnter event?
[ "", "javascript", "dom", "" ]
Seems like this is the kind of thing that would have already been answered but I'm unable to find it. My question is pretty simple, how can I do this in one statement so that instead of having to new the empty list and then aggregate in the next line, that I can have a single linq statement that outputs my final list. details is a list of items that each contain a list of residences, I just want all of the residences in a flat list. ``` var residences = new List<DAL.AppForm_Residences>(); details.Select(d => d.AppForm_Residences).ToList().ForEach(d => residences.AddRange(d)); ```
You want to use the `SelectMany` extension method. ``` var residences = details.SelectMany(d => d.AppForm_Residences).ToList(); ```
Use SelectMany ``` var all = residences.SelectMany(x => x.AppForm_Residences); ```
Linq list of lists to single list
[ "", "c#", "linq", "" ]
Is there any library that aids in implementing the design by contract principle in a C++ application? In particular, I'm looking for a library that facilities the usage of the principle, something like [this](http://www.codeproject.com/KB/cpp/DesignByContract.aspx).
I followed the teachings of the following articles: * [*An exception or a bug?*](http://drdobbs.com/184401686) (Miro Samek, C/C++ Users Journal, 2003) * *Simple Support for Design by Contract in C++* (Pedro Guerreiro, TOOLS, 2001) What I ultimately applied was pretty much Samek's approach. Just creating macros for REQUIRE, ENSURE, CHECK and INVARIANT (based on the existing `assert` macro) was very useful. Of course it's not as good as native language support but anyway, it allows you to get most of the practical value from the technique. As for libraries, I don't think that it pays to use one, because one important value of the assertion mechanism is its simplicity. For the difference between debug and production code, see [When should assertions stay in production code?](https://stackoverflow.com/questions/17732/when-should-assertions-stay-in-production-code).
Simplest? Assert statements at the start of your function to test your requirements. Assert statements at the end of your function to test your results. Yes, it's crude, its not a big system, but its simplicity makes it versatile and portable.
Library to facilitate the use of the "design by contract" principle
[ "", "c++", "design-by-contract", "" ]
I am looking for a sample code implementation on how to invert a 4x4 matrix. I know there is Gaussian eleminiation, LU decomposition, etc., but instead of looking at them in detail I am really just looking for the code to do this. Language ideally C++, data is available in array of 16 floats in column-major order.
here: ``` bool gluInvertMatrix(const double m[16], double invOut[16]) { double inv[16], det; int i; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if (det == 0) return false; det = 1.0 / det; for (i = 0; i < 16; i++) invOut[i] = inv[i] * det; return true; } ``` This was lifted from [MESA](http://www.mesa3d.org/) implementation of the GLU library.
If anyone looking for more costumized code and "easier to read", then I got this ``` var A2323 = m.m22 * m.m33 - m.m23 * m.m32 ; var A1323 = m.m21 * m.m33 - m.m23 * m.m31 ; var A1223 = m.m21 * m.m32 - m.m22 * m.m31 ; var A0323 = m.m20 * m.m33 - m.m23 * m.m30 ; var A0223 = m.m20 * m.m32 - m.m22 * m.m30 ; var A0123 = m.m20 * m.m31 - m.m21 * m.m30 ; var A2313 = m.m12 * m.m33 - m.m13 * m.m32 ; var A1313 = m.m11 * m.m33 - m.m13 * m.m31 ; var A1213 = m.m11 * m.m32 - m.m12 * m.m31 ; var A2312 = m.m12 * m.m23 - m.m13 * m.m22 ; var A1312 = m.m11 * m.m23 - m.m13 * m.m21 ; var A1212 = m.m11 * m.m22 - m.m12 * m.m21 ; var A0313 = m.m10 * m.m33 - m.m13 * m.m30 ; var A0213 = m.m10 * m.m32 - m.m12 * m.m30 ; var A0312 = m.m10 * m.m23 - m.m13 * m.m20 ; var A0212 = m.m10 * m.m22 - m.m12 * m.m20 ; var A0113 = m.m10 * m.m31 - m.m11 * m.m30 ; var A0112 = m.m10 * m.m21 - m.m11 * m.m20 ; var det = m.m00 * ( m.m11 * A2323 - m.m12 * A1323 + m.m13 * A1223 ) - m.m01 * ( m.m10 * A2323 - m.m12 * A0323 + m.m13 * A0223 ) + m.m02 * ( m.m10 * A1323 - m.m11 * A0323 + m.m13 * A0123 ) - m.m03 * ( m.m10 * A1223 - m.m11 * A0223 + m.m12 * A0123 ) ; det = 1 / det; return new Matrix4x4() { m00 = det * ( m.m11 * A2323 - m.m12 * A1323 + m.m13 * A1223 ), m01 = det * - ( m.m01 * A2323 - m.m02 * A1323 + m.m03 * A1223 ), m02 = det * ( m.m01 * A2313 - m.m02 * A1313 + m.m03 * A1213 ), m03 = det * - ( m.m01 * A2312 - m.m02 * A1312 + m.m03 * A1212 ), m10 = det * - ( m.m10 * A2323 - m.m12 * A0323 + m.m13 * A0223 ), m11 = det * ( m.m00 * A2323 - m.m02 * A0323 + m.m03 * A0223 ), m12 = det * - ( m.m00 * A2313 - m.m02 * A0313 + m.m03 * A0213 ), m13 = det * ( m.m00 * A2312 - m.m02 * A0312 + m.m03 * A0212 ), m20 = det * ( m.m10 * A1323 - m.m11 * A0323 + m.m13 * A0123 ), m21 = det * - ( m.m00 * A1323 - m.m01 * A0323 + m.m03 * A0123 ), m22 = det * ( m.m00 * A1313 - m.m01 * A0313 + m.m03 * A0113 ), m23 = det * - ( m.m00 * A1312 - m.m01 * A0312 + m.m03 * A0112 ), m30 = det * - ( m.m10 * A1223 - m.m11 * A0223 + m.m12 * A0123 ), m31 = det * ( m.m00 * A1223 - m.m01 * A0223 + m.m02 * A0123 ), m32 = det * - ( m.m00 * A1213 - m.m01 * A0213 + m.m02 * A0113 ), m33 = det * ( m.m00 * A1212 - m.m01 * A0212 + m.m02 * A0112 ), }; ``` I don't write the code, but my program did. I made a small program *to make a program* that calculate the determinant and inverse of any N-matrix. I do it because once in the past I need a code that inverses 5x5 matrix, but nobody in the earth have done this so I made one. Take a look about the program [here](https://github.com/WelloSoft/N-Matrix-Programmer). EDIT: The matrix layout is row-by-row (meaning `m01` is in the first row and second column). Also the language is C#, but should be easy to convert into C.
Inverting a 4x4 matrix
[ "", "c++", "algorithm", "math", "matrix", "matrix-inverse", "" ]
I have this code: ``` $distance= -1 ;//default //distance calc if($dgalaxy = $galaxy){ if(($dx = $x) && ($dy = $y)) { //inter planitary currently unknown formula }else{ $distance = round(Sqrt(pow(($dx-$x),2)+pow(($dy-$y),2)));//interstllar } }else{//intergalatic if ($galaxy < $dgalaxy){ $distance = (((9-fmod($galaxy,10))*200)+2000+(fmod($dgalaxy,10)*200));//anti clockwise galactic }else{ $distance = (((fmod($galaxy,10))*200)+2000+(fmod(9-$dgalaxy,10)*200));//clockwise galactic } } ``` It should return a value for each calculation except for the inter planetary clause. for interstellar (when ($dgalaxy = $galaxy) and the x,y coordinates differ) this runs the interstellar formula and this works fine. But, when $dgalaxy != $galaxy, it returns with -1 which means that it is not running either of the galactic distance calculations! **What have I done wrong and how can I fix it?**
`$dgalaxy = $galaxy` is an **assignment** not a **comparison**. Use `==`. Ditto elsewhere.
You use = instead of == or ===: ``` $distance= -1 ;//default //distance calc // MISTAKE HERE. USE == INSTEAD of = if($dgalaxy == $galaxy){ if(($dx == $x) && ($dy == $y)) { //inter planitary currently unknown formula }else{ $distance = round(Sqrt(pow(($dx-$x),2)+pow(($dy-$y),2)));//interstllar } }else{//intergalatic if ($galaxy < $dgalaxy){ $distance = (((9-fmod($galaxy,10))*200)+2000+(fmod($dgalaxy,10)*200));//anti clockwise galactic }else{ $distance = (((fmod($galaxy,10))*200)+2000+(fmod(9-$dgalaxy,10)*200));//clockwise galactic } } ```
PHP logic if statments
[ "", "php", "logic", "" ]
I have some hibernate code and I want my code run in 1 transaction let me explain in code ``` public void changeBranch(Branch branch) throws DatabaseException { //some code humanDao.update(he); superBranchUsername = branch.getFatherUsername(); int superBranchId = branchDao.getBranchIdByUserName(superBranchUsername); BranchEntity superBranch = branchDao.load(superBranchId); BranchEntity be = new BranchEntity(); setBranchEntity(be, he, pkId, bname, confirmed, level, studentCount, uname, superBranch); branchDao.update(be); // update kardane jadvale Branch va Set kardane Human motenazer be on //some code } ``` Both `humanDao.update(he);` and `branchDao.update(be);` run in transaction handle by My GenericDAO that humanDao and branchDao are inherited from it. but I want this block of code (wrote above) to also run in a transaction!! How can I get to Hibernate to do this?
I find how should I fix it if I new session in `changeBranch(Branch branch)` and pass this session as a parameter to my DAO my problem solved
DAOs should not handle transactions for exactly the reason you've discovered: they can't know when they're part of a larger transaction. If you were using [Spring](http://www.springsource.org/) declarative transactions, you'd have a service layer that would create the transaction context for both DAOs and deal with everything. I would recommend doing something like that. UPDATE: I added a link to Spring.
Hibernate multi level of transaction
[ "", "java", "hibernate", "transactions", "dao", "data-access-object", "" ]
I'm using Visual Studio 2005. ------------------------[ luapassing.cpp ]-------------------- ``` #include "lua.h" static int myCfunc (Lua_State *L){ double trouble = lua_tonumber(L,1); lua_pushnumber(L,16.0 -trouble); return 1; } int luaopen_luapassing (Lua_State *L){ static const lua_reg Map [] = {{"dothis",myCfunc},{NULL,NULL}}; luaL_register(L,"cstuff",Map); return; } ``` -------------------------[ csample.lua ]------------------------- ``` package.cpath = "./CLua2.dll" require "luapassing" print("hola") print(seth.doThis(120)) ```
I see several issues. I'll describe them, and provide a code fragment that should work as I believe you intended this sample to work. Your first problem is that the C++ compiler mangled the name of the only function exported from your DLL whose name matters to Lua: `luaopen_luapassing()`. The stock binary distribution for Windows was compiled as a C program, and assumes a C style name for the DLL module entry point. Also, you have the protocol for the `luaopen_x` function slightly wrong. The function returns an integer which tells Lua how many items on the top of Lua's stack are return values for use by Lua. The protocol assumed by `require` would prefer that you leave the new module's table object on the top of the stack and return it to Lua. To do this, the `luaopen_x` function would ordinarily use `luaL_register()` as you did, then return 1. There is also the issue of naming. Modules written in pure Lua have the opportunity to be less aware of their names. But modules written in C have to export a function from the DLL that includes the module name in its name. They also have to provide that module name to `luaL_register()` so that the right table is created and updated in the global environment. Finally, the client Lua script will see the loaded module in a global table named like the name passed to `require`, which is also returned from `require` so that it may be cached in a local in that script. A couple of other nits with the C code are that the numeric type really should be spelled `lua_Number` for portability, and that it would be conventional to use `luaL_checknumber()` rather than `lua_tonumber()` to enforce the required argument to the function. Personally, I would name the C implementation of a public function with a name related to its name that will be known publicly by Lua, but that is just a matter of taste. This version of the C side should fix these issues: ``` #include "lua.h" static int my_dothis (Lua_State *L){ lua_Number trouble = luaL_checknumber(L,1); lua_pushnumber(L,16.0 -trouble); return 1; } extern "C" int luaopen_luapassing (Lua_State *L){ static const lua_reg Map [] = { {"dothis", my_dothis}, {NULL,NULL} }; luaL_register(L,"luapassing",Map); return 1; } ``` The sample script then needs to refer to the loaded module by its proper name, and to the functions defined by that module by their proper names. Lua is case sensitive, so if the module creates a function named `dothis()`, then the script must use that same name, and cannot find it named `doThis()`, for example. ``` require "luapassing" print("hola") print(luapassing.dothis(120)) ``` I should add that I haven't actually compiled and run the above, so there might be a typo or two left as an exercise ;-)
If you're going to be doing a lot of C++ to lua binding, you might want to take a look at [luabind](http://www.rasterbar.com/products/luabind.html).
How do I call C++ functions from a Lua script?
[ "", "c++", "visual-c++", "lua", "" ]
I am getting this exception sometimes while running my Windows Forms app for a long time: ``` System.ComponentModel.Win32Exception: The operation completed successfully at System.Drawing.BufferedGraphicsContext.CreateCompatibleDIB(IntPtr hdc, IntPtr hpal, Int32 ulWidth, Int32 ulHeight, IntPtr& ppvBits) at System.Drawing.BufferedGraphicsContext.CreateBuffer(IntPtr src, Int32 offsetX, Int32 offsetY, Int32 width, Int32 height) at System.Drawing.BufferedGraphicsContext.AllocBuffer(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.DataGridView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ``` What could be the cause for this?
Just to sum it up, the custom grid I wrote, that is based on the .Net's DataGridView, uses custom code to draw cells. Rows in my grid can span multiple visual pages. (That was a business requirement) The problem was that .Net pre-allocates a buffer of memory for controls with DoubleBuffering enabled. For DataGridViews grids the buffer needs to be rather large to accommodate possible large rows in the grid. In extreme cases a row can span up to 32000 pixels (because of a .net limitation). Grid widths in the project are usually between 500 and 800 pixels. So the resulting buffer can be (32bpp \* 800 \* 32000 = ~100MB) So in short, the system could not create compatible graphics objects, because occasionally, it could not reserve a buffer large enough to fit the required data. To fix it I had to introduce a series of optimizations: * limited max row height allowed in my custom grid to 1500 pixels * updated buffer re-allocation code to only execute when the new buffer size is greater than the existing * ensured that the buffers are not reallocated with every data binding, and preallocated to a sensible size. * reviewed all code and made sure that unmanaged resources are properly disposed when not in use, as recommended here: <http://nomagichere.blogspot.com/2008/03/systemcomponentmodelwin32exception-is.html>
Windows has a hard limit of **10000 handles** per process. The rather unhelpful exception *"The operation completed successfully"* might indicate that this limit was reached. If this happened because of a resource leak in your code, then you are in luck, as you at least have the opportunity to fix your code. Unfortunately, there is scarcely little you can do about handles created internally by WinForms. For example, the prolific creation of font handles by TreeView control makes it hard to use in a scenario where very large tree needs to be represented in UI. Some useful links: <http://support.microsoft.com/kb/327699> <http://nomagichere.blogspot.com/2008/03/systemcomponentmodelwin32exception-is.html>
System.ComponentModel.Win32Exception: The operation completed successfully
[ "", "c#", ".net", "winforms", "win32exception", "" ]
We trying to choose an IDE for C++ development on Linux. The proposed options are KDevelop and Eclipse. Eclipse is highly customizable, but Java centric and heavy. KDevelop is bounded to particular KDE (I believe because KDE API) and can not be replaced if required. What you use and why? Thanks Dima
KDevelop, because: * It supports [CMake](http://www.cmake.org/). * It fully integrates with the GCC utilities. * It has a good syntax highligher and code editor * It has a relatively quick startup time and is relatively light weight. Since you are comparing KDevelop with Eclipse, let me also point out that: * KDevelop uses a file for its projects, so you can open the project file in your file manager. By contrast, Eclipse stores metadata in folders, so you need to open your Eclipse project by running Eclipse. * Because KDevelop stores its information in a single project file, whereas Eclipse uses lots of hidden metadata, KDevelop leaves your code folders much cleaner than does Eclipse. * KDevelop will never attempt to delete files on your filesystem, unless you specifically ask it to do so. By contrast, it is very easy to accidentally harm files on your filesystem using Eclipse. Also, when I've used KDevelop, I've been using it on Ubuntu which uses the Gnome desktop. On Gnome, KDevelop still beats Eclipse in terms of startup time, and is definitely worth using. Also, one last note, if you use CMake with KDevelop, then you can distribute your source code to users on Windows, Mac, and Linux, and they will be able to compile your source code, even if they don't have KDevelop; CMake can generate a native Makefile, a Visual Studio project, an Xcode project, or a KDevelop project. So, the concern that you can't replace KDevelop really doesn't apply if you use the CMake backend.
I use [Qt Creator](http://www.qtsoftware.com/products/developer-tools), which is excellent if you're considering using Qt. I've found the C++ tools for Eclipse work well though - editor seemed solid, debugging "just worked", so I was happy!
C++ IDE on Linux
[ "", "c++", "linux", "ide", "development-environment", "" ]
I have deployed my windows service (using independently installer class and SC.EXE), but I get an error when I try to start it: ``` --------------------------- Services --------------------------- Could not start the MyName service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` What is the timeout? It felt like around 3 secs. What do I need to do if my service takes longer?
In your service class, use `ServiceBase.RequestAdditionalTime()` in your OnStart/OnStop method: ``` // request an additional 4 seconds to complete the operation RequestAdditionalTime(4000); ```
The normal way of creating a service is to have the startup code create a new thread, and run your service in that thread. The service startup should be nearly instantaneous - nothing more than spawning a new thread with your "real" work in it. If you're taking more than three seconds, that's a sign that you're doing the real work in your main thread, and not creating a separate one for your service.
What is the timeout for starting a windows service?
[ "", "c#", ".net", "windows-services", "timeout", "" ]
I've just discovered the [email-address-saving form on my website](http://www.yoomoot.com) does not work on Opera and Internet Explorer (7 at any rate), and possibly other browsers. Works fine with Firefox. Unfortunately I'm not a developer and no longer have any contact with the guy who wrote the code for the form so I've no idea how to fix it. I assume the problem has something to do with the code below: ``` <?php $str = ''; if (isset($_POST['submit'])) { if(!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['email'])) { $str = "<span style='color: red'>Not a valid email address</span>"; } else { $file = 'emails.txt'; $text = "$_POST[email]\n"; if (is_writable($file)) { if (!$fh = fopen($file, 'a')) { exit; } if (fwrite($fh, $text) === FALSE) { exit; } fclose($fh); } header('Location: thankyou.html'); } } ?> ``` and then the body bit: ``` <form action="index.php" method="post"> <input type="text" name="email" style="width: 250px;" /> <input type="image" src="img/button-submit.png" name="submit" value="Submit" style="position: relative; top: 5px; left: 10px" /> </form> <?php echo $str ?> ``` Anybody feeling pity for a helpless non-dev and have an idea what's not working here?
This is being caused by the fact that the submit input is of type 'image'. On submit, IE7 only returns the x and y coords of the click. This should do the trick: Replace: ``` if (isset($_POST['submit'])) ``` With: ``` if (isset($_POST['submit']) || isset($_POST['submit_x'])) ```
It is a browser based issue in your form, you have used `<input type="image" />` IE doesn't pass name/value pairs for image type input, instead it only sends the key\_x/value\_x and key\_y/value\_y pairs you probaly want to use `<input type="submit" />` as replacement/addition, since this is completely supported on all types of browsers (think also about text browsers please, i still use them.)
Why doesn't this email-address-submitting code work with Opera and Internet Explorer?
[ "", "php", "" ]
``` WebResponse response; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 20000; response = request.GetResponse(); request = (HttpWebRequest)WebRequest.Create(url2); response = request.GetResponse(); } catch(Exception ex) { //do something } finally { } ``` where should response.Close() be called? * after every GetResponse() in try? * after last GetResponse() in try - once? * in finally block?
None of the above. You should be using a `using` block: ``` HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 20000; using (WebResponse response = request.GetResponse()) { using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { var result = reader.ReadToEnd(); // Do something with result } } } ``` A `using` block will ensure that the Dispose method is called, whether or not there is an exception. Dispose will do the same thing as Close. ``` using (var d = new DisposableClass()){code;} ``` is equivalent to: ``` DisposableClass d = null; try { d = new DisposableClass(); code; } finally { if (d != null) ((IDisposable)d).Dispose(); } ```
Put it in the finally block. As per [MSDN](http://msdn.microsoft.com/en-us/library/zwc8s4fz(VS.80).aspx): > The finally block is useful for > cleaning up any resources allocated in > the try block as well as running any > code that must execute even if there > is an exception. Control is always > passed to the finally block regardless > of how the try block exits.
When to call WebResponse.Close()
[ "", "c#", ".net", "httpwebresponse", "" ]
I have been presented with this code. The code displays the title headings of the latest 10 WordPress posts from the database. What I need to do is to eliminate a particular category from this. Can anyone help? ``` <?php require_once 'news/wp-config.php'; $howMany = 0; $query ="SELECT `ID`, `post_title`,'post_category', `guid`,SUBSTRING_INDEX(`post_content`, ' ', 100) AS `post_excerpt` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_type` = \"post\" "; $posts = $wpdb->get_results($query); $posts = array_reverse($posts); foreach($posts as $post) { if($howmany<10) { $link = $post->guid; echo "<li><a target='_blank' href='$link'>$post->post_title</a></li>"; $howmany++; } } ?> ```
Or, you could use a second loop, something like this : ``` <div> <h3>Fresh Posts</h3> <ul> <?php $my_query = new WP_Query("cat=-3&order=DESC&posts_per_page=10"); echo "<pre>"; print_r($my_query->query_vars); echo "</pre>"; // shows the variables used to parse the query echo "<code style='width: 175px;'>"; print_r($my_query->request); echo "</code>"; // shows the parsed query while ($my_query->have_posts()) : $my_query->the_post(); //standard loop stuff $do_not_duplicate[] = $post->ID;?> <li id="post-<?php the_ID(); ?>"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> </div> ``` once again WP 2.8.x. Lots of good info here : [WordPress loop documentation](http://codex.wordpress.org/The_Loop "WordPress loop documentation")
Determine the category you don't need and add an extra AND to your WHERE clause: ``` AND post_category != 3 ```
how to eliminate a particular category from query
[ "", "php", "html", "wordpress", "" ]
I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regarding Facebook connect and GAE are very Django oriented. I have tried messing around with pyfacebook and miniFB found [here](http://wiki.developers.facebook.com/index.php/Python) at the Facebook docs but I haven't been able to make things work with the webapp framework. I'm having trouble seeing the big picture as far as how I can make this work. What advice can you give me on how to make this work or what I should be considering instead? Should I be focusing on using [Javascript](http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works) instead of client libraries? [Account Linking](http://wiki.developers.facebook.com/index.php/Account_Linking) [How to write a good connect app](http://wiki.developers.facebook.com/index.php/How_To_Write_A_Good_Connect_App)
It's not Facebook Connect, really, but at least it's webapp FBML handling: [http://github.com/WorldMaker/pyfacebook/.../facebook/webappfb.py](http://github.com/WorldMaker/pyfacebook/blob/35b6e4dbb83ca14fbb23046bd675fa4d80d568c9/facebook/webappfb.py) [This guy made a post](http://forum.developers.facebook.com/viewtopic.php?pid=164613) about Facebook Connect on Google AppEngine via webapp framework. (It's stickied in [the Connect Authentication forum](http://forum.developers.facebook.com/viewforum.php?id=32), with 8515 views.) Here's an example from May 15: <http://myzope.kedai.com.my/blogs/kedai/236> It's based on the Guestbook example webapp, but with Facebook for authentication instead. The author does note that, "there's code duplication (when instantiating pyfacebook) in different classes," and that there should be a better way to do this. Django sounds like it's better integrated. There's a presentation from 4 months ago on Slideshare called [Where Facebook Connects Google App Engine](http://www.slideshare.net/web2ireland/build-facebook-connect-enabled-applications-with-google-apps-engine) (Robert Mao's talk at Facebook Garage Ireland). It looks like an interesting talk, though no videos of it have been posted at the moment. On slide 13, the following tools are mentioned, *including Django*: Google App Engine SDK, Eclipse, PyDev, Django, [App Engine Patch](http://code.google.com/p/app-engine-patch/) and pyFacebook. Sample application given: <http://github.com/mave99a/fb-guinness/> If you merely want authentication, [this Recipe suggests using RPXnow.com](http://appengine-cookbook.appspot.com/recipe/accept-google-aol-yahoo-myspace-facebook-and-openid-logins/) for Google, AOL, Yahoo, MySpace, Facebook and OpenID logins with the Webapp Framework. Might be helpful, though doesn't appear at first glance to use Connect, is [a contributed howto article on GAE's site](http://code.google.com/appengine/articles/shelftalkers.html) for creating a Facebook App with Best Buy Remix.
Most of Facebook Connect (as it was formerly called, now it's "Facebook for Websites") is Javascript. The only serverside thing you really need (assuming you want to integrate it into your own usersystem) is validation of the user's Facebook login. Either minifb or pyfacebook should accomplish this task.
How can I use Facebook Connect with Google App Engine without using Django?
[ "", "python", "google-app-engine", "authentication", "facebook", "" ]
i have a Problem with DataGridView in c# and i hope you can help me :) I added a DataGridView to my Application and bind it to DataTable. The DataTable changing the content but the DataGridView doesnt display it... How can i change this ? Thanks
Is the data changing at the source, or within the application? If the data is changing at the source, then I think the issue may be that .Net by default supports a [disconnected data paradigm](http://msdn.microsoft.com/en-us/library/7b13c12s(VS.85).aspx) which is different from using a permanently connected model. Once the data is retrieved from the server, the client is no longer connected unless you go and get the data again. For example, if you're using a TableAdapter, you'd have to periodically call the DataAdapter.Fill() command to retrieve the data from the server. If the data is changing in your app based on user interaction, then possibly DataDable.AcceptChanges() followed by Application.DoEvents()?
Did you try DataGridView.Refresh()?
How can i update DataGridView in c# if Source has changes
[ "", "c#", "datagridview", "datatable", "dataset", "" ]
If I declare a base class as follows: ``` abstract class Parent { protected static $message = "UNTOUCHED"; public static function yeah() { static::$message = "YEAH"; } public static function nope() { static::$message = "NOPE"; } public static function lateStaticDebug() { return(static::$message); } } ``` and then extend it: ``` class Child extends Parent { } ``` and then do this: ``` Parent::yeah(); Parent::lateStaticDebug(); // "YEAH" Child::nope(); Child::lateStaticDebug(); // "NOPE" Parent::yeah(); Child::lateStaticDebug() // "YEAH" ``` Is there a way to have my second class that inherits from the first also inherit properties and not just methods? I'm just wondering if there's something about PHP's late static binding and also inheritance that would allow for this. I'm already hacking my way around this...But it just doesn't seem to make sense that an undeclared static property would fall back on its parent for a value!?
The answer is "with a workaround". You have to create a static constructor and have it called to copy the property.
Inheritance and `static` properties does sometime lead to "strange" things in PHP. You should have a look at [Late Static Bindings](http://php.net/manual/en/language.oop5.late-static-bindings.php) in the PHP's manual : it explains what can happen when inheriting and using `static` properties in PHP <= 5.2 ; and gives a solutions for PHP >= 5.3 where you can use the `static::` keywords instead of `self::`, so that static binding is done at execution (and not compile) time.
Is there a way to have PHP subclasses inherit properties (both static and instance)?
[ "", "php", "inheritance", "late-static-binding", "" ]
What is the easiest way to submit an HTTP POST request with a multipart/form-data content type from C#? There has to be a better way than building my own request. The reason I'm asking is to upload photos to Flickr using this api: <http://www.flickr.com/services/api/upload.api.html>
First of all, there's nothing wrong with pure manual implementation of the HTTP commands using the .Net framework. Do keep in mind that it's a framework, and it is supposed to be pretty generic. Secondly, I think you can try searching for a browser implementation in .Net. I saw [this one](http://www.codeproject.com/script/Articles/Article.aspx?aid=18935), perhaps it covers the issue you asked about. Or you can just search for "[C# http put get post request](http://www.google.com/search?hl=en&q=C%23+http+put+get+post+request)". One of the results leads to a non-free library that may be helpful ([Chilkat](http://www.example-code.com/csharp/http_post_form.asp) Http) If you happen to write your own framework of HTTP commands on top of .Net - I think we can all enjoy it if you share it :-)
If you are using .NET 4.5 use this: ``` public string Upload(string url, NameValueCollection requestParameters, MemoryStream file) { var client = new HttpClient(); var content = new MultipartFormDataContent(); content.Add(new StreamContent(file)); System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, string>> b = new List<KeyValuePair<string, string>>(); b.Add(requestParameters); var addMe = new FormUrlEncodedContent(b); content.Add(addMe); var result = client.PostAsync(url, content); return result.Result.ToString(); } ``` Otherwise Based on Ryan's answer, I downloaded the library and tweaked it a bit. ``` public class MimePart { NameValueCollection _headers = new NameValueCollection(); byte[] _header; public NameValueCollection Headers { get { return _headers; } } public byte[] Header { get { return _header; } } public long GenerateHeaderFooterData(string boundary) { StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(boundary); sb.AppendLine(); foreach (string key in _headers.AllKeys) { sb.Append(key); sb.Append(": "); sb.AppendLine(_headers[key]); } sb.AppendLine(); _header = Encoding.UTF8.GetBytes(sb.ToString()); return _header.Length + Data.Length + 2; } public Stream Data { get; set; } } public string Upload(string url, NameValueCollection requestParameters, params MemoryStream[] files) { using (WebClient req = new WebClient()) { List<MimePart> mimeParts = new List<MimePart>(); try { foreach (string key in requestParameters.AllKeys) { MimePart part = new MimePart(); part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\""; part.Data = new MemoryStream(Encoding.UTF8.GetBytes(requestParameters[key])); mimeParts.Add(part); } int nameIndex = 0; foreach (MemoryStream file in files) { MimePart part = new MimePart(); string fieldName = "file" + nameIndex++; part.Headers["Content-Disposition"] = "form-data; name=\"" + fieldName + "\"; filename=\"" + fieldName + "\""; part.Headers["Content-Type"] = "application/octet-stream"; part.Data = file; mimeParts.Add(part); } string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); req.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + boundary); long contentLength = 0; byte[] _footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); foreach (MimePart part in mimeParts) { contentLength += part.GenerateHeaderFooterData(boundary); } //req.ContentLength = contentLength + _footer.Length; byte[] buffer = new byte[8192]; byte[] afterFile = Encoding.UTF8.GetBytes("\r\n"); int read; using (MemoryStream s = new MemoryStream()) { foreach (MimePart part in mimeParts) { s.Write(part.Header, 0, part.Header.Length); while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0) s.Write(buffer, 0, read); part.Data.Dispose(); s.Write(afterFile, 0, afterFile.Length); } s.Write(_footer, 0, _footer.Length); byte[] responseBytes = req.UploadData(url, s.ToArray()); string responseString = Encoding.UTF8.GetString(responseBytes); return responseString; } } catch { foreach (MimePart part in mimeParts) if (part.Data != null) part.Data.Dispose(); throw; } } } ```
How to submit a multipart/form-data HTTP POST request from C#
[ "", "c#", ".net", "http", "post", "multipartform-data", "" ]
I am trying to improve my in-site personal messaging system by making it look nicer and feel more like e-mail. I currently add > before each line of replied text, but I would also like to add formatting such as font color to lines that start with ">" without the quotes. I am not sure how I would close the lines out with a regular expression. To open it I assume I should do something like the following? ``` $new_text = preg_replace("\> \is", "<font color=\"grey\">> ", $text); ```
``` preg_replace("/^(>.*)$/im", "<span style=\"color: red;\">\\1</span>", $reply); ```
``` ereg_replace('^>(.*)', '<span class="quoted">&gt;\\1</span>', $content); ```
Regular Expression to format certain lines of text
[ "", "php", "regex", "formatting", "" ]
Note: There is a very similar question [here](https://stackoverflow.com/questions/404534/python-globals-locals-and-unboundlocalerror). Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case." I just stumbled over this: ``` a = 5 def x() print a a = 6 x() ``` throws an `UnboundLocalException`. Now, I do know why that happens (later in this scope, `a` is bound, so `a` is considered local throughout the scope). In this case: ``` a = 5 def x() print b b = 6 x() ``` this makes very much sense. But the first case has an intuitive logic to it, which is to mean this: ``` a = 5 def x() print globals()["a"] a = 6 # local assignment x() ``` I guess there's a reason why the "intutive" version is not allowed, but what is it? Although this might be a case of "Explicit is better than implicit," fiddling around with the `globals()` always feels a bit unclean to me. To put this into perspective, the actual case where this happened to me was someone else's script I had to change for one moment. In my (short-lived) change, I did some file renaming while the script was running, so I inserted ``` import os os.rename("foo", "bar") ``` into the script. This inserting happend inside a function. The module already imported `os` at the top level (I didn't check that), and some `os.somefunction` calls where made inside the function, but before my insert. These calls obviously triggered an `UnboundLocalException`. So, can someone explain the reasoning behind this implementation to me? Is it to prevent the user from making mistakes? Would the "intuitive" way just make things more complicated for the bytecode compiler? Or is there a possible ambiguity that I didn't think of?
Having the same, identical name refer to completely different variables within the same flow of linear code is such a mind-boggling complexity that it staggers the mind. Consider: ``` def aaaargh(alist): for x in alist: print a a = 23 ``` what is THIS code supposed to do in your desired variant on Python? Have the `a` in the very same `print` statement refer to completely different and unrelated variables on the first leg of the loop vs the second one (assuming there IS a second one)? Have it work differently even for a one-item alist than the non-looping code would? Seriously, this way madness lies -- not even thinking of the scary implementation issues, just trying to document and teach this is something that would probably make me switch languages. And what would be the underpinning motivation for the language, its implementers, its teachers, its learners, its practitioners, to shoulder all of this conceptual burden -- *to support and encourage the semi-hidden, non-explicit use of GLOBAL VARIABLES*?! That hardly seems a worthwhile goal, does it now?!
I believe there is a possible ambiguity. ``` a = 5 def x(): print a a = 6 # could be local or trying to update the global variable x() ``` It could be as you assumed: ``` a = 5 def x(): print globals()["a"] a = 6 # local assignment x() ``` Or it could be they want to update the global variable to 6: ``` a = 5 def x(): global a print a a = 6 x() ```
Reason for unintuitive UnboundLocalError behaviour
[ "", "python", "" ]
I have this `JTextPane` (wrapped in a `JScrollPane`) that is backed by a `HTMLEditorKit`. The contents of the `JTextPane` is simple HTML with some images (local files) embedded using img tags. The problem is that when you load the the `JTextPane`, it takes a split second to load and then it comes up with the scroll bar at the bottom of the page. If I do: ``` JTextPane text = new JTextPane(); JScrollPane scroll = new JScrollPane(text); // do some set up... scroll.getVerticalScrollBar().setValue(0); ``` it sets the scroll bar momentarily and then another thead (presumably that is in charge of loading the images) comes and knocks the scroll bar back to the bottom. I tried adding: ``` ((AbstractDocument)text.getDocument()).setAsynchronousLoadPriority(-1); ``` but that did not fix it. Is there any way to get an event from either `text.getDocument()` or `text` that will notify me when the pane is finished loading so that I can set the scroll bar then? The alternative is that I set up another thread to wait a second or so, and then set the scroll bar, but this is a bad hack. Your suggestions?
Have you tried using invokeLater? ``` final JScrollPane scroll = new JScrollPane(text); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { scroll.getVerticalScrollBar().setValue(0); } }); ``` If that doesn't work, digging into the image views is pretty tough so my next step would be to track down why the scrollbar is changing: ``` scroll.setVerticalScrollbar(new JScrollBar() { public void setValue(int value) { new Exception().printStackTrace(); super.setValue(value); } }); ``` You could also use a debugger in the setValue() method instead of just printing the stack trace.
The following solved the problem for me, after 50 minutes of despair: ``` JTextPane.grabFocus(); JTextPane.setCaretPosition(20); ```
Setting Scroll Bar on a JScrollPane
[ "", "java", "html", "swing", "events", "" ]
I find in my PHP pages I end up with lines and lines of code that look like this: ``` $my_id = isset($_REQUEST['my_id']) ? $_REQUEST['my_id'] : ''; $another_var = isset($_REQUEST['another_var']) ? $_REQUEST['another_var'] : 42; ... ``` Is there a better, more concise, or more readable way to check this array and assign them to a local variable if they exist or apply a default if they don't? EDIT: I don't want to use `register_globals()` - I'd still have the isset problem anyway.
How about wrapping it in a function? ``` <?php function getPost($name, $default = null) { return isset($_POST[$name]) ? $_POST[$name] : $default; } ```
a better method might be to create a singleton/static class to abstract away the details of checking the request data. Something like: ``` class Request { private $defaults = array(); private static $_instance = false; function getInstance () { if (!self::$_instance) { $c = __CLASS__; self::$_instance = new $c; } return self::$_instance; } function setDefaults($defaults) { $this->defaults = $defaults; } public function __get($field) { if (isset($_REQUEST[$field]) && !empty($_REQUEST[$field])) { return $_REQUEST['field']; } elseif (isset($this->defaults[$field])) { return $this->defaults[$field]; } else { return ''; # define a default value here. } } } ``` you can then do: ``` # get an instance of the request $request = Request::getInstance(); # pass in defaults. $request->setDefaults(array('name'=>'Please Specify')); # access properties echo $request->name; echo $request->email; ``` I think this makes your individual scripts loads cleaner and abstracts away the validation etc. Plus loads of scope with this design to extend it/add alternate behaviours, add more complicated default handling etc etc.
Is there a better way to check POSTed variables in PHP?
[ "", "php", "initialization", "" ]
Say I have a table which stores customers order IDs. Such as | Customer ID | Order ID | Order Date How can I get all customers who have ordered today? Also OrderDate would be a DateTime. Something like ``` SELECT DISTINCT CustomerID FROM TableName Where OrderDate > Today ``` But the last part is what I can't figure out.
It's fairly common to only want a date out of a datetime - you should be able to Google for the specifics of your RDBMS (since you don't mention it). The important bit is to make your query [SARGable](http://en.wikipedia.org/wiki/Sargable) by transforming *today's* date1 - not the order date. For MSSQL, something like ``` SELECT DISTINCT CustomerID FROM TableName --I assume you want midnight orders as well - so use >= Where OrderDate >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) ``` would work by taking number of days today is from Date 0 (`DATEDIFF(dd, 0, GETDATE())`) and adding them back to Date 0 (`DATEADD(dd, 0, x)`). That's T-SQL specific, though. 1 If you were searching for an arbitrary date, you'd still transform both arguments: ``` SELECT DISTINCT CustomerID FROM TableName Where OrderDate >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) --You *do not* want midnight of the next day, as it would duplicate orders AND OrderDate < DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()) + 1) ```
In Oracle the statement would look something like: ``` SELECT DISTINCT CustomerID FROM TableName Where OrderDate >= trunc(sysdate) ``` SQL-Server should be similar
SQL statement help -- Select customers who ordered today
[ "", "sql", "datetime", "select", "" ]
I'm not really sure what to call this. But basically I want to be able to have a user click on "Popular Stories from This Week", and it will take them to a page that will have other stuff but mainly the dates. For example, July 10-17. I'm currently using this code: ``` $seven_days_ago = date('j') - 7; $time_span = date('F ' . $seven_days_ago . ' - j'); ``` Now, I ran into a problem when we entered July, because it would display something like July -3 - 4. I need a way for it to detect if the seven days ago variable is negative, and figure out what it should display. Help? Thanks!
You can use [`strtotime`](http://www.php.net/strtotime) for this: ``` $seven_days_ago = strtotime('-7 days'); $time_span = date('F j', $seven_days_ago) . ' - ' . date('F j'); ``` The above gives me "June 28 - July 5" for `$time_span`.
What about using ``` $unix_timestamp = mktime(0, 0, 0, date("m"), date("d")-7, date("Y")); ``` and just take the returned unix timestamp? **Update** Just a little code snipped that will give you a full working example. However I don't like it that much :) ``` <?php $today = date("d F"); list($today_day, $today_month) = explode(" ", $today); $previous = date("d F", mktime(0, 0, 0, date("m"), date("d")-7, date("Y"))); list($previous_day, $previous_month) = explode(" ", $previous); if($today_month != $previous_month){ echo $previous_month." ".$previous_day." - ".$today_month." ".$today_day; }else{ echo $today_month." ".$previous_day." - ".$today_day; } die(); ?> ```
Using PHP date to display weekly dates
[ "", "php", "mysql", "date", "" ]
This is a question from the most recent version of Stroustrup's "The C++ Programming Language". I've been mulling this over in my head for the past couple days. The only thing I can come up with, (and this is probably incorrect) is something like this: ``` int* f(int n) { int* a = &a - n * sizeof(int*); return a; } ``` My intent is to get the address of something higher up on the stack. Does this make any sense? Does anyone else have any other answers? Remember, this is in Chapter 5 (pointers, arrays, and structures) so the answer shouldn't involve something later on in the book.
The only (barely) reasonable case I know of is when you want to pass a pointer to the object itself to its constructor. For example, say you have a cyclic linked list node: ``` class Node { public: Node(Node* next): next(next) {} private: Node* next; }; ``` and you want to create a single-element cyclic list on the stack. You can do this: ``` Node n(&n); ``` A few other examples that aren't really practical (i.e. I don't see why you'd need that sort of thing), but otherwise valid: ``` int n = sizeof(n); void* p = &p; ```
An example I use very often in C code is: ``` C *c = (C*) malloc(sizeof *c); ... free(c); ``` It involves pointers and structures. Surely, `new` frees you from having to use that idiom by saying `new C` instead in C++.
TCPL 5.9.9 (C++): Where would it make sense to use a name in its own initializer?
[ "", "c++", "initializer", "" ]