Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Pretty much the opposite of server-side push, also known as [Comet](http://en.wikipedia.org/wiki/Comet_(programming)). I'm wondering if it is possible to use long lived HTTP connections to push information to the server. Unlike a simple XHR, the connection would be kept alive and data would be streamed to the server at intervals, as the user completes actions etc. Using standard technologies I don't believe this is possible, but I'm open to suggestions on possible exploitations or ingenious ways of accomplishing this. The purpose would be to complete low-latency data pushes to the server for fast and efficient one-directional streaming. I'm not interested in using socket implementations with flash/java bridges because of the hassle of serving cross domain policies or getting the java signed. Crude hacks that work without additional dependencies are welcome. Preferably the solution would be done with javascript.
I once saw a talk by the guy behind <http://orbited.org/> It's a js library that uses standard technology to keep a connection open between the server and the client you can push stuff down.
This can be done in one of a few ways ... You can [keep a connection open](http://en.wikipedia.org/wiki/HTTP_persistent_connections) and do POST's, or I am sure it is possible to do a multi-part POST.
Possible to do client-side HTTP push?
[ "", "javascript", "ajax", "http", "streaming", "comet", "" ]
How can I find whether a singly linked list is circular/cyclic or not? I tried to search but couldn't find a satisfactory solution. If possible, can you provide a pseudo-code or Java-implementation? For instance: `1` → `3` → `5` → `71` → `45` → `7` → `5`, where the second `5` is actually the third element of the list.
The standard answer is to take two iterators at the beginning, increment the first one once, and the second one twice. Check to see if they point to the same object. Then repeat until the one that is incrementing twice either hits the first one or reaches the end. This algorithm finds any circular link in the list, not just that it's a complete circle. Pseudo-code (not Java, untested -- off the top of my head) ``` bool hasCircle(List l) { Iterator i = l.begin(), j = l.begin(); while (true) { // increment the iterators, if either is at the end, you're done, no circle if (i.hasNext()) i = i.next(); else return false; // second iterator is travelling twice as fast as first if (j.hasNext()) j = j.next(); else return false; if (j.hasNext()) j = j.next(); else return false; // this should be whatever test shows that the two // iterators are pointing at the same place if (i.getObject() == j.getObject()) { return true; } } } ```
A simple algorithm called [Floyd's algorithm](http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare) is to have two pointers, a and b, which both start at the first element in the linked list. Then at each step you increment a once and b twice. Repeat until you either reach the end of the list (no loop), or a == b (the linked list contains a loop). Another algorithm is [Brent's algorithm](http://en.wikipedia.org/wiki/Cycle_detection#Brent.27s_algorithm).
What is an efficient algorithm to find whether a singly linked list is circular/cyclic or not?
[ "", "java", "algorithm", "data-structures", "linked-list", "" ]
Is there a way to get GD's function [`imagefilledarc()`'s](http://www.php.net/imagefilledarc) result in using PHP ImageMagick? I've looked around but haven't found a satisfying solution so far. I want it to support transparency, and use it to draw pies.
Since this post gets hit by googlers every now and then, and doesn't have a valid answer, I figured I should give some hints. There is an excellent library called Imagine (<https://github.com/avalanche123/Imagine>) which supports the most popular PHP image libraries (ImageMagick, GraphicsMagick and GD) using the same calls. It's API includes a pieSlice function (<https://imagine.readthedocs.io/en/stable/_static/API/Imagine/Draw/DrawerInterface.html#method_pieSlice>). The source for that function is <https://github.com/avalanche123/Imagine/blob/develop/src/Imagick/Drawer.php#L242>
Your best bet would be to use ImageMagick::Draw. It has an arc command; instead of specifying the center, you specify the bounding rectangle. You just need to add a command before it to set the fill, and perhaps after it to close the fill. <http://us.php.net/manual/en/function.imagickdraw-arc.php>
Drawing pies using PHP ImageMagick
[ "", "php", "graphics", "imagemagick", "draw", "" ]
Getting started with TDD and I want to ground up a Repository-driven Model. However, how can I use NUnit to effectively say: ``` SomeInterfaceExists() ``` I want to create tests for each domain model (E.g. `ICarRepository`, `IDriverRepository`), etc.) Does this actually make sense? Regards
TDD means you drive your development (design) by proceeding in a test-first manner, meaning you 1. Write the outline (methods) of your class you want to test 2. You create a Unit test for the sketch of your class 3. You run your unit test -> it will fail 4. You hack your class, just enough to make the test pass 5. You refactor your class This is repeated for each item.
That's not something you test with TDD. The test is can I call one of the methods of that interface on this class, and does it return the right thing.
TDD - Test Existence of Interface
[ "", "c#", "tdd", "nunit", "" ]
I have a Java program (call it Jack) and an Objective-C program (call it Oscar), which I run on the same Mac OS X computer. Oscar sends a string message via a socket to Jack, once per second. For reliability and performance would it be better to maintain an open socket between Jack and Oscar? Or would it be better to repeatedly open a socket, send the message, then close the socket again?
Keep it open. You are going to need it a lot (once per second), and there's some overhead involved in opening new sockets. Plus, you will be chewing up the heap with new objects until the garbage collector comes by.
Keep it open Jack, keep it open. It takes me some CPU cycles already to open and close the connection only to do it again the next second.
Sending data via a socket from Objective-C to Java
[ "", "java", "objective-c", "sockets", "ipc", "" ]
``` str_replace('Ê','',$line); ``` Ain't working. Is there some special string that represents that?
You need to consider the encoding of the string you want to manipulate. If that’s not encoded with the same character encoding as the file you declared that string above in is, you need to convert between both encodings. The most common error is that either the data or the file is encoded in UTF-8 and the other in ISO 8859-1.
It's not clear if you know this, but str\_replace doesn't work "in place", it returns a new string, so perhaps all you really needed was ``` $line=str_replace('Ê','',$line); ``` Another possibility is that you are looking at a Unicode combining diacritic, which is actually two unicode chars - the E and a circumflex diacritic.
How do I replace Ê with '' in php?
[ "", "php", "string", "character-encoding", "" ]
I have a set of test accounts that are going to be created but the accounts will be setup to require password change on the first login. I want to write a program in C# to go through the test accounts and change the passwords.
You can use the [UserPrincipal](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal.aspx) class' [SetPassword](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.authenticableprincipal.setpassword.aspx) method, provided you have enough privileges, once you've found the correct UserPrincipal object. Use [FindByIdentity](http://msdn.microsoft.com/en-us/library/bb344891.aspx) to look up the principal object in question. ``` using (var context = new PrincipalContext( ContextType.Domain )) { using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName )) { user.SetPassword( "newpassword" ); // or user.ChangePassword( "oldPassword", "newpassword" ); user.Save(); } } ```
Here's a great Active Directory programming quick reference: [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C) See the password reset code near the end. ``` public void ResetPassword(string userDn, string password) { DirectoryEntry uEntry = new DirectoryEntry(userDn); uEntry.Invoke("SetPassword", new object[] { password }); uEntry.Properties["LockOutTime"].Value = 0; //unlock account uEntry.Close(); } ```
How to programmatically change Active Directory password
[ "", "c#", "active-directory", "directoryservices", "" ]
I have a code that goes something like: ``` $cipher_alg = MCRYPT_RIJNDAEL_128; $decrypted_string = mcrypt_decrypt($cipher_alg, $key, $encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv)))); ``` I worry that in the process of decoding the `mcrypt_decrypt` will introduce a gratuitous whitespace or null characters at the back or front of the `$decrypted_string`. So should I trim it? **Note: I could have run the code and find this out. But since I can never run enough samples to prove ( or disprove) my point, I want some concrete and theoretical answers, probably based on the inner working of the `mcrypt_decrypt` algorithm. Another reason I ask is that I believe this is going to help others.** **Note 2: Notwithstanding with [the answer below ( now deleted and only 10K users can see it)](https://stackoverflow.com/questions/1061765/should-i-trim-the-decrypted-string-after-mcryptdecrypt/1061799#1061799), it seems that the [examples here](https://www.php.net/manual/en/function.mcrypt-decrypt.php) do use trimming to get the correct decrypted string.**
Actually both [`mcrypt_encrypt()`](https://www.php.net/manual/en/function.mcrypt-encrypt.php) and [`mcrypt_decrypt()`](https://www.php.net/manual/en/function.mcrypt-decrypt.php) as well as the other en-/decryption functons (like [`mcrypt_generic()`](https://www.php.net/manual/en/function.mcrypt-generic.php) or [`mdecrypt_generic()`](https://www.php.net/manual/en/function.mdecrypt-generic.php)) **do** pad the `$data` parameter to a length of `n * <<blocksize>>`. The padding character is the `NUL` character (`\x0` or `\0`) whereas the `<<blocksize>>` depends on the cipher and the block cipher modes used. You should have a look at [Block cipher modes of operation](http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation) and [Padding (cryptography)](http://en.wikipedia.org/wiki/Padding_(cryptography)). The following is the output of [`mcrypt_get_block_size()`](https://www.php.net/manual/en/function.mcrypt-get-block-size.php) for each of the available ciphers and modes on my machine. Obviously the function does not take into account that modes such as CFB, OFB and CTR *do not require any special measures to handle messages whose lengths are not multiples of the block size, since they all work by XORing the plaintext with the output of the block cipher* (quote from Wikipedia). CBC which is used in your example always requires that the final block is padded before encryption. ``` cast-128 cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported gost cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported rijndael-128 cbc: 16 bytes cfb: 16 bytes ctr: 16 bytes ecb: 16 bytes ncfb: 16 bytes nofb: 16 bytes ofb: 16 bytes stream: not supported twofish cbc: 16 bytes cfb: 16 bytes ctr: 16 bytes ecb: 16 bytes ncfb: 16 bytes nofb: 16 bytes ofb: 16 bytes stream: not supported arcfour cbc: not supported cfb: not supported ctr: not supported ecb: not supported ncfb: not supported nofb: not supported ofb: not supported stream: 1 bytes cast-256 cbc: 16 bytes cfb: 16 bytes ctr: 16 bytes ecb: 16 bytes ncfb: 16 bytes nofb: 16 bytes ofb: 16 bytes stream: not supported loki97 cbc: 16 bytes cfb: 16 bytes ctr: 16 bytes ecb: 16 bytes ncfb: 16 bytes nofb: 16 bytes ofb: 16 bytes stream: not supported rijndael-192 cbc: 24 bytes cfb: 24 bytes ctr: 24 bytes ecb: 24 bytes ncfb: 24 bytes nofb: 24 bytes ofb: 24 bytes stream: not supported saferplus cbc: 16 bytes cfb: 16 bytes ctr: 16 bytes ecb: 16 bytes ncfb: 16 bytes nofb: 16 bytes ofb: 16 bytes stream: not supported wake cbc: not supported cfb: not supported ctr: not supported ecb: not supported ncfb: not supported nofb: not supported ofb: not supported stream: 1 bytes blowfish-compat cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported des cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported rijndael-256 cbc: 32 bytes cfb: 32 bytes ctr: 32 bytes ecb: 32 bytes ncfb: 32 bytes nofb: 32 bytes ofb: 32 bytes stream: not supported serpent cbc: 16 bytes cfb: 16 bytes ctr: 16 bytes ecb: 16 bytes ncfb: 16 bytes nofb: 16 bytes ofb: 16 bytes stream: not supported xtea cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported blowfish cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported enigma cbc: not supported cfb: not supported ctr: not supported ecb: not supported ncfb: not supported nofb: not supported ofb: not supported stream: 1 bytes rc2 cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported tripledes cbc: 8 bytes cfb: 8 bytes ctr: 8 bytes ecb: 8 bytes ncfb: 8 bytes nofb: 8 bytes ofb: 8 bytes stream: not supported ``` Therefore you have to [`rtrim()`](https://www.php.net/manual/en/function.rtrim.php) the output of the decryption functions to get the original string if your cipher operates on fixed length blocks: ``` $output = rtrim($decrypted, "\0"); ```
In my implementation of TripleDES, I found the decrypted string was padded with \5 or \6 characters. This wasn't the expected \0 or \4 characters mentioned above or in the PHP.net examples. To determine the ASCII value of the padding character use the [ord()](http://www.php.net/manual/en/function.ord.php) function. ord() works on a single character so use str\_split() to break up a string or access the character directly with array notation - $string[5]. Final trim result - `trim($decrypt, "\0..\32");` Final code result - ``` $key = "encryption key"; $encrypt = base64_decode($encrypt); $iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $decrypt = mcrypt_decrypt(MCRYPT_3DES, $key, $encrypt, MCRYPT_MODE_ECB, $iv); $final = trim($decrypt, "\0..\32"); // removes potential null padding ```
Should I Trim the Decrypted String after mcrypt_decrypt?
[ "", "php", "encryption", "" ]
I've got a method in a class that's writing to some string, which calls another method which does the same. Something like: ``` void foo() { a += "xyx"; bar(); } void bar() { a += "abc"; } ``` For unit testing purposes, I want to test foo and bar separately. Is there any way to prevent bar from being run when I call foo() or to replace it with another method?
Create a subclass that overrides bar() that does nothing.
Why would you want to do that? You could intercept the code at the byte code level using aspects (not wise); you could take in an object that calls bar: `void foo(MyBarObject m) { a += "xyx"; m.bar(); }` But, as I said, I can't think why this is useful. A unit test is meant to test a public interface. If bar() is private or protected, then it's tested automatically via your call, and later assertions, to foo(). If both foo() and bar() are public, cool, test them separatley. Can you post a real example? Can you change the code under test? Etc.
How do you stub an individual method in java for unit testing?
[ "", "java", "unit-testing", "stub", "" ]
I am using .Net Remoting and trying to access a remote object modified in the Server, here is the object def: The idea is that the MRB object, which I create on the server, is returned to the client and "Set On Server" is printed out when getString() is called on the client. What I get right now is a null string on the client, so the MRB object was not send to the client when new was called on the client. Sorry for all the different classes etc, but its the only way, I trimmed as much as possible. What I really want is for "**Set On The Server"** printed on the client when run. ``` using System; using System.Runtime.Remoting.Lifetime; namespace RemoteType { public class MyRemoteObject : System.MarshalByRefObject { private string sharedString; public string getString() { return sharedString; } public void setString(string value) { sharedString = value; } public MyRemoteObject() { Console.WriteLine("MyRemoteObject Constructor Called"); } public override object InitializeLifetimeService() { return null; } public string Hello() { return "Hello, Welcome to .Net Remoting !"; } } ``` Know here is the server: ``` using System; using System.Runtime.Remoting; using RemoteType; namespace SimpleServer { class SimpleServer { public static MyRemoteObject MRB = null; static void Main(string[] args) { RemotingConfiguration.Configure("RemotingAppServer.exe.config"); MRB = new MyRemoteObject(); MRB.setString("Set on the server"); Console.WriteLine(MRB.getString()); RemotingServices.Marshal((MRB), "MyRemoteObject"); Console.WriteLine("Press return to exit"); Console.ReadLine(); } } ``` And the .NET Remote Config App.Config: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application> <channels> <channel ref="tcp" port="8000" /> </channels> <service> <wellknown mode="Singleton" type="RemoteType.MyRemoteObject, RemoteType" objectUri="MyRemoteObject" /> </service> </application> </system.runtime.remoting> </configuration> ``` Finally the client: ``` using System; using System.Runtime.Remoting; using RemoteType; namespace SimpleClient { class SimpleClient { static void Main(string[] args) { RemotingConfiguration.Configure("RemoteClient.exe.config"); MyRemoteObject robj = new MyRemoteObject(); Console.WriteLine(robj.Hello() + " " + robj.getString()); Console.ReadLine(); } } } ``` And its config too: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <application name = "SimpleClient"> <client> <wellknown type="RemoteType.MyRemoteObject,RemoteType" url="tcp://localhost:8000/MyRemoteObject"/> </client> <channels> <channel ref="tcp" port="0"/> </channels> </application> </system.runtime.remoting> </configuration> ```
I did test your code and worked perfectly. I did set three projects, one with server, another with client and a third one shared between server and client for the remote object. In the remote app.config you can remove the wellknown entry as you are already marshalling it by code.
Are you sure your sockets closes as soon as the application ends? If you test multiple times rapidly this may cause tcp communication problems
Problem with .Net Remoting (C#)
[ "", "c#", ".net", "remoting", "" ]
There's a loop where we get certain data. Depending on the data, file writer needs to write to different files. Is it a good practice?
Since it's not possible to have one `FileWriter` object to write to different files, I'd say it's not good form. Did you mean that you have a `FileWriter` variable that references *different* `FileWriter` objects writing to a different file each? That depends on the use case. If they are all writing similar data to files that have similar meanings then it might be OK. But then again: if your method writes to more than one file, then you probably need to refactor it anyway.
If you are referring to `java.io.FileWriter`, then the answer is that [you can't](http://java.sun.com/javase/6/docs/api/java/io/FileWriter.html). A `FileWriter` instance is tied to the file that you initialised it with. If you're talking about your own file writer class, then the answer is more subjective as it depends entirely on your situation - which you will need to elaborate. But generally, if you're thinking of keeping writers open, then consider the possiblity that you may lose data if you don't close the file after writing but instead hang on to the instance.
Is it ok to use same file writer for writing different files
[ "", "java", "filewriter", "" ]
Say, You have an application which lists down users in your application. Ideally, if you were writing code to achieve this in Java, irrespective of what your UI layer is, I would think that you would write code which retrieves result set from the database and maps it to your application object. So, in this scenario, you are looking at your ORM / Data layer doing its thing and creating a list of "User" objects. Let's assume that your User object looks as follows: ``` public class User { private String userName; private int userid; } ``` You can now use this list of "User" objects, in any UI. (Swing / Webapp). Now, imagine a scenario, where you have to list down the userName and a count of say, departments or whatever and this is a very specific screen in a webapp. So you are looking a object structure like this: ``` public class UserViewBean { private String userName; private int countDepartments; } ``` The easiest way of doing this is writing SQL for retrieving department count along with user name in one query. If I you to write such a query, where would you have this query? In your jsp? But, if you were doing this in a MVC framework, would you move this query to your data layer, get the result set, convert it to UserViewBean and send it to your jsp in request scope? If you write queries directly into jsps/if you are making use of connections directly in JSP, isn't that a bad practice? I know, some of you might say, 'hey, you got your object composition wrong! if department is linked to user, you would want to create a list of departments in your User object' - Yes, I agree. But, think of this scenario - Say, I don't need this department count information anywhere else in my application other than this one screen. Are you saying that whereever I load my User object from the database, I would have to load a list of dependency objects, even if I won't be using them? How long will your object graph get with all the relational integrity? Yes, I do know that you have ORMs for this very reason, so that you get benefits of lazy loading and stuff, but I dont have the privilage to use one. The bottom line question here is: * ***Would you write sqls in to your JSP if it serves just one screen?*** OR * ***Would you compose an anemic object that caters to your view and make your business layer return this object for this screen - just to make it look a bit OOish?*** OR * ***irrespective of what your screen demands, would you compose your objects such that an object graph is loaded and you would get the size of that list?*** What is the best practice here?
Personally, I take a simple pragmatic approach. If I was writing screen that just displays a list of users with their deparment count, so that the entire code is maybe a page, and I don't expect this code to be used on any other screen, I'd probably just throw it all in the JSP. Yes, I know there are all the MVC purists who will say, "business logic should never go in a JSP". But aside from a dogmatic rule, why not? What would it hurt in a case like this? If I found that I had two screens, maybe one where I had to simply display the list and another where I had to do some additional processing on the list, then I would certainly pull the common code out into a class that was called from both places. I believe that the criteria should be: What produces the most maintainable code? What is shortest and easiest to understand? What produces the least linkages between modules? etc. I adamantly refuse to accept the principle: "In some cases this approach leads to problems, therefore never use it." If sometimes it leads to problems, then don't use it in the cases where it leads to problems. Or worse, "Somebody wrote it in a book, therefore it cannot be questioned." Sure, there are some rules that are valid 99.99% of the time, so it gets to be pointless to check if this particular case is an exception. But there are lots of rules that are good 51% of the time and people leap from "mostly" to "always".
I would never put SQL in a JSP. I would use Spring MVC or Struts controllers, or servlets to contain all of that type of logic. It allows for better error handling among other things (you can forward to error pages when queries fail). If you really must do this, use the [JSTL SQL tags](http://www.j2ee.me/j2ee/1.4/docs/tutorial/doc/JSTL7.html).
Using sqls in JSP - What is the best practice?
[ "", "java", "design-patterns", "jsp", "web-applications", "" ]
> **Possible Duplicate:** > [Why C# implements methods as non-virtual by default?](https://stackoverflow.com/questions/814934/why-c-implements-methods-as-non-virtual-by-default) I'm speaking primarily about C#, .NET 3.5, but wonder in general what the benefits are of not considering everything "virtual" - which is to say that a method called in an instance of a child class always executes the child-most version of that method. In C#, this is not the case if the parent method is not labeled with the "virtual" modifier. Example: ``` public class Parent { public void NonVirtual() { Console.WriteLine("Non-Virtual Parent"); } public virtual void Virtual(){ Console.WriteLine("Virtual Parent"); } } public class Child : Parent { public new void NonVirtual() { Console.WriteLine("Non-Virtual Child"); } public override void Virtual() { Console.WriteLine("Virtual Child"); } } public class Program { public static void Main(string[] args) { Child child = new Child(); Parent parent = new Child(); var anon = new Child(); child.NonVirtual(); // => Child parent.NonVirtual(); // => Parent anon.NonVirtual(); // => Child ((Parent)child).NonVirtual(); // => Parent child.Virtual(); // => Child parent.Virtual(); // => Child anon.Virtual(); // => Child ((Parent)child).Virtual(); // => Child } } ``` What exactly are the benefits of the non-virtual behavior observed above? The only thing I could think of was "What if the author of Parent doesn't want his method to be virtual?" but then I realized I couldn't think of a good use case for that. One might argue that the behavior of the class is dependent on how a non-virtual method operates - but then that seems to me there is some poor encapsulation going on, or that the method should be sealed. Along these same lines, it seems like 'hiding' is normally a bad idea. After all, if a Child object and methods were created, it seems that it was done so for a specific reason to override the Parent. And if Child implements (and hides the parents) NonVirtual(), it is super easy to *not* get the what many might consider "expected" behavior of calling Child::NonVirtual(). (I say "expected" because it is sometimes easy to not notice 'hiding' is happening). So, what are the benefits of not allowing everything to have "virtual" behavior? What is a good use-case for hiding a non-virtual parent if it's so easy to get unexpected behavior? If anyone is curious as to why I pose this question - I was recently examining Castle Projects DynamicProxy library. The one main hurdle in using it is that any method (or property) you want to proxy has to be virtual. And this isn't always an option for developers (if we don't have control over the source). Not to mention the purpose of DynamicProxy is to avoid-coupling between your proxied class and whatever behavior you are trying to achieve with the proxy (such as Logging, or perhaps a Memoization implementation). And by forcing virtual methods to accomplish this what is instead achieved is very thin but obtuse coupling of DynamicProxy to all the classes it is proxying - Imagine, you have a ton of methods labeled virtual even though they are never inherited and overridden, so any other developer looking at the code might wonder "why are these even virtual? lets change them back". Anyway, the frustration there led me to wonder what the benefits are of non-virtual, when it seems having everything virtual might have been more clear (IMO, I suppose) and perhaps(?) have more benefits. EDIT: Labeling as community wiki, since it seems like a question that might have subjective answers
[Eric Lippert covers this here, on method hiding](https://web.archive.org/web/20190119000524/https://blogs.msdn.microsoft.com/ericlippert/2008/05/21/method-hiding-apologia/)
Because you don't want people overriding methods that you haven't designed the class for. It takes a significant effort to make sure it is safe to override a method or even derive from a class. It's much safer to make it non-`virtual` if you haven't considered what might happen.
Why not make everything 'virtual'?
[ "", "c#", ".net", "virtual", "overriding", "" ]
I am using a [QWinWidget](http://doc.trolltech.com/solutions/4/qtwinmigrate/qwinwidget.html) inside of an MFC dialog and the QWinWidget is not drawing itself correctly and it is not handling keyboard input correctly. ## Repainting [Unsolved] Within the QWinWidget, I have a QTableWidget. When I scroll the QTableWidget, it does not redraw itself until I stop scrolling, at which point it redraws everything. Similarly, I can type into cells in the QTableWidget and the control is not updated until I force it to re-update by scrolling up or down (it re-updates when the scrolling stops). Since this QWinWidget is housed in an MFC CDialog, I tried overriding the CDialog's OnPaint method and only call the QWinWidget::repaint method, however this has the opposite problem where now only the QWinWidget is updated and the CDialog is never redrawn, resulting in artifacts. If I call QWinWidget::repaint and CDialog::OnPaint, the result is the same as not overriding the OnPaint method. Has anyone ever seen this problem or know how to resolve it? ## Keyboard Input [Solved] None of the controls within the QWinWidget respond to the tab key or arrow keys correctly. The tab/arrow keys simply skip over the entire QWinWidget (and all child controls). Even if I click inside the QWinWidget and select a control, the next time I press the tab key, it skips the focus completely out of the entire QWinWidget. I noticed that the QWinWidget has two functions, QWinWidget::focusNextPrevChild and QWinWidget::focusInEvent and both of them have a comment header saying "\reimp". Am I supposed to override these functions in order to get correct tab functionality? If so, how can these functions be implemented for correct tab functionality.
I have fixed the keyboard input issue. The QWinWidget class needed some changes: in the QWinWidget::init method, the WS\_TABSTOP must be added to the window style: ``` SetWindowLong(winId(), GWL_STYLE, WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_TABSTOP); ``` Also, the QWinWidget::winEvent method needs to respond to the WM\_GETDLGCODE to let Windows know that it is interested in receiving key/tab inputs. I had to add this if block: ``` if(msg->message == WM_GETDLGCODE) { *result = DLGC_WANTARROWS | DLGC_WANTTAB; return(true); } ``` I am still working on getting the widget to paint properly.
I don't know about whether you need to reimplement the `focusNextPrevChild()` and `focusInEvent()` functions, but I do know that the "\reimp" in the comment header is part of Qt's documentation generation, which merely specifies that the function was a reimplementation of another function in a parent class.
QWinWidget Inside MFC Dialog Not Repainting or Responding to Tab/Arrow keys
[ "", "c++", "qt", "mfc", "qt-mfc-migration", "" ]
I understand the IOC concept, which we can mix-and-match different classes using wiring. Every class can get away from hard code it's dependancy by delegating the wiring / relationship handling to base xml (context xml). Here is my question, why do we use xml? we can simply wire all the components by using java class. Instead of ``` <bean id="helloWorld" class="com.vaannila.HelloWorld"> <property name="message" value="HelloWorld"></property> </bean> public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld"); helloWorld.display(); } ``` We can rewrite them using ``` HelloWorld helloWorld = new HelloWorld(); helloWorld.setMessage("HelloWorld"); helloWorld.display(); ```
That's basically the approach that [Guice](http://code.google.com/p/google-guice/) takes, yes. There are advantages to using XML (or some other similar text-based approach though). In particular, you can change your application's wiring without rebuilding anything. If you don't want that, you can certainly do it all by hand or use something like Guice. Additionally, Spring uses the fact that it's all configured declaratively to enable things like AOP. You *can* do all of that by hand, but it's a bit more long-winded.
Check out [Spring JavaConfig](http://www.springsource.org/javaconfig).
why does Spring use XML for component wiring?
[ "", "java", "spring", "inversion-of-control", "" ]
Okay, so I have this form that is set to preload a DB record for editing if you add a ?edit=1 to the url, it will load record #1 for editing into the form. I have a box that is like this- ``` <select class="field select addr"> <option value="no"<?php if($row['has_amenities'] == "no") {echo ' selected=\"selected\"'; } ?>>No</option> <option value="yes"<?php if($row['has_amenities'] == "yes") {echo 'selected=\"selected\"'; } ?>>Yes</option> </select> ``` Now, let's say that $row['has\_amenities'] is "yes" so when the form loads, the select box is showing "Yes". BUT, if I change the select box to "No" and click save, it doesn't write "no" to the DB, but it does wipe out that record's "yes" with nothing. What am I doing wrong? Here's the update code-- ``` $sql = "UPDATE venues SET microsite_title = '$_POST[microsite_title]', microsite_city_title = '$_POST[microsite_city_title]', logo = '$_POST[logo]', photo1 = '$_POST[photo1]', photo2 = '$_POST[photo2]', photo3 = '$_POST[photo3]', photo4 = '$_POST[photo4]', photo5 = '$_POST[photo5]', photo6 = '$_POST[photo6]', photo7 = '$_POST[photo7]', photo8 = '$_POST[photo8]', website_primary = '$_POST[website_primary]', website_secondary = '$_POST[website_secondary]', paragraph_1_title = '$_POST[paragraph_1_title]', paragraph_1 = '$_POST[paragraph_1]', paragraph_2_title = '$_POST[paragraph_2_title]', paragraph_2 = '$_POST[paragraph_2]', paragraph_3_title = '$_POST[paragraph_3_title]', paragraph_3 = '$_POST[paragraph_3]', paragraph_4_title = '$_POST[paragraph_4_title]', paragraph_4 = '$_POST[paragraph_4]', paragraph_5_title = '$_POST[paragraph_5_title]', paragraph_5 = '$_POST[paragraph_5]', paragraph_6_title = '$_POST[paragraph_6_title]', paragraph_6 = '$_POST[paragraph_6]', top10_1 = '$_POST[top10_1]', top10_2 = '$_POST[top10_2]', top10_3 = '$_POST[top10_3]', top10_4 = '$_POST[top10_4]', top10_5 = '$_POST[top10_5]', top10_6 = '$_POST[top10_6]', top10_7 = '$_POST[top10_7]', top10_8 = '$_POST[top10_8]', top10_9 = '$_POST[top10_9]', top10_10 = '$_POST[top10_10]', top10_locale = '$_POST[top10_locale]', contact_title = '$_POST[contact_title]', contact_street_addr = '$_POST[contact_street_addr]', contact_street_addr2 = '$_POST[contact_street_addr2]', contact_city = '$_POST[contact_city]', contact_state = '$_POST[contact_state]', contact_zip = '$_POST[contact_zip]', contact_phone = '$_POST[contact_phone]', contact_tollfree = '$_POST[contact_tollfree]', latitude = '$_POST[latitude]', longitude = '$_POST[longitude]', testimonial = '$_POST[testimonial]', sidebar_title = '$_POST[sidebar_title]', sidebar_content = '$_POST[sidebar_content]', has_amenities = '$_POST[has_amenities]' WHERE id = '$_POST[query]'"; ``` Also, I know it's not a good idea to write $\_POST values without cleaning them first, but this is an internal form behind a firewall, etc. I'll clean it up later after it's working :o) Thanks!
It looks like the <select> element has no name or id--is that the case in your code? If so, I believe $\_POST[has\_amenities] won't be set--there would be no has\_amenities value in $\_POST. You'd get an empty string instead.
### Wrap all of the instances of $\_POST[] in {} (curly braces) so it looks like this ``` '{$_POST['key']}' ``` The curly braces are need to force PHP to evaluate $\_POST as a variable when it's inside a double-quoted string. ### Also, quote your $\_POST array keys like this ``` $_POST['key'] ``` You want to get in the habit of this even though $\_POST[key] will usually work. PHP is treating **key** as an constant which, if it's undefined, is automatically turned into a the string "key" so you get the behavior you're expecting. However, if **key** already exists as a constant (via the **[define()](http://us.php.net/manual/en/function.define.php)**) function, you'll get the *value* of the **key** constant which is not what you want. Take a look at the [Array do's and don'ts](http://www.php.net/manual/en/language.types.array.php) section.
PHP: form select box doesn't write changed selection to DB
[ "", "php", "mysql", "select", "" ]
In the Library of Windows Media Player you can select one or more music files. You can then right-click and in their context menu choose *Open File Location*. This will open up one windows explorer window for each directory that the files are in, and the files will be selected for you. So let's say we have a bunch of mp3 files in our library where three of them are these: * *Z:\Music\Thursday Blues\01. I wish it was friday.mp3* * *Z:\Music\Counting Sheep\01. Sheep #1.mp3* * *Z:\Music\Counting Sheep\02. Sheep #2.mp3* If we select those three (in a view where all of them are visible) and do *Open File Location* then two explorer windows will pop up. One will be the *Z:\Music\Thursday Blues* folder with *01. I wish it was friday.mp3* selected, and the other one will be the \*Z:\Music\Counting Sheep\*\* folder with both *01. Sheep #1.mp3* and *02. Sheep #2.mp3* selected. How can I do this myself in C#? We have an application which is going to export data to various formats, for example CSV and Excel, and I would like to open up explorer windows with these files selected when they are created and ready to be viewed. Currently I just do `Process.Start(path)`, and this works but I would love to be able to highlight those particular files as well. Would make the files that were just created much more obvious. --- Windows Media Player does it so well... I want to do it too =/ Are there any Microsoft employees here that could figure out how it can be done? (A)
Searching for an answer after a coworker had the issue i found none so i wrote a small class to do this. The code [is on Gist](http://gist.github.com/551626) and i will paste the curent version at the end of this post. With your sample files, the syntax will be : ``` ShowSelectedInExplorer.FilesOrFolders( @"Z:\Music\Thursday Blues\01. I wish it was friday.mp3", @"Z:\Music\Counting Sheep\01. Sheep #1.mp3", @"Z:\Music\Counting Sheep\02. Sheep #2.mp3" ); ``` There are some limitations to my code compared to the low level API, mainly : * Selecting on the desktop is not implemented * The parent directory must be a directory or a drive, so you can't select multiple drives in the My Computer folder for example. Anyway, here is the ShowSelectedInExplorer class source code : ``` namespace SHOpenFolderAndSelectItems { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; static class ShowSelectedInExplorer { [Flags] enum SHCONT : ushort { SHCONTF_CHECKING_FOR_CHILDREN = 0x0010, SHCONTF_FOLDERS = 0x0020, SHCONTF_NONFOLDERS = 0x0040, SHCONTF_INCLUDEHIDDEN = 0x0080, SHCONTF_INIT_ON_FIRST_NEXT = 0x0100, SHCONTF_NETPRINTERSRCH = 0x0200, SHCONTF_SHAREABLE = 0x0400, SHCONTF_STORAGE = 0x0800, SHCONTF_NAVIGATION_ENUM = 0x1000, SHCONTF_FASTITEMS = 0x2000, SHCONTF_FLATLIST = 0x4000, SHCONTF_ENABLE_ASYNC = 0x8000 } [ComImport, Guid("000214E6-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComConversionLoss] interface IShellFolder { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void ParseDisplayName(IntPtr hwnd, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In, MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, [Out] out uint pchEaten, [Out] out IntPtr ppidl, [In, Out] ref uint pdwAttributes); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnumObjects([In] IntPtr hwnd, [In] SHCONT grfFlags, [MarshalAs(UnmanagedType.Interface)] out IEnumIDList ppenumIDList); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int BindToObject([In] IntPtr pidl, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindToStorage([In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CompareIDs([In] IntPtr lParam, [In] ref IntPtr pidl1, [In] ref IntPtr pidl2); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CreateViewObject([In] IntPtr hwndOwner, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributesOf([In] uint cidl, [In] IntPtr apidl, [In, Out] ref uint rgfInOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUIObjectOf([In] IntPtr hwndOwner, [In] uint cidl, [In] IntPtr apidl, [In] ref Guid riid, [In, Out] ref uint rgfReserved, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDisplayNameOf([In] ref IntPtr pidl, [In] uint uFlags, out IntPtr pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetNameOf([In] IntPtr hwnd, [In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszName, [In] uint uFlags, [Out] IntPtr ppidlOut); } [ComImport, Guid("000214F2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IEnumIDList { [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int Next(uint celt, IntPtr rgelt, out uint pceltFetched); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int Skip([In] uint celt); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int Reset(); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int Clone([MarshalAs(UnmanagedType.Interface)] out IEnumIDList ppenum); } static class NativeMethods { [DllImport("shell32.dll", EntryPoint = "SHGetDesktopFolder", CharSet = CharSet.Unicode, SetLastError = true)] static extern int SHGetDesktopFolder_([MarshalAs(UnmanagedType.Interface)] out IShellFolder ppshf); public static IShellFolder SHGetDesktopFolder() { IShellFolder result; Marshal.ThrowExceptionForHR(SHGetDesktopFolder_(out result)); return result; } [DllImport("shell32.dll", EntryPoint = "SHOpenFolderAndSelectItems")] static extern int SHOpenFolderAndSelectItems_( [In] IntPtr pidlFolder, uint cidl, [In, Optional, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, int dwFlags); public static void SHOpenFolderAndSelectItems(IntPtr pidlFolder, IntPtr[] apidl, int dwFlags) { var cidl = (apidl != null) ? (uint)apidl.Length : 0U; var result = SHOpenFolderAndSelectItems_(pidlFolder, cidl, apidl, dwFlags); Marshal.ThrowExceptionForHR(result); } [DllImport("shell32.dll")] public static extern void ILFree([In] IntPtr pidl); } static IntPtr GetShellFolderChildrenRelativePIDL(IShellFolder parentFolder, string displayName) { uint pchEaten; uint pdwAttributes = 0; IntPtr ppidl; parentFolder.ParseDisplayName(IntPtr.Zero, null, displayName, out pchEaten, out ppidl, ref pdwAttributes); return ppidl; } static IntPtr PathToAbsolutePIDL(string path) { var desktopFolder = NativeMethods.SHGetDesktopFolder(); return GetShellFolderChildrenRelativePIDL(desktopFolder, path); } static Guid IID_IShellFolder = typeof(IShellFolder).GUID; static IShellFolder PIDLToShellFolder(IShellFolder parent, IntPtr pidl) { IShellFolder folder; var result = parent.BindToObject(pidl, null, ref IID_IShellFolder, out folder); Marshal.ThrowExceptionForHR((int)result); return folder; } static IShellFolder PIDLToShellFolder(IntPtr pidl) { return PIDLToShellFolder(NativeMethods.SHGetDesktopFolder(), pidl); } static void SHOpenFolderAndSelectItems(IntPtr pidlFolder, IntPtr[] apidl, bool edit) { NativeMethods.SHOpenFolderAndSelectItems(pidlFolder, apidl, edit ? 1 : 0); } public static void FileOrFolder(string path, bool edit = false) { if (path == null) throw new ArgumentNullException("path"); var pidl = PathToAbsolutePIDL(path); try { SHOpenFolderAndSelectItems(pidl, null, edit); } finally { NativeMethods.ILFree(pidl); } } static IEnumerable<FileSystemInfo> PathToFileSystemInfo(IEnumerable<string> paths) { foreach (var path in paths) { var fixedPath = path; if (fixedPath.EndsWith(Path.DirectorySeparatorChar.ToString()) || fixedPath.EndsWith(Path.AltDirectorySeparatorChar.ToString())) { fixedPath = fixedPath.Remove(fixedPath.Length - 1); } if (Directory.Exists(fixedPath)) { yield return new DirectoryInfo(fixedPath); } else if (File.Exists(fixedPath)) { yield return new FileInfo(fixedPath); } else { throw new FileNotFoundException (string.Format("The specified file or folder doesn't exists : {0}", fixedPath), fixedPath); } } } public static void FilesOrFolders(string parentDirectory, ICollection<string> filenames) { if (filenames == null) throw new ArgumentNullException("filenames"); if (filenames.Count == 0) return; var parentPidl = PathToAbsolutePIDL(parentDirectory); try { var parent = PIDLToShellFolder(parentPidl); var filesPidl = filenames .Select(filename => GetShellFolderChildrenRelativePIDL(parent, filename)) .ToArray(); try { SHOpenFolderAndSelectItems(parentPidl, filesPidl, false); } finally { foreach (var pidl in filesPidl) { NativeMethods.ILFree(pidl); } } } finally { NativeMethods.ILFree(parentPidl); } } public static void FilesOrFolders(params string[] paths) { FilesOrFolders((IEnumerable<string>)paths); } public static void FilesOrFolders(IEnumerable<string> paths) { if (paths == null) throw new ArgumentNullException("paths"); FilesOrFolders(PathToFileSystemInfo(paths)); } public static void FilesOrFolders(IEnumerable<FileSystemInfo> paths) { if (paths == null) throw new ArgumentNullException("paths"); var pathsArray = paths.ToArray(); if (pathsArray.Count() == 0) return; var explorerWindows = pathsArray.GroupBy(p => Path.GetDirectoryName(p.FullName)); foreach (var explorerWindowPaths in explorerWindows) { var parentDirectory = Path.GetDirectoryName(explorerWindowPaths.First().FullName); FilesOrFolders(parentDirectory, explorerWindowPaths.Select(fsi => fsi.Name).ToList()); } } } class Program { static void Main() { var test = 3; switch (test) { case 0: var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); ShowSelectedInExplorer.FileOrFolder(Path.Combine(mydocs, "Visual Studio 2010"), edit: true); break; case 1: ShowSelectedInExplorer.FileOrFolder(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); break; case 2: ShowSelectedInExplorer.FilesOrFolders(@"C:\Windows\", new[] { "Microsoft.NET", "System32", "Setup" }); break; case 3: ShowSelectedInExplorer.FilesOrFolders(@"C:\Windows\Microsoft.NET\", @"C:\Windows\System32", @"C:\Windows\Setup", @"C:\Program Files"); break; } } } } ```
**Disclaimer: I think [VirtualBlackFox's answer](https://stackoverflow.com/questions/1073353/c-how-to-open-windows-explorer-windows-with-a-number-of-files-selected/3578581#3578581) is better than mine although it has less votes at present, so scroll down and read that one first :)** Easy method (might not work on all platforms): ``` Process.Start(String, String) ``` First argument is the application, second argument is the command line parameters of the application.. So for example: ``` Process.Start("explorer.exe", "/select,Z:\Music\Thursday Blues\01. I wish it was friday.mp3") Process.Start("explorer.exe", "/select,Z:\Music\Counting Sheep\01. Sheep #1.mp3 /select,Z:\Music\Counting Sheep\02. Sheep #2.mp3") ``` (I think you might need escaped quotes around the file paths if they have spaces). more info: <http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx> (compiled from several answers to [this question](https://stackoverflow.com/questions/334630/c-open-folder-and-select-the-file)) --- Harder method, but more likely to work, taken from [this answer to another question](https://stackoverflow.com/questions/9355/programatically-select-multiple-files-in-windows-explorer/9497#9497): Use the shell function [`SHOpenFolderAndSelectItems`](http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx) Here is some sample code showing how to use the function in C/C++, without error checking: ``` //Directory to open ITEMIDLIST *dir = ILCreateFromPath(_T("C:\\")); //Items in directory to select ITEMIDLIST *item1 = ILCreateFromPath(_T("C:\\Program Files\\")); ITEMIDLIST *item2 = ILCreateFromPath(_T("C:\\Windows\\")); const ITEMIDLIST* selection[] = {item1,item2}; UINT count = sizeof(selection) / sizeof(ITEMIDLIST); //Perform selection SHOpenFolderAndSelectItems(dir, count, selection, 0); //Free resources ILFree(dir); ILFree(item1); ILFree(item2); ```
C#: How to open Windows Explorer windows with a number of files selected
[ "", "c#", "file", "windows-explorer", "directory", "" ]
I'm probably missing out on something fundamental here but it seems rather tricky and confusing to me so here goes... to demonstrate the issue I have the following example .aspx page ``` <%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("<script type=text/javascript>alert('Alert from response.write')" & ";</sc" & "ript>") End Sub Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>") End Sub Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>") End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> function helloWorld() { alert('hello!'); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Button runat=server ID="Button1" text=1 OnClick="Button1_Click" /> <asp:Button runat=server ID="Button2" text=2 OnClick="Button2_Click" /> <asp:Button runat=server ID="Button3" text=3 OnClick="Button3_Click" OnClientClick="helloWorld();" /> <asp:Button runat=server ID="Button4" text=4/> </div> </form> </body> </html> ``` So, I have 3 buttons, the first calls response.write to perform a JS alert.. this works. The second tries to call helloWorld() that is defined in the head tag.. this does not work. The third called helloWorld() both in the response.write and also the onClientClick() - only the onClientClick works. Could someone explain why I can't call helloWorld() using the response.write method? Cheers :D
I think Response.Write is probally wiping the the helloWorld() definition in the PostBack. Try inserting the script tags into the HTML using a PlaceHolder. Rich
You are calling helloWorld before the HTML containing the function has even been downloaded. Define your functions before you call them. (And use a validator - you can't have `<script>` tags outside the head or body.)
Javascript scope with asp.net
[ "", "javascript", "asp.net", "vb.net", "scope", "" ]
So I've got a situation where I need to pass a bunch of data to the server to create a bunch of records. So I read [this article](http://www.sommarskog.se/arrays-in-sql-2005.html) and chose the XML method. So I've got the stored procedure all created in sql server 2005. But now I need to call it from asp.net code. Only all I've got for a database connection is an odbcconnection. I see the sqlclient seems to have a native sqldbtype.xml. What do I do if I'm using odbc? Am i SOL?
I think you should use SQLConnection & related classes. Having said that, you can use VS.net Server Explorer, make a connection to SQL Server using ODBC, expand the tree with stored procedures and see your stored procedure with XML parameter. It should show the ODBC data type for it when you do right click, properties on the XML parameter. This is purely based on my memory. I think, this should work. EDIT: See if this [link](http://msdn.microsoft.com/en-us/library/ms130978(SQL.90).aspx) helps. See for DataTypeCompatibility word on this link.
Turns out I can use the implicit varchar/ntext to XML conversion. I tried both Varchar and NText - they both worked. The conversion the other way doesn't support implicit conversion, you have to do explicit conversion according to the docs. Anyway, here is an example function and the stored procedure it is calling. ADO.Net Code ``` Private Sub cmdXMLTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdXMLTest.Click Dim objConnection As System.Data.Odbc.OdbcConnection Dim cmdTest As System.Data.Odbc.OdbcCommand Dim drTest As System.Data.Odbc.OdbcDataReader Dim intCount As System.Int32 Dim strMatter As System.String = "" Dim strXML As System.String = "<Root><Matter mmatter=""11415.09951"" /><Matter mmatter=""06625.06771"" /><Matter mmatter=""00931.09846"" /></Root>" ' build odbc command for getting parties cmdTest = New System.Data.Odbc.OdbcCommand cmdTest.CommandType = CommandType.StoredProcedure cmdTest.CommandTimeout = 60 cmdTest.CommandText = "{CALL uspXMLTest (?)}" cmdTest.Parameters.Add("@list", System.Data.Odbc.OdbcType.NText).Value = strXML objConnection = New System.Data.Odbc.OdbcConnection("Driver={SQL Server};Server=mysqlserver;Database=son_db;Uid=sa;Pwd=mypassword;") objConnection.Open() cmdTest.Connection = objConnection drTest = cmdTest.ExecuteReader(CommandBehavior.CloseConnection) Do While drTest.Read() strMatter = drTest.GetString(0) intCount = intCount + 1 Loop MsgBox("Found " & intCount.ToString() & " Matters - Last One = " & strMatter) End Sub ``` Stored Procedure ``` CREATE PROCEDURE uspXMLTest @list xml AS SET NOCOUNT ON SELECT matter.mmatter, matter.mdesc1 FROM matter INNER JOIN @list.nodes('/Root/Matter') AS ml(mmatter) ON (matter.mmatter = ml.mmatter.value('@mmatter', 'varchar(15)')) GO ```
How do I create an odbcparameter for a sql server xml datatype for an odbccommand object?
[ "", "sql", "sql-server", "xml", "ado.net", "odbc", "" ]
I've written a script to geocode some points which has a structure basically like this: ``` //get an unupdated record $arr_record; while(count($arr_record) > 0) { //strings are derived from $arr_record geocode($string1); geocode($string2); geocode($string3); array_pop($arr_record); } function geocode($string) { //if successful update($coords) } function update($coords) { //update the database header('Location:http://localhost/thisfile.php') } ``` The trouble is that even when the geocode is successful and the database is updated, and teh header resent, the script still goes back into the while loop without reloading the page and starting again on a new record. Is this normal behaviour for PHP? How do I avoid it behaving like this?
After header() use die(); to terminate the script and output.
> How do I avoid it behaving like this? Put exit() after header().
While loop combined with header() in PHP
[ "", "php", "header", "geocoding", "while-loop", "" ]
Given a public instantiation of a class in WinForm1, I attempt to open WinForm2 and eliciting DB parms do a query the results of which I would like use to fill the class instance in WinForm1. However, I cannot figure out how to access the class instance in WinForm1 from WinForm2. The class instance in WinForm1 is coded as a private member / public property: ``` private theClass _classInstance; public theClass ClassInstance {get; set;} ``` I am calling WinForm2 as a modal form. ``` WinForm2 wf2 = new WinForm2(); wf2.ShowDialog(this); ``` Is there way I can refer to ClassInstance (modifying its value) while in wf2 ??
You could pass a reference to the parent form in the constructor or as a property to the child form or hold the reference in a `static` field. ``` class WinForm2 : Form { WinForm1 parentForm; public WinForm2(WinForm1 parentForm) { this.parentForm = parentForm; // .... } // Use `parentForm.ClassInstance` here. } WinForm2 wf2 = new WinForm2(this); wf2.ShowDialog(this); ``` By the way, when you're declaring an *automatic property* like the one you specified, you shouldn't manually create a backing field. The compiler takes care of that for you.
You can create a constructor on WinForm2 that accepts a WinForm1 on instantiation. ``` public partial class WinForm2 : Form { public WinForm2() { InitializeComponent(); } Form parentForm internal WinForm2(Form parent) : this() { parentForm = parent } } ```
In .NET (C#), how does one reference a variable in one WinForm from a child WinForm?
[ "", "c#", "winforms", "" ]
I have a helper function, which basically calls CompareTo on two objects, but does some special corner case checking, converting, etc. Originally I wrote the function as such: ``` public static bool BetterCompare(IComparable lhs, IComparable rhs, out retCode) { ... retCode = lhs.CompareTo(rhs); ... } ``` But the problem is that if I have a `class AwesomeClass : IComparable<AwesomeClass>`. In fact I have several as some older `IComparable` classes have gone `IComparable<T>`. Yet the compiler gets angry because it can't convert these new objects to `IComparable`. I don't know if this makes it worse, but some of them are `abstract` (though the abstract class does provide an implementation). How can I convey "I want two objects that I can call CompareTo on" and not have the compiler give me any lip. Preferably, the new function should NOT look like `BetterCompare<AwesomeClass>(this, that, out retCode);`, but just "do the right thing". Or is there a better way to do this without touching every class making them *both* `IComparable` and `IComparable<T>`?
You can either make `AwesomeClass` implement the nongeneric `IComparable` interface as well as `IComparable<T>`, or you can write a generic `BetterCompare` method: ``` public static bool BetterCompare<T>(T lhs, T rhs, out retCode) where T : IComparable<T> { ... retCode = lhs.CompareTo(rhs); ... } ``` (Note that this can live alongside your existing method.)
You could always change the variables to an object type and then use reflection to see if they implement one of the interfaces and then cast them to the correct interface. NOTE: Reflection is crazy slow, so use it with caution.
How to mix/fix IComparable and IComparable<T> mess
[ "", "c#", "generics", "icomparable", "" ]
I have a standard 3-frame layout; "fnav" on the left, "fheader" at the top and "fcontent" below the header. All files are located locally on the hard drive. This is the JS function that is throwing the error: ``` function writeHeaderFrame() { try { var headerFrame = window.top.frames['fheader']; var headerTable = document.getElementById('headerTable'); if (headerFrame && headerTable) { headerFrame.document.body.style.backgroundColor = "Black"; var headerFrameBody = headerFrame.document.documentElement.childNodes[1]; headerFrameBody.innerHTML = headerTable.innerHTML; } else if (headerTable) { // there is a headerTable, but no headerFrame headerTable.style.display = 'inline' // show the headerTable } } catch (e) { alert('from header.js, writeHeaderFrame(): ' + e.message); } } ``` Clicking on a link in fnav (or initially loading the frameset) loads content into fcontent, then a JS file in fcontent loads the "header" frame... or it is supposed to, anyway. The Javascript runs fine initially, but whenever a link is clicked I get the following error: ``` Permission Denied To Get Window.document ``` I am unable to determine why. Any and all suggestions would be appreciated.
Apparently, the user in question updated his installation without changing the following setting to "false", which allows local documents to have access to all other local documents. ``` pref("security.fileuri.strict_origin_policy", true); ``` Which explains why I was unable to duplicate the error on my machine. Many thanks to all for your assistance.
First off, please post the code being run when you click those links, and their html. secondly, did you have a typo there? Window.document should be window.document, should it? (lowercase w) **Edit** response to changes in OP question Without the html it's a little hard to say, but If I were taking a stab in the dark, I'd say this line: ``` headerFrame.document.body.style.backgroundColor = "Black"; ``` is causing the error. It looks like headerFrame is on a different domain and you don't, for security reasons, have permission to modify the contents of that frame. Of course, some of the following lines will also have the same issue. Also see <http://userscripts.org/topics/25029> and <http://www.webdeveloper.com/forum/showthread.php?t=189515> for similar cases. **Edit 2** From Mozilla Development Center > Note: Firefox 3 alters the security for windows' documents so that only the domain from which it was located can access the document. While this may break some existing sites, it's a move made by both Firefox 3 and Internet Explorer 7, and results in improved security. (see <https://developer.mozilla.org/En/DOM/Window.document>)
Firefox Error: Permission Denied to get Window.Document
[ "", "javascript", "firefox", "" ]
I am trying to update table A with data from table B. I thought I could do something like: ``` UPDATE A SET A.name = B.name WHERE A.id = B.id ``` but alas, this does not work. Anyone have an idea of how I can do this?
Your query does not work because you have no **FROM** clause that specifies the tables you are aliasing via A/B. Please try using the following: ``` UPDATE A SET A.NAME = B.NAME FROM TableNameA A, TableNameB B WHERE A.ID = B.ID ``` Personally I prefer to use more explicit join syntax for clarity i.e. ``` UPDATE A SET A.NAME = B.NAME FROM TableNameA A INNER JOIN TableName B ON A.ID = B.ID ```
For `Microsoft Access` ``` UPDATE TableA A INNER JOIN TableB B ON A.ID = B.ID SET A.Name = B.Name ```
Update with two tables?
[ "", "sql", "sql-server", "" ]
I have a void pointer returned by dlsym(), I want to call the function pointed by the void pointer. So I do a type conversion by casting: ``` void *gptr = dlsym(some symbol..) ; typedef void (*fptr)(); fptr my_fptr = static_cast<fptr>(gptr) ; ``` I have also tried `reinterpret_cast` but no luck, although the C cast operator seems to work..
Converting a `void*` to a function pointer *directly* is not allowed (should not compile using any of the casts) in C++98/03. It is conditionally supported in C++0x (an implementation may choose to define the behavior and if it does define it, then it must do what the standard says it should do. A `void*`, as defined by the C++98/03 standard, was meant to point to objects and not to contain function pointers or member pointers. Knowing that what you are doing is heavily implementation dependent, here is one option that should compile and work (assuming 32 bit pointers, use `long long` for 64 bit) on most platforms, even though it is clearly undefined behavior according to the standard: ``` void *gptr = dlsym(some symbol..) ; typedef void (*fptr)(); fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr)) ; ``` And here is another option that should compile and work, but carries the same caveats with it as the above: ``` fptr my_ptr = 0; reinterpret_cast<void*&>(my_ptr) = gptr; ``` Or, in Slow motion... ``` // get the address which is an object pointer void (**object_ptr)() = &my_ptr; // convert it to void** which is also an object pointer void ** ppv = reinterpret_cast<void**>(object_ptr); // assign the address in the memory cell named by 'gptr' // to the memory cell that is named by 'my_ptr' which is // the same memory cell that is pointed to // by the memory cell that is named by 'ppv' *ppv = gptr; ``` It essentially exploits the fact that the address of the function pointer is an object pointer (`void (**object_ptr)()`) - so we can use `reinterpret_cast` to convert it to any other object pointer: such as `void**`. We can then follow the address back (by dereferencing the `void**`) to the actual function pointer and store the value of the gptr there. yuk - by no means well-defined code - but it should do what you expect it to do on most implementations.
Note that C++11 allows such a conversion and from gcc 4.9 and above this conversion does not generate a warning: <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57869>. See SO discussions: * [Casts between pointer-to-function and pointer-to-object in C and C++](https://stackoverflow.com/questions/14125474/casts-between-pointer-to-function-and-pointer-to-object-in-c-and-c) * [Why are function pointers and data pointers incompatible in C/C++?](https://stackoverflow.com/questions/12358843/why-are-function-pointers-and-data-pointers-incompatible-in-c-c) * [can void\* be used to store function pointers?](https://stackoverflow.com/questions/26917194/can-void-be-used-to-store-function-pointers) * [Using reinterpret\_cast to cast a function to void\*, why isn't it illegal?](https://stackoverflow.com/questions/27229578/using-reinterpret-cast-to-cast-a-function-to-void-why-isnt-it-illegal)
Function pointers casting in C++
[ "", "c++", "casting", "function-pointers", "" ]
I’m working with basic HTML `<input type="text"/>` text field with a numeric value. I’m adding JavaScript event `keyup` to see when user presses arrow up key (`e.which == 38`) – then I increment the numeric value. The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every `<input type="text"/>` text field as far as I know and it makes sense. But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered). The jump at the beginning happens on `keydown` but even with this knowledge I’m not able to prevent it from occuring. I tried the following: ``` input.addEventListener('keydown', function(e) { e.preventDefault(); }, false); ``` Putting `e.preventDefault()` in `keyup` event doesn’t help either. Is there any way to prevent cursor from moving?
To preserve cursor position, backup `input.selectionStart` before changing value. The problem is that WebKit reacts to `keydown` and Opera prefers `keypress`, so there's kludge: both are handled and throttled. ``` var ignoreKey = false; var handler = function(e) { if (ignoreKey) { e.preventDefault(); return; } if (e.keyCode == 38 || e.keyCode == 40) { var pos = this.selectionStart; this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10); this.selectionStart = pos; this.selectionEnd = pos; ignoreKey = true; setTimeout(function(){ignoreKey=false},1); e.preventDefault(); } }; input.addEventListener('keydown',handler,false); input.addEventListener('keypress',handler,false); ```
I found that a better solution is just to `return false;` to prevent the default arrow key behavior: ``` input.addEventListener("keydown", function(e) { if (e.key === 'ArrowUp' || e.key === 'ArrowDown') return false; }, false); ```
Prevent default behavior in text input while pressing arrow up
[ "", "javascript", "events", "input", "keyboard", "default", "" ]
Hi i was wondering if anyone knows how i can calculate the difference between two tables in tsql. I dont mean finding which cells are different - i mean calulcating the numerical difference. eg - Table A has column1, column 2 and only one 1 row. A1 = 40, B1 = 30. Table B has column1, column 2 and only one 1 row. A1 = 25, B1 = 10. So how could i get (A1 = 15, B1 = 20) using TSQL?
Given that you have no way to join the tables, you'll need a Cartesian product of the two. Luckily since each table only has one record that's not a problem. You do it like this: ``` SELECT TableA.A1 - TableB.A1 AS A1, TableA.B1 - TableB.B1 AS B1 FROM TableA, TableB ``` If you had more than one record in each table, this query would return a result for every pair of records in both tables. So if TableA had n records and TableB has m, the result will have n\*m records.
``` SELECT a.column1 - b.column1 , a.column2 - b.column2 FROM a CROSS JOIN b ```
SQL calculate difference between cell values
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using JSF/ICEFaces. The page is ICEFaces however I'm using the JSF datatable because ICEFaces had slow performance for some reason. Anyway, unlike the ICEFaces datatable, the JSF table doesn't come with export to excel so I'm writing my own. I decided to use Apache POI as below. The code executes well but I don't see pop up to save excel file. Am I missing something? ``` public void ExportWithPoi(ActionEvent e) throws IOException{ HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); // ArrayList<PerfStatBean> statFilterResults; Iterator<PerfStatBean> statsIterator = statFilterResults.iterator(); int i=0; HSSFRow row; row = sheet.createRow((short)0); row.createCell((short)0).setCellValue("Current Application ID"); row.createCell((short)1).setCellValue("Event Name"); row.createCell((short)2).setCellValue("Generic Method Name"); while(statsIterator.hasNext()){ i++; row = sheet.createRow((short)i); PerfStatBean perfBean = statsIterator.next(); row.createCell((short)0).setCellValue(perfBean.getCurrent_appl_id()); row.createCell((short)1).setCellValue(perfBean.getCurrent_appl_id()); row.createCell((short)2).setCellValue(perfBean.getGeneric_method_name()); } HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); res.setContentType("application/vnd.ms-excel"); res.setHeader("Content-disposition", "attachment; filename=PerfCollector.xls"); try { ServletOutputStream out = res.getOutputStream(); wb.write(out); out.flush(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } FacesContext faces = FacesContext.getCurrentInstance(); faces.responseComplete(); } ``` And the excel button is: ``` <h:commandButton id="excelBtn" rendered="#{statsDisplayAndFilter.renderNextBtn}" image="./xmlhttp/css/rime/css-images/excel.png" actionListener="#{statsDisplayAndFilter.ExportWithPoi}"/> ``` Thanks, Tam
I'd suggest you pull this code into its own servlet. You're trying to short circuit JSF's usual life-cycle and while you might be able to find a way to do it, it would probably be simpler and possibly even cleaner to simply make a new servlet which handles this XLS file and let it do its own thing. You can place the appropriate objects into session temporarily from your action button, direct them to the servlet, grab them in the servlet and then remove them from session.
I have posted a blog post specifically for an ICEFaces implementation [here](http://karlgrz.blogspot.com/2009/09/stream-excel-workbook-to-client.html).
problem when exporting to excel with JSF
[ "", "java", "jsf", "icefaces", "export-to-excel", "" ]
I have tried [Pamie](http://pamie.sourceforge.net/) a browser automation library for internet explorer. It interfaces IE using COM, pretty neat: ``` import PAM30 ie = PAM30.PAMIE("http://user-agent-string.info/") ie.clickButton("Analyze my UA") ``` Now I would like to do the same thing using [PyXPCOM](https://developer.mozilla.org/en/pyxpcom) with similar flexibility on Firefox. How can I do this? Can you provide sample code? **update: please only pyxpcom**
I've used [webdriver](http://pypi.python.org/pypi/webdriver/0.5) with firefox. I was very pleased with it. As for the code examples, [this](http://code.google.com/p/webdriver/wiki/PythonBindings) will get you started.
My understanding of PyXPCOM is that it's meant to let you create and access XPCOM components, not control existing ones. You may not be able to do this using PyXPCOM at all, per Mark Hammond, the original author: > [It simply isn't what XPCOM is trying to do. I'm not sure if Mozilla/Firefox now has or is developing a COM or any other "automation" mechanism.](http://mail.python.org/pipermail/python-win32/2004-October/002569.html "Mark Hammond, 2004") and: > [If by "automating", you mean "controlling Mozilla via a remote process via xpcom", then as far as I know, that is not possible](http://aspn.activestate.com/ASPN/Mail/Message/pyxpcom/3506917 "Mark Hammond, 2007") You may instead want to take a look at the previously-suggested Webdriver project, [Windmill](http://www.getwindmill.com/ "Windmill"), or [MozMill](http://code.google.com/p/mozmill/ "MozMill"), both of which support automating Firefox/Gecko/XULRunner via Python.
Browser automation: Python + Firefox using PyXPCOM
[ "", "python", "firefox", "automation", "" ]
How can I validate an XML file against a DTD that is stored locally as a file? The XML file does not have any DOCTYPE declaration (or may have one that should then be overridden). I had a look at [this thread](https://stackoverflow.com/questions/470313/net-how-to-validate-xml-file-with-dtd-without-doctype-declaration) but besides the fact they are using .NET I doubt that this is a good solution. Any input appreciated!
In an ideal world, you'd be able to validate using a [Validator](http://java.sun.com/javase/6/docs/api/javax/xml/validation/package-summary.html). Something like this: ``` SchemaFactory schemaFactory = SchemaFactory .newInstance(XMLConstants.XML_DTD_NS_URI); Schema schema = schemaFactory.newSchema(new File( "xmlValidate.dtd")); Validator validator = schema.newValidator(); validator.validate(new StreamSource("xmlValidate.xml")); ``` Unfortunately, the Sun implementation (at least, as of Java 6) does not include support for creating a Schema instance from a DTD. You might be able to track down a 3rd party implementation. Your best bet may be to alter the document to include the DTD before parsing using some other mechanism. --- You can use a [transformer](http://java.sun.com/javase/6/docs/api/javax/xml/transform/package-summary.html) to insert a DTD declaration: ``` TransformerFactory tf = TransformerFactory .newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM, "xmlValidate.dtd"); transformer.transform(new StreamSource( "xmlValidate.xml"), new StreamResult(System.out)); ``` ...but this does not seem to replace an existing DTD declaration. --- This [StAX](http://java.sun.com/javase/6/docs/api/javax/xml/stream/package-summary.html) event reader can do the job: ``` public static class DTDReplacer extends EventReaderDelegate { private final XMLEvent dtd; private boolean sendDtd = false; public DTDReplacer(XMLEventReader reader, XMLEvent dtd) { super(reader); if (dtd.getEventType() != XMLEvent.DTD) { throw new IllegalArgumentException("" + dtd); } this.dtd = dtd; } @Override public XMLEvent nextEvent() throws XMLStreamException { if (sendDtd) { sendDtd = false; return dtd; } XMLEvent evt = super.nextEvent(); if (evt.getEventType() == XMLEvent.START_DOCUMENT) { sendDtd = true; } else if (evt.getEventType() == XMLEvent.DTD) { // discard old DTD return super.nextEvent(); } return evt; } } ``` It will send a given DTD declaration right after the document start and discard any from the old document. Demo usage: ``` XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent dtd = eventFactory .createDTD("<!DOCTYPE Employee SYSTEM \"xmlValidate.dtd\">"); XMLInputFactory inFactory = XMLInputFactory.newInstance(); XMLOutputFactory outFactory = XMLOutputFactory.newInstance(); XMLEventReader reader = inFactory .createXMLEventReader(new StreamSource( "xmlValidate.xml")); reader = new DTDReplacer(reader, dtd); XMLEventWriter writer = outFactory.createXMLEventWriter(System.out); writer.add(reader); writer.flush(); // TODO error and proper stream handling ``` Note that the XMLEventReader could form the source for some other transformation mechanism that performed validation. --- It would be much easier to validate using a W3 schema if you have that option.
im pretty sure the stuff aforementioned will work.. > Thanks for your help, but what if no DOCTYPE has been specified at > all? The EntityResolver would not help me in that case, would it? – > Simon Jul 8 '09 at 6:34 > > @Bluegene: What are you validating against if no DOCTYPE? – J-16 SDiZ > Jul 8 '09 at 7:12 > > Against my own DTD. I just want to make sure the XML I receive > conforms to my DTD, not just any DTD the sender specifies. – Simon Jul > 8 '09 at 23:09 if the problem is you want it to be validated against your dtd rather than the authors you should ensure that there is clear documentation that details the doctype, and what must be in the xml file
Validate an XML file against local DTD file with Java
[ "", "java", "xml", "validation", "dtd", "" ]
I have a list of objects that have two int properties. The list is the output of another linq query. The object: ``` public class DimensionPair { public int Height { get; set; } public int Width { get; set; } } ``` I want to find and return the object in the list which has the largest `Height` property value. I can manage to get the highest value of the `Height` value but not the object itself. Can I do this with Linq? How?
We have an [extension method](https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/MaxBy.cs) to do exactly this in [MoreLINQ](https://github.com/morelinq/MoreLINQ). You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection. In your case you'd do something like: ``` var item = items.MaxBy(x => x.Height); ``` This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as `MaxBy`): * It's O(n) unlike the [previous accepted answer](https://stackoverflow.com/a/1101848/16587) which finds the maximum value on every iteration (making it O(n^2)) * The ordering solution is O(n log n) * Taking the `Max` value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion. * It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element
This would require a sort (O(n *log* n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL: ``` var maxObject = list.OrderByDescending(item => item.Height).First(); ``` Note that this has the advantage of enumerating the `list` sequence just once. While it might not matter if `list` is a `List<T>` that doesn't change in the meantime, it could matter for arbitrary `IEnumerable<T>` objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own `MaxObject` extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)): ``` static class EnumerableExtensions { public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector) where U : IComparable<U> { if (source == null) throw new ArgumentNullException("source"); bool first = true; T maxObj = default(T); U maxKey = default(U); foreach (var item in source) { if (first) { maxObj = item; maxKey = selector(maxObj); first = false; } else { U currentKey = selector(item); if (currentKey.CompareTo(maxKey) > 0) { maxKey = currentKey; maxObj = item; } } } if (first) throw new InvalidOperationException("Sequence is empty."); return maxObj; } } ``` and use it with: ``` var maxObject = list.MaxObject(item => item.Height); ```
How to perform .Max() on a property of all objects in a collection and return the object with maximum value
[ "", "c#", "linq", "object", "max", "" ]
I have my first ever interview for a Java developer role, specifically RMI, Serverlets and JDBC. However, it has been a while (2 years) since I have done any Java coding. I am sure I still have it up there somewhere and I do remember the Java syntax I wanted to ask how can I re-fresh everything in 2-3 days specially the OOP concepts (polymorphism, inheritance) specifically to Java? Any links, references and tutorials appreciated. I am new to this site and I see there is a preference for programming related questions, hope I can get away with this! Would also appreciate those that know any Java interview questions so I can go through them and test myself. Thanks all
I'd suggest you you test yourself, e.g. on [Java Black Belt](http://www.javablackbelt.com/Home.wwa), which has a good question base grouped by categories and detailled explanations for your mistakes. I'd also recommend (re-)reading [Sun's Java Tutorial](http://java.sun.com/docs/books/tutorial/) and (longer) [Thinking in Java](http://www.mindview.net/Books/TIJ/) by Bruce Eckel (3rd edition is free to download).
[Tutorials on RMI](http://java.sun.com/docs/books/tutorial/rmi/index.html) [Java Servlet Technology](http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html) [JDBC Tutorials](http://java.sun.com/docs/books/tutorial/jdbc/index.html) OOP concepts (polymorphism, inheritance): [Head First Design Patterns](http://oreilly.com/catalog/9780596007126/) [Java Interview Questions](http://www.allapplabs.com/interview_questions/java_interview_questions.htm)
Java - How to refresh knowledge? (2 years ago)
[ "", "java", "oop", "" ]
I am using `DateTime.Now` to show something according to today's date, and when working locally (Malta, Europe) the times appear correctly (obviously because of the Time Zone) but ofcourse when I upload it to my hosting server (USA), `DateTime.Now` does not represent the correct time zone. Therefore, in my code, **how can I convert `DateTime.Now` to correctly return the time from a GMT + 1 timezone** ?
Use the TimeZoneInfo class found in System.Core; You must set the DateTimeKind to DateTimeKind.Utc for this. ``` DateTime MyTime = new DateTime(1990, 12, 02, 19, 31, 30, DateTimeKind.Utc); DateTime MyTimeInWesternEurope = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(MyTime, "W. Europe Standard Time"); ``` Only if you're using .Net 3.5 though!
It depends on what you mean by "a GMT + 1 timezone". Do you mean permanently UTC+1, or do you mean UTC+1 or UTC+2 depending on DST? If you're using .NET 3.5, use [`TimeZoneInfo`](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx) to get an appropriate time zone, then use: ``` // Store this statically somewhere TimeZoneInfo maltaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("..."); DateTime utc = DateTime.UtcNow; DateTime malta = TimeZoneInfo.ConvertTimeFromUtc(utc, maltaTimeZone ); ``` You'll need to work out the system ID for the Malta time zone, but you can do that easily by running this code locally: ``` Console.WriteLine(TimeZoneInfo.Local.Id); ``` --- Judging by your comments, this bit will be irrelevant, but just for others... If you're **not** using .NET 3.5, you'll need to work out the daylight savings yourself. To be honest, the *easiest* way to do that is going to be a simple lookup table. Work out the DST changes for the next few years, then write a simple method to return the offset at a particular UTC time with that list hardcoded. You might just want a sorted `List<DateTime>` with the known changes in, and alternate between 1 and 2 hours until your date is after the last change: ``` // Be very careful when building this list, and make sure they're UTC times! private static readonly IEnumerable<DateTime> DstChanges = ...; static DateTime ConvertToLocalTime(DateTime utc) { int hours = 1; // Or 2, depending on the first entry in your list foreach (DateTime dstChange in DstChanges) { if (utc < dstChange) { return DateTime.SpecifyKind(utc.AddHours(hours), DateTimeKind.Local); } hours = 3 - hours; // Alternate between 1 and 2 } throw new ArgumentOutOfRangeException("I don't have enough DST data!"); } ```
C#: Making sure DateTime.Now returns a GMT + 1 time
[ "", "c#", "datetime", "timezone", "" ]
Imagine I have this code: ``` var myFunc1 = function(event) { alert(1); } var myFunc2 = function(event) { alert(2); } element.addEventListener('click', myFunc1); element.addEventListener('click', myFunc2); ``` When the click event is fired myFunc1 is called, then myFunc2. But how do I (if at all possible) stop myFunc2 from being called if some condition in myFunc1 is met? `event.stopPropagation()` is not the solution, as this is not an event capturing/bubbling problem. Thanks.
There's a further problem: the order that event listeners are executed is undefined. You'll need to handle event dispatch on your own to get around this, which leads us to some variant of llimllib's suggestion. ``` function dispatchSleightEvent(evt) { var listeners = evt.currentTarget.sleightListeners[evt.type]; // can't use for-in because enumeration order is implementation dependent for (var i=0; i<listeners.length; ++i) { if (listeners[i]) { if (! listeners[i].call(evt.currentTarget, evt)) { return false; } } } return true; } function mixinSleightTarget(obj) { if (! obj.sleightListeners) { obj.sleightListeners = {} obj.addSleightListener = function(type, listener) { if (!this.sleightListeners[type]) { this.sleightListeners[type] = []; this.addEventListener(type, dispatchSleightEvent); } if (!this.sleightListeners[type+listener] { this.sleightListeners[type+listener] = this.sleightListeners[type].length; this.sleightListeners[type].push(listener); } } obj.removeSleightListener = function(type, listener) { if (this.sleightListeners[type+listener] { delete this.sleightListeners[type][this.sleightListeners[type+listener]]; delete this.sleightListeners[type+listener]; } } } } ``` This code is completely untested. To stop event dispatch while on a single target, an event listener returns `false`. If you want more data hiding, you can rewrite the above from a functional programming standpoint, though this might introduce memory leaks.
The DOM Level 3 method [`event.stopImmediatePropagation`](http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-Event-stopImmediatePropagation) is exactly what I need here. ~~Unfortunately, it's not currently implemented in any browser (that I know of)~~.
JavaScript, stop additional event listeners
[ "", "javascript", "events", "" ]
How can I set a string to "" when using an auto-implemented property like: ``` public string Blah {get; set;} ```
You indicated that you are "using it for a strongly typed view, so I don't have a constructor for it even". If you don't have access to a constructor, it sounds like maybe you shouldn't use an auto-implemented property.
When you use an [automatic property](http://msdn.microsoft.com/en-us/library/bb384054.aspx) like this, the default value for the property type is the value, unless you initialize it elsewhere, like in the constructor: ``` public class Person { public string Name { get; set; } public Person() { Name = string.Empty; } } ``` However, if your automatic property has a public setter (as shown above), then you're still open to someone else setting Name to `null`, which may cause you some problems. I can see two solutions, depending on your context. First, change your automatic property to a private setter: ``` public class Person { public string Name { get; private set; } public Person() { Name = string.Empty; } } ``` This prevents anyone else from changing the property at all. If this isn't convenient, you could use a full property instead, and leverage the [`??`](http://msdn.microsoft.com/en-us/library/ms173224.aspx) ([null-coalescing](http://msdn.microsoft.com/en-us/library/ms173224.aspx)) operator to prevent nulls: ``` public class Person { public string Name { get { return mName; } set { mName = value ?? string.empty; } } public Person() { Name = string.Empty; } private string mName; } ```
How to initialize a string to "" when using auto-implemented property
[ "", "c#", "" ]
I am currently working through this tutorial: [Getting Started with jQuery](http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery) For the two examples below: ``` $("#orderedlist").find("li").each(function (i) { $(this).append(" BAM! " + i); }); $("#reset").click(function () { $("form").each(function () { this.reset(); }); }); ``` Notice in the first example, we use `$(this)` to append some text inside of each `li` element. In the second example we use `this` directly when resetting the form. `$(this)` seems to be used a lot more often than `this`. My guess is in the first example, `$()` is converting each `li` element into a jQuery object which understands the `append()` function whereas in the second example `reset()` can be called directly on the form. Basically we need `$()` for special jQuery-only functions. Is this correct?
Yes you only need `$()` when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind. ``` $(this)[0] === this ``` Basically every time you get a set of elements back jQuery turns it into a [jQuery object](https://learn.jquery.com/using-jquery-core/jquery-object/). If you know you only have one result, it's going to be in the first element. ``` $("#myDiv")[0] === document.getElementById("myDiv"); ``` And so on...
`$()` is the jQuery constructor function. `this` is a reference to the DOM element of invocation. So basically, in `$(this)`, you are just passing the `this` in `$()` as a parameter so that you could call jQuery methods and functions.
What's the difference between '$(this)' and 'this'?
[ "", "javascript", "jquery", "this", "" ]
What is the best rewrite of this method to speed it up? ``` public static bool EndsWith(string line, string term) { bool rb = false; int lengthOfTerm = term.Length; string endOfString = StringHelpers.RightString(line, lengthOfTerm); if (StringHelpers.AreEqual(term, endOfString)) { return true; } else { rb = false; } if (line == term) { rb = true; } return rb; } ```
Maybe I am missing the point completely, but I would spontaneously go for the [`String.EndsWith`](http://msdn.microsoft.com/en-us/library/system.string.endswith.aspx) method.
You may want to drop the method rather than rewrite it... ``` public static bool EndsWith(string line, string term) { return line.EndsWith(term); } ```
What is the fastest way to find out if a string ends with another string?
[ "", "c#", ".net", "string", "" ]
I'm moving my site from an oscommerce store to a commercial application. The new application stores its passwords using straight MD5 encryption. Oscommerce stores the password using MD5, but also adds a random 2 digit number (provided in plaintext) to the hash. Here is what someone posted on a forum: > The two characters added are for creating the hash in such way that > hash=md5(twocharactersPlainPassword) > ie: 2letters: 74 > Plain Password: PaSs > hash=md5('74PaSs')=acaa6e689ae0008285320e6617ca8e95:74 --- Here is the code how Oscommerce encrypts the password: ``` // This function makes a new password from a plaintext password. function tep_encrypt_password($plain) { $password = ''; for ($i=0; $i<10; $i++) { $password .= tep_rand(); } $salt = substr(md5($password), 0, 2); $password = md5($salt . $plain) . ':' . $salt; return $password; } // This funstion validates a plain text password with an encrypted password function tep_validate_password($plain, $encrypted) { if (tep_not_null($plain) && tep_not_null($encrypted)) { // split apart the hash / salt $stack = explode(':', $encrypted); if (sizeof($stack) != 2) { return false; } if (md5($stack[1] . $plain) == $stack[0]) { return true; } } return false; } ``` --- Here is how my new cart encrypts the password: ``` if ($admin_password_encrypt == 1) { $password_match = md5($password); } else { $password_match = $password; } ``` --- Is there any possible way of importing customer passwords from my oscommerce cart to my new cart.
Do not save plain MD5 hashes in your database. Plain MD5 hashes can be reverse engineered quickly and easily using rainbow tables. However, here's how you solve your problem, no matter how you choose to store the passwords in the future: 1. Create a column in your new database that specifies the "version" of the password. This is used to determine if the password was generated by the old application or the new one. 2. Import the old users, setting the aforementioned flag to indicate the password is imported. 3. Create two methods for validating a password. One method uses the code from your old application, the other uses your new validation method. 4. When a user is logging in, check the aforementioned flag and use the appropriate validation method. Anyways, I want to reiterate that plain MD5 hashes are easy to crack for most passwords (since people like short and easy to remember passwords.) Use a salt and/or a more complex algorithm. I'd recommend both, and use a salt that is longer than two characters and not limited to numbers. This will make the passwords really secure.
It appears that you have the source code for your new cart. Since "straight MD5" is a terribly awful way of storing passwords, perhaps you should simply change the to use the same password storage mechanism as OSCommerce. The answer to your question is no, there is no way of converting the passwords.
Importing MD5+Salt Passwords to MD5
[ "", "php", "import", "passwords", "md5", "oscommerce", "" ]
If views are used to show selected columns to the user, and same can be done by using ``` SELECT col1, col2 FROM xyz ``` , what is the point of using views?
All answers above provide an excellent explanation for the difference between a view and a query. The query in the question is simple to an extreme degree, and creating a view for it might be overkill. However, most queries are more complex, for example: ``` ;with Orders2016 as ( select Customers.CustomerID , Customers.CompanyName , TotalOrderAmount = sum(OD.Quantity * OD.UnitPrice) from Customers join Orders O on Customers.CustomerID = O.CustomerID join OrderDetails OD on O.OrderID = OD.OrderID where OrderDate >= '2016-01-01' and OrderDate < '2017-01-01' group by Customers.CustomerID, Customers.CompanyName ) , CustomersGroups as ( select CustomerID , CompanyName , TotalOrderAmount , CustomerGroup = ( case when TotalOrderAmount >= 0 and TotalOrderAmount < 1000 then 'low' when TotalOrderAmount >= 1000 and TotalOrderAmount < 5000 then 'Medium' when TotalOrderAmount >= 5000 and TotalOrderAmount < 10000 then 'High' when TotalOrderAmount >= 10000 then 'VeryHigh' end ) from Orders2016 ) select CustomerGroup , TotalInGroup = Count(*) , PercentageInGroup = Count(*) * 1.0 / (select count(*) from CustomersGroups) from CustomersGroups group by CustomerGroup order by TotalInGroup desc; ``` Imagine rewriting it each time you want to access data. (Or even searching through files, copy & paste). Poor time management. Views also save us tons of time and are a way to be DRY.
* Using a view saves you copying and pasting your queries and adds code reusability, so you can change a single view instead of `10` queries in the different places of your code. * Different permissions can be granted on views and tables, so that you can show only a portion of data to a user * A view can be materialized, which means caching the results of the underlying query
Difference between views and SELECT queries
[ "", "sql", "view", "" ]
I'm looking for a Java library which can notify me about changes on the file system. I found some free libraries, but they all use brute-force detection, i.e. polling in regular intervals. And the other ones are always commercial. What I'm looking for is a library which uses the file monitor functions from the OS, i.e. [FindFirstChangeNotification](http://msdn.microsoft.com/en-us/library/aa364417(VS.85).aspx) for Win32, [FAM](http://wiki.linuxquestions.org/wiki/FAM) for Linux and whatever is available on other OS. I don't mind if brute-force is used as fallback, but for Windows and Linux it should use the available OS features.
[JNotify](http://jnotify.sourceforge.net/) seems to do what you require. Polling a filesystem (say, a directory for update time changes) won't impose a significant load on your system, and shouldn't be discounted. Apps like Tomcat etc. use this for managing hot deploys with few problems. It's not a lot of help now, but the upcoming Java 7 has a [WatchService](http://docs.oracle.com/javase/tutorial/essential/io/notification.html) precisely for this.
If you are comfortable working on the bleeding edge of Java, have a look at [JSR 203: More New I/O APIs](http://jcp.org/en/jsr/detail?id=203) aka nio2 which is due out in **Java 7**. > A new filesystem interface that > supports bulk access to file > attributes, **change notification**, > escape to filesystem-specific APIs, > and a service-provider interface for > pluggable filesystem implementations;
Is there a sophisticated file system monitor for Java which is freeware or open source?
[ "", "java", "file-monitoring", "" ]
This is a two-part question: First, I am interested to know what the best way to remove repeating elements from a collection is. The way I have been doing it up until now is to simply convert the collection into a set. I know sets cannot have repeating elements so it just handles it for me. Is this an efficient solution? Would it be better/more idiomatic/faster to loop and remove repeats? Does it matter? My second (related) question is: What is the best way to convert an array to a Set? Assuming an array arr The way I have been doing it is the following: `Set x = new HashSet(Arrays.asList(arr));` This converts the array into a list, and then into a set. Seems to be kinda roundabout. Is there a better/more idiomatic/more efficient way to do this than the double conversion way? Thanks!
1. Do you have any information about the collection, like say it is already sorted, or it contains mostly duplicates or mostly unique items? With just an arbitrary collection I think converting it to a `Set` is fine. 2. `Arrays.asList()` doesn't create a brand new list. It actually just returns a `List` which uses the array as its backing store, so it's a cheap operation. So your way of making a `Set` from an array is how I'd do it, too.
Use `HashSet`'s standard `Collection` [conversion constructor](http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html#HashSet(java.util.Collection)). According to [The Java Tutorials](http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html): > Here's a simple but useful Set idiom. > Suppose you have a Collection, c, and > you want to create another Collection > containing the same elements but with > all duplicates eliminated. The > following one-liner does the trick. > > ``` > Collection<Type> noDups = new HashSet<Type>(c); > ``` > > It works by creating a Set (which, by > definition, cannot contain a > duplicate), initially containing all > the elements in c. It uses the > standard conversion constructor > described in the [The Collection > Interface](http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html) section. > > Here is a minor variant of this idiom > that preserves the order of the > original collection while removing > duplicate element. > > ``` > Collection<Type> noDups = new LinkedHashSet<Type>(c); > ``` > > The following is a generic method that > encapsulates the preceding idiom, > returning a Set of the same generic > type as the one passed. > > ``` > public static <E> Set<E> removeDups(Collection<E> c) { > return new LinkedHashSet<E>(c); > } > ```
Best way to remove repeats in a collection in Java?
[ "", "java", "arrays", "set", "" ]
i need to implement a genetic algorithm customized for my problem (college project), and the first version had it coded as an matrix of short ( bits per chromosome x size of population). That was a bad design, since i am declaring a short but only using the "0" and "1" values... but it was just a prototype and it worked as intended, and now it is time for me to develop a new, improved version. Performance is important here, but simplicity is also appreciated. I researched around and came up with: for the chromosome : - String class (like "0100100010") - Array of bool - Vector (vectors appears to be optimized for bool) - Bitset (sounds the most natural one) and for the population: - C Array[] - Vector - Queue I am inclined to pick vector for chromossome and array for pop, but i would like the opinion of anyone with experience on the subject. Thanks in advance!
I'm guessing you want random access to the population and to the genes. You say performance is important, which I interpret as execution speed. So you're probably best off using a `vector<>` for the chromosomes and a `vector<char>` for the genes. The reason for `vector<char>` is that `bitset<>` and `vector<bool>` are optimized for memory consumption, and are therefore slow. `vector<char>` will give you higher speed at the cost of x8 memory (assuming `char` = byte on your system). So if you want speed, go with `vector<char>`. If memory consumption is paramount, then use `vector<bool>` or `bitset<>`. `bitset<>` would seem like a natural choice here, however, bear in mind that it is templated on the number of bits, which means that a) the number of genes must be fixed and known at compile time (which I would guess is a big no-no), and b) if you use different sizes, you end up with one copy per `bitset` size of each of the `bitset` methods you use (though inlining might negate this), i.e., code bloat. Overall, I would guess `vector<bool>` is better for you if you don't want `vector<char>`. If you're concerned about the aesthetics of `vector<char>` you could `typedef char gene;` and then use `vector<gene>`, which looks more natural. A `string` is just like a `vector<char>` but more cumbersome.
Specifically to answer your question. I am not exactly sure what you are suggestion. You talk about Array and string class. Are you talking about the STL container classes where you can have a queue, bitset, vector, linked list etc. I would suggest a vector for you population (closest thing to a C array there is) and a bitset for you chromosome if you are worried about memory capacity. Else as you are already using a vector of your string representaion of your dna. ("10110110") For ideas and a good tool to dabble. Recommend you download and initially use this library. It works with the major compilers. Works on unix variants. Has all the source code. All the framework stuff is done for you and you will learn a lot. Later on you could write your own code from scratch or inherit from these classes. You can also use them in commercial code if you want. Because they are objects you can change representaion of your DNA easily from integers to reals to structures to trees to bit arrays etc etc. There is always learning cure involved but it is worth it. I use it to generate thousands of neural nets then weed them out with a simple fitness function then run them for real. galib <http://lancet.mit.edu/ga/>
Best Data Structure for Genetic Algorithm in C++?
[ "", "c++", "data-structures", "artificial-intelligence", "genetic-algorithm", "" ]
I was forced into a software project at work a few years ago, and was forced to learn C# quickly. My programming background is weak (Classic ASP). I've learned quite a bit over the years, but due to the forced nature of how I learned C#, there are a lot of basic concepts I am unclear on. Specifically, an interface. I understand the basics, but when writing an app, I'm having a hard time figuring out a practical use of one. Why would one want to write an interface for their application? Thanks Kevin
An interface says how something should work. Think of it as a contract or a template. It is key to things such as Inverson of Control or Dependancy Injection. I use Structure Map as my IoC container. This allows me to define an interface for all of my classes. Where you might say ``` Widget w = new Widget(); ``` I would say ``` IWidget w = ObjectFactory.GetInstance<IWidget>(); ``` This is very powerful in that my code isn't saying necessarily what a Widget truely is. It just knows what a Widget can do based on the interface of IWidget. This has some great power to it in that now that I am using an IoC container I can do a couple more nifty things. In my unit tests where I need to use a Widget I can create a mock for Widget. So say that my Widget does something very powerful by way of connecting to a database or a web service, my mock can simulate connecting to these resources and return to me stubbed data. This makes my test run faster and behave in a way that is more reliable. Because I am using StructureMap I can tell StructureMap to load the real implementation of my Widget during production use of my code and the mocked version of the Widget during testing either programatically or by configuration. Also, because I am using an IoC container I can provide cool new features to my application such as writing three different ways to cache data. I can have a local developer box cache using a tool such as Lucene.NET for a local cache. I can have a development server use the .NET cache which runs great on one box. And then I can have a third option for my production servers use a cache layer such as MemCache Win32 or Velocity. As long as all three caching implementations conform to the same interface, their actual implementation doesn't concern me (or my code) at all. I simply ask StructureMap to go get the current environments implementation and then go to work. If you follow Dependency Injection at all then interfaces come in handy here also with an IoC container such as StructureMap in that I can declare the usage of a class by way of an Interface in the constructor of my class. ``` public class Widget(IWidgetRepository repository, IWidgetService service) : IWidget { //do something here using my repository and service } ``` And then when I new up an instance of Widget by way of StructureMap such as this ``` IWidget widget = ObjectFactory.GetInstance<IWidget>(); ``` Notice that I am not specifying the repository or service in the constructor. StructureMap knows by way of the interfaces specified in the constructor how to go get the appropriate instances and pass them in too. This makes very powerful and clean code! All from the simple definition of Interfaces and some clever usage of them!
The basic case is the "IWriter" case. Suppose you are making a class that can write to the console, and it has all kinds of useful functions like write() and peek(). Then you would like to write a class that can write to the printer, so instead of reinventing a new class, you use the IWriter interface. Now the cool thing about interfaces is you can write all your writing code, without knowing what is your writing target beforehand, and then can when the user decides (at runtime) weather he wants to write to the console or the printer, you just define the object as a console/printer writer and you don't need to change anything in your writing code, because they both use the same front end (interface).
What are some advantages to using an interface in C#?
[ "", "c#", "oop", "interface", "design-patterns", "" ]
Is there a way to convert an integer to a string in PHP?
You can use the [`strval()`](http://php.net/manual/en/function.strval.php) function to convert a number to a string. From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context. ``` $var = 5; // Inline variable parsing echo "I'd like {$var} waffles"; // = I'd like 5 waffles // String concatenation echo "I'd like ".$var." waffles"; // I'd like 5 waffles // The two examples above have the same end value... // ... And so do the two below // Explicit cast $items = (string)$var; // $items === "5"; // Function call $items = strval($var); // $items === "5"; ```
There's many ways to do this. Two examples: ``` $str = (string) $int; $str = "$int"; ``` See the PHP Manual on [Types Juggling](http://www.php.net/manual/en/language.types.string.php#language.types.string.casting) for more.
Converting an integer to a string in PHP
[ "", "php", "string", "casting", "type-conversion", "integer", "" ]
I have an IEnumerable<DirectoryInfo> that I want to filter down using an array of regular expressions to find the potential matches. I've been trying to join my directory and regex strings using linq, but can't seem to get it right. Here's what I'm trying to do... ``` string[] regexStrings = ... // some regex match code here. // get all of the directories below some root that match my initial criteria. var directories = from d in root.GetDirectories("*", SearchOption.AllDirectories) where (d.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0 && (d.GetDirectories().Where(dd => (dd.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0).Count() > 0// has directories || d.GetFiles().Where(ff => (ff.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0).Count() > 0) // has files) select d; // filter the list of all directories based on the strings in the regex array var filteredDirs = from d in directories join s in regexStrings on Regex.IsMatch(d.FullName, s) // compiler doesn't like this line select d; ``` ... any suggestions on how I can get this to work?
If you only want directories that match all regular expressions. ``` var result = directories .Where(d => regexStrings.All(s => Regex.IsMatch(d.FullName, s))); ``` If you only want directories that match at least one regular expressions. ``` var result = directories .Where(d => regexStrings.Any(s => Regex.IsMatch(d.FullName, s))); ```
I don't think that the approach you're taking is exactly what you want anyhow. That will check the name against ALL regex strings, rather than short circuiting on the first match. Additionally, it would duplicate the directories if one matched more than one pattern. I think you want something like: ``` string[] regexStrings = ... // some regex match code here. // get all of the directories below some root that match my initial criteria. var directories = from d in root.GetDirectories("*", SearchOption.AllDirectories) where (d.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0 && (d.GetDirectories().Where(dd => (dd.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0).Count() > 0// has directories || d.GetFiles().Where(ff => (ff.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0).Count() > 0) // has files) select d; // filter the list of all directories based on the strings in the regex array var filteredDirs = directories.Where(d => { foreach (string pattern in regexStrings) { if (System.Text.RegularExpressions.Regex.IsMatch(d.FullName, pattern)) { return true; } } return false; }); ```
Find matched directories using a list of regular expressions
[ "", "c#", "regex", "linq", "directoryinfo", "" ]
I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?
I'm not an Eclipse expert, but since you didn't get any other answer... If you make the SCons source a part of the Eclipse project, and run the whole command from within Eclipse it should work like any Eclipse debugging. SCons is written in Python, there is no reason it shouldn't be debuggable in Eclipse just like anything else.
You are right. Since the SCons is python based, the SCons scripts are debuggable via EClipse PyDev. For this, you need to do the following in the debug configuration...- 1. Under the main tab, set the main module to the SCons file which will be available under the python/scripts directory if you have installed SCons. If you have not run the install of SCons you can point to this file under the SCons directory.- 2. Under the arguments tab, set the working directory to the root of your project. Now set the breakpoint either on SConstruct or SConcript and run in debug mode. That's all!! With this approach you can not only debug your product code but also the build scripts that builds your product :-) Happy Debugging!!!!
How to debug SCons scripts using eclipse and pydev?
[ "", "python", "eclipse", "pydev", "scons", "" ]
I'm executing the java binary from one of my classes, and a ClassNotFoundException gets thrown: ``` Results of executing:/usr/bin/java -classpath "/home/geo" Geoline Error stream: Exception in thread "main" java.lang.NoClassDefFoundError: Geoline Caused by: java.lang.ClassNotFoundException: Geoline at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:323) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:268) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:336) Could not find the main class: Geoline. Program will exit. Output stream: ``` The Geoline class is located at /home/geo/Geoline.java. The thing is, no matter where in the filesystem I'm located, if I execute the same command manually, the class is executed. Why isn't the same thing happening when the binary is executed with **Runtime.getRuntime().exec**? **edit:** here's the output generated with the verbose flag on: [pastie link](http://pastie.org/533605) **edit:** here's the contents of the file : ``` public class Geoline { public static void main(String[] args) { System.out.println("blabla"); } } ```
It is quite hard to tell what's going on because you didn't post the code. However this is my most educated guess. You're trying to run the whole command into a java **String** and the java interpreter is not recognizing them as different arguments. Try packaging them all in a **String[]** So instead of ``` Runtime.getRuntime().execute("/usr/bin/java -classpath \"/home/geo\" Geoline"); ``` Try with: ``` Runtime.getRuntime().execute( new String[]{ "/usr/bin/java","-classpath","/home/geo","Geoline" }); ``` Or, you could post your actual code and we can see what's going on. **EDIT** This is my attempt. I create the **RunIt.java** class which is basically *Runtime.exec* as I suggested and **Hello.java** which pretty much says **Hello + args[0]** Here's the ouput: ``` $cat RunIt.java import java.io.*; public class RunIt{ public static void main( String [] args ) throws IOException { Process p = Runtime.getRuntime().exec( args ); BufferedReader reader = new BufferedReader( new InputStreamReader ( p.getInputStream() ) ); String line = null; while( ( line = reader.readLine() ) != null ) { System.out.println( line ); } reader.close(); } } $cat Hello.java public class Hello { public static void main( String [] args ) { System.out.println("Hola: " + ( args.length > 0 ? args[0] : " a nadie" ) ); } } $javac RunIt.java $java RunIt javac Hello.java $java RunIt java Hello Mundo Hola: Mundo $ ```
You might need to read this: [When Runtime.exec() won't](https://web.archive.org/web/20130307214351/http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)
I don't understand why this ClassNotFoundException gets thrown
[ "", "java", "exception", "" ]
My application needs to use a couple of **hard-coded symmetric cryptographic keys** (while I know that storing a public key would be the only perfect solution, this is non-negotiable). We want the keys to be stored **obfuscated**, so that they won't be recognizable by analyzing the executable, and be "live" in memory for as little time as possible - as to increase the difficulty of a memory dump retrieving them in clear-text. I'm interested in using **C++** features (using some sort of `scoped_key` comes to mind). The solution must be **portable** - Windows, Linux, MacOS -, so it cannot take advantage of the operating system crypto API. How would you go about designing such a system? Thanks a lot.
your `scoped_key` can be simply a `KeyHolder` object on the stack. Its constructor takes the obfuscated buffer and makes a real key out of it and its destructor zeros out the memory and deallocates the memory. As for how to actually obfuscate the key in the binary, One silly choice you might try is put inside a much larger random binary block and remember its offset and size and probably XOR it with some short random sequence. If you do the XORing thing you can actually avoid ever having the real key in memory. simply modify the decryption to read a byte from the key and before using it, to XOR it with the appropriate value. `*`Add here disclaimer on how foolish security through obscurity is`*`
All you're going for here is security through obscurity. If you have one of us come up with an idea, you won't even have that. [John Skeet has a good article on this too.](http://www.yoda.arachsys.com/csharp/obfuscation.html) Do something random is all I can say.
Cross-platform way of hiding cryptographic keys in C++?
[ "", "c++", "security", "cross-platform", "cryptography", "" ]
OK so I admit right off the top that this is a bit screwy … but it does serve a logical purpose. I’m using C# for a current project and I’m trying to find a way to override a member variable in a derived class, but access the overridden variable in a base class method. To make things more “entertaining” it would be preferable if the overridden member variable was static (this is NOT shown in the example code below). Here is my sample code: ``` class baseclass { protected string[] array = null; public string method() { string str = ""; foreach (string x in this.array) { str += x + " "; } return str; } } class subclass1 : baseclass { new string[] array = new string[] { "class1value1", "class1value2", "class1value3", "class1value4" }; } class subclass2 : baseclass { new string[] array = new string[] { "class2value1", "class2value2", "class2value3", "class2value4" }; } ``` Any thoughts as to why this doesn't work and a way to get around it?
Is there any reason you can't use a virtual property? That would provide exactly the functionality you are looking for. It just wouldn't be a field. ``` protected abstract string[] array { get; } ``` ... ``` protected override string[] array { get { return new string[]{"...","..."}; }} ```
Why do you need to override the variable? Looking from your code, just setting the values would be enough, no? Plus, static variables are tied to the class (not the instance), therefore it's not overridable on any situation.
C# Member variable overrides used by base class method
[ "", "c#", "overriding", "" ]
Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)? There are functions like these: * `scipy.signal.correlate2d` - "the direct method implemented by `convolveND` will be slow for large data" * `scipy.ndimage.correlate` - "The array is correlated with the given kernel using exact calculation (i.e. not FFT)." * `scipy.fftpack.convolve.convolve`, which I don't really understand, but seems wrong numarray had a [`correlate2d()` function with an `fft=True` switch](http://structure.usc.edu/numarray/node61.html), but I guess numarray was folded into numpy, and I can't find if this function was included.
I found `scipy.signal.fftconvolve`, [as also pointed out by magnus](https://stackoverflow.com/a/1477259/125507), but didn't realize at the time that it's *n*-dimensional. Since it's built-in and produces the right values, it seems like the ideal solution. From [Example of 2D Convolution](http://www.songho.ca/dsp/convolution/convolution2d_example.html): ``` In [1]: a = asarray([[ 1, 2, 3], ...: [ 4, 5, 6], ...: [ 7, 8, 9]]) In [2]: b = asarray([[-1,-2,-1], ...: [ 0, 0, 0], ...: [ 1, 2, 1]]) In [3]: scipy.signal.fftconvolve(a, b, mode = 'same') Out[3]: array([[-13., -20., -17.], [-18., -24., -18.], [ 13., 20., 17.]]) ``` Correct! The STSCI version, on the other hand, requires some extra work to make the boundaries correct? ``` In [4]: stsci.convolve2d(a, b, fft = True) Out[4]: array([[-12., -12., -12.], [-24., -24., -24.], [-12., -12., -12.]]) ``` (The STSCI method also requires compiling, which I was unsuccessful with (I just commented out the non-python parts), has some bugs like [this](http://projects.scipy.org/scipy/ticket/973) and modifying the inputs ([1, 2] becomes [[1, 2]]), etc. So I changed my accepted answer to the built-in `fftconvolve()` function.) Correlation, of course, is the same thing as convolution, but with one input reversed: ``` In [5]: a Out[5]: array([[3, 0, 0], [2, 0, 0], [1, 0, 0]]) In [6]: b Out[6]: array([[3, 2, 1], [0, 0, 0], [0, 0, 0]]) In [7]: scipy.signal.fftconvolve(a, b[::-1, ::-1]) Out[7]: array([[ 0., -0., 0., 0., 0.], [ 0., -0., 0., 0., 0.], [ 3., 6., 9., 0., 0.], [ 2., 4., 6., 0., 0.], [ 1., 2., 3., 0., 0.]]) In [8]: scipy.signal.correlate2d(a, b) Out[8]: array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [3, 6, 9, 0, 0], [2, 4, 6, 0, 0], [1, 2, 3, 0, 0]]) ``` and [the latest revision](http://projects.scipy.org/scipy/browser/trunk/scipy/signal/signaltools.py?rev=5968) has been sped up by using power-of-two sizes internally (and then I sped it up more by [using real FFT for real input](https://github.com/scipy/scipy/pull/337) and [using 5-smooth lengths instead of powers of 2](https://github.com/scipy/scipy/pull/3144) :D ).
look at scipy.signal.fftconvolve, signal.convolve and signal.correlate (there is a signal.correlate2d but it seems to return an shifted array, not centered).
FFT-based 2D convolution and correlation in Python
[ "", "python", "image", "numpy", "signal-processing", "fft", "" ]
a few minutes ago I had a discussion with my boss and want now more meanings, if I am wrong or he is. Following problem is given: After a fast change from a colleague a stored procedure went wrong. (I think for the theory here is no more information requiered) We decide to provide the correct version in an Update Script: IF EXIST PROCEDURE X .... DROP PROCEDURE X .... CREATE PROCEDURE X .... For the DBO that the correcture will be execute, we must (should) prepare an rollback mechanism. My Boss comes to me and ask me for preparing an rollback script. I tell him, that we don't have one: Because when the main script failed, there is no option. It went now completly wrong, we can't rollback to the wrong one. It's senseless. He told me, that we need it and it is not senseles.. When I asked for a reason, he goes away. I am wrong?
If this is a production server, where you wouldn't want downtime, you should have a rollback procedure. Even if that procedure is to just back the database up before the upgrade and restore from backup on failure. You also imply that 'create procedure' will either work or not. This is true, but it doesn't mean the procedure will actually work. You can create a stored procedure (at least on SQL Server) that references a table that doesn't exist, and it will compile just fine.
There is some logic to what you're saying, but I could agree with your boss if the argument is tantamount to saying "we don't need to back up code that isn't working" It's still somebody's expensive hours put into that, and the flaw may be a minor one. If it is conceivable that further updates could somehow make things even more wrong, then it is reasonable to request the ability to roll back to the less broken state.
Who is right? - SQL Rollback Question
[ "", "sql", "rollback", "" ]
I have a C++ array declared as mentioned below: ``` CString carray[] = { "A", "B", "C", "D", "E" } ``` I want to determine the length of `carray` at runtime. I am doing: ``` int iLength = sizeof(carray)/sizeof(CString); ``` Is this correct?
Yes. In case the declared element type ever changes, you could also write ``` int iLength = sizeof(carray)/sizeof(carray[0]); ```
You can use the following function template. If you're using Boost, you can call [`boost::size`](http://www.boost.org/doc/libs/1_39_0/libs/range/doc/boost_range.html). ``` template <typename T, std::size_t N> std::size_t size(T (&)[N]) { return N; } int iLength = size(carray); ``` As others have already stated, however, you should prefer `std::vector` to C-style arrays.
Computing length of array
[ "", "c++", "arrays", "" ]
I'm going nuts trying to get a simple [Envers](http://www.jboss.org/files/envers/docs/index.html) example to work. I'm stuck on the `org.hibernate.tool.ant.EnversHibernateToolTask` — it looks like I finally got all the jar files I needed, but now I get the error message ``` [hibernatetool] Persistence unit not found: 'ConsolePU'. BUILD FAILED C:\deka\proj\java\test-database\build.xml:61: Persistence unit not found: 'ConsolePU'. ``` As far as I can tell, persistence units are associated with JPA `persistence.xml` files. But I'm not using a persistence.xml file; I'm using hibernate.cfg.xml — but the envers example has a `<jpaconfiguration>` in the ant task: ``` <hibernatetool destdir="."> <classpath> <fileset dir="src/"> <include name="**/*.hbm.xml"/> </fileset> <path location="${buildDir}" /> </classpath> <jpaconfiguration persistenceunit="ConsolePU" /> <hbm2ddl drop="false" create="true" export="false" outputfilename="versioning-ddl.sql" delimiter=";" format="true"/> </hibernatetool> ``` is there something that I can replace it with to get it to work with the hibernate.cfg.xml file? There seems to be ZERO documentation on how to get all this stuff to work properly. **edit:** OK, so the main problem was I didn't understand the hibernatetool options and what was appropriate for my app. I did find the [Hibernate ant docs](https://www.redhatrenewals.com/docs/en-US/JBoss_Developer_Studio/en/hibernatetools/html/ant.html), fortunately. Thanks. Now I have a new problem: I'm using annotations, but I also have set up a hibernate.cfg.xml for the properties settings. The `hibernatetool` task only lets me run either `<configuration />` or `<annotationconfiguration />` not both, and even `<configuration />` won't work since I already have annotations doing things. How can I migrate my property settings from the hibernate.cfg.xml file to my annotations? **edit:** Duh, I didn't realize you just do: ``` <annotationconfiguration configurationfile="...filename..." /> ``` per the [hibernatetool task docs.](https://www.redhatrenewals.com/docs/en-US/JBoss_Developer_Studio/en/hibernatetools/html/ant.html#d0e3018)
Replace the `<jpaconfiguration />` with the [`<configuration />`](http://docs.jboss.org/tools/nightly/trunk/en/hibernatetools/html_single/index.html#d0e4247) tag, as detailed in Hibernate Tools docs: ``` <configuration configurationfile="hibernate.cfg.xml" propertyfile="hibernate.properties" entityresolver="EntityResolver classname" namingstrategy="NamingStrategy classname"> ```
Just to give you high level prespective. JPA is standard persistence API provided by SUN. You can use any persistence framework like Hibernate,TopLink,JDO etc as persistence provider with JPA. So just to make things clear Your code -----> JPA ----->Persistence Provider(Hibernate). Its will be good practice to use JPA as it is standard library. So what is your persistence provider information should only be known to JPA and not your code specific XML's. This is how your persistence.xml will look like ``` <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="QuarkFrameworkPU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> </persistence-unit> ``` And your Application context will look like (Dependent on JPA , no mention of Hibernate) ``` <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="com.mysql.jdbc.Driver" p:url="${db.url}" /> <!-- ADD PERSISTENCE SUPPORT HERE (jpa,etc) --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="QuarkFrameworkPU" /> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> </bean> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="dataSource" ref="dataSource" /> </bean> ```
what the heck is a JPA configuration?
[ "", "java", "hibernate", "jpa", "ant", "hibernate-envers", "" ]
Unfortunately I haven't coded Java for about five years and I absolutely can not remember how or why the following code is working. I stumbled across a similar example and broke it down to this. The emphasis is on the part below the comment: I don't get the constructor notation followed by the block in double brackets. And unfortunately I can not find anything in the Java documentation or by using Google (what word(s) should I google?). ``` package syntaxtest; public class Main { public static void main(String[] args) { // What kind of notation is this? MyTest tester = new MyTest() {{ setName("John Johnson"); }}; System.out.println(tester.getName()); } } class MyTest { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` So here are my questions: 1. How is this notation/syntax called? 2. Where can I read some documentation about it? I guess/ hope I will be able to answer the second question by myself if somebody can provide me with the answer to the first question. To make it clear: I know the output is `John Johnson` ;) But I don't know why it is working.
This is known as [*double brace initialization*](http://www.c2.com/cgi/wiki?DoubleBraceInitialization): > The first brace creates a new > AnonymousInnerClass, the second > declares an instance initializer block > that is run when the anonymous inner > class is instantiated. This type of > initializer block is formally called > an "instance initializer", because it > is declared within the instance scope > of the class -- "static initializers" > are a related concept where the > keyword static is placed before the > brace that starts the block, and which > is executed at the class level as soon > as the classloader completes loading > the class (specified at > <http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6>) > The initializer block can use any > methods, fields and final variables > available in the containing scope, but > one has to be wary of the fact that > initializers are run before > constructors. > > This only works only for non-final > classes because it creates an > anonymous subclass.
Let's layout the code a bit differently: ``` MyTest tester = new MyTest() { { setName("John Johnson"); } }; ``` What you see here is called *double brace initialization*. You have an anonymous inner subclass of class `MyTest`, along with an initializer block, which is a block that contains code that is run when the object is constructed. Normally, you would put such code in the constructor, but since anonymous inner classes can't have constructors, this is the only way to guarantee the code is run when it's supposed to. Having said that, it's a bit ugly to do this. There are better ways. However, I do use it myself on occasion, usually in the following idiom to create an immutable map: ``` final Map<String, Integer> textToInt = Collections.unmodifiableMap(new HashMap<String, Integer>() {{ put("one", 1); put("two", 2); // etc }}); ``` Which creates a new map, overrides it, adds some values to it in the initializer block, and wraps it in an unmodifiable map.
What is this constructor call with following double braces?
[ "", "java", "syntax", "constructor", "anonymous-class", "" ]
Ok, so as the title says, I have an HTML page that I fetch using libcurl (cURL inside PHP). That page has one <form> that I need to extract the <input> names and values, and I would like to do that using Regex. I'm making it using Regex because I think that's the easier way. If you think I shouldn't use regex, but something like xpath, say how. I don't know if you can understand what I'm trying to say, so feel free to ask. Here's the PHP code (complete): ``` <?php /***** DISABLED BY NETWORK TRAFFIC REASONS... USING LOCAL CACHE $curl = curl_init(); $url = 'https://secure.optimus.pt/Particulares/Kanguru/Login/'; $useragent = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; pt-PT; rv:1.9.1) Gecko/20090624 Firefox/3.5'; curl_setopt($curl,CURLOPT_URL,$url); curl_setopt($curl,CURLOPT_USERAGENT,$useragent); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,true); curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,2); curl_setopt($curl,CURLOPT_CAINFO,getcwd()."\optimus_secure.crt"); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); $contents = curl_exec($curl); */ $contents = file_get_contents('local_secure.html'); preg_match('%<form name="aspnetForm" .*? action="(.*?)" .*?>(.*?)</form>%s',$contents,$matches); //echo '<pre>'.htmlentities($contents).'</pre>'; //array_shift($matches); echo '<pre>---------'; foreach($matches as $match) echo '$match:::::: '.htmlentities($match)."\r\n\r\n"; echo '</pre>'; echo '<pre>__________'; preg_match_all('/<input type=".*?" name="(.*?)" value="(.*?)" \/>/', $matches[0], $matches2); print_r($matches2); echo '</pre>'; ?> ``` Of course that the <pre> tags and all that output is just for debugging. Also, here's the source code of the HTML page (the part that matters): ``` <form name="aspnetForm" method="post" action="../Login?OptimusChannelID=D5774383-A407-42E9-A0AD-4838C97AB162&amp;OptimusContentID=&amp;OptimusSelectedSiteID=B33E7D52-8738-4756-A25D-B907D1823B71&amp;OptimusSelectedAreaID=AF8E0BDF-17E3-4438-9FA9-D53A13A508D8&amp;OptimusSelectedLocalID=D5774383-A407-42E9-A0AD-4838C97AB162" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm"> <div> <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTc4MzE4NTQyNQ9kFgJmD2QWBgIID2QWAgIBD2QWBGYPZBYCAgMPDxYEHhRWYWxpZGF0aW9uRXhwcmVzc2lvbgUCLioeB0VuYWJsZWRoZGQCAQ9kFgICBQ8PFgIeBFRleHQFKk8gY2FtcG8gRW1haWwgJmVhY3V0ZTsgb2JyaWdhdCZvYWN1dGU7cmlvIWRkAgkPZBYCAgEPFgIfAmVkAgoPDxYCHgdWaXNpYmxlaGRkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBSVjdGwwMCRNYWluQ29udGVudFBsYWNlSG9sZGVyJEltZ0xvZ2luBSxjdGwwMCRNYWluQ29udGVudFBsYWNlSG9sZGVyJGltZ0J0blJlY3VwZXJhcorZDETv8JCxlvTojv3w53/dbo9m" /> </div> <script type="text/javascript">....</script> <script src="..." type="text/javascript"></script> <script src="..." type="text/javascript"></script> <script type="text/javascript">...</script> <div class="row_container"> <div class="titulo_barra rosa laranja_empresas"> LOGIN<br/> </div> <div class="PanelLogin"> <div class="Mensagem"> <div class="texto"> Para aceder, por favor, fa&ccedil;a login. </div> </div> <div id="ctl00_MainContentPlaceHolder_PanelLogin" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'ctl00_MainContentPlaceHolder_ImgLogin')"> <div class="Mensagem"> <div> <label for="telem"> User<span id="ctl00_MainContentPlaceHolder_UsernameValidator" style="color:Red;display:none;"></span> </label> <input name="ctl00$MainContentPlaceHolder$TxtUsername" type="text" id="ctl00_MainContentPlaceHolder_TxtUsername" class="text" maxlength="255" /> <label style="padding-left: 10px" for="password"> Password <span id="ctl00_MainContentPlaceHolder_RequiredPasswordValidator" style="color:Red;display:none;"></span><span id="ctl00_MainContentPlaceHolder_UsernameRegexValidator" style="color:Red;display:none;"></span> </label> <input name="ctl00$MainContentPlaceHolder$TxtPassword" type="password" id="ctl00_MainContentPlaceHolder_TxtPassword" class="text" maxlength="5" /> <input type="hidden" name="fromssl" value="" /> <input type="image" name="ctl00$MainContentPlaceHolder$ImgLogin" id="ctl00_MainContentPlaceHolder_ImgLogin" src="/img/btn_password.gif" alt="Login" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContentPlaceHolder$ImgLogin&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" style="border-width:0px;position: absolute; padding-left: 5px " /><br /> </div> <div id="login_error_box"> <div id="ctl00_MainContentPlaceHolder_ValidationSummary1" class="error" style="color:#FF6000;display:none;"> </div> </div> </div> </div> </div> <div class="titulo_barra rosa laranja_empresas"> RECUPERA&Ccedil;&Atilde;O DE PASSWORD </div> <div class="PanelLogin"> <div class="Mensagem"> <div class="texto"> Para recuperar a sua password introduza o seu e-mail. Se pretender recuperar o seu username utilize o link abaixo </div> </div> <div id="ctl00_MainContentPlaceHolder_Panel1" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'ctl00_MainContentPlaceHolder_imgBtnRecuperar')"> <div class="Mensagem"> <div id="Div1"> <label for="telem"> Email</label> <input name="ctl00$MainContentPlaceHolder$txtEmailHabitual" type="text" id="ctl00_MainContentPlaceHolder_txtEmailHabitual" class="text" maxlength="255" /> <input type="image" name="ctl00$MainContentPlaceHolder$imgBtnRecuperar" id="ctl00_MainContentPlaceHolder_imgBtnRecuperar" class="img rosa azul_empresas" src="/img/bot_recuperar.gif" alt="Recuperar" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$MainContentPlaceHolder$imgBtnRecuperar&quot;, &quot;&quot;, true, &quot;email&quot;, &quot;&quot;, false, false))" style="border-width:0px;margin-top: -2px; position: absolute;" /> <br /> <span id="ctl00_MainContentPlaceHolder_EmailValidator" class="error" style="color:Red;display:none;">O campo Email &eacute; obrigat&oacute;rio!</span> <span id="ctl00_MainContentPlaceHolder_EmailRegularExpressionValidator" style="color:Red;display:none;"> Formato do Email inválido.</span> </div> <div class="Mensagem" CssClass="error" DisplayMode="SingleParagraph" ForeColor="#FF6000"> </div> <a id="ctl00_MainContentPlaceHolder_lnkRecuser" href="javascript:__doPostBack('ctl00$MainContentPlaceHolder$lnkRecuser','')"> <div align="left" style="color:#FF7000" class="footerButtonsOrange">Recuperar username</div> </a> </div> </div> </div> </div> <script type="text/javascript">...</script> <script type="text/javascript">...</script> <script type="text/javascript">...</script> <div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBwKQ08lZAqmxyPwLAvCnm8wMAt/Wt8sGAv2svvMEAtCB5oUIAr6ar9wLz+9apOkY23Vs+vCYNJuK2ug3Gm0=" /> </div> <script type="text/javascript">...</script> </form> ``` Also, sorry for the low readability of the source code. If you want, I can try to indent it better. Thank you, Pedro Cunha EDIT: Thank you all for your help. All the answers worked flawlessly, however I chose VolkerK's response, because since it is an HTML page, elements may be nested, and I know (of the few things that I know about XPath) that // is a wildcard.
> If you think I shouldn't use regex, but something like xpath, say how. That would be something like ``` <?php $doc = new DOMDocument; if ( !$doc->loadhtml($contents) ) { echo 'something went wrong'; } else { $xpath = new DOMXpath($doc); foreach($xpath->query('//form[@name="aspnetForm"]//input') as $eInput) { echo 'name=', $eInput->getAttribute('name'), ' value=', $eInput->getAttribute('value'), "\n"; } } ``` If you get annoying warning messages you might want to use @$doc->loadhtml($contents); maybe in conjuction with [libxml\_use\_internal\_errors](http://php.net/libxml_use_internal_errors)() and [libxml\_get\_errors](http://php.net/libxml_get_errors)()
How about this --> <http://simplehtmldom.sourceforge.net/> ``` * A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way! * Require PHP 5+. * Supports invalid HTML. * Find tags on an HTML page with selectors just like jQuery. * Extract contents from HTML in a single line. // Create DOM from URL or file $html = file_get_html('http://www.google.com/'); // Find all images foreach($html->find('img') as $element) echo $element->src . '<br>'; // Find all links foreach($html->find('a') as $element) echo $element->href . '<br>'; ``` Good luck.
Get HTML page <input> values and names using regex on PHP
[ "", "php", "regex", "xhtml", "input", "" ]
I'm having severe issues with Rails, Javascript, and redirects. Basically I have the "simple" issue of redirecting to a different page if JS is disabled. If JS is enabled, then I add a new item inline immediately -- this works like a charm. However, if JS is disabled I want to redirect to the NEW page of a different controller. Basically the model setup is as such: ``` Site -> Buildings -> Controllers (not to be confused with Rails "controllers") ``` I have a "SiteManagerController" that uses JS to manage the whole thing. Basically I have a scenario where I'm trying to do the following: 1) if JS is enabled I want to add the item inline 2) if JS is disabled, I wish to render ":controller => buildings, :action => new" My "link\_to\_remote" is straightforward. As I said, it works for JS. My rails controller code is as follows: def add\_building @building = Building.new @building.name = "Untitled" @building.site\_id = params[:id] @building.save respond\_to do |format| format.html {redirect\_to :controller => "buildings", :action => "new"} format.js end end This does not work. For what it's worth, when viewing page source there is no indication that anything is different when JS is enabled vs disabled. All links look the same -- i.e. Ajaxy. I know it shouldn't be this complex an issue, but I'm rather stumped. Best. P.S. Please don't change the title of this post. ;)
The link\_to\_remote solution mentioned would probably work, but if you're looking for an unobtrusive way to do it, you use some javascript (jQuery) like this: in your .html.erb file: ``` <%=link_to "New Building", new_building_path, :id => 'new_building_link' %> ``` in a javascript file: ``` $(document).load(function() { $("#new_building_link").click(function() { $.ajax({ type: "POST", # or whatever http method you need url: "/buildings/add_building", dataType: "script" }); return false; }); }); ``` Then return some JS that will update the area of the page you want to change. I'm sure there's a similar way to do it with Prototype, the default JS library for rails, but I don't know Prototype. Also note that this uses restful routes (new\_building\_path rather than specifying the controller and the action). This is the preferred method now; you'd just need to add 'map.resources :buildings' to routes.rb. There are a couple of Railscasts about restful routes, and if you have $9 to drop, a Peepcode. As one of the comments mentioned you could shrink your Building creation code by using: `Building.create({:name => "Untitled", :site_id => params[:id]})`
I believe the solution lies in the "link\_to\_remote" and not any particular controller. The following seems to work: ``` <div><%=link_to_remote "NEW BUILDING", {:url => {:action => "add_building", :id => site.id}}, {:href => url_for(:controller => "buildings",:action => "new")}%></div> ``` If you guys have better suggestions, by all means post. Thanks again.
(Ruby,Rails,Javascript) Redirecting/Rendering a different page when Javascript is disabled...?
[ "", "javascript", "ruby-on-rails", "redirect", "render", "" ]
The Java EE specification states that an EJB injection like this: ``` @EJB MyInterface myBean; ``` will create en entry in the Enterprise Naming Context, viz. `java:comp/env/<FQN>.MyInterface/myBean`. It is up to the deployer to bind this context entry to a real value and to inject this value in the myBean field. Now I have the feeling I am missing something here: Why is the context entry necessary? An instance of the requested EJB will be injected, so why is the entry in the context needed? Why does the injection has to happen via the context entry?
All the received answers did not address the issue: why is an ENC entry needed if the injection annotation gives enough information to resolve the injection (so my first thought was that it was redundant). The answer is that the injection can be overridden in the deployment descriptor. This is because the EJB standard defines developer roles. It assumes that the "bean provider" can request an injection, even provide default values. But the "application assembler" can override these values. The "bean provider" is assumed to use annotations or XML, and the "assembler" is assumed to mainly use the XML. That is why the EJB standard defines this relation between the ENC and an injection.
I think if you need to inject an Stateful Session Bean you gonna need some context that knows the relation between your EJB instance and some previously injected EJB dependency (to that instance).
@EJB injection and the Enterprise Naming Context - relation between the two
[ "", "java", "ejb-3.0", "java-ee-5", "" ]
I'm working on a web application that has a lot to download (javascript, images, videos, etc), and I was wondering how many people still consider dial up while developing large web applications? Is there a rule of thumb that you use to determine the individual page sizes? (i.e. home page must be less than 200k)
Remember that today's dial-up is now the phone/mobile market! Making your pages faster to load is better for every user.
No. But I try to limit the amount of material to only what is necessary. Typically use PNGs for images and keep the images to only what is necessary. I also use (for production) minified JS, compression, etc. Most of my apps are intranet apps and are accessed using the company network, though, so YMMV. You might want to think about using the [YSlow](http://developer.yahoo.com/yslow/) extension for Firefox to help minimize your page load time.
Do you take into consideration DialUp connections still?
[ "", "javascript", "html", "" ]
I am storing questions and answers in a database like FAQs and i want to allow the user to search. so for example the user will enter "how to bla bla bla" and i will search for every word and neglect the common words like "the", "to", "is" .... so this was my idea, do you think its a good one or you suggest something better? and how to search for a single word in a sql database? do i have to get a dataset from the table for example and iterate on it and get the questions i want?
[Lucine.net](http://incubator.apache.org/lucene.net/) api should help, it's great open source api provided by apache that index documents you provide and search in that documents depending on your criteria
If you are using MS SQL Server you might want to look into Full Text Searching. See the MSDN [here](http://msdn.microsoft.com/en-us/library/ms142547.aspx).
searching for a word in database
[ "", "sql", "search", "" ]
Since enumeration uses integers, what other structure can I use to give me enum-like access to the value linked to the name: [I know this is wrong, looking for alternative] ``` private enum Project { Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1"), Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2"), Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1"), Sales = new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435"), Replacement = new Guid("11E5CBA2-EDDE-4ECA-BDFD-63BDBA725C8C"), Modem = new Guid("6F686C73-504B-111-9A0B-850C26FDB25F"), Audit = new Guid("30558C7-66D9-4189-9BD9-2B87D11190"), Queries = new Guid("9985242-516A-4151-B7DD-851112F562") } ``` EDIT 2014-07-20 This is a newer answer to this question. Using the Attribute class with a helper method, define the extra attributes needed on your enum. ``` public enum MultiValueEnum { [FooAttribute("alpha", 20d, true)] First, [FooAttribute("beta", 40.91d, false)] Second, [FooAttribute("gamma", 1.2d, false)] Third, } public class FooAttribute : Attribute { internal FooAttribute(string name, double percentage, bool isGood) { this.Name = name; this.Percentage = (decimal)percentage; this.IsGood = isGood; } public string Name { get; private set; } public decimal Percentage { get; private set; } public bool IsGood { get; private set; } } public static TAttribute GetAttribute<TAttribute>(this Enum value) where TAttribute : Attribute { var type = value.GetType(); var name = Enum.GetName(type, value); return type.GetField(name) .GetCustomAttributes(false) .OfType<TAttribute>() .SingleOrDefault(); } ``` Which makes it this easy: ``` MultiValueEnum enumVar = MultiValueEnum.First; var enumStringValue = enumVar.GetAttribute<FooAttribute>().Name; var enumValueDecimal = enumVar.GetAttribute<FooAttribute>().Percentage; var enumBool = enumVar.GetAttribute<FooAttribute>().IsGood; ```
Otherwise you could create a custom Attribute for your enum, which can hold the Guid. Something alongside these lines: ``` class EnumGuid : Attribute { public Guid Guid; public EnumGuid(string guid) { Guid = new Guid(guid); } } ``` And you'd then use it like so: ``` enum Project { [EnumGuid("2ED3164-BB48-499B-86C4-A2B1114BF1")] Cleanup = 1, [EnumGuid("39D31D4-28EC-4832-827B-A11129EB2")] Maintenance = 2 // and so forth, notice the integer value isn't supposed to be used, // it's merely there because not assigning any value is a performance overhead. } ``` And finally you could (I always do this) create an extension for easily getting the guid: ``` static Guid GetEnumGuid(this Enum e) { Type type = e.GetType(); MemberInfo[] memInfo = type.GetMember(e.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumGuid),false); if (attrs != null && attrs.Length > 0) return ((EnumGuid)attrs[0]).Guid; } throw new ArgumentException("Enum " + e.ToString() + " has no EnumGuid defined!"); } ``` So in the end all you have to with your enums is: ``` Guid guid = Project.Cleanup.GetEnumGuid(); ``` I use this approach to attach descriptions to enums, typically longer strings containing spaces, which thus cannot be used as names.
I've seen this method (struct) used by SubSonic to store Column and Table names. ``` internal struct Project { public static Guid Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1"); public static Guid Maintenance = new Guid("39D31D4-28EC-4832-827B-A129EB2"); public static Guid Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1"); public static Guid Sales = new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435"); public static Guid Replacement = new Guid("11E5CBA2-EDDE-4ECA-BD63-B725C8C"); public static Guid Modem = new Guid("6F686C73-504B-111-9A0B-850C26FDB25F"); public static Guid Audit = new Guid("30558C7-66D9-4189-9BD9-2B87D11190"); public static Guid Queries = new Guid("9985242-516A-4151-B7DD-851112F562"); } ``` EDIT:- Thanks for commenting on deficiencies in code. In first place it will compile if the Guid strings are not invalid. As for not create instances to access variables yes they need to be **public static**
Enumerate with return type other than string?
[ "", "c#", "enums", "" ]
What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance. Thanks.
Have a look at [`java.text.NumberFormat`](http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html). For example: ``` import java.text.*; import java.util.*; public class Test { // Just for the sake of a simple test program! public static void main(String[] args) throws Exception { NumberFormat format = NumberFormat.getInstance(Locale.US); Number number = format.parse("835,111.2"); System.out.println(number); // or use number.doubleValue() } } ``` Depending on what kind of quantity you're using though, you might want to parse to a `BigDecimal` instead. The easiest way of doing that is probably: ``` BigDecimal value = new BigDecimal(str.replace(",", "")); ``` or use a [`DecimalFormat`](http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html) with `setParseBigDecimal(true)`: ``` DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US); format.setParseBigDecimal(true); BigDecimal number = (BigDecimal) format.parse("835,111.2"); ```
The easiest is not always the most correct. Here's the easiest: ``` String s = "835,111.2"; // NumberFormatException possible. Double d = Double.parseDouble(s.replaceAll(",","")); ``` I haven't bothered with locales since you specifically stated you wanted commas replaced so I'm assuming you've already established yourself as a locale with comma is the thousands separator and the period is the decimal separator. There are better answers here if you want correct (in terms of internationalization) behavior.
Convert a String to Double - Java
[ "", "java", "format", "" ]
Simple question, I just want to select the text from the <Template> tag. Here's what I have, but the Xpath doesn't match anything. ``` public static void TestXPath() { string xmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"; xmlText += "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\">"; xmlText += "<Template>Normal</Template> <TotalTime>1</TotalTime> <Pages>1</Pages> <Words>6</Words>"; xmlText += "</Properties>"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(new System.IO.StringReader(xmlText)); foreach (XmlNode node in xmlDoc.SelectNodes("//Template")) { Console.WriteLine("{0}: {1}", node.Name, node.InnerText); } } ```
You need to use an [`XmlNamespaceManager`](http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.aspx) because the Template element is in a namespace: ``` XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(new System.IO.StringReader(xmlText)); XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace("ns", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"); foreach (XmlNode node in xmlDoc.SelectNodes("//ns:Template", manager)) { Console.WriteLine("{0}: {1}", node.Name, node.InnerText); } ```
That is a namespace issue; you need to get the name-table, pick an alias, and use that in your query. Or perhaps (in this case) try `GetElementsByTagName`. ``` XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable); mgr.AddNamespace("x", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"); foreach (XmlNode node in xmlDoc.SelectNodes("//x:Template", mgr)) { Console.WriteLine("{0}: {1}", node.Name, node.InnerText); } ``` Or: ``` foreach (XmlNode node in xmlDoc.GetElementsByTagName("Template")) { Console.WriteLine("{0}: {1}", node.Name, node.InnerText); } ```
How to select nodes with XPath in C#?
[ "", "c#", ".net", "xpath", "" ]
I'm a Ruby on Rails / PHP guy, and my company got me to work with ASP.NET. It's not too bad, I'm glad to learn a new language but since I started working with this technology everyone is bothering me about Repeaters. The thing is that I totally fail of seeing the point: what make using a repeater better than just displaying things in a loop? Am I going to programmers' hell for this? **In rails I would do...** *controller* ``` @types= Type.find(:all) ``` *view* ``` <%@types.each do |t| %> <%= t.name %> <%= link_to "view", t%> <%end%> ``` **In ASP.NET I'd do:** *controller class attributes* ``` protected List<Type> _types = null; ``` *controller class PageLoad* ``` _types = MethodThatGetTypeFromDB(); ``` *view* ``` <% foreach (var tin _types){%> <%= t.name %> <%}%> ``` There are no repeaters, but the code is clean, DRY and respects the MVC AP. I don't create methods everywhere to handle `ItemDataBound` or whatever. So what's the idea here? Am I the only one that find that repeaters are a pain to set up and are not worth it compared to the advantages they bring? I think I'm just not getting the idea here. I'm **not** trying to start a battle rails vs the world, it's just that this is what I know the best so this is the paradigm I'm trying to find when I'm developing. I think it's more convenient and I'm used to it, but if someone goes "Repeaters are good because A, B and C, doing what you're doing is terrible because D, E and F", then I'll admit it and change my approach.
Repeaters fit nicely into the code-behind approach. I spent many years where I couldn't stand the sight of *any* code in the markup. All code belonged in the code-behind separated from the markup. This was largely a reaction to the horrid messes I dealt with in classic ASP. Now with ASP.Net MVC, I find I'm going back to exactly what you describe above. But, I'm finding it hard to overcome the instinct to keep markup and code separate. Edit: [Here's](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1049844.html) an article from 2003 about the debate regarding code-behind.
Microsoft frequently tries to maximize what you can do without coding. You can do a lot with repeaters without any code-behind. With data source controls you can do a whole lot without any code at all. One can suppose that as a corporate strategy they want to have the easiest-to-use development environment, and "no code at all" is apparently someone's definition of easy to use. But when you want to move beyond the free automatic behaviors you are knee deep in an event model with lots of twisty passages which all look alike. I am fond of perl's motto, "make the simple things simple and the hard things possible", and Microsoft sometimes seems to prefer "make the simple things trivial and everything else hard". Some have mentioned that the ASP.Net MVC moves away from this. If true, this is the best news I have heard all day.
Why Repeaters in ASP.NET?
[ "", "c#", "asp.net", "ruby-on-rails", "webforms", "repeater", "" ]
Hard to come up with a proper title for this problem. Anyway... I'm currently working on a [GUI](http://en.wikipedia.org/wiki/GUI) for my games in [SDL](http://www.libsdl.org). I've finished the software drawing and was on my way to start on the OpenGL part of it when a weird error came up. I included the "SDL/SDL\_opengl.h" header and compile. It throws "error C2039: 'DrawTextW' : is not a member of 'GameLib::FontHandler'", which is a simple enough error, but I don't have anything called DrawTextW, only FontHandler::DrawText. I search for DrawTextW and find it in a #define call in the header "WinUser.h"! ``` //WinUser.h #define DrawText DrawTextW ``` **Apparently it replaces my DrawText with DrawTextW! How can I stop it from spilling over into my code like that?** It's a minor thing changing my own function's name, but naming conflicts like this seem pretty dangerous and I would really like to know how to avoid them all together. Cheers!
You have a couple of options, all of which suck. * Add `#undef DrawText` in your own code * Don't include `windows.h`. If another library includes it for you, don't include that directly. Instead, include it in a separate .cpp file, which can then expose your own wrapper functions in its header. * Rename your own `DrawText`. When possible, I usually go for the middle option. `windows.h` behaves badly in countless other ways (for example, it doesn't actually compile unless you enable Microsoft's proprietary C++ extensions), so I simply avoid it like the plague. It doesn't get included in my files if I can help it. Instead, I write a separate .cpp file to contain it and expose the functionality I need. Also, feel free to submit it as a bug and/or feedback on connect.microsoft.com. Windows.h is a criminally badly designed header, and if people draw Microsoft's attention to it, there's a (slim) chance that they might one day fix it. The good news is that `windows.h` is the **only** header that behaves this badly. Other headers generally try to prefix their macros with some library-specific name to avoid name collisions, they try to avoid creating macros for common names, and they try avoid using more macros than necessary.
It's an unfortunate side effect of `#include`ing `<windows.h>`. Assuming you're not actually using Windows' `DrawText()` anywhere in your program, it's perfectly safe to `#undef` it immediately after: ``` // wherever you #include <windows.h>, or any other windows header #include <windows.h> #undef DrawText ```
Other's library #define naming conflict
[ "", "c++", "opengl", "sdl", "" ]
I'd like to have a class "A" with a (for example) SortedList collection "SrtdLst" property, and inside this class "A" allow the addition or subtraction of "SrtdLst" items. But in a instance of the class "A", only allow to get or set the content of the items, not to add new items or subtract the existing ones. In code: ``` class A { public SortedList<string, string> SrtdLst = new SortedList<string, string>(); public A() { // This must work: SrtdLst.Add("KeyA", "ValueA"); // This too: SrtdLst["KeyA"] = "ValueAAA"; } } class B { public A a = new A(); public B() { // I want the following code to fail: a.SrtdLst.Add("KeyB", "ValueB"); // But this must work: a.SrtdLst["KeyA"] = "ValueBBB"; } } ``` UPDATE: I want to create a class like System.Data.SqlClient.SqlCommand. For the Stored Procedures you can use the member "DeriveParameters" that fills a collection of "Parameters", so only the value of each item can be modified. How can this be done?
If you want to ban the modifying operations at compile time, you need a type-safe solution. Declare an interface for the publicly allowed operations. Use that interface as the property type. ``` public interface IReadOnlyList<T> { T this[int index] { get; } int Count { get; } } ``` Then declare a class that implements that interface and inherits from the standard collection class. ``` public class SafeList<T> : List<T>, IReadOnlyList<T> { } ``` Assuming you get the interface definition right, you won't need to implement anything by hand, as the base class already provides the implementations. Use that derived class as the type of the field that stores the property value. ``` public class A { private SafeList<string> _list = new SafeList<string>(); public IReadOnlyList<string> { get { return _list; } } } ``` Within class A, you can use `_list` directly, and so modify the contents. Clients of class A will only be able to use the subset of operations available via `IReadOnlyList<T>`. For your example, you're using SortedList instead of List, so the interface probably needs to be ``` public interface IReadOnlyDictionary<K, V> : IEnumerable<KeyValuePair<K, V>> { V this[K index] { get; } } ``` I've made it inherit IEnumerable as well, which is readonly anyway, so is perfectly safe. The safe class would then be: ``` public class SafeSortedList<K, V> : SortedList<K, V>, IReadOnlyDictionary<K, V> { } ``` But otherwise it's the same idea. Update: just noticed that (for some reason I can't fathom) you don't want to ban modifying operations - you just want to ban SOME modifying operations. Very strange, but it's still the same solution. Whatever operations you want to allow, "open them up" in the interface: ``` public interface IReadOnlyDictionary<K, V> : IEnumerable<KeyValuePair<K, V>> { V this[K index] { get; set; } } ``` Of course, that's the wrong name for the interface now... why on earth would you want to ban adding via Add but not ban it via the indexer? (The indexer can be used to add items, just as the Add method can.) **Update** From your comment I think you mean that you want to allow assignment to the value of an existing key/value pair, but disallow assignment to a previously unknown key. Obviously as keys are specified at runtime by strings, there's no way to catch that at compile time. So you may as well go for runtime checking: ``` public class FixedSizeDictionaryWrapper<TKey, TValue> : IDictionary<TKey, TValue> { IDictionary<TKey, TValue> _realDictionary; public FixedSizeDictionaryWrapper(IDictionary<TKey, TValue> realDictionary) { _realDictionary = realDictionary; } public TValue this[TKey key] { get { return _realDictionary[key]; } set { if (!_realDictionary.Contains(key)) throw new InvalidOperationException(); _realDictionary[key] = value; } } // Implement Add so it always throws InvalidOperationException // implement all other dictionary methods to forward onto _realDictionary } ``` Any time you have an ordinary dictionary and you want to hand it to some method that you don't trust to update the existing values, wrap it in one of these.
EDIT: Original answer is below. As earwicker points out, I hadn't noticed that you *aren't* asking for it to be readonly - just to prevent the `Add` operation. That doesn't sound like a good idea to me, as the only difference between `Add` and the indexer-setter is that `Add` throws an exception if the element is already present. That could easily be faked up by the caller anyway. Why do you want to restrict just that one operation? --- **Original answer** For one thing, don't use public fields. That's a surefire way to run into problems. It looks like you want a read-only wrapper class round an arbitrary `IDictionary`. You can then have a public property which returns the wrapper, while you access the private variable from within your class. For example: ``` class A { private SortedList<string, string> sortedList = new SortedList<string, string>(); public IDictionary<string, string> SortedList { get { return new ReadOnlyDictionaryWrapper(sortedList); } public A() { sortedList.Add("KeyA", "ValueA"); sortedList["KeyA"] = "ValueAAA"; } } ``` Now you've just got to find a `ReadOnlyDictionary` implementation... I can't implement it right now, but I'll be back later if necessary...
C# How to make public getters and setters and private methods for a collection?
[ "", "c#", "collections", "setter", "getter", "" ]
Hi I have some experience with programming but I'm not very good with pointers. I've been trying to debug this program I've been working on but it keeps giving me a segmentation fault. My code is the following: ``` #include <iostream> using namespace std; class hexagon { public: hexagon(); ~hexagon(); void setSide(int side, hexagon *hexpiece); hexagon* getSide(int side); void setPos(int x, int y); int getX(); int getY(); void setID(int id); int getID(); private: hexagon *side0, *side1, *side2, *side3, *side4, *side5; int itsid, itsx, itsy; }; hexagon::hexagon() { side0 = NULL; side1 = NULL; side2 = NULL; side3 = NULL; side4 = NULL; side5 = NULL; } hexagon::~hexagon() { } void hexagon::setSide(int side, hexagon *hexpiece) { switch(side) { case 0: side0 = hexpiece; break; case 1: side1 = hexpiece; break; case 2: side2 = hexpiece; break; case 3: side3 = hexpiece; break; case 4: side4 = hexpiece; break; case 5: side5 = hexpiece; break; default: cout << "ERROR: Invalid side passed as argument" << endl; break; } } hexagon* hexagon::getSide(int side) { switch(side) { case 0: return side0; break; case 1: return side1; break; case 2: return side2; break; case 3: return side3; break; case 4: return side4; break; case 5: return side5; break; default: cout << "EROR: Invalide side passed as argument" << endl; cout << "Returning side0 by default" << endl; return side0; break; } } void hexagon::setPos(int x, int y) { itsx = x; itsy = y; } int hexagon::getX() { return itsx; } int hexagon::getY() { return itsy; } void hexagon::setID(int id) { itsid = id; } int hexagon::getID() { return itsid; } int main() { hexagon hexpieces[120]; int tempx, tempy; tempx = 0; tempy = 0; for(int i = 0; i<121; i++) { if(i%11 == 0) { tempx = 7*(i/11); tempy = 12*(i/11); } else { tempx = tempx + 14; } cout << "Setting hexpiece" << i << " x to " << tempx << " and y to " << tempy << endl; hexpieces[i].setPos(tempx, tempy); } for(int i=0; i<121; i++) { cout << "Setting hexpiece" << i << " id" << endl; hexpieces[i].setID(i); for(int j = 0;j<6; j++) { cout << "Setting hexpiece" << i << " side" << j << endl; if(j == 0 && i > 10 && i % 11 != 10) { hexpieces[i].setSide(j,&(hexpieces[i-10])); } else if(j == 1 && i % 11 != 10) { hexpieces[i].setSide(j,&(hexpieces[i+1])); } else if(j == 2 && i < 110) { hexpieces[i].setSide(j,&(hexpieces[i+11])); } else if(j == 3 && i % 11 != 0 && i < 110) { hexpieces[i].setSide(j,&(hexpieces[i+10])); } else if(j == 4 && i % 11 != 0) { hexpieces[i].setSide(j,&(hexpieces[i-1])); } else if(j == 5 && i > 10) { hexpieces[i].setSide(j,&(hexpieces[i-11])); } } } hexagon *itr1; itr1 = hexpieces; cout << "Hexpiece" << itr1->getID() << " side1 is connected to Hexpiece"; itr1 = itr1->getSide(1); cout << itr1->getID() << endl; cout << "Hexpiece" << itr1->getID() << " side2 is connected to Hexpiece"; itr1 = itr1->getSide(2); cout << itr1->getID() << endl; cout << "Hexpiece" << itr1->getID() << " side4 is connected to Hexpiece"; itr1 = itr1->getSide(4); cout << itr1->getID() << endl; return 0; } ``` My problem seems to be with the following part of the code: ``` int tempx, tempy; tempx = 0; tempy = 0; for(int i = 0; i<121; i++) { if(i%11 == 0) { tempx = 7*(i/11); tempy = 12*(i/11); } else { tempx = tempx + 14; } cout << "Setting hexpiece" << i << " x to " << tempx << " and y to " << tempy << endl; hexpieces[i].setPos(tempx, tempy); } ``` When I compile the code and it includes that section it runs the program but then at the end I get a segmentation fault. However, if I comment out that section everything runs fine and there is no segmentation fault. I don't understand how a regular integer could be causing a segmentation fault. If someone could explain what mistake I made and where I made it I would greatly appreciate it. Thanks in advance
`hexpieces` is an array of length 120, so its largest index is 119. You're tring to access `hexpieces[i]` with `i` = 120 (that's the last index your `for` loop takes on). Since you don't "own" that memory, you get a segmentation falut.
When you define your array, you are allocating storage for exactly 120 pieces: ``` hexagon hexpieces[120]; ``` But in your loop, you iterate over indices 0 through 120, which is actually 121 locations: ``` for(int i = 0; i<121; i++) { //... } ``` Either allocate 121 hexpieces in the originaly array, or use `i<120` in the loop to avoid the error.
Not sure what is causing my segmentation fault - C++
[ "", "c++", "segmentation-fault", "" ]
How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code: ``` class CommentForm(forms.Form): comment = forms.CharField(widget=forms.Textarea()) ``` This is the HTML that it produces: ``` <label for="id_text">Text:</label> <textarea id="id_text" rows="10" cols="40" name="text"></textarea> ``` That label is no good and I'd like a way to remove it. That code was produced via: ``` {{ form.as_p }} ``` (I removed the paragraph tags because they are irrelevant) EDIT: I added the class CommentForm part for further clarification. Anyone have any suggestions?
The [Django documentation on customizing labels](http://docs.djangoproject.com/en/dev/ref/forms/api/#ref-forms-api-configuring-label) says it could be turned off with `auto_id` argument to Form constructor: ``` f = ContactForm(auto_id=False) ```
This should work with the latest version (trunk) of django: ``` comment = forms.CharField(label="", help_text="", widget=forms.Textarea()) ``` Hope that helps!
Removing the Label From Django's TextArea Widget
[ "", "python", "django", "textarea", "label", "widget", "" ]
I have a program that allows the user to enter a level number, and then it plays that level: ``` char lvlinput[4]; std::cin.getline(lvlinput, 4) char param_str[20] = "levelplayer.exe " strcat_s(param_str, 20, lvlinput); system(param_str); ``` And the level data is stored in folders \001, \002, \003, etc., etc. However, I have no way of telling whether the user entered three digits, ie: 1, 01, or 001. And all of the folders are listed as three digit numbers. I can't just check the length of the lvlinput string because it's an array, so How could I make sure the user entered three digits?
Here's how you could do this in C++: ``` std::string lvlinput; std::getline(std::cin, lvlinput); if (lvlinput.size() > 3) { // if the input is too long, there's nothing we can do throw std::exception("input string too long"); } while (lvlinput.size() < 3) { // if it is too short, we can fix it by prepending zeroes lvlinput = "0" + lvlinput; } std::string param_str = "levelplayer.exe "; param_str += lvlinput; system(param_str.c_str()); ``` You've got a nice string class which takes care of concatenation, length and all those other fiddly things for you. So use it. Note that I use `std::getline` instead of `cin.getline`. The latter writes the input to a char array, while the former writes to a proper string.
Why not use [std::string](http://www.cplusplus.com/reference/string/string/)? This makes storage, concatenation, and modification much easier. If you need a c-style string after, use: `my_string.c_str()` Here is a hint: To make your input 3 characters long, use [std::insert](http://www.cplusplus.com/reference/string/string/insert/) to prefix your number with 0's.
How to check the length of an input? (C++)
[ "", "c++", "string", "" ]
I have a system that runs like this: main.exe runs sub.exe runs sub2.exe and etc. and etc... Well, would it be any faster of more efficient to change sub and sub2 to dlls? And if it would, could someone point me in the right direction for making them dlls without changing a lot of the code?
DLLs would *definitely* be faster than separate executables. But keeping them separate allows more flexibility and reuse (think Unix shell scripting). [This](http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c9855) seems to be a good DLL tutorial for Win32. As for not changing code much, I'm assuming you are just passing information to theses subs with command line arguments. In that case, just rename the `main` functions, export them from the DLL, and call these renamed "`main`" functions from the main program.
DLL really are executables too. They comply to the PE standard which covers multiple common file extensions for windows, like .exe, .dll, .ocx... When you start 2 executables they each get their own address space, their own memory and such. However when you load an executable and a dll, the dll is loaded into the process space of the executable so they share a lot of things. Now depending on how your 3 executables communicate together (if they even communicate together), you might have to rewrite some code. Basically the general approach to having dlls is to simply call the dll function from inside your program. This is usually much simpler than interprocess communication
Is this a good way to use dlls? (C++?)
[ "", "c++", "performance", "dll", "" ]
In my .htaccess file I have defined the following rule to make my register page URL as `http://example.com/register/` ``` RewriteRule register/ /register.php ``` The above rule is perfectly fine but I can access my register page from `http://example.com/register/` as well as from `http://example.com/register.php`. I don't want that user will be able to access the URL from `http://example.com/register.php` URL, is there any RULE which I can define in .htaccess to stop execution of register.php URL or simply redirect any direct register.php request to /register/
If you are doing this to avoid getting multiple links to the same content, you can simply don't use "register.php" anywhere on your page. I think no search engine will "guess" for a certain file type and if there are no security concerns you are on the safe side, because in my opinion no user will link to this file either. However if you want to be certain just reroute all your functionality through an index.php via one line in your .htaccess which should be placed inside your www-root directory: ``` RewriteEngine on RewriteRule ^(.*?)$ index.php?file=$1 ``` In your index.php you can then simply choose which function/file to invoke by breaking down and checking the $\_GET["file"] parameter. To make 100% certain no one can access your register.php file directly just move it (and all your others) to a separate directory and include a .htaccess file with the following line: ``` DENY from all ``` There are a couple of other options to prevent direct access. Just `define()` a variable somewhere in your index.php and at the top of your register.php just put ``` defined('access') or die('Intruder alert!'); ``` at the top. Another way could be to be honest and simply tell search engines that your content has been moved and that they no longer should use the old link: ``` header("Status: 301"); /* Content moved permanently */ header("Location: http://yourserver/Register/"); exit; ``` **Update** Just one more thing that crossed my mind, you can also check `$_SERVER["REQUEST_URI"]`, whether the user attached any ".php" and act accordingly by either denying access completely or just redirecting to the new location.
It is true that you cannot use location directive, but you can actually paste .htaccess file into any directory. Just if you put this into it, say: ``` Options -Indexes order allow,deny deny from all ``` you can copy paste this file into any (root) directory you want to protect from external execution.
How to stop direct execution of a php page using htaccess rules?
[ "", "php", "apache", ".htaccess", "url-rewriting", "" ]
I am running into integer overflow using the standard *ftell* and *fseek* options inside of G++, but I guess I was mistaken because it seems that *ftell64* and *fseek64* are not available. I have been searching and many websites seem to reference using **lseek** with the *off64\_t* datatype, but I have not found any examples referencing something equal to *fseek*. Right now the files that I am reading in are 16GB+ CSV files with the expectation of at least double that. Without any external libraries what is the most straightforward method for achieving a similar structure as with the *fseek/ftell* pair? My application right now works using the standard GCC/G++ libraries for 4.x.
fseek64 is a C function. To make it available you'll have to define \_FILE\_OFFSET\_BITS=64 before including the system headers That will more or less define fseek to be actually fseek64. Or do it in the compiler arguments e.g. gcc -D\_FILE\_OFFSET\_BITS=64 .... <http://www.suse.de/~aj/linux_lfs.html> has a great overviw of large file support on linux: * Compile your programs with "gcc -D\_FILE\_OFFSET\_BITS=64". This forces all file access calls to use the 64 bit variants. Several types change also, e.g. off\_t becomes off64\_t. It's therefore important to always use the correct types and to not use e.g. int instead of off\_t. For portability with other platforms you should use getconf LFS\_CFLAGS which will return -D\_FILE\_OFFSET\_BITS=64 on Linux platforms but might return something else on e.g. Solaris. For linking, you should use the link flags that are reported via getconf LFS\_LDFLAGS. On Linux systems, you do not need special link flags. * Define \_LARGEFILE\_SOURCE and \_LARGEFILE64\_SOURCE. With these defines you can use the LFS functions like open64 directly. * Use the O\_LARGEFILE flag with open to operate on large files.
If you want to stick to ISO C standard interfaces, use [`fgetpos()`](http://www.opengroup.org/onlinepubs/9699919799/functions/fgetpos.html) and [`fsetpos()`](http://www.opengroup.org/onlinepubs/9699919799/functions/fsetpos.html). However, these functions are only useful for saving a file position and going back to the same position later. They represent the position using the type `fpos_t`, which is not required to be an integer data type. For example, on a record-based system it could be a struct containing a record number and offset within the record. This may be too limiting. POSIX defines the functions [`ftello()`](http://www.opengroup.org/onlinepubs/9699919799/functions/ftello.html) and [`fseeko()`](http://www.opengroup.org/onlinepubs/9699919799/functions/fseeko.html), which represent the position using the `off_t` type. This is required to be an integer type, and the value is a byte offset from the beginning of the file. You can perform arithmetic on it, and can use `fseeko()` to perform relative seeks. This will work on Linux and other POSIX systems. In addition, compile with `-D_FILE_OFFSET_BITS=64` (Linux/Solaris). This will define `off_t` to be a 64-bit type (i.e. `off64_t`) instead of `long`, and will redefine the functions that use file offsets to be the versions that take 64-bit offsets. This is the default when you are compiling for 64-bit, so is not needed in that case.
Seeking and reading large files in a Linux C++ application
[ "", "c++", "c", "linux", "gnu", "large-files", "" ]
I'm trying to properly encapsulate a class A, which should only be operated on by class B. However, I want to inherit from class B. Having A friend B doesn't work -- friendship isn't inherited. What's the generally accepted way of accomplish what I want, or am I making a mistake? To give you a bit more color, class A represents a complex system's state. It should only be modified by B, which are actions that can be applied to change class A's state.
I assume you want to allow descendants of B to access A directly? If A and B are tightly coupled, you can make A a protected class definition within B itself, instead of being an independent definition. E.G. ``` class B { protected: class A { }; }; ``` Another idea is to create protected methods on B that delegate their actions to A. E.G. ``` class A { friend class B; private: void DoSomething(); }; class B { protected: void DoSomething(A& a) { a.DoSomething(); } }; ```
It sounds like you may need to do a redesign; your class A represents a State, but your Class B represents a set of actions. There's a relationship there, but it's not an inheritance relationship. I'd suggest composition; you want more of a HASA relationship than an ISA relationship, as far as I can tell.
C++ Encapsulation Techniques
[ "", "c++", "inheritance", "encapsulation", "" ]
I thought about the following question about computer's architecture. Suppose I do in Python ``` from bisect import bisect index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?) x.insert(index, a) # O(1) + memcpy() ``` which takes `log n`, plus, if I correctly understand it, a memory copy operation for `x[index:]`. Now I read recently that the bottleneck is usually in the communication between processor and the memory so the memory copy *could* be done by RAM quite fast. Is it how that works?
Python is a language. [Multiple implementations exist](https://www.python.org/download/alternatives/), and they *may* have different implementations for lists. So, without looking at the code of an actual implementation, you cannot know for sure how lists are implemented and how they behave under certain circumstances. My bet would be that the references to the objects in a list are stored in contiguous memory (certainly not as a linked list...). If that is indeed so, then insertion using `x.insert` will cause all elements behind the inserted element to be moved. This may be done efficiently by the hardware, but the complexity would still be *O(n)*. For small lists the `bisect` operation may take more time than `x.insert`, even though the former is *O(log n)* while the latter is *O(n)*. For long lists, however, I'd hazard a guess that `x.insert` is the bottleneck. In such cases you must consider using a different data structure.
Use the [blist module](http://www.python.org/pypi/blist/) if you need a list with better insert performance.
Performance of list(...).insert(...)
[ "", "python", "architecture", "memory", "list", "memcpy", "" ]
I am writing some plugins and themes for WordPress, and I finding it hard to debug because somehow by the time the page has loaded, $\_GET, $\_POST and $\_REQUEST are all empty. Even with error reporting set on, I am not getting error messages either other than a blank page whenever there is a fatal error. Is there anyway to enable a 'debug mode' for WordPress? Thanks!
Pear Debug Wordpress plugin: <http://wordpress.org/extend/plugins/wp-pear-debug/> **Update 4/08/2015:** The above plugin hasn't been updated in a few years. You can also use the built-in WordPress PHP debugging functions in `wp-config.php` , i.e.: ``` // Enable WP_DEBUG mode define('WP_DEBUG', true); // Enable Debug logging to the /wp-content/debug.log file define('WP_DEBUG_LOG', true); // Disable display of errors and warnings define('WP_DEBUG_DISPLAY', false); @ini_set('display_errors',0); // Use dev versions of core JS and CSS files (only needed if you are modifying these core files) define('SCRIPT_DEBUG', true); ``` See <https://codex.wordpress.org/Debugging_in_WordPress> for the complete docs
There's (more than one/) a way to enable "a 'debug mode'" for php in general. And that's installing a debugger extension like e.g. [xdebug](http://www.xdebug.org/). You need a client that connects to the debugger and retrieves+displays the information. [Netbeans](http://www.netbeans.org) 6.7 has been [released](http://www.netbeans.org/downloads/index.html) and its php module supports xdebug. It has become a nice [IDE for PHP development](http://www.netbeans.org/features/php/index.html).
PHP and WordPress: Debugging
[ "", "php", "debugging", "wordpress", "" ]
I'm putting together a Swing application where I often want to replace the contents of a JPanel. To do this, I'm calling `removeAll()`, then adding my new content, then calling `revalidate()`. However I'm finding that the old content is still actually visible (though obscured by the the new content). If I add a call to `repaint()` in addition to `revalidate()`, it works as expected. I'm sure on other occasions I've experienced that just calling `revalidate()` is enough. So basically my question is - should I need to call both functions and if not, when should I call each of them?
You need to call `repaint()` and `revalidate()`. The first one tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by `removeAll()`); the second one tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause *children* of the panel to repaint, but may not cause the panel itself to do so (see [this](http://www.oracle.com/technetwork/java/painting-140037.html#triggers) for the list of repaint triggers). On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.
Any time you do a remove() or a removeAll(), you should call ``` validate(); repaint(); ``` after you have completed add()'ing the new components. Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs. My own testing indicates that repaint() is also necessary. I'm not sure exactly why.
Java Swing revalidate() vs repaint()
[ "", "java", "swing", "" ]
I've got some network code to process an arbitary TCP connection. It all seems to work as expected but seems slow. When i've profiled the code the it seems to spend a good 600 ms in NetworkStream.Read() and I'm wondering how to improve it. I've fiddled with the buffer sizes and alternated between a massive buffer to read all of the data in one go or a small one which should concatenate the data into a StringBuilder. Currently the client i'm using is a web-browser but this code is generic and it may well not be HTTP data that is being sent to it. Any ideas? My code is this: ``` public void StartListening() { try { lock (oSyncRoot) { oTCPListener = new TcpListener(oIPaddress, nPort); // fire up the server oTCPListener.Start(); // set listening bit bIsListening = true; } // Enter the listening loop. do { // Wait for connection TcpClient newClient = oTCPListener.AcceptTcpClient(); // queue a request to take care of the client oThreadPool.QueueUserWorkItem(new WaitCallback(ProcessConnection), newClient); } while (bIsListening); } catch (SocketException se) { Logger.Write(new TCPLogEntry("SocketException: " + se.ToString())); } finally { // shut it down StopListening(); } } private void ProcessConnection(object oClient) { TcpClient oTCPClient = (TcpClient)oClient; try { byte[] abBuffer = new byte[1024]; StringBuilder sbReceivedData = new StringBuilder(); using (NetworkStream oNetworkStream = oTCPClient.GetStream()) { // set initial read timeout to nInitialTimeoutMS to allow for connection oNetworkStream.ReadTimeout = nInitialTimeoutMS; int nBytesRead = 0; do { try { bool bDataAvailable = oNetworkStream.DataAvailable; while (!bDataAvailable) { Thread.Sleep(5); bDataAvailable = oNetworkStream.DataAvailable; } nBytesRead = oNetworkStream.Read(abBuffer, 0, abBuffer.Length); if (nBytesRead > 0) { // Translate data bytes to an ASCII string and append sbReceivedData.Append(Encoding.UTF8.GetString(abBuffer, 0, nBytesRead)); // decrease read timeout to nReadTimeoutMS second now that data is coming in oNetworkStream.ReadTimeout = nReadTimeoutMS; } } catch (IOException) { // read timed out, all data has been retrieved nBytesRead = 0; } } while (nBytesRead > 0); //send the data to the callback and get the response back byte[] abResponse = oClientHandlerDelegate(sbReceivedData.ToString(), oTCPClient); if (abResponse != null) { oNetworkStream.Write(abResponse, 0, abResponse.Length); oNetworkStream.Flush(); } } } catch (Exception e) { Logger.Write(new TCPLogEntry("Caught Exception " + e.StackTrace)); } finally { // stop talking to client if (oTCPClient != null) { oTCPClient.Close(); } } } ``` Edit: I get roughly the same figures on two entirely seperate machines (my XP development machine and a 2003 box in a colo). I've put some timing into the code around the relevant parts (using System.Diagnostic.StopWatch) and dump it to a log: ``` 7/6/2009 3:44:50 PM : Debug : While DataAvailable took 0 ms 7/6/2009 3:44:50 PM : Debug : Read took 531 ms 7/6/2009 3:44:50 PM : Debug : ProcessConnection took 577 ms ```
After some more research it seems that the only way to speed this up is to break after the first x bytes have been read. The delay seems to be on the second read. If I change the buffer to be 8096 bytes (probably the max my application will be sent at any one go) and break here: ``` if (nBytesRead > 0) { // Translate data bytes to an ASCII string and append sbReceivedData.Append(Encoding.UTF8.GetString(abBuffer, 0, nBytesRead)); if (bTurboMode) { break; } else { // decrease read timeout to nReadTimeoutMS second now that data is coming in oNetworkStream.ReadTimeout = nReadTimeoutMS; } } ``` Then the response time goes from 600ms to about 80ms. This is an acceptable solution for me currently. I can toggle the bTurboMode from the calling application and speed things up substantially for this case
I recommend you use Microsoft Network Monitor or something like it to see what's going on in terms of those 600ms. NetworkStream is a piece of networking software - when looking at its behavior, always consider what the network is doing.
.NET NetworkStream Read slowness
[ "", "c#", ".net", "sockets", "c#-2.0", "networkstream", "" ]
I'm playing around with html client side storage and wanted to know if there are any facilities for introspection of the database - is there an equivalent of sqlite ".tables" or ".schema" ? Also, I'm not seeing my tables show up in AppData\Local\Apple Computer\Safari\LocalStorage . Is there another place tables are stored?
This is browser specific. For Safari, you need Safari 4 -- they have a [inspection tool](http://developer.apple.com/safari/library/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/UsingtheWebInspector/UsingtheWebInspector.html)(Figure 2-11) for that purpose.
Safari stores the tables in "AppData\Local\Apple Computer\Safari\Databases". First Databases.db is an sqlite3 database with 2 tables. > Origins tracks what site created the database and maximum storage for that database. > > Databases tracks the specific databases and their folder, common and file name I use sqlite3 command line tool or sometimes SQLite Administrator. Any sqlite3 app will do. Your database will be in a subfolder like http\_exeample\_com\_0\00000000003.db
HTML5 Database administration / introspection?
[ "", "sql", "database", "safari", "html", "" ]
``` template<typename T> class vec3 { public: typename T type_t; T x; T y; T z; }; template<typename T> struct numeric_type_traits_basic_c { typedef T type_t; typedef T scalar_t; }; template<typename T> struct numeric_type_traits_vec3_c { typedef T type_t; typedef typename T::type_t scalar_t; }; typedef numeric_type_traits_basic_c<int> int_type_traits; typedef numeric_type_traits_vec3_c< vec3<int> > vec3_int_type_traits; ``` This is type traits for scalar and vector, the only difference is that the scalar type, for a vector, is the type of its element. Works fine. But I'd really like to be able to use the same name for those two classes. ``` template<typename T> struct numeric_type_traits_c { typedef T type_t; typedef ????? scalar_t; }; ``` I know this is possible to do so if the class is explicitly specialized for each type I need: int, float, vec3, vec3... That's a lot of duplication... How can I keep the simplicity of the first bit of code but have the same class name at the same time?
This is the syntax for partial class template specialisation: ``` template<typename T> struct numeric_type_traits // basic template { typedef T type_t; typedef T scalar_t; }; template<typename T> struct numeric_type_traits< vec3<T> > // partial specialisation for vec3's { typedef vec3<T> type_t; typedef T scalar_t; }; ``` And so on, e.g.: ``` template <typename T, typename T_Alloc> struct numeric_type_traits< std::vector<T,T_Alloc> > // part. spec. for std::vector { typedef std::vector<T,T_Alloc> type_t; // deal with custom allocators, too typedef T scalar_t; }; ```
Maybe you should instantiate your template with two types? See: ``` template<typename TYPE, typename SCALAR> struct numeric_type_traits_c { typedef TYPE type_t; typedef SCALAR scalar_t; }; typedef numeric_type_traits_c<int,int> int_type_traits; typedef numeric_type_traits_c<vec3<int>, vec3<int>::type_t> vec3_type_traits; ```
type traits specialization
[ "", "c++", "templates", "" ]
So I am trying to invoke methods on a page and I know the values that I want to put inside the methods but I can't seem to get the syntax to work. I feel so, well.. lamerized. Ok so here is the javascript method on the page ``` function ReturnValue (sValue, sText) { window.focus(); var oForm = document.EditForm; switch (szType) // Form element name { case 'agt': oForm.agt.value = sText; oForm.agentman.value = sValue; oForm.agtid.value = sValue; oForm.getagt.focus(); break; case 'county': oForm.County.value = sValue; sCurrentCounty = new String(sValue); document.all("CountyDisp").innerHTML = sText; document.all("City").value = ""; document.all("CityDisp").innerHTML = ""; document.all("Area").value = ""; document.all("AreaDisp").innerHTML = ""; break; default: break; } // End switch return; } ``` Very straight forward function and you would assume that the parameters were strings, right? So in the IE8 Script Debugger Console I tried this: > ReturnValue("adf","asdf"); > //FAIL > "Object expected" Object expected huh, well maybe I need single quotes for the strings I assumed next (just in case). > ReturnValue('adf','asdf'); //FAIL > "Object expected" Okay, just making sure.. So I need an object that stores a string. How about using a var I thought.. > var o = "adf"; var p = "dfsa"; ReturnValue(o,p); //FAIL "Object expected" I tried with single quotes just to be sure. So after all that I am sure an object is needed. So I tried to create an Object. > o = new Object(); k = new Object(); //{...} Now I from here I didn't know how to add a string to an object so I just did this. > o.value = "text"; k.value = "field"; // "text" ... "field" Okay so now I am feeling excited I have an object with some string in there so now I try to put it all together again. > ReturnValue(o,z) > // EPIC FAIL "Object expected" I am putting Objects in there! Now I'm back to square one, can someone help? Okay problem still not solved. Upon further investigation I found that the script does infact run once at the very beginning of the page load. I can debug and break and while its paused through the code I can run the methods. But after I release and it finishes declaring all the variables I can't run any methods. But, for some reason the same method that I am trying to run is able to run from a Popup using the Window.Opener.ReturnValue(string,string); I dont get it! Javascript guru's where are you when I need you!
Assuming you've defined szType somewhere else, I pasted this function into a scratch page and played around with it and I can't reproduce this issue in IE8 (or FireFox 3). Googling around, the only thing I found was a reference saying that if you set the script type incorrectly you might get this as IE won't parse the script block at all. Is your script block set as "text/javascript"? If that doesn't work, can you provide more of the code involved (perhaps the markup too)? On another note, you might want to look at using something like [jQuery](http://jquery.com/) or one of the other JS libraries. Browser-specific JS like this is evil (death to document.all).
What's the value of szType? I can't see it being set anywhere, maybe that's what it is bombing on? Also, those document.all and form. probably won't work in anything other than IE. document.getElementById('theid') is much better for retrieving dom elements. Also, can you try setting a breakpoint on the ReturnValue function and step through it? I haven't used the IE8 console this way, but I know you can debug that way. **edit** Is it able to execute functions that way? Maybe comment out *everything* in ReturnValue and make sure it can actually execute the function itself. You might have to be in a debug session, or invoke the function via window.ReturnValue
Javascript setting variables and object and proper syntax (debug console)
[ "", "javascript", "function", "object", "declaration", "invoke", "" ]
I'm in the process of architecting a library that will be used in multiple releases of a product, and part of its job is to augment some of the functionality that doesn't exist in .NET 1.1, since we're required to use it. Probably the best example of this is the String.IsNullOrEmpty method, whose functionality we rely on fairly heavily. The String class in .NET is sealed; I've thought about using either the Adapter or Decorator patterns to extend the functionality of the class by wrapping the original string, but I'm not convinced that this is a very intuitive approach for what I'm trying to do. I've also looked at [another post on StackOverflow](https://stackoverflow.com/questions/657503/how-to-handle-a-class-you-want-to-extend-which-is-sealed-in-the-net-library) about a similar question, but it again raises the issue I just mentioned. I could definitely use Adapter to create the functionality I'm looking for, but I can't imagine doing this for every string: ``` bool isEmpty = new StringExtensionAdapter(myXmlNode.SelectSingleNode(myXpathString)).IsNullOrEmpty(); if (isEmpty) { // Do something } ``` I don't necessarily dislike this approach, but it seems like it results in a lot of memory management where a different solution might be better. Also, I'm not crazy about creating a "StringUtility" library since that approach takes me further away from the object-oriented design I'd like to follow. Any input would be helpful; if I'm just crazy and should use one of these approaches, let me know. I'm searching more for best practices than a solution, since I have several.
I would prefer the "StringUtility" library with a static IsNullOrEmpty method personally. In essence you would be creating [extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx) without the nice syntax for calling them.
By definition, there is no clean approach. I think the adapter approach is the best you can do in .NET 1.1. Of course, this will require you to go back and forth when dealing with the outside world.
What is a clean/intuitive approach to extending a sealed class in .NET 1.1?
[ "", "c#", ".net", "architecture", ".net-1.1", "" ]
Is there a way to make this line shorter? ``` bool pass = d != null && d["k"] != null && (bool)d["k"]; ``` Note: "k" is actually "a longer id"; I replaced it to make it more readable in this post. Many of your suggestions don't check whether d is null.
Try this: ``` bool pass = d != null && (bool)(d["k"] ?? false); ```
It is already barely readable, so why make it any shorter?
null shorthand in C#?
[ "", "c#", "null", "" ]
Is a table intrinsically sorted by it's primary key? If I have a table with the primary key on a BigInt identity column can I trust that queries will always return the data sorted by the key or do I explicitly need to add the "ORDER BY". The performance difference is significant.
Data is physically stored by clustered index, which is usually the primary key but doesn't have to be. Data in SQL is not guaranteed to have order without an ORDER BY clause. You should always specify an ORDER BY clause when you need the data to be in a particular order. If the table is already sorted that way, the optimizer won't do any extra work, so there's no harm in having it there. Without an ORDER BY clause, the RDBMS might return cached pages matching your query while it waits for records to be read in from disk. In that case, even if there is an index on the table, data might not come in in the index's order. (Note this is just an example - I don't know or even think that a real-world RDBMS will do this, but it's acceptable behaviour for an SQL implementation.) **EDIT** If you have a performance impact when sorting versus when not sorting, you're probably sorting on a column (or set of columns) that doesn't have an index (clustered or otherwise). Given that it's a time series, you might be sorting based on time, but the clustered index is on the primary bigint. SQL Server doesn't know that both increase the same way, so it has to resort everything. If the time column and the primary key column are a related by order (one increases if and only if the other increases or stays the same), sort by the primary key instead. If they aren't related this way, move the clustered index from the primary key to whatever column(s) you're sorting by.
Without an explicit ORDER BY, there is no default sort order. A very common question. As such, there is a canned answer: [Without ORDER BY, there is no default sort order.](http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/05/20/without-order-by-there-is-no-default-sort-order.aspx) Can you elaborate why "The performance difference is significant."?
Primary Key Sorting
[ "", "sql", "sql-server", "indexing", "" ]
VS 2005, C# 2.0, .NET 2.0/3.0, Win2003 I'm trying to install a set of performance counters for a MultiInstance. I noticed that some system performance counter categories manage to keep a "**total**" alive even when there are no other instances. ASP.NET Apps 2.0.50727 is an example. So I've been trying to duplicate this. I created the following routine in an Installer class which I then add to a Custom Action in a setup project. ``` public override void Install(System.Collections.IDictionary stateSaver) { //Debugger.Break(); CounterCreationData data = new CounterCreationData("ZCounter", "ZCtrHelp", PerformanceCounterType.NumberOfItems32); PerformanceCounterCategory.Create("ZCategory", "ZCatHelp", PerformanceCounterCategoryType.MultiInstance, new CounterCreationDataCollection(new CounterCreationData[] { data })); PerformanceCounter counter = new PerformanceCounter(); counter.CategoryName = "ZCategory"; counter.CounterName = "ZCounter"; counter.InstanceName = "ZTotal"; counter.InstanceLifetime = PerformanceCounterInstanceLifetime.Global; counter.ReadOnly = false; counter.RawValue = 0; base.Install(stateSaver); } ``` If I uncomment the `Debugger.Break()` line, and step through, I can see the counter is actually created with the right instance name, and Visual Studio Server Explorer shows the instance along with the InstanceLifetime set to Global. I do not call the RemoveInstance() method in the setup program. Nevertheless, a few seconds after the setup program completes, that instance disappears from the Performance Monitor and from the VS Server Explorer. How do I make it stick? Or can I?
Some code has to be actively maintaining the counter. In all the instances you can think of, such as ASP.Net, there is a service keeping the counter up. As you aren't happy with having a \_Total instance only active while some instance of your app is running, **you have to write some code that will maintain the performance counter** outside of your application. There's no magic. You can write a small service that does your monitoring needs. This will maintain the \_Total counter. You need to decide on an update regimen. The easiest is to have every instance of your app update both instances (their own and \_Total). A bit of background on performance counters - the main thing to understand is that there is typically a shared memory region shared between processes that is updated via interlocked operations. A tool like PerfMon (or any other app) ends up connecting to the shared memory region to get the current values. So some process has to have that shared memory region opened and owned. Thus why you need code running. PerfMon is not creating the \_Total instance for you (it does have some pretty convoluted combinations of counters allowing for averages and rates, but not a sum to create a summary instance).
AFAIK a Global Performance Counter category will remain alive as long as any process has an active handle referencing it. System counters achieve this by keeping a handle to the total counter instance in some service.
Installing a Total instance for Performance Counters
[ "", "c#", ".net", "windows", "installation", "performancecounter", "" ]
I finally discovered a way to use command line Matlab from .NET without linking: 1. Write variables from .NET to a MAT file using David A. Zier's "csmatio" dll. 2. Read the file from Matlab, process it and save the results to a MAT file: ``` var process = new Process() { StartInfo = new ProcessStartInfo() { FileName = MatlabExecutableFileName, Arguments = "-nodisplay " + "-nojvm " + " -r \"somecommands; " + "save FILENAME OUTPUTVARIABLES; " + "exit;\"" } }; process.Start(); ``` 3. **The worst part:** Wait until the process finishes. The naive approach: ``` process.WaitForExit(); ``` Doesn't work because matlab spawns the main application in a new thread Watching for the output file for changes is tricky: ``` new FileSystemWatcher(MatlabPath, fileName) .WaitForChanged(WatcherChangeTypes.All) ``` Was not working because of a bug on this class. The currently working code is longer: ``` using (var watcher = new FileSystemWatcher(MatlabPath, fileName)) { var wait = new EventWaitHandle(false, EventResetMode.AutoReset); watcher.EnableRaisingEvents = true; watcher.Changed += delegate(object sender, FileSystemEventArgs e) { wait.Set(); }; foreach(var i in Enumerable.Range(0, 2)) { if (!wait.WaitOne(MillissecondsTimeout)) { throw new TimeoutException(); } } Thread.Sleep(1000); } ``` But I am concerned about the last line of code. The code block above was written with the intent of avoiding it, but I don't know what else to do. This amount of time will be too much on some computers and too little on others. **SOLUTION** ``` var previousProcesses = Process .GetProcessesByName("Matlab") .Select(a => a.Id) .ToArray(); process.Start(); process.WaitForExit(); var currentProcess = Process .GetProcessesByName("Matlab") .Where(a => !previousProcesses.Contains(a.Id)) .First(); currentProcess.WaitForExit(); ```
A much better option is the `-wait` flag for matlab. It tells the matlab starter to terminate together with the main matlab process.
Not sure if I completely understand the question (you're essentially trying to detect when the matlab process finishes right?), but couldn't you find matlab's main application process & wait for it to exit? i.e. something like this: ``` process.WaitForExit(); //only waits for the launcher process to finish //but now matlab should be running in a new process... var matlabProcess = Process.GetProcessesByName("whatever process is called"); //assuming only one matlab instance running... //you'd probably want to write some defensive code here... matlabProcess[0].WaitForExit(); ``` Seems like that would be simpler than trying to watch it change files & guess when its finished...
How to use command line Matlab from .NET without linking?
[ "", "c#", ".net", "matlab", "process", "filesystemwatcher", "" ]
I have a login setup on a site that stores login information in PHP's $\_SESSION, and additionally sets a two-week cookie with login information if a checkbox is checked. The user is considered logged in if valid login information is either submitted by POST or either cookie is true. The behavior on FF3/Chrome is as intended, at least with the "Remember me" checkbox checked: log in anywhere and everywhere on the site you are treated as being logged in. However, someone working with IE6 said that she logged on one place, clicked around on links to other sections of the site, and was asked to log in again. I ran into some trouble with my (Multiple IE) IE6, but I reproduced similar behavior on IE8, including setting Advanced Privacy Settings->Always allow session cookies, and otherwise set cookie permissions to be as tolerant as I could. The behavior was identical: log in one place in a way that should set both \_SESSION and the two-week cookie, click on links to another pages, and the page presents you with a login screen because it doesn't recognize you as logged in. PHP is 5.2.8 on a Gentoo server. Any suggestions or resources to getting recognized cookies? -- [Added after checking on traffic with Fiddler:] Thank you; I have downloaded Fiddler 2. Fiddler is reporting Set-Cookie: [name]=deleted... on the logouts in question. I'm presently puzzled as to why. The included file that checks and displays a login screen only has one area where it can delete the relevant cookies, inside a conditional if $\_GET['logout'] is set. I didn't see that happening, and when I put an error\_log() statement inside the conditional before the statements to delete cookies, no additional messages appear to be being logged.
What I eventually found was as follows: Firefox and IE were behaving differently because they were treating caching differently when a missing document was within the 14 day Expires: headers that had been set. Firefox was apparently checking once for missing data, and then not requesting it again. IE, on the other hand, kept on checking for an item a stylesheet gave the wrong path for, got 404 pages, and the custom 404 page did a boilerplate invitation to log in that triggered the user being logged out (perhaps not the best boilerplate). I guess the stylesheet was cached, but IE kept on asking for items that were missing. So it was caching differences plus indirect inclusion plus 404 page behavior.
Couple of suggestions * Try using [Fiddler](http://www.fiddler2.com/fiddler2/) or similar to examine the HTTP requests and responses to see the cookies being sent and transmitted. This provide more insight into what is going wrong * Try having your app output a [P3P header](http://msdn.microsoft.com/en-us/library/ms537343(VS.85).aspx), e.g. `header('P3P: CP="CAO PSA OUR"');`
Why would cookies be vanishing in IE6/8, and what can I do about it?
[ "", "php", "internet-explorer", "session", "cookies", "" ]
How can I define a composite primary key consisting of two fields in SQL? I want to make a table name `voting` with fields `QuestionID`, `MemberID`, and `vote`. And the Composite primary key consists of the fields `QuestionID` and `MemberID`. How should I do this?
Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a **composite primary key**. It is defined as follows: ``` CREATE TABLE voting ( QuestionID NUMERIC, MemberID NUMERIC, PRIMARY KEY (QuestionID, MemberID) ); ``` The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this: ``` SELECT * FROM voting WHERE QuestionID = 7 ``` it will use the primary key's index. If however you do this: ``` SELECT * FROM voting WHERE MemberID = 7 ``` it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table. If necessary, add an index on the other: ``` CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID); ```
``` CREATE TABLE `voting` ( `QuestionID` int(10) unsigned NOT NULL, `MemberId` int(10) unsigned NOT NULL, `vote` int(10) unsigned NOT NULL, PRIMARY KEY (`QuestionID`,`MemberId`) ); ```
How can I define a composite primary key in SQL?
[ "", "sql", "primary-key", "composite-primary-key", "" ]
I have a datatable like ``` public DataTable functiongettable() { DataTable dt = new DataTable(); dt.Columns.Add("Name"); dt.Rows.Add("Name1"); dt.Rows.Add("Name5"); dt.Rows.Add("Name6"); dt.Rows.Add("Name3"); dt.Rows.Add("Name3"); dt.Rows.Add("Name6"); dt.Rows.Add("Name3"); dt.Rows.Add("Name5"); dt.Rows.Add("Name5"); return dt; } ``` By using linq query I want to perform Sorting and need unique records. I am doing like this ``` var query = from c in functiongettable().AsEnumerable().OrderBy("Name").Distinct() select c; ``` But getting error: The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. How to solve this? Thanks in advance
Try specifying the **DataRowComparer.Default** in the **Distinct** statement. **UPDATE:** And use row.Field("Name") when sorting **UPDATE again:** ``` var query = (from c in functiongettable().AsEnumerable() orderby c.Field<string>("Name") select c).Distinc(DataRowComparer.Default); ```
You need to pass a delegate to [`OrderBy`](http://msdn.microsoft.com/en-us/library/bb534966.aspx), not a `string`. Try this: ``` var query = dt.AsEnumerable() .OrderBy(dr => dr.ItemArray[0] as string) .Distinct(DataRowComparer.Default).Select(dr => dr.ItemArray[0]); foreach (var item in query) { Console.WriteLine(item); } ```
Sorting & Unique Records in Linq
[ "", "c#", "linq", "" ]
So I've got some data. There are entities. Entities have an arbitrary number of items. Items can be one of a defined set of types. An entity can have more than one item of a given type. I can get a list of items that an entity has. What I want is to get a list of types that an entity doesn't have an item for. Here's my schema: ``` entities id name 1 Bob 2 Alice item_types id name 1 red 2 yellow 3 green 4 blue 5 orange items entity_id item_type_id name 1 1 apple 1 2 banana 1 3 lime 1 3 tree 2 3 money 2 5 traffic cone ``` I would like to query Bob's id (1) and get this list: ``` 4 blue 5 orange ``` And query Alice's id (2) and get: ``` 1 red 2 yellow 4 blue ``` It's probably starting me in the face. I'm gonna keep working on it but I bet you SO peeps beat me to it. Thank you kindly for your time.
``` select id, name from item_types where id not in (select i.item_type_id from items i inner join entities e on e.id = t.entity_id where e.Name = 'Bob') ``` or (sometimes faster, but optimizers are getting better all the time): ``` select disctinct t.id, t.name from item_types t left outer join items i on i.item_type_id = t.id left outer join entities e on e.id = i.entity_id and e.Name = 'Bob' where e.id is null ```
for Bob ``` SELECT t.id, t.name FROM items i INNER JOIN entities e ON e.id = i.entity_id INNER JOIN item_types t ON t.id = i.item_type_id WHERE e.id <> 1 ``` for Alice just swap e.id <> 1 to e.id <> 2
SELECT item types not provided by an entity
[ "", "sql", "select", "not-exists", "" ]
I want to duplicate a row, not the keys of course, without explicity using the field names. Is there a SQL way or do I have to enumerate the field names through code? I don't want to explicity use field names because I want to minimize code and db dependencies. I am going to use it in the Ms Access 2003. I mention it in case that no standard way exists.
``` INSERT INTO `<table>` (column1, column2, ...) -- Not IDENTITY columns SELECT column1, column2, ... FROM ... ``` This will also allow you to insert replacement values for the primary key columns, etc. I've used this, along with a common table expression, to take a set of test data from the month of February, and to pretend they're really from June. I know you said you want to do it without the field names, but I don't think you can. It's also not a good idea, as it would tie you to the order of the columns.
If you don't have any uniques to worry about: ``` INSERT INTO <table> (SELECT * FROM <table> WHERE <condition>) ``` Otherwise, [John Saunders' answer](https://stackoverflow.com/questions/1086964/is-there-a-standard-way-to-duplicate-a-row-in-a-database-table/1087030#1087030) is probably your best bet.
Is there a standard way to duplicate a row in a database table?
[ "", "sql", "ms-access", "duplicate-data", "" ]
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do. It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good! Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python. UPDATE: This is now a community wiki, so we can add the big differences here. ## Ruby has a class reference in the class body In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished. An example: ``` class Kaka puts self end ``` self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions). ## All classes are mutable in Ruby This lets you develop extensions to core classes. Here's an example of a rails extension: ``` class String def starts_with?(other) head = self[0, other.length] head == other end end ``` Python (imagine there were no `''.startswith` method): ``` def starts_with(s, prefix): return s[:len(prefix)] == prefix ``` You could use it on any sequence (not just strings). In order to use it you should import it *explicitly* e.g., `from some_module import starts_with`. ## Ruby has Perl-like scripting features Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs. ## Ruby has first class continuations Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language. ## Ruby has blocks With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators. Ruby: ``` amethod { |here| many=lines+of+code goes(here) } ``` Python (Ruby blocks correspond to different constructs in Python): ``` with amethod() as here: # `amethod() is a context manager many=lines+of+code goes(here) ``` Or ``` for here in amethod(): # `amethod()` is an iterable many=lines+of+code goes(here) ``` Or ``` def function(here): many=lines+of+code goes(here) amethod(function) # `function` is a callback ``` Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator. Ruby: ``` def themethod yield 5 end themethod do |foo| puts foo end ``` Python: ``` def themethod(): yield 5 for foo in themethod(): print foo ``` Although the principles are different, the result is strikingly similar. ## Ruby supports functional style (pipe-like) programming more easily ``` myList.map(&:description).reject(&:empty?).join("\n") ``` Python: ``` descriptions = (f.description() for f in mylist) "\n".join(filter(len, descriptions)) ``` ## Python has built-in generators (which are used like Ruby blocks, as noted above) Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator [4](http://wiki.github.com/rdp/ruby_tutorials_core/enumerator) [docs.python.org](http://docs.python.org/tutorial/classes.html#generators) has this generator example: ``` def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] ``` Contrast this with the above block examples. ## Python has flexible name space handling In Ruby, when you import a file with `require`, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes. In Python, the file is a module, and you can import its contained names with `from themodule import *`, thereby polluting the namespace if you want. But you can also import just selected names with `from themodule import aname, another` or you can simply `import themodule` and then access the names with `themodule.aname`. If you want more levels in your namespace you can have packages, which are directories with modules and an `__init__.py` file. ## Python has docstrings Docstrings are strings that are attached to modules, functions and methods and can be introspected at runtime. This helps for creating such things as the help command and automatic documentation. ``` def frobnicate(bar): """frobnicate takes a bar and frobnicates it >>> bar = Bar() >>> bar.is_frobnicated() False >>> frobnicate(bar) >>> bar.is_frobnicated() True """ ``` Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source\_location [example use](http://github.com/rdp/ri_for "example use") ## Python has multiple inheritance Ruby does not ("on purpose" -- see Ruby's website, [see here how it's done in Ruby](http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/)). It does reuse the module concept as a type of abstract classes. ## Python has list/dict comprehensions Python: ``` res = [x*x for x in range(1, 10)] ``` Ruby: ``` res = (0..9).map { |x| x * x } ``` Python: ``` >>> (x*x for x in range(10)) <generator object <genexpr> at 0xb7c1ccd4> >>> list(_) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ``` Ruby: ``` p = proc { |x| x * x } (0..9).map(&p) ``` Python **2.7+**: ``` >>> {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} ``` Ruby: ``` >> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}] => {1=>"4", 3=>"16"} ``` ## Python has decorators Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python. ## Syntax differences Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <http://github.com/michaeledgar/seamless>
You can have code in the class definition in both Ruby and Python. However, in Ruby you have a reference to the class (self). In Python you don't have a reference to the class, as the class isn't defined yet. An example: ``` class Kaka puts self end ``` self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python.
Ruby has the concepts of *blocks*, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a `yield` statement. For example, a simple definition of an `each` method on `Array` might be something like: ``` class Array def each for i in self yield(i) # If a block has been passed, control will be passed here. end end end ``` Then you can invoke this like so: ``` # Add five to each element. [1, 2, 3, 4].each{ |e| puts e + 5 } > [6, 7, 8, 9] ``` Python has anonymous functions/closures/lambdas, but it doesn't quite have blocks since it's missing some of the useful syntactic sugar. However, there's at least one way to get it in an ad-hoc fashion. See, for example, [**here**](http://nicolas-lara.blogspot.com/2009/01/emulating-ruby-blocks-in-python.html).
What does Ruby have that Python doesn't, and vice versa?
[ "", "python", "ruby", "" ]
I have been provided with a C++ DLL and associated header file in order to integrate it with my application. To begin with, I am simply trying to call the DLL from a simple Win32 console application (I'm using Visual Studio 2008 Express). I've linked the DLL by specifying it as an additional dependency in the project settings. The interface (i.e. the only exported function) simply returns a pointer to an instance of the Class that I actually need to call. I can successfully call this, get the pointer and call the first function that I need to (an "init" function). When I come to call the function that actually does the processing I require, I'm intermittently getting a "0xC0000005: Access violation reading location...." error. That is, I run the program - it works successfully and exits - I try to run it again (changing nothing - all parameters are hard coded) and get the error (and continue to do so). I can't consistently recreate the problem but I'm beginning to think that it may be something to do with the DLL not being unloaded properly - after getting the error on one occasion I tried deleting the DLL and was told by Windows that it was in use. That said, on another occasion I was able to delete the DLL after getting the error, copy it back, then still got the error on the next run. Should the DLL be correctly unloaded when my .exe finishes? Would I be better off trying to explicitly load/unload the DLL rather than doing it implicitly? Any other help or advice greatly appreciated.
It won't have anything to do with the DLL being unloaded; different processes using the same DLL do not share any state. Also, the DLL will be unloaded when the process exits; perhaps not gracefully, but it will be unloaded. I can think of two likely reasons for an intermittent failure. Most likely, the DLL has a race condition. This could be one that's exposed if the DLL has been cached, causing the timing to change. That would explain why your first run didn't fail but subsequent ones did. I think it's also possible that the DLL didn't release its lock on some file. If there is some file you know is accessed by this DLL, try checking to see if that file is locked after the process ends. Also, get this in a debugger. Turn on first-chance exceptions in visual studio and look at the callstack where the AV is happening, and post it here.
What types are involved in the classes exported by the DLL? We have often had these kinds of problems with Visual Studio when the classes make use of STL - I'd guess that any template usage would probably be a way to potentially cause this sort of problem.
C++ - linking to 3rd party DLL - intermittent access violation
[ "", "c++", "dll", "" ]
I know C# has both value and reference types, but how can you do a this: ``` int age = 100; string blah = age.ToString(); ``` If age is a value type, how does it have a ToString method on it? Does it get converted to an object ONLY when required internally then?
You want to look up boxing/unboxing. [Boxing](http://msdn.microsoft.com/en-us/library/yz2be5wk(VS.80).aspx)
> If age is a value type, how does it > have a ToString method on it? Value types are allowed to have methods on them. Why wouldn't they? **A method "on a type" is just a hunk of code that happens to be associated with a particular type**; why do you believe that it matters whether that type is classified as a "reference type" or "value type"? That's not a rhetorical question. I am interested in learning about what intuitions people have about code, particularly when those intuitions are incorrect. By understanding what people get wrong intuitively, we can try to come up with better abstractions that are more intuitive. > Does it get converted to an object ONLY when required internally then? What exactly do you mean by "converted to an object"? Do you mean "boxed"? There are many situations in which a value type must be boxed. Some of them are straightforward -- like when you cast a value type to object or an interface. Some of them are obscure. (There are bizarre situations in generic methods where we must box and unbox things in ways you might not expect.) In this particular situation there is no boxing. Calling a method directly implemented on a value type simply calls that hunk of code. There's no need to treat the thing as "object"; the hunk of code we're calling knows the type of the thing.
C# supports value types and reference types, but are they all objects?
[ "", "c#", "value-type", "reference-type", "" ]
Is there an easy way to create a multiline string literal in C#? Here's what I have now: ``` string query = "SELECT foo, bar" + " FROM table" + " WHERE id = 42"; ``` I know PHP has ``` <<<BLOCK BLOCK; ``` Does C# have something similar?
You can use the `@` symbol in front of a `string` to form a [verbatim string literal](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim): ``` string query = @"SELECT foo, bar FROM table WHERE id = 42"; ``` You also [do not have to escape special characters](http://www.peachpit.com/articles/article.aspx?p=31938&seqNum=10) when you use this method, except for double quotes as shown in Jon Skeet's answer.
It's called a [*verbatim string literal*](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string) in C#, and it's just a matter of putting @ before the literal. Not only does this allow multiple lines, but it also turns off escaping. So for example you can do: ``` string query = @"SELECT foo, bar FROM table WHERE name = 'a\b'"; ``` This includes the line breaks (using whatever line break your source has them as) into the string, however. For SQL, that's not only harmless but probably *improves* the readability anywhere you see the string - but in other places it may not be required, in which case you'd either need to not use a multi-line verbatim string literal to start with, or remove them from the resulting string. The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol: ``` string quote = @"Jon said, ""This will work,"" - and it did!"; ```
Multiline string literal in C#
[ "", "c#", "string", "shorthand", "" ]
I am creating a windows application. I am now concentrating on the Reporting Module of my Application. I have two ideas to do this task. Either through Crystal Reports or using the Windows Forms and placing the Data Grid View. Can any one suggest me which option should I choose? Also the report should be able to Export in the Excel and PDF format and even it should be Printable. I heard from others that Crystal Reports gives some problem at the time of Deployment. Please suggest me. I am very much confused. Thanks in advance!
Yes, I would advise not to use Crystal Reports (or Crusty Reports as they have unfortunately become known as in my department). We have had a whole load of problems from reports being corrupted and requiring recreating to simply being clunky and slow. As our applications are being upgraded we are moving over to MS Report Viewer, which is far better. You can export to Excel from the report viewer.
Visual Studio 2005 and later comes with Microsoft Reporting tools that are so nice and, for me, better than Crystal Reports. **Update:** You can install the Microsoft Report Viewer Redistributable [2005](http://www.microsoft.com/DOWNLOADS/details.aspx?familyid=8A166CAC-758D-45C8-B637-DD7726E61367&displaylang=en) or [2008](http://www.microsoft.com/downloadS/details.aspx?familyid=BB196D5D-76C2-4A0E-9458-267D22B6AAC6&displaylang=en).
Generating Reports in C#
[ "", "c#", "" ]
I need a simple application, preferably a cross-platform one, that enables sending of files between two computers. It just need to accept and send the files, and show a progress bar. What applications could I use or how could I write one?
**Sending and Receiving Files** The sending and receiving of a file basically breaks down to two simple pieces of code. Recieving code: ``` ServerSocket serverSoc = new ServerSocket(LISTENING_PORT); Socket connection = serverSoc.accept(); // code to read from connection.getInputStream(); ``` Sending code: ``` File fileToSend; InputStream fileStream = new BufferedInputStream(fileToSend); Socket connection = new Socket(CONNECTION_ADDRESS, LISTENING_PORT); OutputStream out = connection.getOutputStream(); // my method to move data from the file inputstream to the output stream of the socket copyStream(fileStream, out); ``` The sending piece of code will be ran on the computer that is sending the code when they want to send a file. The receiving code needs to be put inside a loop, so that everytime someone wants to connect to the server, the server can handle the request and then go back to waiting on serverSoc.accept(). To allow sending files between both computers, each computer will need to run the server (receiving code) to listen for incoming files, and they will both need to run the sending code when they want to send a file. **Progress Bar** The `JProgressBar` in Swing is easy enough to use. However, getting it to work properly and show current progress of the file transfer is slightly more difficult. To get a progress bar to show up on a form only involves dropping it onto a `JFrame` and perhaps setting `setIndeterminate(false)` so hat it shows that your program is working. To implement a progress bar correctly you will need to create your own implementation of a [`SwingWorker`](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html). The Java tutorials have a good example of this in their[lesson in concurrency](http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html). This is a fairly difficult issue on its's own though. I would recommend asking this in it's own question if you need more help with it.
Woof is a cool Python script that might work for you: <http://www.home.unix-ag.org/simon/woof.html>
How to transfer files from one computer to another over the network using Java?
[ "", "java", "file", "networking", "" ]
How can I obtain the physical machine name that my jvm is running in? (Physical = OS, up to vmware...) *Added from poster's comment:* I mean the name of the computer the JVM is running in. Most likely a physical computer, but if the JVM is running inside another virtual machine then that name is good.
``` String computername=InetAddress.getLocalHost().getHostName(); System.out.println(computername); ```
On Windows, if you want the workstation name, you can use: ``` System.getenv("COMPUTERNAME") ```
Find physical machine name in Java
[ "", "java", "" ]
I am working on the I18n of our java application and we have decided that we will only support data in one locale whereas the user interface may support many. My question is this: **Should sorting and filtering of data be performed using the user's locale or the data's?** Orginally we had assumed it made sense to sort according to data's locale but having read articles like the one below it seems to make more sense to sort by the user's. *"Sorts can also vary depending on the fundamental order the language and culture use for the alphabet. For example, the Swedish language has an "Ä" character that it sorts after "Z" in the alphabet. The German language also has this character, but sorts it like "ae", after "A" in the alphabet."* <http://msdn.microsoft.com/en-us/library/a7zyyk0c.aspx> Has anyone had to make this decision before? What did you decide? Opinions? Can anyone think of examples that require the use of the data's locale for sorting or filtering? Thanks in advance.
I guess it'll have to depend on the use-cases, i.e. **what helps the users the most**? If you're an American working with Swedish names, and Swedish people, it'd really help you to view the data sorted using Swedish rules, since that is what most people you're interacting with would expect.
The obvious answer is "what the user expects" Only that it is not so easy to guess what the user expects :-) For the first answer: "an American working with Swedish names". Can we be sure that the American is familiar with the Swedish sorting rules? I think not. But we are sure he is familiar with the American sorting rules. (if I want to search for the phone number of a friend in Sweden, does it mean I know how they sort over there?) Some frameworks/OSes can help. There are usually settings in the "Control Panel" (or equivalent) on what locale should be used to do formatting, or sorting. Find out what the API is to retrieve that info and use it. Usually the UI is localized in one "flavor" of the language, not enough to decide what to do about formatting, sorting, etc. (Think English UI. But I can be in Australia, or UK, or India, where some conventions are different) If you give some info about your environment, I might be able to point you to the proper APIs.
I18n - Data is in one locale, ui in another, which locale do I use for sorting?
[ "", "java", "internationalization", "locale", "" ]
In [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms), you can know, at any time, the current position of the cursor thanks to the [Cursors](https://msdn.microsoft.com/en-us/library/system.windows.forms.cursors%28v=vs.110%29.aspx) class. The same thing doesn't seem to be available for the keyboard. Is it possible to know if, for example, the `Shift` key is pressed? Is it absolutely necessary to track down every keyboard notification (KeyDown and KeyUp events)?
``` if ((Control.ModifierKeys & Keys.Shift) != 0) ``` This will also be true if `Ctrl`+`Shift` is down. If you want to check whether Shift alone is pressed, ``` if (Control.ModifierKeys == Keys.Shift) ``` If you're in a class that inherits `Control` (such as a form), you can remove the `Control.`
The code below is how to detect almost all currently pressed keys, not just the `Shift` key. ``` private KeyMessageFilter m_filter = new KeyMessageFilter(); private void Form1_Load(object sender, EventArgs e) { Application.AddMessageFilter(m_filter); } public class KeyMessageFilter : IMessageFilter { private const int WM_KEYDOWN = 0x0100; private const int WM_KEYUP = 0x0101; private bool m_keyPressed = false; private Dictionary<Keys, bool> m_keyTable = new Dictionary<Keys, bool>(); public Dictionary<Keys, bool> KeyTable { get { return m_keyTable; } private set { m_keyTable = value; } } public bool IsKeyPressed() { return m_keyPressed; } public bool IsKeyPressed(Keys k) { bool pressed = false; if (KeyTable.TryGetValue(k, out pressed)) { return pressed; } return false; } public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_KEYDOWN) { KeyTable[(Keys)m.WParam] = true; m_keyPressed = true; } if (m.Msg == WM_KEYUP) { KeyTable[(Keys)m.WParam] = false; m_keyPressed = false; } return false; } } ```
How to detect the currently pressed key?
[ "", "c#", ".net", "winforms", "keyboard", "" ]
I set up a hitcounter so that each time someone goes to my site, one of 7 different sidebars loads up. There is a file called counter.php that writes to a text file called hitcounter.txt. All the references to files seem to be relative but when I moved them to a new directory at my new host I got this error instead of a happy hit counter: > **Warning**: fopen(hitcounter.txt) [*function.fopen*]: failed to open stream: Permission denied in **/usr/local/apache/sites/MY-SITE/counter.php** on line **5** Counter.php is pasted in its entirety below, line 5 is the first reference to fopen, both counter.php and hitcounter.txt have 775 permissions, same as they did on the old host. What am I doing wrong? I'm obviously missing something really simple and embarrassing, so feel free to give me any scorn or abuse with while helping me out. ### counter.php: ``` <?php $count_my_page = ("hitcounter.txt"); $hits = file($count_my_page); $hits[0]++; $fp = fopen($count_my_page , "w"); if ($fp) { fputs($fp , "$hits[0]"); fclose($fp); } if($hits[0]<=1) $random_number=0; else if($hits[0]>1 && $hits[0]<=2) $random_number=1; else if($hits[0]>2 && $hits[0]<=3) $random_number=2; else if($hits[0]>3 && $hits[0]<=4) $random_number=3; else if($hits[0]>4 && $hits[0]<=5) $random_number=4; else if($hits[0]>5 && $hits[0]<=6) $random_number=5; else if($hits[0]>6 && $hits[0]<=7) $random_number=6; else if($hits[0]>7 && $hits[0]<=8) $random_number=7; else if($hits[0]>8 && $hits[0]<=9) { $random_number=8; if($hits[0]==9) { $count_my_page=("hitcounter.txt"); $fp = fopen($count_my_page , "w"); $hits[0]=0; fputs($fp , "$hits[0]"); fclose($fp); } } ?> ```
First, you don't need 775 permissions. You need 666 permissions on the hitcounter.txt. The PHP file can be 644. The web server probably isn't a member of the group, depending on the host, so you'd need to give the 'Everyone' group write permissions. The "Execute" bit is needed for folders but not for individual files, since they are not being executed by the OS. So you know, the 775 is : Owner, Group, Everyone * Owner = Read + Write + Execute * Group = Read + Write + Execute * Everyone = Read + Execute 666 means * Owner = Read + Write * Group = Read + Write * Everyone = Read + Write 644 means * Owner = Read + Write * Group = Read * Everyone = Read
It probably has something to do with permissions. Set it to 777 and see what happens. If apache runs with own permissions and is not part of your this might be the reason, but I have a couple of suggestions: * use file\_put\_contents/file\_ get\_ contents for simple read/writes! * please use $random\_number = rand(0,8) OR mt\_rand(0,8) if possible instead of these countless lines and as a bonus get rid of all the file reading/writing Good luck! **Update** Nothing beats a nice example: ``` <?php $random_number = mt_rand(0,8); file_put_contents("hitcounter.txt", $random_number); /* dont know if you still need it */ ?> ``` If you really want to (btw. NOT random!): ``` <?php $file = "hitcounter.txt"; $number = (int)file_get_contents($file); $number = ++$number % 9; file_put_contents($file, $number); ?> ```
Counter won't work when I move it to another server
[ "", "php", "file-io", "deployment", "fopen", "" ]
I was working with generator functions and private functions of a class. I am wondering 1. Why when yielding (which in my one case was by accident) in \_\_someFunc that this function just appears not to be called from within \_\_someGenerator. Also what is the terminology I want to use when referring to these aspects of the language? 2. Can the python interpreter warn of such instances? Below is an example snippet of my scenario. ``` class someClass(): def __init__(self): pass #Copy and paste mistake where yield ended up in a regular function def __someFunc(self): print "hello" #yield True #if yielding in this function it isn't called def __someGenerator (self): for i in range(0, 10): self.__someFunc() yield True yield False def someMethod(self): func = self.__someGenerator() while func.next(): print "next" sc = someClass() sc.someMethod() ``` I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.
I'll try to answer the first of your questions. A regular function, when called like this: ``` val = func() ``` executes its inside statements until it ends or a `return` statement is reached. Then the return value of the function is assigned to `val`. If a compiler recognizes the function to actually be a generator and not a regular function (it does that by looking for `yield` statements inside the function -- if there's at least one, it's a generator), the scenario when calling it the same way as above has different consequences. Upon calling `func()`, *no code inside the function is executed*, and a special `<generator>` value is assigned to `val`. Then, the first time you call `val.next()`, the actual statements of `func` are being executed until a `yield` or `return` is encountered, upon which the execution of the function stops, value yielded is returned and generator waits for another call to `val.next()`. That's why, in your example, function `__someFunc` didn't print "hello" -- its statements were not executed, because you haven't called `self.__someFunc().next()`, but only `self.__someFunc()`. Unfortunately, I'm pretty sure there's no built-in warning mechanism for programming errors like yours.
A "generator" isn't so much a language feature, as a name for functions that "yield." Yielding is pretty much always legal. There's not really any way for Python to know that you didn't "mean" to yield from some function. This PEP <http://www.python.org/dev/peps/pep-0255/> talks about generators, and may help you understand the background better. I sympathize with your experience, but compilers can't figure out what you "meant for them to do", only what you actually told them to do.
Can I be warned when I used a generator function by accident
[ "", "python", "function", "generator", "language-features", "" ]