Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have this code... ``` internal static void Start() { TcpListener listenerSocket = new TcpListener(IPAddress.Any, 32599); listenerSocket.Start(); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null); } ``` Then my call back function looks like this... ``` private static void AcceptClient(IAsyncResult asyncResult) { MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult)); ThreadPool.QueueUserWorkItem((object state) => handler.Process()); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null); } ``` Now, I call BeginAcceptTcpClient, then some time later I want to stop the server. To do this I have been calling TcpListener.Stop(), or TcpListener.Server.Close(). Both of these however execute my AcceptClient function. This then throws an exception when I call EndAcceptTcpClient. What is the best practice way around this? I could just put a flag in to stop the execution of AcceptClient once I have called stop, but I wonder if I am missing something. **Update 1** Currently I have patched it by changing the code to look like this. ``` private static void AcceptClient(IAsyncResult asyncResult) { if (!shutdown) { MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult)); ThreadPool.QueueUserWorkItem((object state) => handler.Process()); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null); } } private static bool shutdown = false; internal static void Stop() { shutdown = true; listenerSocket.Stop(); } ``` Update 2 I changed it to impliment the answer from Spencer Ruport. ``` private static void AcceptClient(IAsyncResult asyncResult) { if (listenerSocket.Server.IsBound) { MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult)); ThreadPool.QueueUserWorkItem((object state) => handler.Process()); listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null); } } ```
I just ran into this issue myself, and I believe your current solution is incomplete/incorrect. There is no guarantee of atomicity between the check for `IsBound` and the subsequent call to `EndAcceptTcpClient()`. You can still get an exception if the listener is `Stop()`'d between those two statements. You didn't say what exception you're getting but I assume it's the same one I'm getting, `ObjectDisposedException` (complaining that the underlying socket has already been disposed). You should be able to check this by simulating the thread scheduling: * Set a breakpoint on the line after the `IsBound` check in your callback * Freeze the thread that hits the breakpoint (Threads window -> right click, "Freeze") * Run/trigger the code that calls `TcpListener.Stop()` * Break in and step through the `EndAcceptTcpClient()` call. You should see the `ObjectDisposedException`. IMO the ideal solution would be for Microsoft to throw a different exception from `EndAcceptTcpClient` in this case, e.g. `ListenCanceledException` or something like that. As it is, we have to infer what's happening from the `ObjectDisposedException`. Just catch the exception and behave accordingly. In my code I silently eat the exception, since I have code elsewhere that's doing the real shutdown work (i.e. the code that called `TcpListener.Stop()` in the first place). You should already have exception handling in that area anyway, since you can get various `SocketExceptions`. This is just tacking another catch handler onto that try block. I admit I'm uncomfortable with this approach since in principle the catch could be a false positive, with a genuine "bad" object access in there. But on the other hand there aren't too many object accesses in the `EndAcceptTcpClient()` call that could otherwise trigger this exception. I hope. Here's my code. This is early/prototype stuff, ignore the Console calls. ``` private void OnAccept(IAsyncResult iar) { TcpListener l = (TcpListener) iar.AsyncState; TcpClient c; try { c = l.EndAcceptTcpClient(iar); // keep listening l.BeginAcceptTcpClient(new AsyncCallback(OnAccept), l); } catch (SocketException ex) { Console.WriteLine("Error accepting TCP connection: {0}", ex.Message); // unrecoverable _doneEvent.Set(); return; } catch (ObjectDisposedException) { // The listener was Stop()'d, disposing the underlying socket and // triggering the completion of the callback. We're already exiting, // so just return. Console.WriteLine("Listen canceled."); return; } // meanwhile... SslStream s = new SslStream(c.GetStream()); Console.WriteLine("Authenticating..."); s.BeginAuthenticateAsServer(_cert, new AsyncCallback(OnAuthenticate), s); } ```
No you're not missing anything. You can check the IsBound property of the Socket object. At least for TCP connections, while the socket is listening this will be set to true and after you call close it's value will be false. Though, your own implementation can work just as well.
Stopping a TcpListener after calling BeginAcceptTcpClient
[ "", "c#", "sockets", "tcpclient", "" ]
This class uses a `StreamWriter` and therefore implements `IDisposable`. ``` public class Foo : IDisposable { private StreamWriter _Writer; public Foo (String path) { // here happens something along the lines of: FileStream fileWrite = File.Open (path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); _Writer = new StreamWriter (fileWrite, new ASCIIEncoding ()); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } ~Foo() { Dispose (false); } protected virtual void Dispose (bool disposing) { if (_Disposed) { return; } if (disposing) { _Writer.Dispose (); } _Writer = null; _Disposed = true; } private bool _Disposed; } ``` } Is there any issue with the current implementation? I.e., do I have to release the underlying `FileStream` manually? Is `Dispose(bool)` written correctly?
You don't need to use this extensive version of IDisposable implementation if your class doesn't directly use unmanaged resources. A simple ``` public virtual void Dispose() { _Writer.Dispose(); } ``` will suffice. If your consumer fails to Dispose your object it will be GC'd normally without a call to Dispose, the object held by \_Writer will also be GC'd and it will have a finaliser so it still gets to clean up its unmanaged resources properly. **Edit** Having done some research on the links provided by Matt and others I've come to the conclusion that my answer here *stands*. Here is why:- The premise behind the disposable implementation "pattern" (by that I mean the protected virtual Dispose(bool), SuppressFinalize etc. marlarky) on an inheritable class is that a sub-class **might** hold on to an unmanaged resource. However in the real world the vast majority of us .NET developers never go anywhere near an unmanaged resource. If you had to quantify the "**might**" above what probabilty figure would you come up with for you sort of .NET coding? Lets assume I have a Person type (which for sake of argument has a disposable type in one of its fields and hence ought to be disposable itself). Now I have inheritors Customer, Employee etc. Is it really reasonable for me to clutter the Person class with this "Pattern" just in case someone inherits Person and wants to hold an unmanaged resource? Sometimes we developers can over complicate things in an attempt to code for all possible circumstances without using some common sense regarding the relative probability of such circumstances. If we ever wanted to use an unmanaged resource directly the sensible pattern would be wrap such a thing in its own class where the full "disposable pattern" would be reasonable. Hence in the significantly large body of "normal" code we do not to have to worry about all that mucking about. If we need IDisposable we can use the simple pattern above, inheritable or not. Phew, glad to get that off my chest. ;)
You don't need a `Finalize` (destructor) method since you don't have any unmanaged objects. However, you should keep the call to `GC.SuppressFinalize` in case a class inheriting from Foo has unmanaged objects, and therefore a finalizer. If you make the class sealed, then you know that unmanaged objects are never going to enter the equation, so it isn't necessary to add the `protected virtual Dispose(bool)` overload, or the `GC.SuppressFinalize`. Edit: @AnthonyWJones's objection to this is that if you know that the subclasses will not reference unmanaged objects, the whole `Dispose(bool)` and `GC.SuppressFinalize` is unnecessary. But if this is the case you should really make the classes `internal` rather than `public`, and the `Dispose()` method should be `virtual`. If you know what you are doing, then feel free not to follow Microsoft's suggested pattern, but you should know and understand the rules before you break them!
Am I implementing IDisposable correctly?
[ "", "c#", "idisposable", "" ]
I have to import a log file to SQL Server Database. File size is big, around 6MB with 40000 lines. The task of importing has to be done everyday with daily log. Each line of the log file contains many fields, which I have to import into properly columns in Database for post-processing. I'm confused of these solutions: -Use SQL Server Integration Services to do this. -Write a C# app using BULK COPY I'm relatively free to choose solution (in SQL Server and .NET framework). What solution is better for this, or you can suggest another one. Thank you very much. //Edit: I tried SSIS and saw that it's really simple. But everyday, after receiving log file, my program has to automatically import it into database. How can I do that?
I would write an SSIS package to do this. You could use the import/export wizard to generate the beginings of a package and adapt it to meet your exact needs. To do this in SQL 2005, Right click on your database in object explorer in SQL Management Studio, go Tasks > Import Data, follow the wizard and at the end select to save the package. I imagine it's a similar process in SQL 2008, but I don't have it to hand. After you have saved your package it's possible to schedule it using the SQL Server aAgent, when setting up the job, choose "SQL Server Integraton Services Package" as the type and select your packege.
I would probably write a script that converts the log file into an sql dump that insert the log file strings and then load that sql dump into the database.
import from text file to SQL Server Database, what solution I should choose?
[ "", "c#", "sql-server", "ssis", "" ]
I have a following problem. I am executing an OS command line from within Oracle database that executes an external jar file with some parameters. I can't see shell output but I can connect with a different user to that same server through ssh/ftp and read files. There are multiple versions of Java on that server and I would like to see which one Oracle is using. Is it possible? And before you start - no, ``` java -version > out.txt ``` does not work. It prints Java version to console and creates an empty file.
The version message gets printed to STDERR, not STDOUT. If you're on linux/unix, try ``` java -version >& version.txt ``` instead
``` System.getProperty("java.version") ```
Is there a way to determine Java version without seeing shell output?
[ "", "java", "" ]
I have class `foo` that contains a std::auto\_ptr member that I would like to copy construct but this does not appear to be allowed. There's a similar thing for the assignment. See the following example: ``` struct foo { private: int _a; std::string _b; std::auto_ptr< bar > _c; public: foo(const foo& rhs) : _a(rhs._a) , _b(rhs._b) , _c(rhs._c) // error: Cannot mutate rhs._c to give up ownership - D'Oh! { } foo& operator=(const foo& rhs) { _a = rhs._a; _b = rhs._b; _c = rhs._c; // error: Same problem again. } }; ``` I could just declare `_c` as `mutable` but I'm not sure this is correct. Does anyone have a better solution? **EDIT** OK, I'm not getting the kind of answer that I was expecting so I'll be a little more specific about the problem. * An object of type `foo` is created on the stack and passed by value into a container class (not stl) and then goes out of scope. I don't have any control over the container code. (It's actually an active queue implementation, with bugs.) * The `bar` class is a fairly heavyweight parser. It has very poor performance on `new` and `delete` so even if it was copy constructable, it would be way too expensive. * We can guarantee that when a `bar` object is created, it will only ever need to be owned in 1 place at a time. In this case it is being passed between threads and deleted when the transaction is completed. This is why I was hoping to use a `std::autp_ptr`. * I am very willing to consider boost smart pointers but I was hoping to guarantee this uniqueness if there is an alternative.
You might want to try following code: ``` foo(const foo& rhs) : _a(rhs._a) , _b(rhs._b) , _c(_rhs._c.get() ? new bar(*_rhs._c.get()) : 0) { } ``` (Assignment operator is similar.) However this will only work if `bar` is CopyConstructible and if this indeed does what you want. The thing is that both `foo` objects (`_rhs` and constructed one) will have different pointers in `_c`. If you want them to share the pointer then you must not use `auto_ptr` as it does not support shared ownership. Consider in such case use of `shared_ptr` from [Boost.SmartPtr](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/smart_ptr.htm) for example (which will be included in new C++ standard). Or any other shared pointer implementation as this is such a common concept that lots of implementations are available.
As you have discovered you can't copy a `std::auto_ptr` like that. After the copy who owns the object pointed to? Instead you should use a reference counted smart pointer. The [Boost library](http://www.boost.org/) has a [shared\_ptr](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm) you could use.
How do use a std::auto_ptr in a class you have to copy construct?
[ "", "c++", "smart-pointers", "auto-ptr", "" ]
I have some code in Java as follows: ``` private Object addVertex(String label, int posX, int posY) { Vertex newVertex = new Vertex(); this.getModel().beginUpdate(); try { newVertex = insertVertex(parent, null, label, posX, posY, 80, 30); } finally { this.getModel().endUpdate(); } return newVertex; } ``` That code wont work because of a type mismatch, insertVertex will return an Object, but I get a type mismatch since it can't convert from Object to Vertex (which is an object I created). Firstly, how come that can't work, since the object Vertex inherits Object by default surely you should be able to do that. Also, if I try and type cast the Object to a Vertex as follows ``` newVertex = (Vertex) insertVertex(parent, null, label, posX, posY, 80, 30); ``` I get an error saying I can't make that conversion.
`Vertex` inherits from `Object`, but not the other way round. Basically you're trying to do: ``` Object tmp = insertVertex(...); newVertex = tmp; ``` You can't assign an `Object` reference to `newVertex` because the latter is of type `Vertex`. Now, with your cast it *should* be okay, so long as `insertVertex` is genuinely returning a `Vertex` at execution time. Please give details of *exactly* what error message you're getting.
Try to use ``` Object insertResult = insertVertex(parent, null, label, posX, posY, 80, 30); if(insertResult instanceof Vertex){ newVertex = (Vertex)insertResult; } ``` If you get the default implementation the returned type is not a Vertex object. **The insertVertex method has to return an Object which extends from Vertex!**
Type casting from an Object
[ "", "java", "" ]
How would I go about finding the unix timestamp of midnight of the previous Wednesday? My only approach would be to get the day index and day number of today, and subtract the difference, but I can think of several scenarios where this would fail, for example, early in a month before a Wednesday has happened. I guess, more concisely, how do I find the date of the previous Wednesday? Any help would be appreciated.
What about [`strtotime`](http://php.net/strtotime) ? ``` $timestamp = strtotime("last Wednesday"); var_dump($timestamp); var_dump(date('Y-m-d H:i:s', $timestamp)); // to verify ``` And you get this output : ``` int 1247608800 string '2009-07-15 00:00:00' (length=19) ``` which is indeed last wednesday, midnight.
It's easier than you might think...observe the awesome firepower of this fully operational battle station, er, I mean [strtotime](http://php.net/strtotime) ``` $t=strtotime("last wednesday"); echo strftime("%d %b %Y %H:%M:%S", $t); ``` This will output ``` 15 Jul 2009 00:00:00 ``` Which, at the time of writing, is last wednesday :)
Get the unix timestamp of midnight on the previous Wednesday
[ "", "php", "datetime", "unix-timestamp", "" ]
Is it possible to have a C++ template function which can access different fields in its input data depending on what *type* of input data was passed to it? e.g. I have code of the form: ``` typedef struct { int a; int b; }s1; typedef struct { int a; }s2; template <class VTI_type> void myfunc(VTI_type VRI_data, bool contains_b) { printf("%d", VRI_data.a); if(contains_b) // or suggest your own test here printf("%d", VRI_data.b); // this line won't compile if VTI_type is s2, even though s2.b is never accessed } void main() { s1 data1; data1.a = 1; data1.b = 2; myfunc <s1> (data1, true); s2 data2; data2.a = 1; myfunc <s2> (data2, false); } ``` So we want to use field A from many different data types, and that works fine. However, some data also has a field B that needs to be used - but the code which accesses field B needs to be removed if the template knows it's looking at a data type that doesn't contain a field B. (in my example, the structures are part of an external API, so can't change)
To elaborate the suggested use of template specialization: ``` template <class T> void myfunc(T data) { printf("%d", VRI_data.a); } // specialization for MyClassWithB: template <> void myfunc<MyClassWithB>(MyClassWithB data) { printf("%d", data.a); printf("%d", data.b); } ``` However, that requires a specialization per-class, there is no "auto-detection" of b. Also, you repeat a lot of code. You could factor out that "having b" aspect into a helper template. A simple demonstration: ``` // helper template - "normal" classes don't have a b template <typename T> int * GetB(T data) { return NULL; } // specialization - MyClassWithB does have a b: template<> int * GetB<MyClassWithB>(MyClassWithB data) { return &data.b; } // generic print template template <class T> void myfunc(T data) { printf("%d", VRI_data.a); int * pb = GetB(data); if (pb) printf("%d", *pb); } ```
Solution 1: You could use template *specialization*. The specialization might be performed on per-class basis, or on some more general trait.
C++ template function that uses field present in only some data-types?
[ "", "c++", "templates", "" ]
I would like to write an add-on for IE 8, but I want to use pure managed C#. Is this possible yet? I know for the longest time we were talking only C++.
Ultimately, the C# will end up calling into IE8's COM functions. There's a framework called Spicie that makes this easier, and some other examples here: <http://www.enhanceie.com/ie/dev.asp> Generally, it's a bad idea to write browser extensions in .NET because there's a severe performance impact, and there's the possibility of runtime collisions because only one version of .NET can be loaded into a process currently; if two addons want to use conflicting .NET versions, one will fail.
Have a look at this <http://code.msdn.microsoft.com/SpicIE>
How do I write an IE 8 Add-On in pure managed C#
[ "", "c#", "internet-explorer", "add-in", "" ]
Say I have: ``` t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) ``` And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not matter really, I want to search for a string in only the lowercase values. ``` if 'fish' in t: print "Fish in t." ``` Doesn't work. Is there a good way of doing this without doing a for loop with if statements?
The elements of a tuple can be extracted by specifying an index: `('a', 'b')[0] == 'a'`. You can use a [list comprehension](http://docs.python.org/3.0/tutorial/datastructures.html#list-comprehensions) to iterate over all elements of some *iterable*. A tuple is also iterable. Lastly, [`any()`](http://docs.python.org/3.0/library/functions.html#any) tells whether any element in a given iterable evaluates to `True`. Putting all this together: ``` >>> t = ( ... ('dog', 'Dog'), ... ('cat', 'Cat'), ... ('fish', 'Fish'), ... ) >>> def contains(w, t): ... return any(w == e[0] for e in t) ... >>> contains('fish', t) True >>> contains('dish', t) False ```
Try: ``` any('fish' == tup[0] for tup in t) ``` EDIT: Stephan is right; fixed 'fish' == tup[0]. Also see his more complete answer.
Looking for values in nested tuple
[ "", "python", "" ]
So far I've been using the C# [Mersenne Twister](http://en.wikipedia.org/wiki/Mersenne_twister) found here to generate random numbers: <http://www.centerspace.net/resources.php> I just discovered **[SFMT](http://en.wikipedia.org/wiki/Mersenne_twister#SFMT)** which is supposed to be twice as fast here: <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/> **Can anyone point me at a C# implementation of SFMT**? My requirements are to generate an integer between (and including) 0 and 2^20 (1048576). I need to do this **trillions of times everyday** for a simulation running on a 24 hour clock so I am prepared to spend days tweaking this to perfection. Currently I've tweaked the Center Space Mersenne Twister by adding a new method to fit my requirements: ``` public uint Next20() { return (uint)(genrand_int32() >> 12); } ``` Using the method `genrand_int32()` I'd like to produce my own version, `genrand_int20()`, that generates an integer between (and including) 0 and 2^20 to save on the **cast above and shift** but I don't understand the mathematics. Exactly how can I do this? Also is using an **uint going to be faster that int**, or is just a matter of addressable numbers? Because I only need up to 1048576, I am only concerned with speed. Also this will be running on a **Windows Server 2003 R2 SP2 (32bit) box with .NET 2. Processor is [AMD Opteron 275](http://en.wikipedia.org/wiki/List_of_AMD_Opteron_microprocessors#Opteron_200-series_.22Italy.22_.28E6.2C_90_nm.29) (4 core)**.
What you can do is download the [source from the link](http://www.codeproject.com/KB/DLL/SFMT_dll.aspx?msg=3130186) you discovered on Code Project. Unzip it, load the solution in Visual Studio and compile it. This will give you source, an unmanaged c dll and a .lib file. You can P/Invoke the functions in this dll, (there are only 5 simple functions exported, of which you need only two) or you can use this dll, lib, and the SFMT header file to create a managed wrapper dll you can use in C# without P/Invoke. I just tried this method and it was very simple to do. There was no explicit marshalling involved. Here's how. Once you have downloaded and compiled the ***source*** (you need the header and the lib file that is created in addition to the dll) create a new C++ CLR Class Library project. Call it WrapSFMT or something. Go the project properties. Under C++/Precompiled Headers, change to "Not using precompiled headers." Under the Linker/General/Additional Library Directories, enter the path to the SFMT.lib. Under Linker/Input/Additional Dependencies, add SFMT.lib. Close the property pages. Copy SFMT.h to your project folder and include it in the project. Edit WrapSFMT.h to read as follows: ``` #pragma once #include "SFMT.H" using namespace System; namespace WrapSFMT { public ref class SRandom { public:SRandom(UInt32); public:UInt32 Rand32(void); }; } ``` These declare the methods that will be in your class. Now edit WrapSFMT.cpp to read: ``` #include "WrapSFMT.h" namespace WrapSFMT { SRandom::SRandom(UInt32 seed) { init_gen_rand(seed); } UInt32 SRandom::Rand32() { return gen_rand32(); } } ``` These implement the methods you declared in the header file. All you are doing is calling functions from the SFMT.dll, and C++/CLI is automatically handling the conversion from unmanaged to managed. Now you should be able to build the WrapSFMT.dll and reference it in your C# project. Make sure the SFMT.dll is in the path, and you should have no problems.
You can find a C# implementation of SFMT (plus other RNG algorithms) at... <http://rei.to/random.html> The page and source code comments are in Japanese but you should be able to figure it out. You can also find a Google-translated version (to English) of the page at... <http://translate.google.com/translate?hl=en&sl=ja&u=http://rei.to/random.html>
C# Mersenne Twister random integer generator implementation (SFMT) monte carlo simulation
[ "", "c#", "random", "montecarlo", "" ]
I need to remove all chars that cant be part of urls, like spaces ,<,> and etc. I am getting the data from database. For Example if the the retrieved data is: Product #number 123! the new string should be: Product-number-123 Should I use regex? is there a regex pattern for that? Thanks
An easy regex to do this is: ``` string cleaned = Regex.Replace(url, @"[^a-zA-Z0-9]+","-"); ```
Here is a an example on how to generate an url-friendly string from a "normal" string: ``` public static string GenerateSlug(string phrase) { string str = phrase.ToLower(); str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // invalid chars str = Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); // cut and trim it str = Regex.Replace(str, @"\s", "-"); // hyphens return str; } ``` You may want to remove the trim-part if you are sure that you always want the full string. [Source](http://www.intrepidstudios.com/blog/2009/2/10/function-to-generate-a-url-friendly-string.aspx)
How to Format a string to be a part of URL?
[ "", "c#", "asp.net", "" ]
I'm trying to write a Javascript function to edit content from clipboard before pasting. Right now i got bound event 'paste' to function via JQuery. ``` $(this.elementDoc).bind('paste', function(event){ self.OnPaste(event); }); ``` But that's not important. Now I would like to get Data from clipboard, but I can't find out how. I would be glad for every hint.
This is a toughie. If I recall correctly, IE allows access to the clipboard, but by default Firefox does not due to security issues. I had to do this for a project I was working on, and was forced to use a small SWF file that did the copying. <http://www.jeffothy.com/weblog/clipboard-copy/>
The `clipboardData` can contains data in various potential formats. Its possible a program will add clipboard data in multiple formats. To look through the formats, look through `clipboardData.types`. Often the clipboard data contains plain text, and the first type listed in `types` will be the MIME type "text/plain". If you copy text from a browser tho, you will see two types in the list: "text/plain" and "text/html". Depending on which string you pass into `getData`, you can grab the plain text, or the html. It seems that "text" is shorthand for "text/plain" and "url" is short for "text/uri-list". ``` element.addEventListener('paste', function(event) { var cb = event.clipboardData if(cb.types.indexOf("text/html") != -1) { // contains html var pastedContent = cb.getData("text/html") } else if(cb.types.indexOf("text/html") != -1) { // contains text var pastedContent = cb.getData("text/html") } else { var pastedContent = cb.getData(cb.types[0]) // get whatever it has } // do something with pastedContent }) ``` For more info on how to use `clipboardData.getData`, see [the ugly spec](https://html.spec.whatwg.org/multipage/interaction.html#dom-datatransfer-getdata).
Get clipboard data
[ "", "javascript", "jquery", "clipboard", "http-get", "" ]
How do you say, add 1 hour to a given result from calendar.getTime?
# tl;dr ``` Instant.now().plusHours( 1 ) ``` …or… ``` ZonedDateTime.now( ZoneId.of( "America/Montreal" ).plusHours( 1 ) ``` # Using java.time The accepted Answer is correct but outdated. The troublesome old legacy date-time classes have been supplanted by the java.time classes. Instead of `Calendar`, use `ZonedDateTime`. ``` ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = ZonedDateTime.now( z ); ZonedDateTime zdtOneHourLater = zdt.plusHours( 1 ); ``` Note that the [wall-clock time](https://en.wikipedia.org/wiki/Wall-clock_time) may not be an hour later. Anomalies such as [Daylight Saving Time (DST)](https://en.wikipedia.org/wiki/Daylight_saving_time) means an hour later may appear to be *two* hours later jumping from 1 AM to 3 AM for DST switch-over. For converting from old `Calendar` to modern java.time types, see [this Question](https://stackoverflow.com/q/36639154/642706). Most of your work should be in UTC. For that, use the `Instant` class. ``` Instant hourLater = Instant.now().plusHours( 1 ); ``` # About java.time The [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as `java.util.Date`, `.Calendar`, & `java.text.SimpleDateFormat`. The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to java.time. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Much of the java.time functionality is back-ported to Java 6 & 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to [Android](https://en.wikipedia.org/wiki/Android_(operating_system)) in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) (see [*How to use…*](https://stackoverflow.com/q/38922754/642706)). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as `Interval`, `YearWeek`, `YearQuarter`, and more.
Well, you can add 1000 \* 60 \* 60 to the millisecond value of the `Date`. That's probably the simplest way, if you don't want to mutate the `Calendar` instance itself. (I wouldn't like to guess exactly what `Calendar` will do around DST changes, by the way. It may well not be adding an hour of UTC time, if you see what I mean.) So if you *do* want to go with the Date approach: ``` date.setTime(date.getTime() + 1000 * 60 * 60); ``` This will *always* add an actual hour, regardless of time zones, because a `Date` instance doesn't have a time zone - it's just a wrapper around a number of milliseconds since midnight on Jan 1st 1970 UTC. However, I'd strongly advise (as I always do with Java date/time questions) that you use [Joda Time](http://joda-time.sourceforge.net/) instead. It makes this and myriad other tasks a *lot* easier and more reliable. I know I sound like a broken record on this front, but the very fact that it forces you to think about whether you're *actually* talking about a local date/time, just a date, a local midnight etc makes a big difference.
Adding java time objects
[ "", "java", "datetime", "time", "" ]
I have a table with dated records. I want a query that will show the number of records for each date. Not hard, just a GROUP BY, right? Sure. *But I want to also show days where there were NO records.* In this case, I would need to left join against a one-column table of consecutive dates, since a GROUP BY isn't going to show a date that doesn't exist. Is there a better way of doing this? Or do I have to create a populate a table of dates just so I can join against it?
It would probably be easiest to build out the dates table For example, if you wanted all dates from Jan 1, 2009 to today you could do the following: ``` DECLARE @start AS DATETIME, @end AS DATETIME SELECT @start = '2009-01-01', @end = getdate() DECLARE @dates TABLE ( dt DATETIME ) WHILE (@start < @end) BEGIN INSERT @dates SELECT @start SELECT @start = DATEADD(day, 1, @start) END SELECT * FROM @dates ``` @dates will have a record for each day from @start to @end.
If you really don't want a table. On Oracle you could do something like: ``` select D.D, count(T.CompareDate) from (select to_date('2009-07-01', 'YYYY-MM-DD') + LEVEL - 1 as D from dual connect by LEVEL <= 30) D left outer join T ON T.CompareDate = D.D group by D.D ``` Where the date inside to\_date is the starting date, and you test against level for the number of days you want in your results. On SQL Server 2005/2008: ``` ; with X1 (X) as (select 1 union all select 1) , X2 (X) as (select 1 from X1 a cross join X1 b) , X4 (X) as (select 1 from X2 a cross join X2 b) , X8 (X) as (select 1 from X4 a cross join X4 b) , X16 (X) as (select 1 from X8 a cross join X8 b) , NUM (N) as (select row_number() over (order by X) from X16) , D (D) as (select dateadd(day, N-1, '20090701') from NUM where NUM.N <= 30) select D.D, count(T.CompareDate) from D left outer join T on T.CompareDate = D.D group by D.D ``` The `with` clause is to build the dates. The date specified in the `dateadd` is the starting date, and the number of days is tested at `NUM.N <=30`. You could also test against the end date `where dateadd(day, N-1, StartDate) <= EndDate`. I would recommend encapsulating the with clause to create the ranges as an inline table valued function. The number generation is based on code I've seen from Itzik Ben-gan. Each X gives you number of rows equal to power of 2 of the X number (X1 = 2 rows and X8 = 256 rows). If you need more that 65,536, you will need to add more cross joins. If you never need more than 256, then you can eliminate X16. Also, if you have a table of numbers lying around, you can use that and date arithemetic to generate the dates you need on the fly.
Is it possible to effect a join against a table of consecutive dates without having to maintain an actual table of consecutive dates?
[ "", "sql", "" ]
I have this code down and this working fine from command line ... But when I put this in applet I get following error com.sun.star.lang.IllegalArgumentException at com.sun.star.comp.bridgefactory.BridgeFactory.createBridge(BridgeFactory.java:158) at com.sun.star.comp.urlresolver.UrlResolver$\_UrlResolver.resolve(UrlResolver.java:130) Anybody have solution for this problem ? Where I can find BridgeFactory source ? ``` Runtime.getRuntime().exec("C:/Program Files/OpenOffice.org 3/program/soffice.exe -accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"); // oooUrlW - the url of soffice.exe Thread.sleep(5000); XComponentContext xLocalContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null); XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); Object urlResolver = xLocalServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver",xLocalContext); XUnoUrlResolver xUnoUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class,urlResolver); Object initialObject = xUnoUrlResolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"); XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,initialObject); XComponentContext remoteContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, xPropertySet.getPropertyValue("DefaultContext")); XMultiComponentFactory remoteServiceManager = remoteContext.getServiceManager(); Object desktop = remoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext); xDesktop =(XDesktop) UnoRuntime.queryInterface( XDesktop.class, desktop); XComponent xCalcComponent = newDocComponent(xDesktop, "scalc"); XSpreadsheetDocument xCalcDocument = (XSpreadsheetDocument)UnoRuntime.queryInterface( XSpreadsheetDocument.class, xCalcComponent); XSpreadsheets a=xCalcDocument.getSheets(); Object o = a.getByName("Sheet1"); XSpreadsheet sheet = (XSpreadsheet)UnoRuntime.queryInterface( XSpreadsheet.class, o); XCell jjjj = sheet.getCellByPosition(0, 0); jjjj.setFormula("Some Text "); ```
It is signed, and I found kind of solution - on client I grant `permission java.security.AllPermission;` and now everything work... I still did'nt try grant SignedBy "MyCompany" permission java.securyty.AllPermission which I must do... Error message is misleading me com.sun.star.lang.IllegalArgumentException ... stupid message I must use applet ... it is Oracle Forms application and I need to start Calc on client and fill some data. Thanks on help.
Is your applet **signed** ? else I don't think you can call ``` Runtime.getRuntime().exec("C:/Program Files/OpenOffice.org 3/program/soffice.exe-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"); ``` from an applet.
Starting OpenOffice from applet
[ "", "java", "applet", "openoffice.org", "" ]
This question is based on [this thread](https://stackoverflow.com/questions/1146470/to-read-sos-data-dump-effectively). I run unsuccessfully ``` sudo mysql \. /users/cs/SO_db/posts.sql ``` I get the error ``` ERROR 1146 (42S02): Table 'personal.posts' doesn't exist ``` [MySQL's manual](http://dev.mysql.com/doc/refman/4.1/en/error-messages-server.html) says > A five-character SQLSTATE value > ('42S02'). The values are specified by > ANSI SQL and ODBC and are more > standardized. Not all MySQL error > numbers are mapped to SQLSTATE error > codes. The value 'HY000' (general > error) is used for unmapped errors. and > Error: 1146 SQLSTATE: 42S02 > (ER\_NO\_SUCH\_TABLE) > > Message: Table '%s.%s' doesn't exist **How can you solve the error message?**
As I mentioned in the post you referenced, you NEED to create the tables first. Peek at the XML or the SQL output on what columns you need. e.g. here is a table that can hold the output from badges.xml (I don't have the others available right now..) ``` CREATE TABLE `badges` ( `Id` int(11) NOT NULL default '0', `UserId` int(11) not NULL, `Date` datetime not NULL, `Name` varchar(32) not NULL, PRIMARY KEY (`Id`), KEY `Date` (`Date`), KEY `UserId` (`UserId`) ) ; ```
The SQL script you have loaded makes reference to a database and/or table which does not exist in the database. Typically one would not call the `mysql` tool with `sudo`, as the system user privileges are different from MySQL users. To execute an SQL script through mysql I would try something like: ``` cat somefile.sql | mysql -u <mysqluser> -p <mysqldb> ``` This command would load 'somefile.sql' into `mysql` tool, connecting to a MySQL server on `localhost` as user `<mysqluser>` and selecting the database `<mysqldb>`. The `mysql` tool will prompt for `<mysqluser>`'s access password before executing the script.
To run a .sql -file in MySQL
[ "", "mysql", "sql", "mysql-error-1146", "" ]
I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one. First, some context: I have a page that spits out reports of sales data. The data can be filtered by a number of things but is mostly filtered by date. This makes it a bit hard to cache it as the possibilities for results is nearly endless. There are a lot of numbers and calculations done but it was never much of a problem to handle within PHP. UPDATES: * After some additional testing there is nothing within my view that is causing the slowdown. If I am simply number-crunching the data and spitting out 5 rows of rendered HTML, it's not that slow (still slower than PHP), but if I am rendering a lot of data, it's VERY slow. * Whenever I ran a large report (e.g. all sales for the year), the CPU usage of the machine goes to 100%. Don't know if this means much. I am using mod\_python and Apache. Perhaps switching to WSGI may help? * My template tags that show the subtotals/totals process anywhere from 0.1 seconds to 1 second for really large sets. I call them about 6 times within the report so they don't seem like the biggest issue. Now, I ran a Python profiler and came back with these results: ``` Ordered by: internal time List reduced from 3074 to 20 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 2939417 26.290 0.000 44.857 0.000 /usr/lib/python2.5/tokenize.py:212(generate_tokens) 2822655 17.049 0.000 17.049 0.000 {built-in method match} 1689928 15.418 0.000 23.297 0.000 /usr/lib/python2.5/decimal.py:515(__new__) 12289605 11.464 0.000 11.464 0.000 {isinstance} 882618 9.614 0.000 25.518 0.000 /usr/lib/python2.5/decimal.py:1447(_fix) 17393 8.742 0.001 60.798 0.003 /usr/lib/python2.5/tokenize.py:158(tokenize_loop) 11 7.886 0.717 7.886 0.717 {method 'accept' of '_socket.socket' objects} 365577 7.854 0.000 30.233 0.000 /usr/lib/python2.5/decimal.py:954(__add__) 2922024 7.199 0.000 7.199 0.000 /usr/lib/python2.5/inspect.py:571(tokeneater) 438750 5.868 0.000 31.033 0.000 /usr/lib/python2.5/decimal.py:1064(__mul__) 60799 5.666 0.000 9.377 0.000 /usr/lib/python2.5/site-packages/django/db/models/base.py:241(__init__) 17393 4.734 0.000 4.734 0.000 {method 'query' of '_mysql.connection' objects} 1124348 4.631 0.000 8.469 0.000 /usr/lib/python2.5/site-packages/django/utils/encoding.py:44(force_unicode) 219076 4.139 0.000 156.618 0.001 /usr/lib/python2.5/site-packages/django/template/__init__.py:700(_resolve_lookup) 1074478 3.690 0.000 11.096 0.000 /usr/lib/python2.5/decimal.py:5065(_convert_other) 2973281 3.424 0.000 3.424 0.000 /usr/lib/python2.5/decimal.py:718(__nonzero__) 759014 2.962 0.000 3.371 0.000 /usr/lib/python2.5/decimal.py:4675(__init__) 381756 2.806 0.000 128.447 0.000 /usr/lib/python2.5/site-packages/django/db/models/fields/related.py:231(__get__) 842130 2.764 0.000 3.557 0.000 /usr/lib/python2.5/decimal.py:3339(_dec_from_triple) ``` tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. Decimal.py makes sense since the report is essentially 90% numbers. I have no clue what the built-in method `match` is as I am not doing any Regex or similar in my own code (Something Django is doing?) The closest thing is I am using itertools ifilter. It seems those are the main culprits and if I could figure out how to reduce the processing time of those then I would have a much much faster page. Does anyone have any suggestions on how I could start on reducing this? I don't really know how I would fix this the tokenize/decimal issues without simply removing them. Update: I ran some tests with/without filters on most of the data and the result times pretty much came back the same, the latter being a bit faster but not much to be the cause of the issue. What is exactly going on in tokenize.py?
There is a lot of things to assume about your problem as you don't have any type of code sample. Here are my assumptions: You are using Django's built-in ORM tools and models (i.e. sales-data = modelobj.objects().all() ) and on the PHP side you are dealing with direct SQL queries and working with a query\_set. Django is doing a lot of type converting and casting to datatypes going from a database query into the ORM/Model object and the associated manager (objects() by default). In PHP you are controlling the conversions and know exactly how to cast from one data type to another, you are saving some execution time based on that issue alone. I would recommend trying to move some of that fancy number work into the database, especially if you are doing record-set based processing - databases eat that kind of processing from breakfast. In Django you can send RAW SQL over to the database: <http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql> I hope this at least can get you pointed in the right direction...
"tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. " Makes no sense at all. See <http://docs.python.org/library/tokenize.html>. > The tokenize module provides a lexical > scanner for Python source code, > implemented in Python Tokenize coming out on top means that you have dynamic code parsing going on. AFAIK (doing a search on the Django repository) Django does not use tokenize. So that leaves your program doing some kind of dynamic code instantiation. Or, you're only profiling the **first** time your program is loaded, parsed and run, leading to false assumptions about where the time is going. You should **not** ever do calculation in template tags -- it's slow. It involves a complex meta-evaluation of the template tag. You should do all calculations in the view in simple, low-overhead Python. Use the templates for presentation only. Also, if you're constantly doing queries, filters, sums, and what-not, you have a data warehouse. Get a book on data warehouse design, and follow the data warehouse design patterns. You must have a central fact table, surrounded by dimension tables. This is very, very efficient. Sums, group bys, etc., are can be done as `defaultdict` operations in Python. Bulk fetch all the rows, building the dictionary with the desired results. If this is too slow, then you have to use data warehousing techniques of saving persistent sums and groups separate from your fine-grained facts. Often this involves stepping outside the Django ORM and using RDBMS features like views or tables of derived data.
Django (?) really slow with large datasets after doing some python profiling
[ "", "python", "django", "optimization", "" ]
I have a jar or war. I'm programmaticaly reading this jar, and when I find jar inside this jar I'd like to programmaticaly read it again. But JarFile provides only getInputStream, which I cannot pass to JarFile(File file) constructor. How to read jar from jar? EDIT: I was thinking about getting the File somehow from classloader or so.
you can create jar file in File System, something like ``` File tempFile=TempFile.createFile("newJar",".jar"); ``` and write Stream into it. After that you can construct your JarFile(tempFile) and handle it... Forget about it if program is running as unsigned applet/JNLP since you will not have right to create file in file system...
**Update:** Sorry this is probably too late for your needs, I just spotted your last question in the comments though. So I've modified the example to show each nested entry being copied directly to an `OutputStream` without any need to inflate the outer jar. In this case the `OutputStream` is `System.out` but it could be any `OutputStream` (e.g. to a file...). --- There's no need to use a temporary file. You can use `JarInputStream` instead of `JarFile`, pass the `InputStream` from the outer entry to the constructor and you can then read the contents of the jar. For example: ``` JarFile jarFile = new JarFile(warFile); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) entries.nextElement(); if (jarEntry.getName().endsWith(".jar")) { JarInputStream jarIS = new JarInputStream(jarFile .getInputStream(jarEntry)); // iterate the entries, copying the contents of each nested file // to the OutputStream JarEntry innerEntry = jarIS.getNextJarEntry(); OutputStream out = System.out; while (innerEntry != null) { copyStream(jarIS, out, innerEntry); innerEntry = jarIS.getNextJarEntry(); } } } ... /** * Read all the bytes for the current entry from the input to the output. */ private void copyStream(InputStream in, OutputStream out, JarEntry entry) throws IOException { byte[] buffer = new byte[1024 * 4]; long count = 0; int n = 0; long size = entry.getSize(); while (-1 != (n = in.read(buffer)) && count < size) { out.write(buffer, 0, n); count += n; } } ```
JarFile from inside a *.jar or inputstream to file?
[ "", "java", "" ]
I have a class with code as follows ``` private readonly object m_lock = new object(); private IClient m_client private object m_context; ``` When setting the client and context, I lock as follows ``` lock(m_lock) { m_client = theClientFromSomewhere; m_context = contextObject; } ``` My question is, if I only need to get the `m_client` by itself, is it safe to do this? ``` var localClient = m_client; Debug.Assert(localClient != null); localClient.DoStuff(); ``` `m_client` is a reference type, so the read (when assigning to `localClient`) [is guaranteed to be atomic](http://en.csharp-online.net/ECMA-334:_12.5_Atomicity_of_variable_references), so this should work fine on a single CPU. I could (also in theory) make the `m_client` variable `volatile`, and then this would be safe across multiple cpu's by preventing out-of-order reads by other CPU's, but the question is, does the lock-when-writing make it safe to read without being volatile? Does locking when writing "flush" the CPU caches so that when they do a read it won't be out-of-order?
`lock` in C# (and, in general, the `Monitor` that it expands to in .NET) is a memory barrier - specifically, read barrier on acquire, write barrier on release. As for `volatile`, it adds a barrier for *every* read and write to the field. So, yes, you should be safe with `volatile` (assuming the rest of your code, which you didn't show, is doing everything correctly).
If you didn't have m\_context, you wouldn't need the lock as both the read and the write are atomic. If, however, when you read m\_client you also use m\_context, then you have to lock both to prevent a situation where there's a context switch after updating m\_client but before updating m\_context.
If I lock when writing to a variable, do I also need to lock when reading, if the read is otherwise atomic?
[ "", "c#", "multithreading", "locking", "volatile", "" ]
I am trying to follow tecnhique of unobtrusive JavaScript / graceful degradation. I'd like to serve page with different links when JavaScript is turned on, and when JavaScript is turned off. For example when JavaScript is turned off the link would be ``` <a href="script.cgi?a=action"> ``` and when JavaScript is turned on ``` <a href="script.cgi?a=action;js=1"> ``` (or something like that). Both versions (with JavaScript and without JavaScript) of link lead to server side script, but with different parameters. The version that is meant to be called when JavaScript is turned off performs more on server, therefore it would be unproductive to detect JavaScript there (e.g. redirecting from server script for non-JavaScript to the other version via `window.location`). **Note:** I would prefer solution without using JavaScript libraries / frameworks like jQuery.
Well, the answer is to render the page as normal with the non-Javascript links. Then get the Javascript to replace the links with the JS=1 versions. ``` var links = document.getElementsByTagName('a'); for (var i=0;i<links.length;i++) { links[i].href += ";js=1"; } ```
Start with the non-Javascript-enabled link, then simply use some Javascript code to modify the link to its Javascript-enabled value. This ensures that the link will always be the correct version. For example: ``` <a id="link_to_change" href="script.cgi?a=action"> <script type="text/javascript"> window.onload = function(){ document.getElementById("link_to_change").href += ";js=1"; } </script> ```
How to generate different links on web page if JavaScript is enabled?
[ "", "javascript", "unobtrusive-javascript", "graceful-degradation", "" ]
I have written a simple test application using asp.net mvc with C#. The application uses MySQL by using dblinq to generate linq to MySQL files and the application is working both in windows and linux. I have now started to use NUnit to test my code, mostly since I need to test if the code working under windows also will work in linux. My NUnit tests runs well under Windows but not under Linux. This my Windows environment: > NUnit version 2.5.1.9189 Copyright (C) > 2002-2009 Charlie Poole. Copyright (C) > 2002-2004 James W. Newkirk, Michael C. > Copyright (C) 2000-2002 Philip Craig. > All Rights Reserved. > > Runtime Environment - OS Version: > Microsoft Windows NT 5.1.2600 Service > CLR Version: 2.0.50727.3053 ( Net > 2.0.50727.3053 ) This my Linux environment with the error (Library is my application name): > NUnit version 2.4.8 Copyright (C) > 2002-2007 Charlie Poole. Copyright (C) > 2002-2004 James W. Newkirk, Michael C. > Two, Alexei A. Vorontsov. Copyright > (C) 2000-2002 Philip Craig. All Rights > Reserved. > > Runtime Environment - OS Version: > Unix 2.6.24.24 CLR Version: > 1.1.4322.2032 ( Mono 2.4.2.2 ) > > \*\* (/usr/local/lib/mono/1.0/nunit-console.exe:4888): > WARNING \*\*: The class > System.ComponentModel.INotifyPropertyChanged > could not be loaded, used in System, > Version=2.0.0.0, Culture=neutral, > PublicKeyToken=b77a5c561934e089 File > or assembly name Library.Tests, > Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null, or one of its > dependencies, was not found. I can't figure out what I am doing wrong. Do you have any tips? It seems like I need to include System.ComponentModel.INotifyPropertyChanged, I have searched the Internet to see if it is implemented in mono but I can't find any information. Thank you
Somehow you've started the 1.1 CLR - note "CLR Version: 1.1.4322.2032 ( Mono 2.4.2.2 )" I'm not sure how you've done that, but I'm pretty sure that's the problem... How exactly are you running NUnit? I suspect that the problem is you're using a version of NUnit compiled against .NET 1.1, so Mono decides to load its own CLR v1.1. Assuming you're explicitly calling the `mono` binary, try specifying the `--runtime` argument, like this: ``` mono --runtime=2.0.50727 (whatever you previously had here) ``` EDIT: To find out which runtime version you've got, try this Test.cs file: ``` using System; class Test { static void Main() { Console.WriteLine(Environment.Version); } } ``` Then compile and run it: ``` $ gmcs Test.cs $ mono Test.exe 2.0.50727.1433 ``` What version do you get out at the bottom?
Most recent Mono distributions come with two different nunits - one is nunit-console (note no .exe suffix needed, since the packaging supplies convenience shell-scripts), and the other one is nunit-console2. The first is nunit compiled against the CLR 1.1 profile, and the second is nunit compiled against the CLR 2.0 profile. So, the short version - you needed to use "nunit-console2" instead of "nunit-console" to get the correct nunit version for your tests.
Nunit .net vs mono
[ "", "c#", "mono", "nunit", "" ]
> **Possible Duplicate:** > [Encrypt php code](https://stackoverflow.com/questions/764927/encrypt-php-code) I am looking for a encoder to encode php scripts on fly, so that i can request users url through installation file and return a encoded file locked to that url. I found this after searching on net. <http://www.codelock.co.nz/codelock_dynamic.php> but it seems they havent updated it for a long time now and decoders are also available online for this software which people claim working. **/////////////////////EDITED/////////////////** Zend guard is quite expensive i am looking for something below 300$, ioncube <http://www.ioncube.com/sa_encoder.php> provides encoders for linux platform so can i use it the way i specified above? Thank You.
I use Zend Guard. It provides encoding, obfuscation, and license controlls. While Chacha is right that it is impossible to make true 1-way encoding, it is not useless. Your goal isnt too make it impossible to reverse-engineer your code, just not economically feasible.
Encoding PHP script is ultimately useless because there is always a way to crack it. You can make it hard to decode, but it is still very much decodable no matter what. You must put the 'eval' function somewhere, and changing the to a 'echo' will reveal all your code, fully editable. The only true way to keep people from knowing your code is to never give it to them in the first place. If you want to make money using your software A) provide updates/support B) Work for someone, C) Host it on your own server, having people pay for accounts. Anything can be easily hacked and modified, so you have to change your business model rather than your coding.
encoding php scripts on fly
[ "", "php", "" ]
I've written an n-ary tree ADT which works fine. However, I need to store its serialization in a variable a calling class. eg. ``` DomTree<String> a = Data.createTreeInstance("very_large_file.xml"); String x = a.toString(); ``` I've written method which serves the purpose exactly how I need it, but on very large inputs it takes forever (20mins on a 100MB xml file) - I have timed the methods and building the tree from the xml file is quick, but calling toString() as shown above is very slow. ``` @Override public String toString(){ return printTree(this); } public String printTree(AbstractTree<E> tree){ if (tree.isLeaf()){ return tree.getNodeName(); }else{ String tStr = tree.getNodeName() + "("; int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ tStr += printTree(child.next()) + ", "; i++; } tStr += printTree(child.next()) + ")"; return tStr; } } ``` I'm guessing it is to do with the way the string is built up rather than how the tree is traversed? Is there a better way to do this? UPDATE: Following the example of Skaffman, the following code give outOfMemoryError for very large input. ``` @Override public String toString(){ StringBuilder buffer = new StringBuilder(); printTree(this, buffer); return buffer.toString(); ``` } ``` public String printTree(AbstractTree<E> tree, StringBuilder buffer){ if (tree.isLeaf()){ return tree.getNodeName(); }else{ buffer.append(tree.getNodeName()); buffer.append("("); int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ buffer.append(printTree(child.next(), buffer)); buffer.append(", "); i++; } buffer.append(printTree(child.next(), buffer)); buffer.append(")"); return buffer.toString(); } } ``` UPDATE: Works perfectly now, using Skaffmans example
String concats like that are punishingly slow. Use a StringBuilder. ``` @Override public String toString(){ StringBuilder buffer = new StringBuilder(); printTree(this, buffer); return buffer.toString(); } public void printTree(AbstractTree<E> tree, StringBuilder buffer){ if (tree.isLeaf()){ buffer.append(tree.getNodeName()); } else { buffer.append(tree.getNodeName()); buffer.append("("); int i = 0; Iterator<AbstractTree<E>> child = tree.getChildren().iterator(); while (i < tree.getChildren().size() - 1){ printTree(child.next(), buffer); buffer.append(", "); i++; } printTree(child.next(), buffer); buffer.append(")"); } } ```
Don't use string concatenation in loops. It does not scale. Use StringBuilder, this does not make new objects all the time, like string concatenation.. ``` void print() { StringBuilder sb = new StringBuilder(); sb.append("hello"); sb.append(" World!"); System.out.println(sb.toString()); ``` }
Slow string concatenation over large input
[ "", "java", "optimization", "string-concatenation", "" ]
The Query: ``` SELECT MemberId, a.MemberName, GROUP_CONCAT(FruitName) FROM a LEFT JOIN b ON a.MemberName = b.MemberName GROUP BY a.MemberName ``` Table a ``` MemberID MemberName -------------- ---------- 1 Al 1 Al 3 A2 ``` Table b ``` MemberName FruitName --------------- -------------- Al Apple Al Mango A2 Cherry ``` Resulting Output from above query: ``` MemberId MemberName GROUP_CONCAT(FruitName) 3 A2 Cherry 1 A1 Apple,Apple,Mango,Mango ``` The actual tables I am using have 10 columns apiece so just storing everything in one table is not a workaround. That said, how can I change the query to only return `'Apple,Mango'` for `MemberNam`e?
Add the keyword [DISTINCT](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) to the grouped column: ``` GROUP_CONCAT(DISTINCT FruitName) ```
try ``` GROUP_CONCAT(Distinct FruitName) ```
sql: why does query repeat values when using 'GROUP CONCAT' + 'GROUP BY'?
[ "", "sql", "group-by", "left-join", "group-concat", "" ]
i want to convert: ``` HECHT, WILLIAM ``` to ``` Hecht, William ``` in c#. any elegant ways of doing this?
``` string name = "HECHT, WILLIAM"; string s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(name.ToLower()); ``` (note it only works lower-to-upper, hence starting lower-case)
I'd just like to include an answer that points out that although this seems simple in theory, in practice properly capitalizing the names of everyone can be *very* complicated: * [Peter O'Toole](http://www.imdb.com/name/nm0000564/) * [Xavier Sala-i-Martin](http://en.wikipedia.org/wiki/Xavier_Sala-i-Martin) * [Salvador Domingo Felipe Jacinto Dalí i Domènech](http://en.wikipedia.org/wiki/Salvador_Dal%C3%AD) * [Francis Sheehy-Skeffington](http://en.wikipedia.org/wiki/Francis_Sheehy-Skeffington) * [Asma al-Assad](http://en.wikipedia.org/wiki/Asma_al-Assad) * [Maggie McIntosh](http://en.wikipedia.org/wiki/Maggie_McIntosh) * [Vincent van Gogh](http://en.wikipedia.org/wiki/Vincent_van_Gogh) Anyway, just something to think about.
string conversion, first character upper of each word
[ "", "c#", "string", "" ]
Is there any explanation why find() algorithm doesn't work for maps and one have to use map::find instead?
1. It does work on maps, but you need to compare against a `map::value_type` (which is `std::pair<const map::key_type, map::mapped_type>`), not the key type. 2. Because map.find takes a key and returns a key/value pair iterator.
As noted elsewhere, it does work, but the type is the key/value pair, so you need to supply a functor/function to do the comparison. (You could probably do it with a custom operator==() overload too, though I've never tried such a thing) However you probably do want to use the map member function find() anyway since it will give the O(logN) lookup, the algorithm std::find() is O(N). Additional: I think you could also use std::equal\_range/lower\_bound/upper\_bound() with a map ok, these are also O(LogN).
Why STL algorithm find() doesn't work on maps?
[ "", "c++", "stl", "dictionary", "" ]
I am looking at JDM. Is this simply an API to interact with other tools that do the actual data mining? Or is this a set of packages that contain the actual data mining algorithms?
Ah, the wonders of [the interweb](http://en.wikipedia.org/wiki/Java_Data_Mining): > Java Data Mining (JDM) is a standard > Java API for developing data mining > applications and tools. JDM defines an > object model and Java API for data > mining objects and processes. JDM > enables applications to integrate data > mining technology for developing > predictive analytics applications and > tools. The JDM 1.0 standard was > developed under the Java Community > Process as JSR 73. As of 2006, the JDM > 2.0 specification is being developed under JSR 247. Lists some implementations also, although it looks like it may be a dead duck.
Wikipedia [says](http://en.wikipedia.org/wiki/Java_Data_Mining): > Java Data Mining (JDM) is a standard Java API for developing data mining applications and tools. JDM defines an object model and Java API for data mining objects and processes. According to [this article](http://www.artima.com/lejava/articles/data_mining.html) and [the JSR for JDM 2.0 (#247)](http://www.jcp.org/en/jsr/detail?id=247): > By extending the existing JDM standard with new mining functions and algorithms, data mining clients can be coded against a single API that is independent of the underlying data mining system. The goal of JDM is to provide for data mining systems what JDBCTM did for relational databases. So it appears that, yes, JDM is an API to interact with other tools that do the actual mining. It also appears that this JSR is currently inactive.
What is Java Data Mining, JDM?
[ "", "java", "api", "data-mining", "" ]
How do I obtain the HTTP headers in response to a POST request I made with PHP?
How did you issue the POST? I use a socket and then read back the response where I get headers and body.
Create an [HTTP stream context](http://php.net/manual/en/function.stream-context-create.php) and pass it into `file_get_contents()`. Afterwards, you can: ``` $metaData = stream_get_meta_data($context); $headers = $metaData['wrapper_data']; ```
PHP process HTTP headers
[ "", "php", "http", "http-headers", "header", "" ]
I have a data structure which is a collection of tuples like this: ``` things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) ``` The first and third elements are each unique to the collection. What I want to do is retrieve a specific tuple by referring to the third value, eg: ``` >>> my_thing = things.get( value(3) == "Blurgle" ) (154, 33, "Blurgle") ``` There must be a better way than writing a loop to check each value one by one!
If `things` is a list, and you know that the third element is uniqe, what about a list comprehension? ``` >> my_thing = [x for x in things if x[2]=="Blurgle"][0] ``` Although under the hood, I assume that goes through all the values and checks them individually. If you don't like that, what about changing the `my_things` structure so that it's a `dict` and using either the first or the third value as the key?
A loop (or something 100% equivalent like a list comprehension or genexp) is really the only approach if your outer-level structure is a tuple, as you indicate -- tuples are, by deliberate design, an extremely light-weight container, with hardly any methods in fact (just the few special methods needed to implement indexing, looping and the like;-). Lightning-fast retrieval is a characteristic of dictionaries, not tuples. Can't you have a dictionary (as the main structure, or as a side auxiliary one) mapping "value of third element" to the subtuple you seek (or its index in the main tuple, maybe)? That could be built with a single loop and then deliver as many fast searches as you care to have! If you choose to loop, a genexp as per Brian's comment an my reply to it is both more readable and on average maybe twice as fast than a listcomp (as it only does half the looping): ``` my_thing = next(item for item in things if item[2] == "Blurgle") ``` which reads smoothly as "the next item in things whose [2] sub-item equale Blurgle" (as you're starting from the beginning the "next" item you find will be the "first" -- and, in your case, only -- suitable one). If you need to cover the case in which no item meets the predicate, you can pass `next` a second argument (which it will return if needed), otherwise (with no second argument, as in my snippet) you'll get a StopIteration exception if no item meets the predicate -- either behavior may be what you desire (as you say the case should never arise, an exception looks suitable for your particular application, since the occurrence in question would be an unexpected error).
Retrieving a tuple from a collection of tuples based on a contained value
[ "", "python", "tuples", "" ]
I am working on a project where we'd like to pull content from one of our legacy applications, BUT, we'd like to avoid showing the "waiting for www.somehostname.com/someproduct/..." to the user. We can easily add another domain that points to the same server, but we still have the problem of the `someproduct` context root in the url. Simply changing the context root is not an option since there are hundreds of hard coded bits in the legacy app that refer to the existing context root. What I'd like to do is be able to send a request to a different context root (Say `/foo/bar.do`), and have it actually go to `/someproduct/bar.do`, (but without a redirect, so the browser still shows `/foo/bar.do`). I've found a few URL rewriting options that do something similar, but so far they seem to all be restricted to catching/forwarding requests only to/from the same context root. Is there any project out there that handles this type of thing? We are using weblogic 10.3 (on legacy app it is weblogic 8). Ideally we could host this as part of the new app, but if we had to, we could also add something to the old app. Or, is there some completely different solution that would work better that we haven't though of? **Update:** I should mention that we already originally suggested using apace with mod\_rewrite or something similar, but management/hosting are giving the thumbs down to this solution. :/ **Update 2 More information:** The places where the user is able to see the old url / context root have to do with pages/workflows that are loaded from the old app into an iframe in the new app. So there is really nothing special about the communication between the two apps that client could see, it's plain old HTTPS handled by the browser.
I think you should be able to do this using a fairly simple custom servlet. At a high level, you'd: * Map the servlet to a mapping like /foo/\* * In the servlet's implementation, simply take the request's [pathInfo](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html#getPathInfo()), and use that to make a request to the legacy site (using HttpUrlConnection or the Apache Commons equivalent). * Pipe the response to the client (some processing may be necessary to handle the headers).
Why not front weblogic with **Apache**. This is a very standard setup and will bring lots of other advantages also. URL rewriting in apache is extremely well supported and the documentation is excellent. Don't be put off by the setup it's fairly simple and you can run apache on the same box if necessary.
Java HTTP Proxy
[ "", "java", "http", "proxy", "url-rewriting", "url-obsfucation", "" ]
I need to create a function that returns if a URL is reachable or valid. I am currently using something like the following to determine a valid url: ``` static public function urlExists($url) { $fp = @fopen($url, 'r'); if($fp) { return true; } return false; } ``` It seems like there would be something faster, maybe something that just fetched the page header or something.
You could check [http status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html). Here is a code you could use to check that an url returns 2xx or 3xx http code to ensure the url works. ``` <?php $url = "http://stackoverflow.com/questions/1122845"; function urlOK($url) { $url_data = parse_url ($url); if (!$url_data) return FALSE; $errno=""; $errstr=""; $fp=0; $fp=fsockopen($url_data['host'],80,$errno,$errstr,30); if($fp===0) return FALSE; $path =''; if (isset( $url_data['path'])) $path .= $url_data['path']; if (isset( $url_data['query'])) $path .= '?' .$url_data['query']; $out="GET /$path HTTP/1.1\r\n"; $out.="Host: {$url_data['host']}\r\n"; $out.="Connection: Close\r\n\r\n"; fwrite($fp,$out); $content=fgets($fp); $code=trim(substr($content,9,4)); //get http code fclose($fp); // if http code is 2xx or 3xx url should work return ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE; } echo $url; if (urlOK($url)) echo " is a working URL"; else echo " is a bad URL"; ?> ``` Hope this helps!
You can use curl as follows: ``` $ch = curl_init($url); curl_setopt($ch, CURLOPT_NOBODY, true); // set to HEAD request curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // don't output the response curl_exec($ch); $valid = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200; curl_close($ch); ```
What is the fastest way to determine if a URL exists in PHP?
[ "", "php", "url", "" ]
The book *Effective Java* and other sources provide a pretty good explanation on how and when to use the `readObject()` method when working with serializable Java classes. The `readResolve()` method, on the other hand, remains a bit of a mystery. Basically all documents I found either mention only one of the two or mention both only individually. Questions that remain unanswered are: * What is the difference between the two methods? * When should which method be implemented? * How should `readResolve()` be used, especially in terms of returning what? I hope you can shed some light on this matter.
`readResolve` is used for *replacing* the object read from the stream. The only use I've ever seen for this is enforcing singletons; when an object is read, replace it with the singleton instance. This ensures that nobody can create another instance by serializing and deserializing the singleton.
Item 90, Effective Java, 3rd Ed covers `readResolve` and `writeReplace` for serial proxies - their main use. The examples do not write out `readObject` and `writeObject` methods because they are using default serialisation to read and write fields. `readResolve` is called after `readObject` has returned (conversely `writeReplace` is called before `writeObject` and probably on a different object). The object the method returns replaces `this` object returned to the user of `ObjectInputStream.readObject` and any further back references to the object in the stream. Both `readResolve` and `writeReplace` may return objects of the same or different types. Returning the same type is useful in some cases where fields must be `final` and either backward compatibility is required or values must copied and/or validated. Use of `readResolve` does not enforce the singleton property.
Java serialization: readObject() vs. readResolve()
[ "", "java", "serialization", "singleton", "" ]
``` class Base { public: virtual void foo() {} }; class Derived: public Base { public: virtual void foo() {} }; int main() { Base *pBase = NULL; Base objBase; Derived objDerived; pBase = &objDerived; pBase->foo(); /*Here Derived class foo will be called, but i want this to call a base class foo. Is there any way for this to happen? i.e. through casting or something? */ } ```
``` pBase->Base::foo() ```
Both responses above are correct...But be careful, if you need to do that, maybe you have a big problem about the conception or the design...
How to call Base class method through base class pointer pointing to derived class
[ "", "c++", "polymorphism", "" ]
**The title may be incorrect, if so please change. I'm not sure how to ask my question so just look at the code as it should be obvious.** Using the commented code will work but I want to know why the actual code does not work. I'm sure it's wrong but how can it be fixed? Or is this not how its done? ``` using System; namespace SomethingAwful.TestCases.Structs { public class Program { public static void Main() { Foo f = new Foo(); f.Bar.Baz = 1; Console.WriteLine(f.Bar.Baz); } } public class Foo { public struct FooBar { private int baz; public int Baz { get { return baz; } set { baz = value; } } public FooBar(int baz) { this.baz = baz; } } private FooBar bar; public FooBar Bar { get { return bar; } set { bar = value; } } //public FooBar Bar; public Foo() { this.bar = new FooBar(); //this.Bar = new FooBar(); } } } ```
A struct is copied only by value, so all you wind up doing is changing the copy that was returned. Use a class.
Use ``` Foo.FooBar myFooBar = new Foo.FooBar { Baz = 1 }; f.Bar = myFooBar; ``` Like Steven said, you need to create an instance of a struct, and set the property to it. Otherwise it is passed by value.
How is a struct defined as a property?
[ "", "c#", "struct", "properties", "" ]
I have an abstract class, **AbsClass** that implements an interface, **IClass**. **IClass** has a couple properties with only Get accessors. **AbsClass** implements the properties of **IClass** as abstract properties to be defined in the classes that derive from **AbsClass**. So all of the classes that derive from **AbsClass** will also need to satisfy **IClass** by having the same properties with Get accessors. However, in some cases I want to be able to add set accessors to the properties from **IClass**. Yet if I try to override the abstract properties in **AbsClass** with a set accessor I get this error *ConcClassA.Bottom.Set cannot override because AbsClass.Bottom does not have an overridable set accessor* See **ConcClassA** below. If I have a class that is only implementing the **IClass** interface, but not inheriting from AbsClass then I am able to add a set accessor with out problems. See **ConcClassB** below. I could just implement IClass at each derivation of AbsClass rather then directly for AbsClass. Yet I know from my design that every AbsClass needs to also be an IClass so I'd rather specify that higher up in the hierarchy. ``` public interface IClass { double Top { get; } double Bottom { get; } } abstract class AbsClass:IClass { public abstract double Top { get; } public abstract double Bottom { get; } } class ConcClassA : AbsClass { public override double Top { get { return 1; } } public override double Bottom { get { return 1; } //adding a Set accessor causes error: //ConcClassA.Bottom.Set cannot override because AbsClass.Bottom does not have an overridable set accessor //set { } } } class ConcClassB : IClass { public double Top { get { return 1; } //added a set accessor to an interface does not cause problem set { } } public double Bottom { get { return 1; } } } ``` --- **Update** So I think this will make more sense if I explain exactly what I'm trying to do rather then using the abstract example. I work for an Architecture firm and these are business objects related to an architectural design project. I have an abstract class **RhNodeBuilding** that represents one type of building on a project. There is some general functionality, like the ability to have floors, that is defined in **RhNodeBuilding**. **RhNodeBuilding** also inherits from another abstract classes that allow it be part of a larger project tree structure. **RhNodeBuilding** implements from an interface **IBuilding** which defines a number of read only properties that all buildings should be able to provide such as **TopElevation**, **BottomElevation**, **Height**, **NumberOfFloors**, etc..etc.. Keep in mind there are other building types that do not derive from **RhNodeBuilding**, but still need to implement **IBuilding**. Right now I have two types that derive from **RhNodeBuilding**: **MassBuilding** and **FootPrintBuilding**. **MassBuilding** is defined by a 3D shape created by the user. That shape has a **TopElevation** and a **BottomElevation** that should be accessible through the corresponding properties, but you shouldn't be able to edit the 3D volume by changing the properties. **FootPrintBuilding** on the other hand is defined by a closed curve and a height range to extrude that curve through. So not only should the class be able to return what the current elevations are but these elevations should also be able to be changed to redefine the height range. So in summary. All buildings (**IBuildings**) need to be able to return a **TopElevation** and **BottomElevation**, but not all buildings should allow **TopElevation** or **BottomElevation** to be set directly. All **RhNodeBuildings** are **IBuildings**, and classes that derive from **RhNodeBuilding** may or may not need to be able to directly set **TopElevation** and **BottomElevation**. ``` public interface IBuilding { double Top { get; } double Bottom { get; } } abstract class RhNodeBuilding:IBuilding { public abstract double Top { get; } public abstract double Bottom { get; } } class MassBuilding: AbsClass { //mass building only returns Top and Bottom properties so it works fine public override double Bottom { get { return 1; } } public override double Top { get { return 1; } } } class FootPrintBuilding: AbsClass { //Top and Bottom of FootPrintBuilding can both be retrieved and set public override double Top { get { return 1; } //adding a Set accessor causes error: //cannot override because RhNodeBuilding.Top does not have an overridable set accessor //set { } } public override double Bottom { get { return 1; } //adding a Set accessor causes error: //cannot override because RhNodeBuilding.Bottom does not have an overridable set accessor //set { } } } ``` Right now it seems like the best option is to not have **RhNodeBuilding** implement **IBuilding**, but rather have every class that derives from **RhNodeBuilding** implement IBuilding. That way I can define the properties from **IBuilding** directly rather then as overrides. ``` abstract class AltRhNodeBuilding { public abstract double Top { get; } } class AltFootPrintBuilding: IClass { public override double Top { get { return 1; } //Can't add set access to overridden abstract property set { } } //No problem adding set accessor to interface property public double Bottom { get { return 1; } set { } } } ```
This works the way it does because properties aren't truly virtual - their accessor methods are. Thus, you cannot override `set` if there wasn't one in the base class. What you can do is override *and shadow* the base class implementation, and provide your own new read/write properties. I don't know of any way to do this without introducing an additional class in the hierarchy: ``` class AbsClassB : AbsClass { public override double Top { get { return ((ConcClassB)this).Top } } public override double Bottom { get { return ((ConcClassB)this).Bottom } } } class ConcClassB : AbsClassB { new public double Top { get { ... } set { ... } } new public double Bottom { get { ... } set { ... } } } ``` A better idea would be to define a protected virtual method right in `AbsClass`, and implement `Top.get` and `Bottom.get` in terms of that method. Then you can override that method directly in `ConcClassB`, and shadow the properties, without the need for an extra class: ``` abstract class AbsClass : IClass { public double Top { get { return GetTop(); } } public double Bottom { get { return GetBottom(); } } protected abstract double GetTop(); protected abstract double GetBottom(); } class ConcClassB : AbsClass { new public double Top { get { ... } set { ... } } new public double Bottom { get { ... } set { ... } } protected override double GetTop() { return Top; } protected override double GetBottom() { return Bottom; } } ```
I am kind of curious as to why you would want these implementation classes to have public setter methods that are not part of the public interface. It sounds to me like you may actually want these to be more restricted than public? Other than that, I'm having a hard time thinking of a problem with this approach. They would "hide" any properties from the superclass, but there are no property setters in the superclass anyway, so that seems ok. It seems like it may be the simplest workaround.
Adding a set accessor to a property in a class that derives from an abstract class with only a get accessor
[ "", "c#", "interface", "properties", "abstract-class", "" ]
What is the most pythonic way of adding the values of two or more tuples to produce a total for each 'column'? Eg: ``` >>> a = (10, 20) >>> b = (40, 50) >>> c = (1, 3) >>> ??? (51, 73) ``` I've so far considered the following: ``` def sumtuples(*tuples): return (sum(v1 for v1,_ in tuples), sum(v2 for _,v2 in tuples)) >>> print sumtuples(a, b, c) (51, 73) ``` I'm sure this far from ideal - how can it be improved?
I guess you could use `reduce`, though it's debatable whether that's pythonic .. ``` In [13]: reduce(lambda s, t: (s[0]+t[0], s[1]+t[1]), [a, b, c], (0, 0)) Out[13]: (51, 73) ``` Here's another way using `map` and `zip`: ``` In [14]: map(sum, zip(a, b, c)) Out[14]: [51, 73] ``` or, if you're passing your collection of tuples in as a list: ``` In [15]: tups = [a, b, c] In [15]: map(sum, zip(*tups)) Out[15]: [51, 73] ``` and, using a list comprehension instead of `map`: ``` In [16]: [sum(z) for z in zip(*tups)] Out[16]: [51, 73] ```
Since we're going crazy, ``` a = (10, 20) b = (40, 50) c = (1, 3) def sumtuples(*tuples): return map(sum, zip(*tuples)) sumtuples(a,b,c) [51, 73] ``` Truth is, almost every time I post one of these crazy solutions, the 'naive' method seems to work out faster and more readable...
Adding tuples to produce a tuple with a subtotal per 'column'
[ "", "python", "tuples", "" ]
I am using VSTS 2008 + C# + .Net 2.0. And I want to invoke IE to open an html file located under pages sub-folder of my current executable. Since my program may run under Windows Vista, I want to invoke IE under administrative permissions (Run As Administrator). Any code to make reference? I am especially interested in how to write portable code, which works on both Windows Vista and Windows XP (I think Windows XP does not have function like Run As Administrator) EDIT 1: I am using the following code, but there is no UAC (User Access Control) prompt message box opened up to let me select Continue to run with Administrator. Any ideas what is wrong? ``` ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe"); startInfo.Verb = "RunAs"; startInfo.Arguments = @"C:\test\default.html"; Process.Start(startInfo); ``` thanks in advance, Geroge
``` using System.Diagnostics; Process the_process = new Process(); the_process.StartInfo.FileName = "iexplore.exe"; the_process.StartInfo.Verb = "runas"; the_process.StartInfo.Arguments = "myfile.html"; the_process.Start(); ``` the verb "runas" will make it prompt the UAC And run under administrative priviliges. you can run that code underboth vista and XP. It will yield same effect. As for the file which you want to open, you can pass it as the argument to iexplore.exe by using the\_process.arguments = "
For working with relative paths, give a look to the [GetFullPath method](http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx). ``` string fullPath = Path.Combine(Path.GetFullPath(@".\dir\dir2"), "file.html"); System.Diagnostics.Process.Start("iexplore.exe", fullPath); ```
how to invoke IE to open a local html file?
[ "", "c#", ".net", "internet-explorer", "" ]
I'm trying to export a database table as a .csv downloadable from the browser. My code is zend framework based and I'm almost there with the following action: ``` public function exportTableAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $fileName = $this->_getParam('fileName'); $tableName = $this->_getParam('tableName'); header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$fileName.'"'); echo $this->getCsv($tableName, $fileName); } ``` I can download my .csv file containing valid data. However, even if I disabled the layout and the renderer, I still get the output of the header, sidebar, and footer of my page at the end of my .csv file. Is there a way to disable any html output other than the one generated in my exportTableAction? Or can I send the header information and the csv string to the browser in a different way? BTW: I'm using the action stack plugin to help me render the header and sidebar as follows: ``` ... $actionStack = $front->getPlugin('Zend_Controller_Plugin_ActionStack'); $actionStack->pushStack($userlogAction); $actionStack->pushStack($rightcolAction); ``` Cheers, Adrian
We found a solution to the problem. I replaced the following line ``` $this->_helper->viewRenderer->setNoRender(); ``` by ``` $this->_helper->viewRenderer->setNeverRender(); ``` If setNeverRender() is used, no views are rendered (from plugin neither).
You can use contextSwitch action helper. ``` public $contexts = array( 'test' => array('csv') ); public function testAction() { $filename = time() . '.csv'; $this->_helper->contextSwitch()->addContext('csv', array('suffix' => 'csv', 'headers' => array('Content-Type' => 'application/csv', 'Content-Disposition' => 'attachment; filename="'. $filename.'"')))->initContext('csv'); ........................ ........................ } ```
export csv in zend framework
[ "", "php", "zend-framework", "csv", "" ]
those reqular expressions drive me crazy. I'm stuck with this one: ``` test1:[[link]] test2:[[gold|silver]] test3:[[out1[[inside]]out2]] test4:this|not ``` *Task: Remove all [[ and ]] and if there is an option split choose the later one so output should be:* ``` test1:link test2:silver test3:out1insideout2 test4:this|not ``` I came up with (PHP) ``` $text = preg_replace("/\\[\\[|\\]\\]/",'',$text); // remove [[ or ]] ``` this works for part1 of the task. but before that I think I should do the option split, my best solution: ``` $text = preg_replace("/\\[\\[(.*\|)(.*?)\\]\\]/",'$2',$text); ``` Result: ``` test1:silver test3:[[out1[[inside]]out2]] this|not ``` I'm stuck. may someone with some free minutes help me? Thanks!
This is impossible to do in one regular expression since you want to keep content in multiple "hierarchies" of the content. It *would* be possible otherwise, using a recursive regular expression. Anyways, here's the simplest, most greedy regular expression I can think of. It should *only* replace if the content matches your exact requirements. You will need to escape all backslashes when putting it into a string (`\` becomes `\\`.) ``` \[\[((?:[^][|]+|(?!\[\[|]])[^|])++\|?)*]] ``` As others have already explained, you use this with multiple passes. Keep looping while there are matches, performing replacement (only keeping match group 1.) Difference from other regular expressions here is that it will allow you to have single brackets in the content, without breaking: ``` test1:[[link]] test2:[[gold|si[lv]er]] test3:[[out1[[in[si]de]]out2]] test4:this|not ``` becomes ``` test1:[[link]] test2:si[lv]er test3:out1in[si]deout2 test4:this|not ```
I think the easiest way to do this would be multiple passes. Use a regular expression like: ``` \[\[(?:[^\[\]]*\|)?([^\[\]]+)\]\] ``` This will replace option strings to give you the last option from the group. If you run it repeatedly until it no longer matches, you should get the right result (the first pass will replace [[out1[[inside]]out2]] with [[out1insideout2]] and the second will ditch the brackets. **Edit 1**: By way of explanation, ``` \[\[ # Opening [[ (?: # A non-matching group (we don't want this bit) [^\[\]] # Non-bracket characters * # Zero or more of anything but [ \| # A literal '|' character representing the end of the discarded options )? # This group is optional: if there is only one option, it won't be present ( # The group we're actually interested in ($1) [^\[\]] # All the non-bracket characters + # Must be at least one ) # End of $1 \]\] # End of the grouping. ``` **Edit 2**: Changed expression to ignore ']' as well as '[' (it works a bit better like that). **Edit 3**: There is no need to know the number of nested brackets as you can do something like: ``` $oldtext = ""; $newtext = $text; while ($newtext != $oldtext) { $oldtext = $newtext; $newtext = preg_replace(regexp,replace,$oldtext); } $text = $newtext; ``` Basically, this keeps running the regular expression replace until the output is the same as the input. Note that I don't know PHP, so there are probably syntax errors in the above.
Regular Expressions: how to do "option split" replaces
[ "", "php", "regex", "" ]
I'm trying to get my head around how type inference is implemented. In particularly, I don't quite see where/why the heavy lifting of "unification" comes into play. I'll give an example in "pseudo C#" to help clarify: The naive way to do it would be something like this: Suppose you "parse" your program into an expression tree such that it can be executed with: ``` interface IEnvironment { object lookup(string name); } interface IExpression { // Evaluate this program in this environment object Evaluate(IEnvironment e); } ``` So something like "Multiplication" might be implemented with: ``` class Multiply : IExpression { IExpression lhs; IExpression rhs; // etc. public object Evaluate(IEnvironment e) { // assume for the moment C# has polymorphic multiplication return lhs.Evaluate(e) * rhs.Evaluate(e); } } ``` Then to "implement" type inference, you could just do something like: ``` interface ITypeEnvironment { Type getType(string name); } interface IExpression { //as before object Evaluate(IEnvironment e); // infer type Type inferType(ITypeEnvironment typeEnvironment); } ``` Then "Multiplication"'s type inference might just be something like: ``` class Multiply : IExpression { IExpression lhs; IExpression rhs; // ... public Type inferType(ITypeEnvironment typeEnvironment) { Type lhsType = lhs.inferType(typeEnvironment); Type rhsType = rhs.inferType(typeEnvironment); if(lhsType != rhsType) throw new Exception("lhs and rhs types do not match"); // you could also check here that lhs/rhs are one of double/int/float etc. return lhsType; } } ``` lhs and rhs might be simple constants, or "variables" which are looked up in the environment: ``` class Constant : IExpression { object value; public Type inferType(ITypeEnvironment typeEnvironment) { return value.GetType(); // The type of the value; } public object Evaluate(IEnvironment environment) { return value; } } class Variable : IExpression { string name; public Type inferType(ITypeEnvironment typeEnvironment) { return typeEnvironment.getType(name); } public object Evaluate(IEnvironment environment) { return environment.lookup(name); } } ``` But nowhere in this do we end up with the need for a "unification" algorithm. So, clearly, my example is not complex enough. Does it need higher order functions? Do we need "parametric polymorphism"? What is the simplest possible example where "unification" is actually needed to correctly infer the type of an expression. An example in Scheme would be ideal (i.e. an example of a very small Scheme program where you require unification to correctly infer the type of the s-expression).
> ``` > public Type inferType(ITypeEnvironment typeEnvironment) > { > return typeEnvironment.getType(name); > } > ``` What if you just don't know the type of the variable? That's the whole point of type inference, right? Something very simple like this (in some pseudocode language): ``` function foo(x) { return x + 5; } ``` You don't know the type of `x`, until you infer the addition, and realize that it must be an integer because it's added to an integer, or something like that. What if you have another function like this: ``` function bar(x) { return foo(x); } ``` You can't figure out the type of `x` until you have figured out the type of `foo`, and so on. So when you first see a variable, you have to just assign some placeholder type for a variable, and then later, when that variable is passed to some kind of function or something, you have to "unify" it with the argument type of the function.
Let me completely ignore your example and give you an example of where we do method type inference in C#. (If this topic interests you then I encourage you to read the "[type inference](http://blogs.msdn.com/ericlippert/archive/tags/Type+Inference/default.aspx)" archive of my blog.) Consider: ``` void M<T>(IDictionary<string, List<T>> x) {} ``` Here we have a generic method M that takes a dictionary that maps strings onto lists of T. Suppose you have a variable: ``` var d = new Dictionary<string, List<int>>() { ...initializers here... }; M(d); ``` We have called `M<T>` without providing a type argument, so the compiler must infer it. The compiler does so by "unifying" `Dictionary<string, List<int>>` with `IDictionary<string, List<T>>`. First it determines that `Dictionary<K, V>` implements `IDictionary<K, V>`. From that we deduce that `Dictionary<string, List<int>>` implements `IDictionary<string, List<int>>`. Now we have a match on the `IDictionary` part. We unify string with string, which is obviously all good but we learn nothing from it. Then we unify List with List, and realize that we have to recurse again. Then we unify int with T, and realize that int is a bound on T. The type inference algorithm chugs away until it can make no more progress, and then it starts making further deductions from its inferences. The only bound on T is int, so we deduce that the caller must have wanted T to be int. So we call `M<int>`. Is that clear?
Simplest example of need for "unification" in type inference
[ "", "c#", "scheme", "type-inference", "unification", "" ]
How can I create something like: $this->layout()->sidebar, I'm trying for about 4 hours...but it doesn't work for me!Can you give me an example?
I'm still not certain what you are trying to do - but maybe this code that I'm using would help. ``` // setup the info column into the placeholder $this->placeholder('rightcol') ->set($this->render('index/view_infoCol.phtml')); // later in the layout template echo $this->placeholder('rightcol'); ```
use [setResponseSegment](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html)('sidebar') in you controller to make $this->layout()->sidebar work...
Zend Framework problem with Zend_Layout
[ "", "php", "zend-framework", "" ]
I am using VSTS 2008 + .Net + C# 3.5 to develop WCF service (self-hosted as a Windows Service). From client side, I am using ChannelFactory to connect to WCF service. My confusion is, when I change client side code from "public string response" to "public string responseAliasName", the value of responseAliasName is null. But when change back to variable name response, the response value is correct (value is "hi WCF"). My confusion is, I think variable name should not matter as long as the layout is the same from client and server side. Any ideas what is wrong? Server side code: ``` namespace Foo { // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config. [ServiceContract] public interface IFoo { [OperationContract] FooResponse Submit(string request); } [DataContract] public class FooResponse { [DataMember] public string response; } } namespace Foo { // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file. public class FooImpl : IFoo { public FooResponse Submit(string request) { FooResponse foo = new FooResponse(); foo.response = "hi WCF"; return foo; } } } ``` Client side code: ``` namespace Foo { // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config. [ServiceContract] public interface IFoo { [OperationContract] FooResponse Submit(string request); } [DataContract] public class FooResponse { [DataMember] // public string responseAliasName; public string response; } } namespace FooTestClient1 { class Program { static void Main(string[] args) { ChannelFactory<IFoo> factory = new ChannelFactory<IFoo>( "IFoo"); IFoo f = factory.CreateChannel(); FooResponse response = f.Submit("Hi!"); return; } } } ```
you can use ``` [DataContract(Name="ResponseAliasName")] public string response; ``` on Server side and it will work as you expect, DataContract by default uses field or property name to serialize data, and the server can't find correct data
No, the member name is included in the serialization. If you change it on the client side, it can't deserialize back into that member.
why my WCF client gets empty result?
[ "", "c#", ".net", "wcf", "visual-studio-2008", "" ]
I am trying to find the best way to only have to load my view one time and re-use them on different pages. For the home page for example I have this code: ``` function index() { /* Load Includes for all pages */ $header = $this->load->view('includes/header','',true); $scripts = $this->load->view('includes/scripts','',true); $navigation = $this->load->view('includes/navigation','',true); $footer = $this->load->view('includes/footer','',true); /* Load widgets for Home Page*/ $rotator = $this->load->view('widgets/home_feature','',true); $login = $this->load->view('widgets/login','',true); $cal = $this->load->view('widgets/calendar_home','',true); $gallery = $this->load->view('widgets/photos_scroll','',true); $tags = $this->load->view('widgets/tags_view','',true); $spotlight = $this->load->view('widgets/spotlight','',true); $recent = $this->load->view('widgets/activityfeed','',true); $data=array( 'title'=>'Philly2Night.com', 'MetaDesc'=>'Cities2Night new social network', 'MetaKeywords'=>'Social, Party, Plan, Events', //Load Includes 'header'=>$header, 'scripts'=>$scripts, 'navigation'=>$navigation, 'footer'=>$footer, //Load Widgets 'feature'=>$rotator, 'login'=>$login, 'calendar'=>$cal, 'photos'=>$gallery, 'tags'=>$tags, 'spotlight'=>$spotlight, 'recent'=>$recent ); $this->load->vars($data); $this->load->view('pages/home_view'); } ``` How do I create new pages, but referencing these views? I tried making the var global, ideally I want to use switch, and define cases but that alas did not work either.
If I understand correctly, I think you just want to have one common place for all the load code, so that you do not have to copy/paste that part for each action in the controller. If that's the case... Create a constructor in your controller, move the `load->view`s there, and store them into variables inside the class: ``` function __construct() { parent::__construct(); /* Load Includes for all pages */ $this->header = $this->load->view('includes/header','',true); $this->scripts = $this->load->view('includes/scripts','',true); $this->navigation = $this->load->view('includes/navigation','',true); $this->footer = $this->load->view('includes/footer','',true); } ``` Be sure to change any $header, $scripts, etc references to $this->header, $this->scripts, etc. Also, replace `__construct` with your class name if you're using PHP4.
First of all you shouldn't be loading so many pages. Each file system request takes it's toll on performance. Rather than having "header" and "footer" just combine them into the "home\_view" page. Second, your question sounds like you are stating that once you load the views you want them to remain loaded for each page request afterward. That isn't possible with PHP as each request is a whole new load. However, if you are doing a lot of database queries or calculations and then loading widgets you can cache the widgets for 5 mins or so and save the queries each page. Look in the CodeIgniter forums for cache classes.
Multiple pages with codeigniter?
[ "", "php", "jquery", "codeigniter", "" ]
Using jQuery, how can I find the column index of an arbitrary table cell in the example table below, such that cells spanning multiple columns have multiple indexes? # HTML ``` <table> <tbody> <tr> <td>One</td> <td>Two</td> <td id="example1">Three</td> <td>Four</td> <td>Five</td> <td>Six</td> </tr> <tr> <td colspan="2">One</td> <td colspan="2">Two</td> <td colspan="2" id="example2">Three</td> </tr> <tr> <td>One</td> <td>Two</td> <td>Three</td> <td>Four</td> <td>Five</td> <td>Six</td> </tr> </tbody> </table> ``` # jQuery ``` var cell = $("#example1"); var example1ColIndex = cell.parent("tr").children().index(cell); // == 2. This is fine. cell = $("#example2"); var example2ColumnIndex = cell.parent("tr").children().index(cell); // == 2. It should be 4 (or 5, but I only need the lowest). How can I do this? ```
Here's a plugin which can calculate the 'noncolspan' index. ``` $(document).ready( function() { console.log($('#example2').getNonColSpanIndex()); //logs 4 console.log($('#example1').getNonColSpanIndex()); //logs 2 } ); $.fn.getNonColSpanIndex = function() { if(! $(this).is('td') && ! $(this).is('th')) return -1; var allCells = this.parent('tr').children(); var normalIndex = allCells.index(this); var nonColSpanIndex = 0; allCells.each( function(i, item) { if(i == normalIndex) return false; var colspan = $(this).attr('colspan'); colspan = colspan ? parseInt(colspan) : 1; nonColSpanIndex += colspan; } ); return nonColSpanIndex; }; ```
Mine is quite similar to SolutionYogi's, minus the creation of a plugin. It took me a bit longer... but I'm still proud of it so here it is :) ``` cell = $("#example2"); var example2ColumnIndex2 = 0; cell.parent("tr").children().each(function () { if(cell.get(0) != this){ var colIncrementor = $(this).attr("colspan"); colIncrementor = colIncrementor ? colIncrementor : 1; example2ColumnIndex2 += parseInt(colIncrementor); } }); console.log(example2ColumnIndex2); ```
Finding column index using jQuery when table contains column-spanning cells
[ "", "javascript", "jquery", "html-table", "" ]
I have some database information stored in config.inc.php and i'm trying to use it to access the database in a class I have, but for some reason, the variables are null. heres the code: ``` <?php require_once 'dbinterface.php'; require_once 'config.inc.php'; class user { ... function user($id) { $this->db = new db($DB['host'], $DB['user'], $DB['pass'], $DB['database']); ... } ... ?> ``` and here's config.inc.php: ``` <?php $DB['host'] = '192.168.1.107'; $DB['user'] = '****'; $DB['pass'] = '****'; $DB['database'] = 'qa'; ?> ``` I'm not sure why i'm getting nulls, but here's my proof: > Fatal error: Uncaught exception > 'Exception' with message 'No database > selected' in > D:\development\PHP\qanda\dbinterface.php:18 > Stack trace: #0 > D:\development\PHP\qanda\user.class.php(17): > db->db(NULL, NULL, NULL, NULL) #1 > D:\development\PHP\qanda\log.php(17): > user->user('1') #2 {main} thrown in > D:\development\PHP\qanda\dbinterface.php > on line 18
You would have to declare `$DB` as `global` for this to work: ``` global $DB; $DB['host'] = '192.168.1.107'; $DB['user'] = '****'; $DB['pass'] = '****'; $DB['database'] = 'qa'; ``` And in your class definition: ``` function user($id) { global $DB; $this->db = new db($DB['host'], $DB['user'], $DB['pass'], $DB['database']); ... } ```
You have a [variable scoping](http://www.php.net/manual/en/language.variables.scope.php) issue. If your config.inc file is included in the global context, then this should work: ``` function user($id) { global $DB; $this->db = new db($DB['host'], $DB['user'], $DB['pass'], $DB['database']); ... } ```
php defined variables have null values
[ "", "php", "variables", "null", "" ]
Alright, here's an odd one from an MS Access database I'm running. I have a SQL query: ``` SELECT * FROM [Service Schedule] WHERE ID=2 AND Volume <= 3000 AND Term='Monthly' AND special = 'Regular' ORDER BY volume ``` When I put that into the SQL view of the query builder, I get 2 records, one with a volume of 0 and one with a volume of 3000. When I use this code: ``` sSQL = "SELECT * FROM [Service Schedule] WHERE ID=2 AND Volume <= 3000 AND Term='Monthly' and special = 'Regular' ORDER BY volume" Set rsServiceSched = CurrentDb.OpenRecordset(sSQL, dbOpenDynaset, dbSeeChanges) ``` \*\* To see what I'm getting from the query in the code, I'm using Debug.Print to output the recordcount and the volume. I only get 1 record, the one with the volume of 0. Here's where it gets really strange... When I change Volume <= 3000 to Volume < 3000 I get one record (volume = 0) When I change Volume <= 3000 to Volume = 3000 I get one record (volume = 3000) Anyone spot anything blatantly wrong with what I'm doing?
It sounds like you are expecting to 'see' all of the records, but I think you are just retrieving the first record. I say this because you are seeing what would be the first record with each case. You will probably need to move to the next record in your recordset in order to see the next one. ``` rsServiceSched.MoveNext ```
## Digression: A discussion of the Recordcount of DAO recordsets The recordcount of a DAO recordset is not guaranteed accurate until after a .MoveLast, but if any records are returned by the recordset, .RecordCount will be 1 or more. Note that a table-type recordset will return an accurate .RecordCount immediately, without the .MoveLast, but keep in mind that you can't open a table-type recordset on a linked table. Also, be careful and don't assume you're getting the recordset type you want unless you've explicitly specified it. While dbOpenTable is the default recordset type, if the table or SQL string can't be opened as a table-type recordset, it will fall over to opening a dynaset. Thus, you can think you're opening a table-type recordset with this because table-type is the default and you've passed a table name: ``` Set rs = CurrentDB.OpenRecordset("MyTable") ``` but you have to remember that just because you pass it a table, it won't necessarily open a table-type recordset, and the recordcount won't necessarily be accurate. If you really want to be sure you're opening a table-type recordset, you need to specify that explicitly: ``` Set rs = CurrentDB.OpenRecordset("MyTable", dbOpenTable) ``` If "MyTable" is a linked table, that will throw an error. If you have a mix of linked tables and local tables, you'll have to use two different methods to obtain a table-type recordset. Otherwise (i.e., if you're not specifying the recordset type and letting it be table-type when possible and a dynaset when not), you need to know when you need to .MoveLast to get an accurate .RecordCount. If you really want to be efficient in that case, you'll test the .Type of the recordset: ``` Set rs = CurrentDB.OpenRecordset("MyTable") If rs.Type = dbOpenDynaset Then rs.MoveLast End If ``` At that point, you'll have an accurate .RecordCount property whether the recordset opened as table-type or as a dynaset. But keep in mind that it's very seldom that you need to use a full recordset to get a recordcount. Usually, you will examine the .RecordCount only to see if your recordset has returned any records, and in that case, you don't need an accurate count. Likewise, if you're going to walk through the full recordset, you'll eventually have an accurate RecordCount. That is, it would be senseless to do this: ``` Set rs = CurrentDB.OpenRecordset("MyTable") rs.MoveLast If rs.RecordCount > 0 Then .MoveFirst Do Until rs.EOF [something or other] .MoveNext Loop End If Debug.Print rs.RecordCount ``` The .MoveLast is completely unneeded in that context as you don't need to know the exact count at that point in the code. Also, keep in mind that in some contexts where you really do need to know the exact .RecordCount, it may be more efficient to just use the built-in Access DCount() function, or to do something like this: ``` Dim lngRecordCount As Long lngRecordCount = CurrentDB.OpenRecordset("SELECT COUNT(*) FROM MyTable")(0) ``` Or: ``` lngRecordCount = DBEngine.OpenDatabase(Mid(CurrentDB.TableDefs("MyTable").Connect, 11)).TableDefs("MyTable").RecordCount ``` There are all sorts of efficient shortcuts to get the accurate RecordCount without forcing the recordset pointer to travel to the last record. BTW, one of the reason the RecordCount for a pure Table-Type record is accurate is because it doesn't have to be calculated -- Jet/ACE maintains the RecordCount property as part of its regular operations. ## Digression: A discussion of the Recordcount of ADO recordsets By @onedaywhen For an ADO recordset, the `RecordCount` property will always be the final value. That is, unlike DAO, if you check its value it cannot subsequently change. Navigating `EOF` does not affect the `RecordCount` value in any way for ADO. This is true even when fetching records asynchronously (something DAO recordsets does not explicitly support): that is, even when the recordset is not yet full, the `RecordCount` property still reflects the final value (not the number of records fetched so far, as for DAO). Some combinations of `CursorLocation` and `CursorType` will cause `RecordCount` to always be -1, meaning the property is not supported. But, again, this will remain constant i.e. if it is initially -1 then it will always be -1. The applicable combinations for the Access database engine for which `RecordCount` is not supported are `adOpenForwardOnly` and `adOpenDynamic` but only when using a server side cursor location. (Note the Access database engine doesn't actually support dynamic cursors: instead `adOpenDynamic` is overloaded for the user to provide an optimization 'hint' to the engine that the recordset's `Source` is dynamic SQL code). Note that setting the recordset's `Filter` property will change the `RecordCount` to reflect the number of records after the filter has been applied.
Odd Results from an SQL query in MS Access
[ "", "sql", "ms-access", "" ]
I have a WinForms ListView, obviously containing ListViewItems. I'd like to be able to attach a click event to each item, instead of to the entire ListView (and then trying to figure out what item was clicked). The reason for this is that I need to perform a different action based on which item was selected. The ListViewItem class seems to be very limited in this regard. Is there any way to do what I want, or am I forced to use the ListView.Click event?
I would still use the ListView Click event. A trick I've used in these situations is to use the Tag property of a ListViewItem. It's great for storing per item data and you can put anything in it.
It may make sense to subclass `ListViewItem` and use virtual dispatch to select the appropriate behavior based on the selected `ListViewItem` in the appropriate `ListView` event. E.g. (uncompiled) ``` public abstract class MyItems : ListViewItem { public abstract DoOperation(); } public class MyItemA : MyItems { public override DoOperation() { /* whatever a */ } } public class MyItemB : MyItems { public override DoOperation() { /* whatever b */ } } // in ListView event MyItems item = (MyItems)this.SelectedItem; item.DoOperation(); ``` As others have mentioned, it may also make sense to use the appropriate Tag property. Which technique you go for really depends on what your action is (and therefore where it belongs, architecturally). I assumed the subclass made more sense because you're looking for a click on a listview item, and that (to me) seems more likely to be presentation-layer b/c you're overriding some standard control behavior (which would normally just select an item) as opposed to doing something in response to behavior.
Is there an easy way to associate an event with a ListViewItem?
[ "", "c#", ".net", "winforms", "listview", "listviewitem", "" ]
Is there any difference between pointer to const and usual pointer for functions? When it is suitable to use const qualifier for stand alone functions? I wrote short sample to illustrate my question: ``` #include <iostream> using namespace std; int sum( int x, int y ) { return x + y; } typedef int sum_func( int, int ); int main() { const sum_func* sum_func_cptr = &sum; // const function sum_func* sum_func_ptr = &sum; // non-const function ? // What is the difference between sum_func_cptr and sum_func_ptr int x = sum_func_cptr( 2, 2 ); cout << x << endl; int y = sum_func_ptr( 2, 2 ); cout << y << endl; sum_func_cptr = 0; sum_func_ptr = 0; return 0; } ``` g++ gives no warnings. That's why I ask.
Your code is **ill-formed** with regard to C++03. You can **not** ever construct a const (or volatile) qualified function type. Whenever you do, your program becomes ill-formed. This rule [has been changed](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#295) for C++1x, to make the compiler ignore the `const` / `volatile`. C++ compilers will usually already implement this rule even in C++03 mode. Thus, the following two will define the same function twice, and results in a compilation error. ``` typedef void Ft(); void f(Ft const*) { } void f(Ft *) { } // another definition! ``` Here is the proof of my claim. C++03, `8.3.5/1` > A cv-qualifier-seq shall only be part of the function type for a nonstatic member function, the function type to which a pointer to member refers, or the top-level function type of a function typedef declaration. The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type, i.e., it does not create a cv-qualified function type. In fact, if at any time in the determination of a type a cv-qualified function type is formed, the program is ill-formed. Here is that text for C++1x, `8.3.5/7` n2914: > A cv-qualifier-seq shall only be part of the function type for a non-static member function, the function type to which a pointer to member refers, or the top-level function type of a function typedef declaration. The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. The above says that the below is valid, though, and creates the function type for a function that can declare a const member function. ``` typedef void Ft() const; struct X { Ft cMemFn; }; void X::cMemFn() const { } ```
Stand alone functions are const by definition. Hence there is no difference between a const and a non-const function pointer.
pointer to const vs usual pointer (for functions)
[ "", "c++", "function-pointers", "" ]
[MochaUI](http://mochaui.com/demo) is very intuitive and the modal iframes almost perfectly replicate Windows. Unfortunately, I have scripts written in Jquery that I use, and I hear there are conflicts when putting both Mootools and Jquery on one html file (is this true?). How can I get the MochaUI features in Jquery? At the very least, is there a similar modal dialog system? I've seen JqueryUI Dialog but it makes the background go dark and nonfunctional, which is not what I am looking for.
With some tweaking (enable JQuery noConflict-Mode, replace the $ selector by something like $jq) you should be able to get to work both. However you might easily end up with a Frankenstein app that mixes MooTools and Jquery plugins. Also the javascript load is quite enormous, because you have to include Mootools, JQuery AND their top-level UI toolkits. I'd recommend that you investigate if JQuery UI could replace MochaUI (or vice versa). One combination of JS lib + UI toolkit is far easier to maintain. The downside of MochaUI is that it has some issues with IE8, furthermore it is not very up-to-date (last release Sept 2008). JQuery UI is much more modular (you can just pick the parts you need), has a visual CSS Theme Editor (Themeroller) and offers a 2-month release schedule. Its disadvantages: it doesn't yet cover essential UI components (such as a menu, a "viewport" manager that renders you UI components, palettes). However, these features are expected soon.
I really love mocha-ui, and anyone who suggests jquery UI as an alternative just doesn't "get it". Mocha-ui is smooth and beautiul, it looks professional, like a windows app in your browser. I'm sure with css updates in the browsers it'll be very easy to accomplish what Mocha-UI already does, sadly we're not there yet. If anyone ever does come out with a jquery plugin that has all of the functionality of mocha-UI, I hope they post it here and other places so we can all share with the goodness. :)
What is Jquery's alternative to Mootools MochaUI?
[ "", "javascript", "jquery", "user-interface", "mootools", "" ]
I've got a table with a BLOB column. What I want to do is get it to be able to pick out words and list them in order. For example if it contained: * Bob Smith likes cheese but loves reading * Charlie likes chocolate milk * Charl loves manga but also likes cookies Then I would get 1. likes 2. loves as a result... is this possible and if so how? I'd like to be able to do it in just mysql alone, but I can use php as well. Thanks in advance, kenny
I've re-worked my code so I no longer need to do this... it seems impossible with standart setups
Don't think there is any built in MySQL function to do this so you are probably best using PHP to do the work for you using either `explode(' ', $myString)` or `str_word_count($myString, 1)` to create an array containing each word. Then loop through each word in the array and count them.
How can I get the most popular words in a table via mysql?
[ "", "php", "mysql", "popularity", "" ]
Seems like the problem with this is the PHP syntax, but no luck in Wordpress forums. This first code block generates a link to the newest post in category "posts." ``` <?php $my_query = new WP_Query('category_name=posts&showposts=1'); ?> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> <?php endwhile; ?> ``` This next code block should display the custom field data for the latest post in "posts," with the key of the custom field being "qanda." But it doesn't and it displays nothing. ``` <?php $my_query = new WP_Query('category_name=posts&showposts=1'); ?> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <?php echo get_post_meta($post->ID, "qanda", $single = true); ?> <?php endwhile; ?> ``` Thanks, Mark
try renaming your second query, otherwise Wordpress will think it is already done ``` <?php $my_other_query = new WP_Query('category_name=posts&showposts=1'); while ($my_other_query->have_posts()) : $my_other_query->the_post(); echo get_post_meta($post->ID, "qanda", true); endwhile; ?> ```
Apart fromthat `$single = true` should just be `true` it looks OK... try [`var_dump`](http://php.net/var_dump) instead of `echo` and see what you get.
Is the syntax problematic with this PHP code for Wordpress?
[ "", "php", "wordpress", "" ]
I have an application that declares textboxes in various places, like in styles and datatemplates, and now I'm in a situation where I need to change every textbox's standard behavior for getting and losing focus. What's a good way to do this? I was thinking of two solutions: one is to derive a new class from TextBox, which I understand is generally frowned upon. The other is to create some kind of style that uses EventSetters, but since the styles and datatemplates in my application don't have codebehind files I donno how an event will find the appropriate event handler.
You can create a style that applies to all TextBoxes using the Key property as follows: ``` <Style x:Key={x:Type TextBox}> ... </Style> ``` You can then modify the Template property of the TextBox and use Triggers to add special behavior to the OnGotFocus and OnLostFocus events.
Based on your feedback, I'd recommend an attached behavior used as follows: ``` <TextBox b:TextBox.SuppressOnFocus="True"/> ``` The attached behavior implementation would simply attach to GotFocus and LostFocus and clear/reapply the binding as appropriate.
Changing the standard behavior of a TextBox?
[ "", "c#", "wpf", "textbox", "" ]
I am new to .NET 3/3.5 (C#) Programming. It may be simple for you but not for me. I have a task to executing stored procedure from c# application, using command and it returns 3 different data tables proc is already done in sql 2005,but I want to know how to get data in c#. exactly need c# code how to handle data tables form the result set,if result set returns more than one datatable. Thanks
You can use the [SqlDataAdapter.Fill()](http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.fill.aspx) method to fill a [DataSet](http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx). This way you can access the multiple result tables using this - ``` ds.Tables[0].Rows[0]["Column X"]; ds.Tables[1].Rows[0]["Column Y"]; ds.Tables[2].Rows[0]["Column Z"]; ... ``` Or, you can use a [SqlDataReader](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx) (which is faster if you want to process your data in a forward-only fashion). For reading the records of the first result set, you can iterate a `while` loop and call the [SqlDataReader.Read()](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx) method. ``` while(reader.Read()) { //Process the first result set here. } ``` For fetching the next result set, you call the [SqlDataReader.NextResult()](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult.aspx) method. ``` reader.NextResult(); while(reader.Read()) { //Process the next result set here. } ```
Use NextResult in case of ExecuteReader ``` SqlDataReader reader = command.ExecuteReader(); while (reader.HasRows) { Console.WriteLine("\t{0}\t{1}", reader.GetName(0),reader.GetName(1)); while (reader.Read()) { Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0), reader.GetString(1)); } reader.NextResult(); } ```
C# objects and code examples
[ "", "c#", "" ]
I have a set of strings. I want to select all strings that contains another string. But I want to have as the first items, the items that start with the search, and then, alphabetically the other items. But the following code doesn't work: ``` items = items .Where(a => a.Contains(contained)) .OrderBy(a => a) ; var startsWith = items.Where(a => a.StartsWith(contained)); items = startsWith.Union(items.Except(startsWith)); ``` What I have to do?
Replace startsWith.Union with startsWith.Concat
As well as Michael's option, you could also order by a Boolean: ``` items = items.OrderBy(x => !x.Contains(contained)) .ThenBy(x => x); ``` Note that `false` sorts before `true` hence the ! here - you could also use a conditional to make it clearer: ``` items = items.OrderBy(x => x.Contains(contained) ? 0 : 1) .ThenBy(x => x); ``` Test program: ``` using System; using System.Linq; public class Test { static void Main() { var items = new string[] { "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" }; var query = items.OrderBy(x => !x.Contains("o")) .ThenBy(x => x); foreach (string word in query) { Console.WriteLine(word); } } } ``` Output: ``` brown dog fox over jumps lazy quick the the ```
How to use two ordering criteria in C#?
[ "", "c#", ".net", "linq", "c#-3.0", "" ]
After going through some links on exception handling ([1](http://msdn.microsoft.com/en-us/library/hatewcfd(VS.71).aspx), [2](http://www.cplusplus.com/reference/std/exception/exception/), and [3](http://www.cplusplus.com/doc/tutorial/exceptions/)), I know that C++ programs can throw pretty much anything as exceptions (`int`, `char*`, `string`, `exception` class). I know that `std::exception` is the base class for standard exceptions thrown by the program. However, I'm trying to design a `try`...`catch` block as such: ``` try { MyFunc(); } catch (certain exceptions) { // deal with the exception accordingly } catch (the rest of the exceptions) { // deal with these accordingly } ``` while `MyFunc()` contains the following: ``` void MyFunc() { ... if (certain condition is true) throw exception; ... } ``` The trouble is that in that part of `MyFunc` function, I'm not sure what type of exception I should throw. To keep the code clean by implementing my own exceptions class, I have no idea what would be a good way to implement such exceptions class.
You would derive your own class from [`std::exception`](http://en.cppreference.com/w/cpp/error/exception), so that there is some way of uniformly handling exceptions. If this seems like overkill, you can throw [`std::logic_error`](http://en.cppreference.com/w/cpp/error/logic_error) or one of the other standard exception types intended for applications to use. You could also use these as base classes for your own more specific exceptions: this saves a little work because they take care of implementing the `what` method for you. Note that deep exception hierarchies can be unusable, because you're basically making a guess in advance about how to categorize the errors, and your clients may disagree.
Here is a code snippet that shows how to extend and use the std::exception class: (BTW, this code has a bug, which I will explain later). ``` #include <iostream> #include <string> #include <exception> class my_exception : public std::exception { public: explicit my_exception(const std::string& msg) : msg_(msg) {} virtual ~my_exception() throw() {} virtual const char* what() const throw() { return msg_.c_str(); } private: std::string msg_; }; void my_func() throw (my_exception&) { throw my_exception("aaarrrgggg..."); } int main() { try { my_func(); } catch (my_exception& ex) { std::cout << ex.what() << '\n'; } return 0; } ``` Note that the constructor is explicit and the destructor and what() are declared (using throw()) to indicate that they themselves will not throw exceptions. This is where the bug is. Is it guaranteed that the call to msg\_.c\_str() will not throw exceptions of its own? What about the string constructor we are using to initialize msg\_? It can also raise exceptions. How can we design an exception class that is safe from exceptions raised by member objects? The answer is - inherit from std::runtime\_error or a similar std::exception subclass. So the proper way to implement my\_exception would be: ``` class my_exception : public std::runtime_error { public: my_exception(const std::string& msg) : std::runtime_error(msg) { } }; ``` We need not override what(), as it is already implemented in std::runtime\_error. Proper handling of the message buffer is done by std::runtime\_error, so we can be sure that my\_exception itself will not throw some unknown error at runtime.
What type of exception should I throw?
[ "", "c++", "exception", "" ]
I've got to validate numerous dates with my current project. Unfortunately, these dates can vary wildly. Examples include: 1. 1983-07-10 (After 1970) 2. 1492-10-11 (Before 1970, year of Unix Timestamps - this eliminates strtotime() on some systems) 3. 200 B.C. (Really old...) Dates will not exceed 9999 b.c., nor will they be future (beyond 'today'). What would be the best way to validate that the values submitted are indeed dates, and proper dates at that? **Updates...** All dates must be sortable within their global list. Meaning dates 1 and 3 above must be comparable to one-another, and sorted ASC or DESC. I'm fully aware of the calendar-changes that have taken place in the past, and the confusion around these changes. My project assumes the user has already performed the proper calibration to find out the date according to our modern-calendar system. I won't be performing this calibration for them.
How about a series of carefully-written regular expressions that recognize each possible format. Once you know the format, you can validate and perhaps put it into a uniform representation (e.g., 64-bit time\_t). e.g., ``` /(\d{4})-(\d{2})-(\d{2})/ /(\d+)(bc|b.c.|bce|b.c.e)/i etc. ``` Since it sounds like each form has its own validation rules, and you're not implementing any widely-available standard, I think you're stuck validating each case separately. Update: > All dates must be sortable within their global list. It seems to me that in order to be able to sort dates that appear in different formats you would need a uniform representation for each one internally, as I mentioned before. For example, use a multi-key dictionary (std::multimap in C++, not sure about PHP) to store (uniform representation)->(input representation) mappings. Depending on the implementation of the container, you may get reverse lookups or key ordering for free.
What about using Zend\_Date. [Zend's date library](http://framework.zend.com/manual/en/zend.date.html) is a very good date utility library. It can work standalone or with other Zend Libraries and can work with date\_default\_timezone\_set() so dates are automatically parsed for the set timezone and it will work for dates outside of the Unix timestamp range. It can be a little long-winded to write sometimes, but it's strengths greatly outweigh its weaknesses. You may have to implement your own custom parsing for BC/AD as I'm not sure it would work for that, but it might be worth a try. [Pear also has a date library](http://pear.php.net/package/Date) that might be worth looking at, however, I haven't used it and have heard from a lot of people that they prefer Zend\_Date to Pear's Date package. You could always write your own, but why re-invent the wheel. If it doesn't roll the way you want, take it and improve upon it ;)
Advanced Date-Validation with PHP
[ "", "php", "validation", "date", "" ]
I've got an IntPtr marshaled across an unmanaged/managed boundary that corresponds to an Icon Handle. Converting it to an Icon is trivial via the FromHandle() method, and this was satisfactory until recently. Basically, I've got enough thread weirdness going on now that the MTA/STA dance I've been playing to keep a hosted WinForm from breaking the primary (WPF-tastic) UI of the application is too brittle to stick with. So the WinForm has got to go. So, how can I get an ImageSource version of an Icon? Note, I've tried ImageSourceConverter to no avail. As an aside, I can get the underlying resource for *some* but not all of the icons involved and they generally exist outside of my application's assembly (in fact, they often exist in unmanaged dll's).
Try this: ``` Icon img; Bitmap bitmap = img.ToBitmap(); IntPtr hBitmap = bitmap.GetHbitmap(); ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ``` **UPDATE**: Incorporating Alex's suggestion and making it an extension method: ``` internal static class IconUtilities { [DllImport("gdi32.dll", SetLastError = true)] private static extern bool DeleteObject(IntPtr hObject); public static ImageSource ToImageSource(this Icon icon) { Bitmap bitmap = icon.ToBitmap(); IntPtr hBitmap = bitmap.GetHbitmap(); ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!DeleteObject(hBitmap)) { throw new Win32Exception(); } return wpfBitmap; } } ``` Then you can do: ``` ImageSource wpfBitmap = img.ToImageSource(); ```
Simple conversion method without creating any extra objects: ``` public static ImageSource ToImageSource(this Icon icon) { ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon( icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return imageSource; } ```
Convert System.Drawing.Icon to System.Media.ImageSource
[ "", "c#", "wpf", "windows", "winforms", "" ]
Can this ever happen ? 3 asserts, where one should activate. ``` int nr = perform_calc(); assert( nr == 0); assert( nr > 0); assert( nr < 0); ``` Can there be a case when the program doesn't activate the asserts on g++ 3.4.4. And no I don't have the possibility to change the code in order to print the number out in case the asserts don't activate. Any ideas? Edit: After reading several comments I was forced to edit. Show the code? why are you doing this stupid thing ? I don't believe it ! Where is it used ? From my question it should have been obvious that I will not post/change the code because of several possible reasons: * I'm a total beginner and is ashamed of the code (no crime there, sure it makes answering to the question much easier if I did post it) * I was asked to help out a friend with only little information (and no I did not ask him why can't you check the number returned, or why can't he just add a breakpoint). * I am writing my code in emacs without any compiler and is sending it to a remote server that compiles it, runs it and only can return failed asserts if something goes wrong. If you believed that I was making a prank or a hoax you should have voted for a closure of the thread instead. I would have been perfectly fine with that. But adding unnecessary comments like this only made me want an "attitude" flag to be implemented. I want to thank others for their comments and answers that actually tried to explain and answered my question.
As I've seen so ugly things in my life, it could be explained if perform\_calc() has a buffer overrun that overwrites the return address in the stack. When the function ends, the overwritten address is recovered from the stack and set to the current PC, leading to a jump maybe in another area of the program, apparently past the assertion calls. Although this is a very remote possibility, so it's what you are showing. Another possibility is that someone did an ugly macro trick. check if you have things like ``` #define assert ``` or some colleague put something like this in a header while you were at the restroom ``` #define < == #define > == ``` As suggested in another answer, check with gcc -E to see what code is actually compiled.
`assert` is unchecked if the macro `NDEBUG` is defined. Make sure you `#undef NDEBUG` when compiling this translation unit. You can invoke gcc with the `-E` switch to verify that your assert statements are still in the code.
C/C++ an int value that isn't a number?
[ "", "c++", "c", "numbers", "int", "assert", "" ]
note: I am using the Infragistics control because this is inherited legacy code, but I am not above rewritting with an ASP.NET control if that is a better solution. I have a Repeater control that uses an Infragistics WebDateChooser to select a date for a record. Let's say each item in the Repeater represents a customer, and I am selecting an activation date or something of that nature. It could be any time past, present, or future. When you render this control 20 times, it writes all of the heavy html for showing all of the dates (month names, weekdays, etc etc) 20 times and bloats the html dramatically. This causes the browser to really struggle with rendering the page in any reasonable amount of time, even for 20 records (paging implemented on the repeater just to prevent the browser from crashing on massive page). This is also true to a lesser (but still significant) degree with the standard ASP.NET calendar control. What I'm looking for is a way to possibly make all 20 date choosers share the resources of 1 calendar so they don't each need to render their own strings and crap for displaying verbose dates. **EDIT:** I understand many users have not used Infragistics, but it's still just as true with the standard, built in ASP:Calendar control. Put one in a repeater and display n > 20 times. It bogs down the browser when rendering. Also, just to clarify incase this matters to anyone's potential solution, this codebase is on .NET 2.0 and has to support IE6.
Another thing you might consider is to have one instance of the calendar on the page. When the user clicks a textbox that "activates" the calendar, you can use a client-side javascript framework like jquery to show the calendar and move it the correct expected position. Once the date is selected, store the selected date in the correct text box and hide the calendar again. You'll have to write some javascript but it beats downloading all the extra bloat!
If what you are looking for is a Datepiker that is called and displayed on each date field in a grid, calling a JavaScript calendar is the most efficient. Check out the JQuery ui calendar and just put the call on each field -- see: jqueryui.com/demos/. HTML -- note the class is the same and ID different: ``` <input type="text" class="datepicker" id="d1" /> <input type="text" class="datepicker" id="d2" /> ``` JQuery then selects the css class: ``` $(.datepicker.each(function() { $(this).datepicker(); }); ``` The older ASP.Net solution is for a control to be declared and dynamically instantiated on the server when the click even is fired. There are many example of this on lots of blogs. Or 20 of them can be created on page load and placed in a datagrid or something. But what if the datagrid has 100 entries? It cannot scale. But there is a calendar in the AJAX control toolkit that is created once on a panel and then that panel is displayed where you tell it. It is one calendar, shown many times. ``` <asp:Panel ID="panelCal" runat="server">       <asp:UpdatePanel ID="update" runat="server">            <ContentTemplate>    <asp:Calendar ID="theonlyCal"runat="server"/>            </ContentTemplate>       </asp:UpdatePanel> </asp:Panel> ``` Now say there are 20 rows: ``` <asp:TextBox ID="twenty" runat="server" /> ``` Now each text box needs a popup control extender. ``` <ajaxToolkit:PopupControlExtenderID="twentExtenders"runat="server" TargetControlID="twenty" PopupControlID="panelCal" Position="Bottom" /> ``` ASP.NET AJAX can use lots of bandwidth.
rendering multiple Calendars bloats html, bogs down page
[ "", "c#", "asp.net", "html", "calendar", "" ]
I have a console application written in C# which processes some data then prints the results. Until the results are available there is a little animation ( / - \ | ) and progress percentage ( xx% ) which is constantly updating. Obviously if the user redirects the output of my application this will be printed to the text file where output is redirected to. If possible I would like to avoid this. So is there a way to detect if the output of my application is redirected? I am considering only showing the progress indicators when run with a specified parameter, but I'm hoping someone will have a good answer for me.
You can't. Redirected output is totally and wholly outside the scope of the executing program. You **can** however add a commandline option to disable your pretty output so that it can be used redirected too. **EDIT: You CAN (now)...** with .NET 4.5 onwards (see [Matt Brooks' answer](https://stackoverflow.com/a/31982628/1245420)).
From .NET Framework 4.5 onwards you can use the [`Console.IsOutputRedirected` property](https://msdn.microsoft.com/en-us/library/system.console.isoutputredirected(v=vs.110).aspx) to detect this. There's also `Console.IsErrorRedirected`.
Check if output is redirected
[ "", "c#", ".net", "redirect", "console", "" ]
I'm writing a c++ shared library that is intended to be used by other library or executable. What is the best way to add a generic logging in my library? Ideally I'd like to adapt my library to logging functionality chosen by the library's user. Suppose i have a class in my library ``` class A { public: void method(string param1, int param2); } void A::method(string param1, int param2){ /* i want to log values of param1 and param2, but actual logging method must be defined outside of my library. Maybe some kind of macro should help here. */ /*e.g.*/ GENERICLOG_DEBUG("param1=" + param1+ " param2="+param1); /*if so, what that macro body should look like ? */ } ``` I don't want to make my library tied to any log4XXX specific API.
You can provide a callback mechanism to allow the library's user to provide your library with an adapter into their logging. I.e., in your library provide an abstract logging interface class, e.g.: ``` class Logger { public: virtual ~Logger () {} virtual void log (const std::string& message) = 0; }; ``` and a class to regster a Logger with: ``` class Log { private: static Logger* logger_; public: static void registerLogger (Logger& logger) { logger_ = &logger; } static void log (const std::string& message) { if (logger_ != 0) logger_->log (message); } }; ``` Your library then logs with something like: ``` Log::log ("My log message"); ``` The application using your library should provide an implementation of Logger (i.e. a concrete subclass) and register it with your Log class. Their Logger impl will implement logging as they see fit. This allows your library to be used by applications which use different logging libraries. Note the above code is basic and untested. In practice you may want to change the log methods to include a logging level parameter, etc.
Declare prototype of logging function in your library: ``` extern void __cdecl UserLog(char* stText); ``` Do not implement it in your library. The user of your library should be implement this function and your library will use user's implementation. User's implementation could look like the following (that's just a sample): ``` void __cdecl UserLog(char* stText) { std::cout << stText << std::endl; } ``` ***That's valid if your library is static library.*** In your code you'll be able to use in the following way: ``` class A { public: void method(string param1, int param2); } void A::method(string param1, int param2){ string formatted = str( boost::format( "param1=%s param2=%d" ) % param1 % param2 ); UserLog( formatted.c_str() ); } ```
Adding generic logging support in C++ shared library
[ "", "c++", "logging", "shared-libraries", "" ]
I'm getting a pure binary MP3 stream from an ajax call. No headers, nothing. Just straight MP3 bits. (Actually is that really even a stream at all?) I'd like to be able to play it in a web page (and, if possible, offer it for downloading). Is this possible? And if so what's the best way to do it? If it is not possible, what are some other ways to handle this?
You cant play music with pure javascript. you will need to get that stream and pass it to a flash player. try [JW flash player](http://www.longtailvideo.com/players/jw-flv-player/), though i am not sure if it can handle the type of stream you are talking about. you will have to do some research about what it can handle
as indeed mentioned, you'll need a mp3 playing plugin, flash being the most widely available. The [JMP3](http://www.sean-o.com/jquery/jmp3/) jquery plugin makes that task easier for you. It does rely on a flash file for the sound processing.
How to play binary MP3 stream with jQuery/Javascript?
[ "", "javascript", "jquery", "mp3", "" ]
I have: ``` var keys = [ "height", "width" ]; var values = [ "12px", "24px" ]; ``` And I'd like to convert it into this object: ``` { height: "12px", width: "24px" } ``` In Python, there's the simple idiom `dict(zip(keys,values))`. Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?
Simple JS function would be: ``` function toObject(names, values) { var result = {}; for (var i = 0; i < names.length; i++) result[names[i]] = values[i]; return result; } ``` Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D
The simplest ES6 one-liner solution using Array `reduce`: ``` const keys = ['height', 'width']; const values = ['12px', '24px']; const merged = keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {}); console.log(merged); ```
Merge keys array and values array into an object in JavaScript
[ "", "javascript", "json", "object", "" ]
For javascript I use the jQuery framework but can easily integrate any javascript functions into it. The problem I have is I have a div that fade's in when I click a link. How can I get it to align in the center of the page and stay even when scrolling. Below is an example of what I currently have implemented: HTML code: ``` <div id="dividname"> <h2>Heading Goes Here</h2> <p>content goes here</p> <p><a href="#" class="close-box">Close Box</a></p> </div> ``` CSS code: ``` #dividname { position:absolute; z-index:100; width:600px; height:600px; display:none; } ``` jQuery code: ``` $(document).ready( function() { // on click show div $('a.popup').click( function() { $('#dividname').fadeIn('slow'); } } } ); ```
try this [modal div](http://malsup.com/jquery/block/) for jquery This tool will take care of the moving for you if the user scrolls ``` // to show $.blockUI({ message: $('[id$=div]'), css: { top: 50%; left: 50%; margin-top: -300px; margin-left: -300px; } }); // to hide $.unblockUI({ message: $('[id$=div]') }); ```
Try this: ``` #dividname { position: fixed; top: 50%; left: 50%; margin-top: -300px; margin-left: -300px; z-index: 100; width: 600px; height: 600px; } ``` Where `margin-top` and `margin-left` is half of `height` and `width` respectively.
Javascript centering a div on the page
[ "", "javascript", "jquery", "css", "" ]
I am using ExtJS version 2. I am clicking a button to add new tab to a TabPanel. The new tab function looks like this: ``` function addTab(tabTitle, targetUrl){ tabPanel.add({ title: tabTitle, iconCls: 'tabs', closable:true }).show(); } ``` I would like to know if it's possible to get the targetUrl and display it in new tab. If i set `html: targetUrl`, my tab content would obviously be just a text with my URL. If I set up the `autoLoad: {url: targetUrl}` it works but it is reading the file contents as if they were texts or scripts.. The problem is that I would need to open images and I just get their source with `autoLoad`, not the actual display of the image. I just want my new tab to act like a new pop-up window with a default link. Can anybody help ? Thanks.
Nevermind, I have used the ManagedIframe script witch happens to do exactly what I requested. Thanks anyway.
In Extjs you can load any panel with the contents of a url. You can do it like this ``` var panel = new Ext.Panel({ title: 'Your Tile', closable: true, iconCls: 'tabs', autoLoad: { url: targetUrl } }); tabPanel.add(panel); tabPanel.doLayout(); tabPanel.setActiveTab(panel); ``` You can find more details in the Extjs API documentation.
ExtJS display link in new tab
[ "", "javascript", "extjs", "hyperlink", "" ]
I am currently trying to get my head round DI and IoC. Blogs and article are all well and good but I'd like to see some real working source code however I am currently stuck with web forms at work for the time being and most open source projects that I know of that are implementing these kind of development practices seem to be based on ASP.NET MVC i.e. nerd dinner. Can anyone point me in the direction of an open source web form based project that uses DI/IoC?
The [MSDN page](http://msdn.microsoft.com/en-us/library/cc816062.aspx) for Unity contains a tiny web project. It might not be as big a project as you're looking for, but it's really clear and should help with understanding.
Take a look at [n2 cms](http://n2cms.com/) it's an open source CMS
Is there an open source .NET web form project using DI/IoC?
[ "", "c#", "asp.net", "open-source", "dependency-injection", "inversion-of-control", "" ]
I've built a script in PHP for a small shop that does a few things. Initiate a DB connection, and query the DB a couple times. Read/Write Sessions Make a request to PayPal PDT with fsockopen() parse the results save the order to db After some testing, the server stopped loading. Support let me know that there were 20 PHP processes running (which was the limit) For some reason, they are not closing properly ``` USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND bobbysue 970 0.0 0.1 23836 8708 ? S 15:46 0:00 /usr/local/bin/php5.cgi index.php bobbysue 1574 0.0 0.1 23836 8708 ? S 15:47 0:00 /usr/local/bin/php5.cgi index.php bobbysue 2328 0.0 0.1 23840 8708 ? S 15:47 0:00 /usr/local/bin/php5.cgi index.php bobbysue 4031 0.0 0.1 23836 8704 ? S 15:49 0:00 /usr/local/bin/php5.cgi index.php bobbysue 7112 0.0 0.1 23836 8708 ? S 15:51 0:00 /usr/local/bin/php5.cgi index.php... ``` 1) How can I troubleshoot my script to see where the problem might lie? 2) How do I make sure processes that startup get terminated properly? Thanks Rich
You can use a PHP debugger. DBG is a pretty good one. I use PHPEd, but I believe DBG will work other ways too. <http://www.php-debugger.com/dbg/> <http://www.php-debugger.com/dbg/installation.php> <http://www.nusphere.com/products/php_debugger.htm> There are a few other decent free or near-free PHP debugging options: <http://www.google.com/search?client=opera&rls=en&q=php+debugger&sourceid=opera&ie=utf-8&oe=utf-8> Or, if these are daemon processes, or not running in a browser, you will likely have to go with writing info to a log file. I am not sure if they can be debugged - check google. **Edit** Suggested from comment, XDebug looks pretty good too. <http://xdebug.org/docs/> **Update 2** It looks like you can now debug php-cli with dbg, too.
LOP. Lots of print statements. Find out where the app is hanging and deal with it there. you can have the script write to a log file if it is disconnected from the terminal/apache process. Of course a debugger works well for this too ;)
How to troubleshoot PHP processes
[ "", "php", "process", "" ]
Assuming I have an instance of an object that I know belongs to a subclass of a certain subtype passed to me through a reference of a supertype in C#, I'm used to seeing typecasting done this Java-like way (Assuming "reference" is of the supertype): ``` if (reference is subtype){ subtype t = (subtype)reference; } ``` But recently I've come across examples of what appears to be the same thing done this way: ``` if (reference is subtype){ subtype t = reference as subtype; } ``` Are those two completely equivalent? Is there any difference?
They are the same used that way, but neither is the best option. You should do the type checking only once: ``` subtype t = reference as subtype; if (t != null) { ... } ``` Checking for null is more efficient than checking for type.
The difference is one will throw an exception and the other one will return a null value if the casting is incorrect. Also, "as" keyword does not work on value type. ``` BaseType _object; //throw an exception AnotherType _casted = (AnotherType) _object; //return null AnotherType _casted = _object as AnotherType; ``` **Edit:** In the example of *Fabio de Miranda*, the exception will not be thrown due to the use of "is" keyword which prevents to enter in the "if" statement.
C#: Any difference whatsoever between "(subtype)data" and "data as subtype" typecasting?
[ "", "c#", ".net", "types", "oop", "casting", "" ]
I imagine I need to remove chars 0-31 and 127. Is there a function or piece of code to do this efficiently?
## 7 bit ASCII? If your Tardis just landed in 1963, and you just want the 7 bit printable ASCII chars, you can rip out everything from 0-31 and 127-255 with this: ``` $string = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $string); ``` It matches anything in range 0-31, 127-255 and removes it. ## 8 bit extended ASCII? You fell into a Hot Tub Time Machine, and you're back in the eighties. If you've got some form of 8 bit ASCII, then you might want to keep the chars in range 128-255. An easy adjustment - just look for 0-31 and 127 ``` $string = preg_replace('/[\x00-\x1F\x7F]/', '', $string); ``` ## UTF-8? Ah, welcome back to the 21st century. If you have a UTF-8 encoded string, then the `/u` [modifier](http://php.net/manual/en/reference.pcre.pattern.modifiers.php) can be used on the regex ``` $string = preg_replace('/[\x00-\x1F\x7F]/u', '', $string); ``` This just removes 0-31 and 127. This works in ASCII and UTF-8 because both share the [same control set range](http://www.fileformat.info/info/charset/UTF-8/list.htm) (as noted by mgutt below). Strictly speaking, this would work without the `/u` modifier. But it makes life easier if you want to remove other chars... If you're dealing with Unicode, there are [potentially many non-printing elements](https://stackoverflow.com/questions/3770117/what-is-the-range-of-unicode-printable-characters), but let's consider a simple one: [NO-BREAK SPACE (U+00A0)](https://unicode-table.com/en/00A0/) In a UTF-8 string, this would be encoded as `0xC2A0`. You could look for and remove that specific sequence, but with the `/u` modifier in place, you can simply add `\xA0` to the character class: ``` $string = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $string); ``` ## Addendum: What about str\_replace? preg\_replace is pretty efficient, but if you're doing this operation a lot, you could build an array of chars you want to remove, and use str\_replace as noted by mgutt below, e.g. ``` //build an array we can re-use across several operations $badchar=array( // control characters chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7), chr(8), chr(9), chr(10), chr(11), chr(12), chr(13), chr(14), chr(15), chr(16), chr(17), chr(18), chr(19), chr(20), chr(21), chr(22), chr(23), chr(24), chr(25), chr(26), chr(27), chr(28), chr(29), chr(30), chr(31), // non-printing characters chr(127) ); //replace the unwanted chars $str2 = str_replace($badchar, '', $str); ``` Intuitively, this seems like it would be fast, but it's not always the case, you should definitely benchmark to see if it saves you anything. I did some benchmarks across a variety string lengths with random data, and this pattern emerged using php 7.0.12 ``` 2 chars str_replace 5.3439ms preg_replace 2.9919ms preg_replace is 44.01% faster 4 chars str_replace 6.0701ms preg_replace 1.4119ms preg_replace is 76.74% faster 8 chars str_replace 5.8119ms preg_replace 2.0721ms preg_replace is 64.35% faster 16 chars str_replace 6.0401ms preg_replace 2.1980ms preg_replace is 63.61% faster 32 chars str_replace 6.0320ms preg_replace 2.6770ms preg_replace is 55.62% faster 64 chars str_replace 7.4198ms preg_replace 4.4160ms preg_replace is 40.48% faster 128 chars str_replace 12.7239ms preg_replace 7.5412ms preg_replace is 40.73% faster 256 chars str_replace 19.8820ms preg_replace 17.1330ms preg_replace is 13.83% faster 512 chars str_replace 34.3399ms preg_replace 34.0221ms preg_replace is 0.93% faster 1024 chars str_replace 57.1141ms preg_replace 67.0300ms str_replace is 14.79% faster 2048 chars str_replace 94.7111ms preg_replace 123.3189ms str_replace is 23.20% faster 4096 chars str_replace 227.7029ms preg_replace 258.3771ms str_replace is 11.87% faster 8192 chars str_replace 506.3410ms preg_replace 555.6269ms str_replace is 8.87% faster 16384 chars str_replace 1116.8811ms preg_replace 1098.0589ms preg_replace is 1.69% faster 32768 chars str_replace 2299.3128ms preg_replace 2222.8632ms preg_replace is 3.32% faster ``` The timings themselves are for 10000 iterations, but what's more interesting is the relative differences. Up to 512 chars, I was seeing preg\_replace alway win. In the 1-8kb range, str\_replace had a marginal edge. I thought it was interesting result, so including it here. *The important thing is not to take this result and use it to decide which method to use, but to benchmark against your own data and then decide.*
Many of the other answers here do not take into account unicode characters (e.g. öäüßйȝîûηыეமிᚉ⠛ ). In this case you can use the following: ``` $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $string); ``` There's a strange class of characters in the range `\x80-\x9F` (Just above the 7-bit ASCII range of characters) that are technically control characters, but over time have been misused for printable characters. If you don't have any problems with these, then you can use: ``` $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $string); ``` If you wish to also strip line feeds, carriage returns, tabs, non-breaking spaces, and soft-hyphens, you can use: ``` $string = preg_replace('/[\x00-\x1F\x7F-\xA0\xAD]/u', '', $string); ``` Note that you *must* use single quotes for the above examples. If you wish to strip everything except basic printable ASCII characters (all the example characters above will be stripped) you can use: ``` $string = preg_replace('/[^[:print:]]/', '', $string); ``` For reference see <http://www.fileformat.info/info/charset/UTF-8/list.htm>
How to remove all non printable characters in a string?
[ "", "php", "utf-8", "ascii", "" ]
I'm new to programming and have some questions about classes. I'll use Karel as an example: ``` public class Karel extends robot{ .... } ``` then I extend Karel: ``` public class SuperKarel extends Karel{ .... } ``` but then I want to organize some groups of methods: ``` public class KarelJumps extends SuperKarel { .... } public class KarelColor extends SuperKarel { .... } ``` But then if I want to make Karel jump I have to create an instance of `KarelJumps` rather the `SuperKarel`. But because `KarelJumps` is a different object then `KarelColor` I couldn't use any of its methods. So would I just put all of the `KarelJumps` and `KarelColor` methods inside `SuperKarel?` Do I just make one large object?
The most useful reason for extending a class is so that you can use the underlying class's functionality in new objects, and then add behaviors and characteristics that are unique to the new type. If there are no compelling reasons for doing so, and very often there are not, then don't do it. Don't overcomplicate your design, just to try to make use of polymorphism and inheritance. You want to use these techniques to make your applications less complex not more so. For a new programmer, I would recommend that you get the book "Code Complete" and make it your Bible for a while. You will not learn a language from it per se, but you will learn how things should be done and why that is.
It looks like you're trying to understand polymorphism more than classes. Inheritance doesn't provide a mechanism of "method grouping." The core concept of classic inheritance and polymorphism is conveniently captured in the [Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). Stolen from that wiki page: > if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program. Ensure that your sub-classes are substitutable for the super classes and that they add some significant, appropriate functionality besides, otherwise don't use inheritance.
Understanding Classes
[ "", "java", "" ]
In Java Servlets, one can access the response body via `response.getOutputStream()` or `response.getWriter()`. Should one call `.close()` on this `OutputStream` after it has been written to? On the one hand, there is the Blochian exhortation to always close `OutputStream`s. On the other hand, I don't think that in this case there is an underlying resource that needs to be closed. The opening/closing of sockets is managed at the HTTP level, to allow things like persistent connections and such.
Normally you should not close the stream. The servlet container will automatically close the stream after the servlet is finished running as part of the servlet request life-cycle. For instance, if you closed the stream it would not be available if you implemented a [Filter](http://java.sun.com/javaee/5/docs/api/javax/servlet/Filter.html). Having said all that, if you do close it nothing bad will happen as long as you don't try to use it again. EDIT: [another filter link](http://java.sun.com/products/servlet/Filters.html) EDIT2: adrian.tarau is correct in that if you want to alter the response after the servlet has done its thing you should create a wrapper extending HttpServletResponseWrapper and buffer the output. This is to keep the output from going directly to the client but also allows you to protect if the servlet closes the stream, as per this excerpt (emphasis mine): > A filter that modifies a response must > *usually* capture the response before it > is returned to the client. The way to > do this is to pass the servlet that > generates the response a stand-in > stream. The stand-in stream prevents > the servlet from closing the original > response stream when it completes and > allows the filter to modify the > servlet's response. [Article](http://java.sun.com/products/servlet/Filters.html#72674) One can infer from that official Sun article that closing the `OutputStream` from a servlet is something that is a normal occurrence, but is not mandatory.
The general rule of them is this: if you opened the stream, then you should close it. If you didn't, you shouldn't. Make sure the code is symmetric. In the case of `HttpServletResponse`, it's a bit less clear cut, since it's not obvious if calling `getOutputStream()` is an operation that opens the stream. The Javadoc just says that it "`Returns a ServletOutputStream`"; similarly for `getWriter()`. Either way, what is clear is that `HttpServletResponse` "owns" the stream/writer, and it (or the container) is responsible for closing it again. So to answer your question - no, you should not close the stream in this case. The container must do that, and if you get in there before it, you risk introducing subtle bugs in your application.
Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?
[ "", "java", "servlets", "outputstream", "" ]
I need to get content from an external page and pass it as an argument to a function. I have looked into the url() method in the JQuery documentation but it seems it's only possible to use it to insert external content into div or some other HTML element. Basically what I need to do is: ``` // I need to insert external page's content into the cont variable, how to do that? var cont; // so I can pass it to the bt() function (it's a tooltip plugin) $('.class').bt(cont, { fill: '#2a4d6b', cssStyles: {color: 'orange', fontWeight: 'bold', width: 'auto'} }); ``` Can anyone tell me if something like that is possible?
You want to use .get (<http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype>) insetad of load. It takes a callback function as an argument. The below will load a link and display it in an alert. ``` $.get('http://your.website.com/page.html', function (data) { alert(data) } ); ``` your example rewritten: ``` $.get('http://your.website.com/page.html', function (data) { setClass(data); }); function setClass(cont) { $('.class').bt(cont, { fill: '#2a4d6b', cssStyles: {color: 'orange', fontWeight: 'bold', width: 'auto'} }); } ```
``` $.load("http://someplace", function(data){ $('.class').bt(data, { fill: '#2a4d6b', cssStyles: {color: 'orange', fontWeight: 'bold', width: 'auto'} }); }); ``` no? also by external, how external? you cant get anything from another domain, otherwise that will work
JQuery - AJAX load() method help
[ "", "javascript", "jquery", "ajax", "plugins", "" ]
We're looking for a syntax checker for C#, something like Checkstyle for Java. Does anyone have any recommendations for any tools that we can use? Ideally it would have a plugin to Visual Studio 2008.
You mean, something like StyleCop? There is a plugin for ReSharper as far as I know. You can find it at [StyleCopForResharper](http://StyleCopForReSharper.CodePlex.com). Works like a champ btw.
[FxCop](http://en.wikipedia.org/wiki/FxCop) or [StyleCop](http://code.msdn.microsoft.com/sourceanalysis).
Syntax checker for C#
[ "", "c#", "visual-studio", "syntax", "static-analysis", "linter", "" ]
I am currently fighting Google Chrome on the following action: ``` location.href = url ``` --- ``` location.replace(url) ``` --- ``` document.location = url ``` --- ``` window.navigate(url) // doesn't work in Chrome/Firefox ``` --- ``` location.assign(url) ``` --- ``` window.open(url, '_self') ``` --- ``` window.location.href = url ``` --- I have tried all, and neither will add a history entry. Is there a way in Google Chrome to do a javascript redirect WITH history? Thanks. --- **Explanation** We have a table of items, when clicking on the row, I want the page to navigate to a specified URL, if anyone has a good solution to this other than using the onclick=send method we are using now, please let me know. --- **Update** It appears that Stackoverflow its-self has this exact same issue. In the main view, click on one of the first 3 columns in the question list (# answers, etc..), then click the back button, it will take you back 2 pages.
Although, I first must say that this is Chrome behaving stupid, and you probably should not worry about it. Try to create a dummy form and with a GET method and programmatically submit it... ``` <form id="dummyForm" method="GET" action="#"> <input type="hidden" name="test" value="test" /> </form> ``` Then your onclick... ``` var frm = document.forms["dummyForm"]; frm.action = url; frm.submit(); ```
all javascript solution based on @Josh Stodola answer ``` function goTo(url, data){ var ele_form = document.createElement("FORM"); ele_form.method = "POST"; ele_form.id = 'dummy_form'; ele_form.action = url; if (!!data){ for(key in data){ var dummy_ele = document.createElement('INPUT'); dummy_ele.name = key; dummy_ele.value = data[key]; dummy_ele.type = 'hidden'; ele_form.appendChild(dummy_ele); } } document.getElementsByTagName('body')[0].append(ele_form); document.getElementById('dummy_form').submit(); } ```
What is a good solution for cross browser javascript redirect with history?
[ "", "javascript", "html", "cross-browser", "" ]
I was wondering if it is possible to add multiple generic constraints? I have an Add method that takes an Object (Either Email, Phone or Address), so i was thinking something like: ``` public void Add<T>(T Obj) where T : Address where T : Email where T : Phone { if (Obj is Address) m_Address.Add(Obj as Address); else if (Obj is Email) m_Email.Add(Obj as Email); else m_Phone.Add(Obj as Phone); } ``` But I keep getting: `"A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause."`
You can't do that. Why not just have three methods and let the compiler do the hard work for you? ``` public void Add(Address address) { m_Address.Add(address); } public void Add(Email email) { m_Email.Add(email); } public void Add(Phone phone) { m_Phone.Add(phone); } ```
CLR does not allow multiple inheritance, which is precisely what you're trying to express. You want `T` to be `Address`, `Email` an `Phone` at the same time (I assume those are class names). Thus is impossible. What's event more, this whole method makes no sense. You'll either have to introduce a base interface for all three classes or use three overloads of an `Add` method.
C# Multiple generic constraints
[ "", "c#", "constraints", "generics", "" ]
I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack. I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python. I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work. From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the `struct`s that define the packets structure. **I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?**
You do it like this: First you disable your network card's automatic checksumming: ``` sudo ethtool -K eth1 tx off ``` And then send your dodgy frame from python 2 (You'll have to convert to Python 3 yourself): ``` #!/usr/bin/env python from socket import socket, AF_PACKET, SOCK_RAW s = socket(AF_PACKET, SOCK_RAW) s.bind(("eth1", 0)) # We're putting together an ethernet frame here, # but you could have anything you want instead # Have a look at the 'struct' module for more # flexible packing/unpacking of binary data # and 'binascii' for 32 bit CRC src_addr = "\x01\x02\x03\x04\x05\x06" dst_addr = "\x01\x02\x03\x04\x05\x06" payload = ("["*30)+"PAYLOAD"+("]"*30) checksum = "\x1a\x2b\x3c\x4d" ethertype = "\x08\x01" s.send(dst_addr+src_addr+ethertype+payload+checksum) ``` Done.
Sockets system calls (or Winsocks, on Windows), are already wrapped in the standard module `socket`: [intro](http://docs.python.org/howto/sockets.html), [reference](http://docs.python.org/library/socket.html). I've never used raw sockets but it looks like they can be used with this module: > The last example shows how to write a > very simple network sniffer with raw > sockets on Windows. The example > requires administrator privileges to > modify the interface: > > ``` > import socket > > # the public network interface > HOST = socket.gethostbyname(socket.gethostname()) > > # create a raw socket and bind it to the public interface > s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) > s.bind((HOST, 0)) > > # Include IP headers > s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) > > # receive all packages > s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) > > # receive a package > print s.recvfrom(65565) > > # disabled promiscuous mode > s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) > ```
How Do I Use Raw Socket in Python?
[ "", "python", "sockets", "raw-sockets", "" ]
I'm trying to get the ip, user, and most recent timestamp from a table which may contain both the current ip for a user and one or more prior ips. I'd like one row for each user containing the most recent ip and the associated timestamp. So if a table looks like this: ``` username | ip | time_stamp --------------|----------|-------------- ted | 1.2.3.4 | 10 jerry | 5.6.6.7 | 12 ted | 8.8.8.8 | 30 ``` I'd expect the output of the query to be: ``` jerry | 5.6.6.7 | 12 ted | 8.8.8.8 | 30 ``` Can I do this in a single sql query? In case it matters, the DBMS is Postgresql.
Try this: ``` Select u.[username] ,u.[ip] ,q.[time_stamp] From [users] As u Inner Join ( Select [username] ,max(time_stamp) as [time_stamp] From [users] Group By [username]) As [q] On u.username = q.username And u.time_stamp = q.time_stamp ```
Nice elegant solution with ROW\_NUMBER window function (supported by PostgreSQL - see in **[SQL Fiddle](http://sqlfiddle.com/#!15/f82a8/4)**): ``` SELECT username, ip, time_stamp FROM ( SELECT username, ip, time_stamp, ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn FROM Users ) tmp WHERE rn = 1; ```
SQL query to get most recent row for each instance of a given key
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I have a winform app that needs to be aware of when a SQL server is available so as to allow the Merge Syncing functionality. I have tried variations of the below, which work on a one time basis, but I would like to come up with something a little more dynamic. The below funcion(Thank you [Alex\_L](https://stackoverflow.com/users/136639/alexl)) is checking for the 1433 port that SQL runs on and works great. What I am trying to accomplish is a way to monitor this in Real-Time. Would I have to create a Windows Service? What about any other network events like the Network Connection changing? The usage of this sometimes connected app is simple. If they are on our network then the Merge Replication portion is available. If they are not on our network then it is not. The SQL Server should never be available of our network and it SHOULD always be available when on. That being said, I would be open to solutions involing detecting our current network in lieu of the SQL instance. ``` private static bool IsSqlAvailable() { TcpClient tcpc = new TcpClient(); try { tcpc.Connect("10.250.50.30", 1433); return true; } catch { return false; } } ```
You can check port 1433 of SQL Server (or another, if used): ``` TcpClient tcpc = new TcpClient(); try { tcpc.Connect("10.250.50.30", 1433); return true; } catch { return false; } ```
I have an entry on my blog showing [how to detect network availability changes](http://rusanu.com/2009/07/21/detect-network-connectivity-changes-in-net-applications/). It uses the [NotifyAddrChange](http://msdn.microsoft.com/en-us/library/aa366329(VS.85).aspx) windows API to raise a managed event whenever there is a change in the IP interface address mapping table. Since such changes are associated with network availability changes (cable plug in, WiFi join, VPN connect, dial-up, 3G dial-up etc) you can use the event to test for the server availability and start your synchronization.
Real-Time monitoring of Network State. What events are raised?
[ "", "c#", "sql-server", "winforms", "monitoring", "detection", "" ]
I am experimenting with makefile...mainly when sources are in many directories I have following situation... project/src/ contains directory A, B, Main Directory A contains A.h and A.cpp; B contains B.cpp and B.h; and Test contains test.cpp A.cpp includes A.h; B.cpp includes B.h and Main.cpp includes A.h, B.h project/lib contains libA.a libB.a Makefile for A and B is fine...no problem with that...i am creating libs from objects and then copying them into lib directory eg. makefile for directory A, and similar for B ``` all:test test : A.cpp A.hh g++ -c A.cpp -o A ar cru libA.a A.o cp libA.a pathto/project/lib ``` I have makefile for Main directory as ``` all: test test: test.o g++ -I.. -L../../lib test.o -o test -lA -lB test.o : test.cpp g++ -c test.cpp -o test.o ``` Everything works fine...only thing that I want to solve is that final executable 'test' depends on objects from libA and libB, so when A.h or A.cpp or B.h or B.cpp changes, it should be made again So, I now changed my makefile as ``` test: test.o ../../libA.a ../../libB.a g++ -I.. -L../../lib test.o -o test -lA -lB ``` Now, problem is how I can modify this so that it will make test again only when its dependencies are newer than the 'test'. There is no direct rule to make libA and libB, which Makefile requires and complains about; since I am copying these libs from directory A and B into directory project/lib. So, I guess one solution would be to call make in respective directory A and B when anything is new than 'test' but how do I exactly do that ? Or, any other better solution is appreciated. Thanks a lot :) EDIT Here what I did and it solved the problem ``` .PHONY : libA libB ``` ../../libA.a : libA libA : cd pathtoDirA; $(MAKE) ../../libB.a : libB libB : cd pathtoDirB; $(MAKE)
You really need to add a rule which knows how to make libA and libB, then add the dependency from test onto that rule. The rule can either call make in that directory (recursive make), or explicitly encode the rules for building the libs in your makefile. The first one is more traditional and is pretty simple to understand. It works with almost all situations you will encounter in the field, but there are some [potential issues](http://miller.emu.id.au/pmiller/books/rmch/) that can arise if you have more complex build setup (I would probably go with it anyway because it is simpler).
`make -C dir` is your friend here. Do something like: ``` PROJECTS = A B C D build: for dir in $(PROJECTS); do \ $(MAKE) -C $$dir build; \ done ``` And list your sub-projects in the order you want them to be built.
Makefile, source in multiple directories, dependency problem
[ "", "c++", "makefile", "" ]
How to force std::stringstream operator >> to read an entire string instead of stopping at the first whitespace? I've got a template class that stores a value read from a text file: ``` template <typename T> class ValueContainer { protected: T m_value; public: /* ... */ virtual void fromString(std::string & str) { std::stringstream ss; ss << str; ss >> m_value; } /* ... */ }; ``` I've tried setting/unsetting stream flags but it didn't help. **Clarification** The class is a container template with automatic conversion to/from type T. Strings are only one instance of the template, it must also support other types as well. That is why I want to force operator >> to mimic the behavior of std::getline.
As operator >> is not satisfying our requirement when T=string, we can write a specific function for [T=string] case. This may not be the correct solution. But, as a work around have mentioned. Please correct me if it won't satisfy your requirement. I have written a sample code as below: ``` #include <iostream> #include <sstream> #include <string> using namespace std; template <class T> class Data { T m_value; public: void set(const T& val); T& get(); }; template <class T> void Data<T>::set(const T& val) { stringstream ss; ss << val; ss >> m_value; } void Data<string>::set(const string& val) { m_value = val; } template <class T> T& Data<T>::get() { return m_value; } int main() { Data<int> d; d.set(10); cout << d.get() << endl; Data<float> f; f.set(10.33); cout << f.get() << endl; Data<string> s; s.set(string("This is problem")); cout << s.get() << endl; } ```
Here is a solution : ``` std::istream & ReadIntoString (std::istream & istr, std::string & str) { std::istreambuf_iterator<char> it(istr), end; std::copy(it, end, std::inserter(str, str.begin())); return istr; } ``` (Thanks to the original poster in C++ newsgroup)
How to force std::stringstream operator >> to read an entire string?
[ "", "c++", "stl", "stringstream", "stdstring", "" ]
First off, I'm a real beginer at C# so please be gentle. I'm trying to have a circle follow my cursor. I don't want any "trails" to be left behind. ``` private void Form1_MouseMove(object sender, MouseEventArgs e) { drawCircle(e.X, e.Y); } private void drawCircle(int x, int y) { Pen skyBluePen = new Pen(Brushes.DeepSkyBlue); Graphics graphics = CreateGraphics(); graphics.DrawEllipse( skyBluePen, x - 150, y - 150, 300, 300); graphics.Dispose(); this.Invalidate(); } ``` This works ok, as it draws it and centers on the mouse for every mouse move. However, the "this.Invalidate();" is wrong. It "undraws" the shape after every movement, so I can only see glimpses of it. However, not including it causes every single drawn circle to remain on screen. How do I get one circle to "gracefully" follow my mouse around, without being too jumpy and without retaining all of the past circles?
You can do something like this: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Paint(object sender, PaintEventArgs e) { Point local = this.PointToClient(Cursor.Position); e.Graphics.DrawEllipse(Pens.Red, local.X-25, local.Y-25, 20, 20); } private void Form1_MouseMove(object sender, MouseEventArgs e) { Invalidate(); } } ``` Basically, on the mouse move, invalidate. On the Paint, draw your circle.
This works - just tested it... ``` private int x = 0; private int y = 0; private void Form1_MouseMove(object sender, MouseEventArgs e) { x = e.X; y = e.Y; this.Invalidate(); } private void Form1_Paint(object sender, PaintEventArgs e) { Pen skyBluePen = new Pen(Brushes.DeepSkyBlue); e.Graphics.DrawEllipse(skyBluePen, x - 150, y - 150, 300, 300); } ```
Want a drawn circle to follow my mouse in C#
[ "", "c#", "winforms", "" ]
I often see Java class names like ``` XmlReader ``` instead of ``` XMLReader ``` My gut feeling is to completely upper case acronyms, but apparently many people think differently. Or maybe it's just because a lot of code generators are having trouble with acronyms... So i would like to hear the the public opinion. How do you capitalize your class names containing acronyms?
We use the camel case convention like Java and .NET do. Not for reasons of code generators, but for readability. Consider the case of combining two acronyms in one name, for example a class that converts XML into HTML. ``` XMLHTMLConverter ``` or ``` XmlHtmlConverter ``` Which one do you prefer?
Two reasons: 1. It's easier to distinguish where one acronym ends and the other begins in identifiers where they're placed after each other, for instance in `XmlHtmlConverter`. Now XML and HTML aren't such good examples, because everyone knows what XML is, and what HTML is. But sometimes you'll see less obvious acronyms and then this becomes important. 2. Eclipse is smart with words and their initials. For `XmlHtmlConverter`, you can type in `XHC` in the Open Type dialog and it will find it. For an `XMLHTMLConverter`, the initials would be `XMLHTMLC` which is of course a bit longer.
Acronyms in Camel Back
[ "", "java", "naming-conventions", "camelcasing", "" ]
I'm writing a program to add some code to html files I was going to use a series of indexof and loops to find what is essentially ""X (where X is the spot im looking for) It occurred to me that there might be a more eloquent way of doing this does anyone have any suggestions. what it looks like currently ``` <body onLoad="JavaScript:top.document.title='Abraham L Barbrow'; if (self == parent) document.getElementById('divFrameset').style.display='block';"> ``` what it should look like when im done --- ``` <body onLoad="JavaScript:top.document.title='Abraham L Barbrow'; if (self == parent) document.getElementById('divFrameset').style.display='block';"> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-9xxxxxx-1"); pageTracker._trackPageview(); } catch(err) {}</script> ```
I'm not sure I'm understanding you, but do you mean this? ``` // Given an HTML document in "htmlDocument", and new content in "newContent" string newHtmlDocument = htmlDocument.Replace("</body>", newContent+"</body>"); ``` And it's probably obvious I don't know c#... You'd probably want to make the "body" tag case insensitive via regexps.
I would recommend to use [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) to parse the html into DOM and work with it.
best way to find end of body tag in html
[ "", "c#", ".net", "html", "winforms", "indexof", "" ]
I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I'd like to do this without actually editing every function, Is such a thing even possible? I would settle for having a function called as the first instruction of every function call instead of it being called right before.
[AspectC++](http://www.aspectc.org/) is what you want. I haven't used it myself, but [Aspect-Oriented Programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) paradigm tries to solve this exact problem.
I would suggest using the Non Virtual Interface idiom. All public functions are non-virtual. All virtual functions are protected or private. Public members delegate the calls to virtual members and are usually implemented as inline functions. This is the way IOStreams are implemented in STL. You can read more about it at [C++ Wikibooks](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface). > Intent: To modularize/refactor common before and after code fragments (e.g., invariant checking, acquiring/releasing locks) for an entire class hierarchy at one location. Regards, Ovanes
Run Code Before Every Function Call for a Class in C++
[ "", "c++", "aop", "" ]
Ok I'm just at a loss for what the correct terminology is for this. I'm looking for the correct name to call a progress bar that "loops". Instead of the standard progress bar that fills up from left to right to 100%, this looks exactly like the progress bar but a small portion of the fill color constantly loops, never filling the whole progress bar to 100%, basically making it an eternal progress bar similar to a [Ajax loading image](http://www.ajaxload.info/). Microsoft likes to use this progress bar in their dialogs now. What do you call this thing so I can search for some controls, etc.? Does .Net have a control for this? Thanks
In Windows the progress bars are said to be in Marquee mode I think. See <http://msdn.microsoft.com/en-us/library/bb760816%28VS.85%29.aspx>
[Indeterminate progress bar](http://en.wikipedia.org/wiki/Progress_bar)? Java's [`JProgressBar`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JProgressBar.html) specifically refers to "Indeterminate mode"
What do you call a looping progress bar?
[ "", "c#", ".net", "vb.net", "progress-bar", "" ]
Is there a "better" way (built-in function, better algorithm) to normalize the case of all the keys in a PHP array? Looping though and creating a new array works ``` $new = array(); foreach( $old as $key=>$value) { $key = strToLower($key); if(!array_key_exists($key,$new) { $new[$key] = $value; } else { throw new Exception('Duplicate Key Encountered'); } } ``` but it seems like these should be a way to do this "in place". **Update**: It looks like there is a built in, the not deceptively named yet somehow missed by me `array_change_key_case`. I'd still be interesting in seeing algorithmic approaches that would let you better handle what happens when you hit "duplicate" keys.
I believe `array_change_key_case` does what you're looking for. <https://www.php.net/manual/en/function.array-change-key-case.php>
I found that builtin functions are *much* faster than loops when processing large arrays. This might do what you want (untested code): ``` $lowerCaseKeys = array_map('strtolower', array_keys($array)); $duplicates = array_filter(array_count_values($lowerCaseKeys), create_function('$count', 'return $count > 1;')); if (!empty($duplicates)) { throw new Exception('duplicate keys found: ' . implode(',', array_keys($duplicates))); } # Recreate the array with lower-case keys $array = array_combine($lowerCaseKeys, array_values($array)); ``` **EDIT** Or the pragmatic approach (should be much faster): ``` $lowerCaseKeyArray = array_change_key_case($array); if (count($lowerCaseKeyArray) !== count($array)) { # You can extract the duplicate keys here as above, if you like throw new Exception('duplicate keys found!'); } ```
Normalize the case of array keys in PHP
[ "", "php", "arrays", "key", "lowercase", "" ]
I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...: ``` // Create a new anonymous function, to use as a wrapper (function(){ // The variable that would, normally, be global var msg = "Thanks for visiting!"; // Binding a new function to a global object window.onunload = function(){ // Which uses the 'hidden' variable alert( msg ); }; // Close off the anonymous function and execute it })(); ``` Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does): ``` (function (msg){alert(msg)})('SO'); ``` My question is what kind of magic happens here? I thought that when I wrote: ``` (function (msg){alert(msg)}) ``` then a new unnamed function would be created like function ""(msg) ... but then why doesn't this work? ``` (function (msg){alert(msg)}); ('SO'); ``` Why does it need to be in the same line? Could you please point me some posts or give me an explanation?
Drop the semicolon after the function definition. ``` (function (msg){alert(msg)}) ('SO'); ``` Above should work. DEMO Page: <https://jsfiddle.net/e7ooeq6m/> I have discussed this kind of pattern in this post: [jQuery and $ questions](https://stackoverflow.com/questions/1122690/jquery-and-questions/1122740#1122740) **EDIT:** If you look at [ECMA script specification](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf), there are 3 ways you can define a function. (Page 98, Section 13 Function Definition) ## 1. Using Function constructor ``` var sum = new Function('a','b', 'return a + b;'); alert(sum(10, 20)); //alerts 30 ``` ## 2. Using Function declaration. ``` function sum(a, b) { return a + b; } alert(sum(10, 10)); //Alerts 20; ``` ## 3. Function Expression ``` var sum = function(a, b) { return a + b; } alert(sum(5, 5)); // alerts 10 ``` So you may ask, what's the difference between declaration and expression? From ECMA Script specification: > FunctionDeclaration : > function Identifier ( FormalParameterListopt ){ FunctionBody > } > > FunctionExpression : > function Identifieropt ( FormalParameterListopt ){ FunctionBody > } If you notice, 'identifier' is **optional** for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier. This means following is valid. ``` var sum = function mySum(a, b) { return a + b; } ``` Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example: ``` var test1 = function test2() { alert(typeof test2); } alert(typeof(test2)); //alerts 'undefined', surprise! test1(); //alerts 'function' because test2 is a function. ``` [Live Demo](http://jsbin.com/esupa) Compare this to ``` function test1() { alert(typeof test1) }; alert(typeof test1); //alerts 'function' test1(); //alerts 'function' ``` --- Armed with this knowledge, let's try to analyze your code. When you have code like, ``` function(msg) { alert(msg); } ``` You created a function expression. And you can execute this function expression by wrapping it inside parenthesis. ``` (function(msg) { alert(msg); })('SO'); //alerts SO. ```
It's called a self-invoked function. What you are doing when you call `(function(){})` is returning a function object. When you append `()` to it, it is invoked and anything in the body is executed. The `;` denotes the end of the statement, that's why the 2nd invocation fails.
Why do you need to invoke an anonymous function on the same line?
[ "", "javascript", "anonymous-function", "iife", "" ]
I am developing a windows app in c#. I have used three decimal variables: `counter`, `narrow`, and `broad` which store different values based on some calculations. On clicking a button, a message box is displayed showing these three decimal values and then the application exits.. Now I want to add another form having three labels in which these variable values needs to be shown. Please explain, how can I pass those variables in the next form to display in individual labels?
Create a new Form... ``` public class CalculationResultForm : Form { public CalculationResultForm(){} public decimal Counter { set { labelCounter.Text = value.ToString(); } } public decimal Broad { set { labelBroad.Text = value.ToString(); } } public decimal Narrow { set { labelNarrow.Text = value.ToString(); } } private void OkButton_Click(object sender, EventArgs e) { // This will close the form (same as clicking ok on the message box) DialogResult = DialogResult.OK; } } ``` Then within your existing form button click handler... ``` private void MyButton_Click(object sender, EventArgs e) { CalculationResultForm resultForm = new CalculationResultForm(); resultForm.Counter = _counter; resultForm.Narrow = _narrow; resultForm.Broad = _broad; resultForm .ShowDialog(); Application.Exit(); } ```
One method is to create a new constructor in the 2nd form. THen you can use those values from the 2nd form. ``` public Form2(decimal x, decimal y, decimal z):this() { this.TextBox1.Text = Convert.ToString(x); this.Label1.Text = Convert.ToString(y); etc... }; ``` From main form ``` Form2 frm2 = new Form2(x,y,z); frm2.Show(); ```
passing variables into another form
[ "", "c#", "winforms", "" ]
I cannot for the life of me attach the java source code to eclipse so I can see the inner workings of the language. Not even something as simple as the String Class. when I run java -version this is what I have: ``` java version "1.6.0_14" Java(TM) SE Runtime Environment (build 1.6.0_14-b08) Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode, sharing) ``` I am downloading the java souce from: <http://download.java.net/jdk6/source/> And in eclipse when I attach it It says: ``` The JAR file "C:\Program Files\Java\jre6\jdk-6u14-fcs-src-b08-jrl-21_may_2009.jar" has no source attachment. ``` What am I doing wrong?
Normally, if you have installed the JDK6u14, eclipse should detect it and declare it automatically in its "installed JRE" list. If not, you can add that JDK through "Windows/Preferences": `Java > Installed JREs`: Just point to the root directory of your JDK installation: it should include the sources of the JDK (`src.zip`), automatically detected and attached to `rt.jar` by eclipse. ![Add JRE VM, from pic.dhe.ibm.com/infocenter/iadthelp/v8r0/topic/org.eclipse.jdt.doc.user/tasks/images/task-add_jre_std_vm.PNG](https://i.stack.imgur.com/pVOlY.png)
You don't necessarily need to **add** the source, but you rather may need to **remove** a **JRE that does not have the source attached**. On looking at the "installed JRE's" I saw that my JDK was setup properly with source, but the default JRE on the machine had no sources. Eclipse was defaulting to that when looking for source. I just used the *remove* button to expel the JRE, leaving my JDK. I then hit F3 and the source was there. Yeah!
Attach the Java Source Code
[ "", "eclipse", "java", "" ]
I have this HTML: ``` <ul><li><a href="/web3/showProfile.do;jsessionid=812E1C87A4FB4184650C551F27ADADAB.6-1?clientId=ZGVfX05FWFQ-&amp;cid=6-1&amp;activity=userdata&amp;levelFirstItem=0">Zugangsdaten</a></li><li><a href="/web3/setBookingTemplate.do;jsessionid=812E1C87A4FB4184650C551F27ADADAB.6-1?clientId=ZGVfX05FWFQ-&amp;cid=6-1&amp;activity=template&amp;levelFirstItem=1">Buchungsvorlagen</a></li><li><a href="/web3/showProfile.do;jsessionid=812E1C87A4FB4184650C551F27ADADAB.6-1?clientId=ZGVfX05FWFQ-&amp;cid=6-1&amp;activity=showFavorites&amp;levelFirstItem=2">Hotelfavoriten</a></li><li><a href="/web3/showProfile.do;jsessionid=812E1C87A4FB4184650C551F27ADADAB.6-1?clientId=ZGVfX05FWFQ-&amp;cid=6-1&amp;activity=showLightHistory&amp;levelFirstItem=3">Buchungshistorie</a></li><li><a href="/web3/showProfile.do;jsessionid=812E1C87A4FB4184650C551F27ADADAB.6-1?clientId=ZGVfX05FWFQ-&amp;cid=6-1&amp;activity=showHotelRating&amp;levelFirstItem=4">Hotelbewertung</a></li></ul> ``` How can I extract any HREF ending in `levelFirstItem=2`? Example: ``` /web3/showProfile.do;jsessionid=812E1C87A4FB4184650C551F27ADADAB.6-1?clientId=ZGVfX05FWFQ-&amp;cid=6-1&amp;activity=showFavorites&amp;levelFirstItem=2 ```
This will capture everything within the quotes for only levelFirstItem=2: ``` /href="([^"]*levelFirstItem=2)"/ ```
In general, it's better to find an HTML library that will allow you to grab information from HTML. Using regular expressions will get very messy quickly. What language are you using? I'm sure people here can direct you to a good HTML parsing library for any popular language.
How to write regex capture any HREF ending with a certain parameter?
[ "", "java", "regex", "" ]
I'm trying to play with Google Web Toolkit (GWT 1.6) on Google AppEngine with Java (GAE/J) and I have encountered problem storing data files to GAE. So I have decided to use S3 to store my files but when I googled, I've found library called [gwt-s3 that](http://code.google.com/p/gwt-s3/) allows me to store File to S3 using GWT, but the problem is that it only allows storing files on S3 only if GWT app is hosted on/with S3. Here is what its saying on the front page: > Due to same-origin security policy > limitations, this module only works > with GWT applications that are hosted > on Amazon S3. You should also have an > account with Amazon S3. So, is there any other way of storing data files (text, doc, video, swf, etc) on S3 with GWT without hosting my app on S3.
Here's some directions/code for getting GAE to play nicely with S3 <http://bizo-dev.blogspot.com/2009/05/google-app-engine-java-and-s3.html>
Note - GAE now has large-file support so you don't need 3rd party storage as much as before. See [the blobstore](http://code.google.com/appengine/docs/java/blobstore/overview.html) docs
GWT on GAE and S3
[ "", "java", "gwt", "amazon-s3", "storage", "" ]
This program has the user input `name`/`age` pairs and then outputs them, using a class. Here is the code. ``` #include "std_lib_facilities.h" class Name_pairs { public: bool test(); void read_names(); void read_ages(); void print(); private: vector<string>names; vector<double>ages; string name; double age; }; void Name_pairs::read_names() { cout << "Enter name: "; cin >> name; names.push_back(name); cout << endl; } void Name_pairs::read_ages() { cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; } void Name_pairs::print() { for(int i = 0; i < names.size() && i < ages.size(); ++i) cout << names[i] << " , " << ages[i] << endl; } bool Name_pairs::test() { int i = 0; if(ages[i] == 0 || names[i] == "0") return false; else{ ++i; return true;} } int main() { cout << "Enter names and ages. Use 0 to cancel.\n"; while(Name_pairs::test()) { Name_pairs::read_names(); Name_pairs::read_ages(); } Name_pairs::print(); keep_window_open(); } ``` However, in `int main()` when I'm trying to call the functions I get `"cannot call 'whatever name is' function without object."` I'm guessing this is because it's looking for something like `variable.test` or `variable.read_names`. How should I go about fixing this?
You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The `main()` function could, for example, look like this: ``` int main() { Name_pairs np; cout << "Enter names and ages. Use 0 to cancel.\n"; while(np.test()) { np.read_names(); np.read_ages(); } np.print(); keep_window_open(); } ```
If you want to call them like that, you should declare them static.
cannot call member function without object
[ "", "c++", "" ]
Try as I might, I can't get a RegEx to exclude space or single quotes. * The string "abc" is allowed * Not allowed: "a'bc", "'", "'abc", "'''", "abc''" etc * Spaces could replace the ' too in the above example * Trailing and leading spaces are assumed to be removed already * Empty strings are checked elsewhere * Target language is javascript I'd use PATINDEX if I was in SQL. Or NOT a positive match on either space or single quote, if I could negate... I've tried (for single quote only) * `\w*[^']\w*` * `^\w*[^']\w*$` * others I forget now Please put me out of my misery so I can sleep tonight. Edit: * Target string will not be surrounded by Quotes. I thought thy might add clarity * If "Target language is javascript" is wrong, then it's c#. I'd have to check where we do the validation exactly: client javascript or server c#
``` ^[^\'\ ]*$ ``` ?
Quite simple. Does not allow empty strings. ``` ^[^' ]+$ ```
Exclude certain characters using RegEx
[ "", "javascript", "regex", "" ]
Trying to debug PHP using its default current-line-only error messages is horrible. How can I get PHP to produce a backtrace (stack trace) when errors are produced?
[Xdebug](http://xdebug.org/) prints a backtrace table on errors, and you don't have to write any PHP code to implement it. Downside is you have to install it as a PHP extension.
My script for installing an error handler that produces a backtrace: ``` <?php function process_error_backtrace($errno, $errstr, $errfile, $errline, $errcontext) { if(!(error_reporting() & $errno)) return; switch($errno) { case E_WARNING : case E_USER_WARNING : case E_STRICT : case E_NOTICE : case E_USER_NOTICE : $type = 'warning'; $fatal = false; break; default : $type = 'fatal error'; $fatal = true; break; } $trace = array_reverse(debug_backtrace()); array_pop($trace); if(php_sapi_name() == 'cli') { echo 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ':' . "\n"; foreach($trace as $item) echo ' ' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()' . "\n"; } else { echo '<p class="error_backtrace">' . "\n"; echo ' Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ':' . "\n"; echo ' <ol>' . "\n"; foreach($trace as $item) echo ' <li>' . (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()</li>' . "\n"; echo ' </ol>' . "\n"; echo '</p>' . "\n"; } if(ini_get('log_errors')) { $items = array(); foreach($trace as $item) $items[] = (isset($item['file']) ? $item['file'] : '<unknown file>') . ' ' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ' calling ' . $item['function'] . '()'; $message = 'Backtrace from ' . $type . ' \'' . $errstr . '\' at ' . $errfile . ' ' . $errline . ': ' . join(' | ', $items); error_log($message); } if($fatal) exit(1); } set_error_handler('process_error_backtrace'); ?> ``` Caveat: it is powerless to affect various ['PHP Fatal Errors'](http://us.php.net/set_error_handler), since Zend in their wisdom decided that these would ignore `set_error_handler()`. So you still get useless final-location-only errors with those.
How can I get PHP to produce a backtrace upon errors?
[ "", "php", "debugging", "error-handling", "stack-trace", "backtrace", "" ]
I read somewhere that java can allocate memory for objects in about 12 machine instructions. It's quite impressive for me. As far as I understand one of tricks JVM using is preallocating memory in chunks. This help to minimize number of requests to operating system, which is quite expensive, I guess. But even CAS operations can cost up to 150 cycles on modern processors. So, could anyone explain real cost of memory allocation in java and which tricks JVM uses to speed up allocation?
The JVM pre-allocates an area of memory for each thread (TLA or Thread Local Area). When a thread needs to allocate memory, it will use "Bump the pointer allocation" within that area. (If the "free pointer" points to adress 10, and the object to be allocated is size 50, then we just bump the free pointer to 60, and tell the thread that it can use the memory between 10 and 59 for the object).
The best trick is the generational garbage-collector. This keeps the heap unfragmented, so allocating memory is increasing the pointer to the free space and returning the old value. If memory runs out, the garbage-collection copy objects and creates this way a new unfragmented heap. As different threads have to synchronize over the pointer to the free memory, if increasing it, they preallocate chunks. So a thread can allocate new memory, without the lock. All of this is explained in more detail here: <http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html>
Java nonblocking memory allocation
[ "", "java", "jvm", "memory-management", "" ]
I am looking for a working crawler sample code written in either c# or in Vb.net.
<http://www.codeproject.com/KB/IP/Crawler.aspx> (Credits to [Mehrdad](https://stackoverflow.com/users/33708/mehrdad)). Will remove this answer if he posts his own.
Try <http://code.google.com/p/abot/> From its description... Abot is an open source C# web crawler built for speed and flexibility. It takes care of the low level plumbing (multithreading, http requests, scheduling, link parsing, etc..). You just register for events to process the page data. You can also plugin your own implementations of core interfaces to take complete control over the crawl process.
Seeking a crawler in C# or VB.net
[ "", "c#", "asp.net", "vb.net", "" ]
Coming from a perl background, I have always defined a 2D array using `int[][]`. I know you can use `int[,]` instead so what are the differences?
The difference here is that the first sample, int[][] creates a [jagged array](http://msdn.microsoft.com/en-us/library/2s05feca.aspx), while the second creates a [rectangular array](http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx) (of dimension 2). In a jagged array each "column" can be of a different size. In a true multidimensional array, each "column" (in a dimension) is the same size. For more complete information see the [Array section](http://msdn.microsoft.com/en-us/library/9b9dty7d.aspx) of the [C# Programming Guide](http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx).
[Here's a good comparison](https://stackoverflow.com/questions/597720/what-is-differences-between-multidimensional-array-and-array-of-arrays-in-c/597744) Basically int[][] is a "jagged" array, it looks like this: ``` [] -> [1, 2, 3] [] -> [1, 2] [] -> [1, 2, 3, 4] ``` While int[,] is a multidimentional array which always has the same width and height: ``` [1, 2, 3, 4 5, 6, 7, 8 9, 1, 2, 3] ``` Each have their uses depending on what you're trying to accomplish.
What are the differences between using int[][] and int[,]?
[ "", "c#", ".net", "multidimensional-array", "" ]
I have code I'm working on to instantiate a CRC algorithm dependent on a polynomial passed in, and a string `s` that contains "crc8" or "crc16" or "crc32". The classes `CRC8`, `CRC16`, and `CRC32` all extend a class `CRC` and implement an interface `HashAlgorithm`. Each of them has a constructor `CRCx(int polynomial)`. My problem is, I get this error on all 3 of the getConstructor() lines: ``` Type mismatch: cannot convert from Constructor<HashFactory.CRC16> to Constructor<HashFactory.CRC> ``` Can anyone help explain why and help me fix this? ``` int polynomial; // assign from somewhere Constructor<CRC> crc = null; if ("crc8".equals(s)) { crc = CRC8.class.getConstructor(Integer.TYPE); } if ("crc16".equals(s)) { crc = CRC16.class.getConstructor(Integer.TYPE); } if ("crc32".equals(s)) { crc = CRC32.class.getConstructor(Integer.TYPE); } if (crc != null) { CRC crcInstance = crc.newInstance(polynomial); return (HashAlgorithm) crcInstance; } ```
Try ``` int polynomial; // assign from somewhere if ("crc8".equals(s)) { return new CRC8(polynomial); } else if ("crc16".equals(s)) { return new CRC16(polynomial); } else if ("crc32".equals(s)) { return new CRC32(polynomial); } ``` Or ``` package tests; import java.lang.reflect.Constructor; public class Construct { static interface CRC { } static class CRC8 implements CRC { public CRC8(int p) { } } static class CRC16 implements CRC { public CRC16(int p) { } } static class CRC32 implements CRC { public CRC32(int p) { } } public static CRC getAlg(String s, int polynomial) { try { Class<?> clazz = Class.forName("tests.Construct$" + s.toUpperCase()); Constructor<?> c = clazz.getConstructor(Integer.TYPE); return CRC.class.cast(c.newInstance(polynomial)); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } throw new AssertionError("Unknown algorithm: " +s); } public static void main(String[] args) throws Exception { System.out.println(getAlg("crc8", 0)); System.out.println(getAlg("crc16", 0)); System.out.println(getAlg("crc32", 0)); System.out.println(getAlg("crc48", 0)); } } ``` "Factory" pattern: ``` public static HashAlgorithm getHashAlgorithm(String s, int polynomial) { if ("crc8".equals(s)) { return new CRC8(polynomial); } else if ("crc16".equals(s)) { return new CRC16(polynomial); } else if ("crc32".equals(s)) { return new CRC32(polynomial); } throw new AssertionError("Unknown algorithm: " +s); } ``` It can be done several other ways (e.g HashMap of algorithms to duplicatable classes of CRCs, etc.)
Try declaring the `crc` variable like this: ``` Constructor<? extends CRC> crc = null; ```
help with reflection + constructors
[ "", "java", "reflection", "constructor", "" ]
I'm making an ASP.NET MVC website and I have a certain group of forms that are related (let's called them Foo). My first attempt to organized them was to have this structure: ``` Controllers/FooController.cs ``` ...and to have routes like this: ``` Foo/{type}/{action}/{id} ``` Unfortunately, since there are about 8 Foo sub-types, the `FooController` was getting quite large and containing it's own sub-routing information. My next stab at it was to have this structure: ``` Controllers/Foo/Form1Controller.cs Controllers/Foo/Form2Controller.cs Controllers/Foo/Form3Controller.cs ... ``` With a controller for each form, which makes more sense to me since that's basically the layout I use for other forms in the app. Unfortunately, I can't seem to find any easy way to make the route: ``` Foo/{controller}/{action}/{id} ``` ...map to: ``` Controllers/Foo/{controller}Controller.cs ``` Basically what I want to do is tell ASP.NET MVC that I want all routes that match the Foo route to look in the `Foo` subfolder of `Controllers` for their controllers. Is there any easy way to do that via routing, or do I need to write my own `IControllerFactory`? Thanks.
I ended up using a variation of the solution discussed here: <http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx>
I think what you are looking for is [SubControllers](http://jeffreypalermo.com/blog/mvccontrib-now-with-subcontroller-support/).
ASP.NET MVC Custom Controller directory
[ "", "c#", ".net", "asp.net", "asp.net-mvc", "routes", "" ]