Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I would like to trace performance inside a c# mobile application, in order to know the amount of time needed by some long-running methods. The goal is to know the performance at the level of methods. This tracing would be decided at runtime. First idea that came is to maintain a global variable "doWeHaveToTrace", to check it each time a potentially traceable method is called, and trace it if that variable is true. And in this case, I probably would use a Logger or a TraceListener to write tracing infos into a file. But I think this mechanism is quite heavy, because a variable has to be checked in each method, and the logger calls have to be coded. I also thought about aspect programming (insert tracing code in `before()` and `after()` methods), but I don't think aspect programming could be allowed inside this project. So I was wondering, is there any other good mechanisms that could provide such performance tracing ? Is it possible to trace a whole method ? And to decide to stop or resume tracing at runtime ?
Not sure exactly what you are trying to trace, but if you're trying to track time between long running methods, perhaps you'd be better off hooking into the [.NET Profiling API](http://msdn.microsoft.com/en-us/library/bb384358.aspx). Here is a [tutorial on usage.](http://www.blong.com/Conferences/DCon2003/Internals/Profiling.htm) A commerical profiler would be another, simpler option.
Read about how to [Compile Conditionally with Trace and Debug](http://msdn.microsoft.com/en-us/library/64yxa344.aspx) in .NET (assuming you are using .NET). The **Trace** and **Debug** classes will provide you with all the run-time output you need for development purposes. Then you can remove all your debug/trace code (and the associated run-time overhead) in your deployed application simply by removing the TRACE compiler directives. **OR** You can use an **external profiling application** to do your performance and memory profiling. See here (from StackOverflow.com): [What Are Some Good .NET Profilers?](https://stackoverflow.com/questions/3927/what-are-some-good-net-profilers)
Performance tracing in C#
[ "", "c#", "performance", "logging", "mobile", "trace", "" ]
I have written a Python TCP/IP server for internal use, using win32serviceutil/py2exe to create a Windows service. I installed it on a computer running Windows XP Pro SP3. However, I can't connect to it when it's running as a service. I can confirm that it's binding to the address/port, because I get a conflict when I try to bind to that address/port with another application. Further, I have checked the Windows Firewall settings and have added appropriate exceptions. If I run the server as a simple console application, everything works as expected. However, when I run it as a service, it doesn't work. I vaguely remember running into this problem before, but for the life of me can't remember any of the details. Suggestions, anyone?
First of all, whenever you implement a Windows service, be sure to add proper logging. My worker threads were terminating because of the exception, "The socket operation could not complete without blocking." The solution was to simply call `sock.setblocking(1)` after accepting the connection.
Possibly the program may be terminated just after initialization. Please check whether it is continuously listening to the requests. ``` netstat -an |find /i "listening" ``` And analyze the command line parsed to the programs. You may use [procexp](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to do that.
Cannot access Python server running as Windows service
[ "", "python", "windows-services", "tcp", "" ]
The "yield" statement in python allows simple iteration from a procedure, and it also means that sequences don't need to be pre-calculated AND stored in a array of "arbitrary" size. Is there a there a similar way of iterating (with yield) from a C procedure?
*Here follows a community-wiki copy of the self-answer, which can be chosen as "the" answer. Please direct up/downvotes to the actual self-answer* Here is the method I found: ``` /* Example calculates the sum of the prime factors of the first 32 Fibonacci numbers */ #include <stdio.h> typedef enum{false=0, true=1}bool; /* the following line is the only time I have ever required "auto" */ #define FOR(i,iterator) auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i) #define DO { #define YIELD(x) if(!yield(x))return #define BREAK return false #define CONTINUE return true #define OD CONTINUE; } /* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement. * * Otherwise the lambda will return random value from stack, and may terminate early */ typedef void iterator; /* hint at procedure purpose */ static volatile void *yield_init; #define YIELDS(type) bool (*yield)(type) = yield_init iterator fibonacci(int n){ YIELDS(int); int i; int pair[2] = {0,1}; YIELD(0); YIELD(1); for(i=2; i<n; i++){ pair[i%2] = pair[0] + pair[1]; YIELD(pair[i%2]); } } iterator factors(int n){ YIELDS(int); int i; for(i=2; i*i<=n; i++){ while(n%i == 0 ){ YIELD(i); n/=i; } } YIELD(n); } main(){ FOR(int i, fibonacci(32)){ printf("%d:", i); int sum = 0; FOR(int factor, factors(i)){ sum += factor; printf(" %d",factor); CONTINUE; } printf(" - sum of factors: %d\n", sum); CONTINUE; } } ``` Got the idea from <http://rosettacode.org/wiki/Prime_decomposition#ALGOL_68> - but it reads better in C
I pull this URL out as a joke from time to time: [Coroutines in C](http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html). I think the correct answer to your question is this: there's no direct equivalent, and attempts to fake it probably won't be nearly as clean or easy to use.
Python style iterators in C
[ "", "python", "c", "iterator", "jit", "algol68", "" ]
**Duplicate:** [Choosing a STL container with uniqueness and which keeps insertion ordering](https://stackoverflow.com/questions/769097/choosing-a-stl-container) I'm looking for a data structure that acts like a set in that it doesn't allow duplicates to be inserted, but also knows the order in which the items were inserted. It would basically be a combination of a set and list/vector. I would just use a list/vector and check for duplicates myself, but we need that duplicate verification to be fast as the size of the structure can get quite large.
Take a look at [Boost.MultiIndex](http://www.boost.org/doc/libs/1_38_0/libs/multi_index/doc/tutorial/basics.html). You may have to write a wrapper over this.
A [Boost.Bimap](http://www.boost.org/doc/libs/1_38_0/libs/bimap/doc/html/index.html) with the insertion order as an index should work (e.g. boost::bimap < size\_t, Foo > ). If you are removing objects from the data structure, you will need to track the next insertion order value separately.
Is there a data structure that doesn't allow duplicates and also maintains order of entry?
[ "", "c++", "data-structures", "" ]
I've built an open source ASP.NET web application and now I'm moving towards release. I'm keen to offer an easy install for my users but I'm having real problems coming up with a solution. The app needs to have a site setup in IIS and a SQL Database installed. What is the easiest deployment process for my users you can think of?
Look into the new Web Platform Installer. <http://www.microsoft.com/Web/downloads/platform.aspx> I haven't watched this but know Paul: <http://www.motusconnect.com/blog/2009/4/29/installing-umbraco-using-the-web-platform-installer>
You can create setup and deployment projects from within Visual Studio to aid in getting the application placed properly within IIS. As for database setup, you might consider writing a setup form within your website that can be called once to initialize the database based on user input (think about the setup process from popular open-source projects like WordPress or phpBB that perform a wizard-type function). Scott Guthrie also has a really cool blog post about creating deployment projects [here](http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx)
ASP.NET Application Install - Strategy needed
[ "", "asp.net", "sql", "iis", "" ]
Given an interface or interfaces, what is the best way to generate an class implementation? ``` interface Vehicle { Engine getEngine(); } @Generated class Car implements Vehicle { private final Engine engine; public Car(Engine engine) { this.engine = engine; } public Engine getEngine() { return engine; } // generated implementation of equals, hashCode, toString, } ``` The class variables should be derived from the getter methods of the interface. Ideally, covariant return types in the interfaces would be handled. The implementation should favour immutability by using private final variables and constructor instantiation. The equals, hashCode and toString methods should be generated.
The cleaner way is using [CGLIB](http://cglib.sourceforge.net/) to generate dynamically the class at runtime. Obviously, you are not able to browse the source file. If you need the source file, you could try [codemodel](https://codemodel.dev.java.net/) and do something like: ``` JCodeModel cm = new JCodeModel(); x = cm._class("foo.bar.Car"); x.field(Engine.class, "engine"); for (PropertyDescriptor pd: Introspector. getBeanInfo(Vehicle.class).getPropertyDescriptors()) { g = x.method(JMod.PUBLIC, cm.VOID, pd.getReaderMethod().getName()); g.body()... s = x.method(JMod.PUBLIC, cm.VOID, "set" + pd.getName()); s.body()... } hc = x.method(JMod.PUBLIC, cm.VOID, "hashCode")); hc.body()... cm.build(new File("target/generated-sources")); ``` Or as suggested previously, use the IDE (in Eclipse: Menu "Source", "Generate hashcode() and equals()...", i.e.)
Do just like eclipse do when implementing a class for an interface. If a method starts with get then consider that as a getter and parse the method to extract variable name and its type. Create a constructor for those fields as well and also implement equals, hashcode and toString methods. You can do normal file parsing or maybe reflection can also help not sure.
Autogenerate value objects
[ "", "java", "annotations", "runtime", "code-generation", "compile-time", "" ]
**foreword:** I have a component, lets call it IView. This component is implemented by BaseView class which holds most of it's functionality. We are using the template pattern to delegate logic to inheretting classes. **The problem:** We have a property named IView.Visible, that indicates if the component should or should not be visible. This property is **not virtual** since it involves some logic in our BaseView. We have created a virtual protected method **IsVisible** which is invoked from BaseView.Visible to decide the final value of IView.Visible. We feel that this property name, IsVisible, is not descriptive and clear enough to the implementor of the derived class. It's been suggested to rename it to ShouldBeVisible, but we still fill that there is a better name. What do you think ? Do you have a better name ? Is there a good naming convention that covers this topic of template methods ? --- **Update:** Just to clarify a point, the Visible and IsVisible properties don't have side effect on the component, The Visible property uses the value from IsVisible to decide if the value of Visible should be true, but it is not the only consideration and couple other of the internal states of the component to give the final verdict.
I've never been especially keen on this naming convention, but the [Framework Design Guidelines](http://www.amazon.co.uk/Framework-Design-Guidelines-Conventions-Development/dp/0321545613/ref=sr_1_1?ie=UTF8&s=books&qid=1240489957&sr=8-1) book suggests the usage of 'Core' as the suffix for this type of pattern. This code is taken from the Microsoft System.Windows.Forms.Control class ``` public bool CanSelect { get { return this.CanSelectCore(); } } internal virtual bool CanSelectCore() { ... } ``` My concern with this solution is that you are exposing a method of unknown complexity with possible side effects as a property, but since you can rummage through the .NET framework code and see that this convention is used quite often if you are looking for a standard this may be as close as you'll get.
There is no 'right' or 'wrong' in this question, only 'better' or 'worse'. Personally I would make the Property that "involves some logic" a method GetVisible() to make clear that there is some logic (even if it is that simple that it could be property as well). The property holding the information could be just Visible. This are like different members are understood: Property is data (or an illusion of data) and methods are logic.
How to name pure virtual protected property
[ "", "c#", ".net", "properties", "naming-conventions", "" ]
Guys, I need to develop a tool which would meet following requirements: 1. Input: XHTML document with CSS rules within `head` section. 2. Output: XHTML document with CSS rules computed in tag attributes The best way to illustrate the behavior I want is as follows. Example input: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <style type="text/css" media="screen"> .a { color: red; } p { font-size: 12px; } </style> </head> <body> <p class="a">Lorem Ipsum</p> <div class="a"> <p>Oh hai</p> </div> </body> </html> ``` Example output: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <body> <p style="color: red; font-size: 12px;">Lorem Ipsum</p> <div style="color: red;"> <p style="font-size: 12px;">Oh hai</p> </div> </body> </html> ``` What tools/libraries will fit best for such task? I'm not sure if BeautifulSoup and cssutils is capable of doing this. Python is not a requirement. Any recommendations will be highly appreciated.
There is a [premailer python package on Pypi](http://pypi.python.org/pypi/premailer)
Try premailer [code.dunae.ca/premailer.web](http://code.dunae.ca/premailer.web/) More info: [campaignmonitor.com](http://www.campaignmonitor.com/blog/post/2455/automatically-generate-inline/)
CSS parser + XHTML generator, advice needed
[ "", "python", "css", "parsing", "xhtml", "" ]
Can anyone help, seem to have an issue placing a onclick event of an anchor tag, it works on an image.. I have this ``` this.whereAreWe = document.getElementById('where_are_we'); this.whereAreWe.onclick = this.whereAreWe; ``` I have placed a A tag using the id of "where\_are\_we" ... but it never executes.. if I change it to an image it works.. I also put the href="#" Is there something special about anchor tags and applying the onclick via code? I also tried removing the href, If I remove the href it doesn't show me the little hand icon. I have put a breakpoint in the function and with an image it enters but using the anchor it doesn't Any ideas?
> I also tried removing the href, If i remove the href it doesn't show me the little hand icon. You need the 'href' attribute for the 'a' tag in order to specify the URL of the destination document or web resource. In case you do not specify it - mouseover doesn't change the cursor. Of course you could use CSS to modify that but that is a different question.
The code you provided is confusing. The following code works correctly for me: ``` <a href="#" id="whereWeAre">a link</a> <script type="text/javascript"> var whereWeAre = document.getElementById("whereWeAre"); function testClick() { alert("You clicked!"); } whereWeAre.onclick = testClick; </script> ``` If your example was a little more specific we could probably be more helpful.
Placing a Click event on an achor tag in html from javascript?
[ "", "javascript", "html", "onclick", "" ]
There are a number of questions already on the definition of "ref" and "out" parameter but they seem like bad design. Are there any cases where you think ref is the right solution? It seems like you could always do something else that is cleaner. Can someone give me an example of where this would be the "best" solution for a problem?
In my opinion, `ref` largely compensated for the difficulty of declaring new utility types and the difficulty of "tacking information on" to existing information, which are things that C# has taken huge steps toward addressing since its genesis through LINQ, generics, and anonymous types. So no, I don't think there are a lot of clear use cases for it anymore. I think it's largely a relic of how the language was originally designed. I do think that it still makes sense (like mentioned above) in the case where you need to return some kind of error code from a function as well as a return value, but nothing else (so a bigger type isn't really justified.) If I were doing this all over the place in a project, I would probably define some generic wrapper type for thing-plus-error-code, but in any given instance `ref` and `out` are OK.
Well, `ref` is generally used for specialized cases, but I wouldn't call it redundant or a legacy feature of C#. You'll see it (and `out`) used a lot in XNA for example. In XNA, a `Matrix` is a `struct` and a rather massive one at that (I believe 64 bytes) and it's generally best if you pass it to functions using `ref` to avoid copying 64 bytes, but just 4 or 8. A specialist C# feature? Certainly. Of not much use any more or indicative of bad design? I don't agree.
In C#, where do you use "ref" in front of a parameter?
[ "", "c#", "ref", "" ]
[Edit] My original-question was "Why to decide between static and non-static? Both do the same..." Unfortunately it was edited to a C#-specific question what I really wanted to avoid. So, let me do some additions: When I say interface, I don't mean the C#-keyword-interface but what I understand something like a C++-interface: A set of well defined functions to operate with my object. When saying weaken my interface, I mean I have different functions (static/non-static) that do the same thing. My interface is not well defined anymore when there are different functions to do the same thing. So, as Bob the Janitor posted, I can implement a Validate()-function ``` Document.Validate(myDocumentObject); ``` but also ``` myConcreteDocumentObject.Validate(); ``` To get back to my Copy()-example one could implement Copy() like ``` myConcreteDocument.Copy(toPath); ``` but also ``` Document.Copy(myConcreteDocumentObject, toPath) ``` or ``` Document.Copy(fromPath, toPath) ``` when I think of a folder that contains all the files belonging to my Document (in this case I'm not dependent of a concrete instance - but I'm dependent from other things :)). In general I'm talking about static methods not static classes (sorry, if I forgot to mension). But as Anton Gogolev said I think my Document class is not a good example and not well designed so I think I will have to have a look at the Single Responsibility Principle. I could also implement some kind of ManagerClass that operates with my DocumentClass: For example: ``` myDocumentManagerObject.Copy(myConcreteDocumentObject, toPath); ``` or ``` myDocumentManagerObject.Copy(myConcreteDocumentObject, toPath); ``` but if I refer to approach 1) I would tend to create objects that perform their tasks by themself rather than other objects (DocumentManager) that do something *with* my DocumentObject. (I hope this will not take the direction of a religious discussion about OOP ;).) [/EDIT] --- ## Old Version: At first this seems to be a very basic question like "when to use static methods and when not" but this is something I'm confronted every now and then (and I have difficulties to describe what the real problem is; perhaps it's just to get reasons why (not) to use 1) or why (not) to use 2)). (Although I'm using C#-Syntax this is not a C#-restricted problem) In OOP there are two approaches (amongst others) of working with objects: 1) If I want my object to do something, I just tell him to do so: ``` myConcreteObject.DoSomething(); ``` It's just like talking to an object. 2) Or if you're a fan of static methods: ``` ObjectClass.JustDoIt(); ``` In some way I think static functions just "feel" better. So I tend to use static methods very often (to be independent from a concrete instance - independency is always good thing). So, when designing a class I often have to decide if I take approach 1) or approach 2): Imagine you have a class "Document" which should stand for a document that should be saved into a database: A Document * consists of one or more image files from filesystem (these become the single document pages) * has something like a bibliography - fields the user can add information about the document to - which is saved to an extra file * and should have some operations like Copy(), AddPage(), RemovePage() etc. Now I'm confrontated with several ways to create this class: ``` //----- 1) non static approach/talking to objects ----- Document newDocument = new Document(); // Copy document to x (another database, for example) newDocument.Copy(toPath); ``` I like this: I tell the document to copy itself to database x and the object does so by itself. Nice. ``` //----- 2) static approach ---------------------------- Document.Copy(myDocumentObject, toPath); ``` Why not? Also nice, feels very handy... So, which one to implement? Both? Or putting the static approach to a kind of helper class? Or choose approach 1) and stick with it to not weaken the interface of my Document-class? When thinking about both approaches I come to the conclusion that (in theory) one could implement any function as a static function: ``` Class.Function(aConcreteClassObject, parameters); ``` but also non-static: ``` aConcreteObject.DoSomething(parameters); ``` To give a real-world example: [EDIT(Added parameter fromPath "Sorry, I forgot")] ``` //----- 2) static approach ---------------------------- File.Copy(fromPath, toPath); // .Net-Framework-like ``` [/EDIT] but also: ``` //----- 1) non static approach ------------------------ ExampeFileClass fileObject = new ExampleFileClass(); fileObject.Copy(toPath); ``` or even (kind of OOP-Overkill): ``` //----- 1) non static approach, too ------------------- fileObject.ToPath = @"C:\Test\file.txt"; // property of fileObject fileObject.Copy(); // copy to toPath ``` So, why (not) to use 1) or why (not) to use 2)? (I would not concentrate on the Document class example too much, since it's more a general question about good class design.)
KISS. If you don't have to call a constructor, even better. Also, a method being static should tell you a little about how the function operates: * It doesn't operate on variables outside of what's passed to it. * It doesn't require any memory other than when the method is called (not counting what is returned from the function) There are some other important things to note: * Static methods in some instances (Java) are not able to be overridden/subclassed, so they are better suited for cases where the ***implementation will not need to change***. * Some would argue that static methods are [intrinsically difficult to test](http://googletesting.blogspot.com/2008/12/static-methods-are-death-to-testability.html). I would also refer to this [thread](https://stackoverflow.com/questions/475097/is-there-a-rule-of-thumb-for-when-to-code-a-static-method-vs-an-instance-method), and a [simple google search](http://www.google.com/search?q=why+use+static+methods&sourceid=navclient-ff&ie=UTF-8&rlz=1B3GGGL_enUS309US309) which frankly provides copious amounts of discussion on this very topic.
Here we go. First off: > So I tend to use static methods very often (to be independent from a concrete instance - independency is always good thing). Quite the contrary: when using static methods you're very dependent on the concrete instance. As far as your `Document` is concerned, I'd go neither way. You've listed all responsibilities of `Document` class, which includes aggregation of data, saving itself to the database plus operations on pages and copying. This is way to much. Per [SRP](http://en.wikipedia.org/wiki/Single_responsibility_principle), each "module" (here "module" used as a catch-all term) should have only one reason to change. Your `Document` has lots of responsibilities, hence it has a whole slew of reasons to change. This is no good. With that in mind, I'd move all logic to other classes with strictly defined responsibilities. A more or less accepted criterion of what to move was introduced, I believe, by either Herb Sutter or Andrei Alexandrescu, an is as follows: all operations (think methods) that can be performed with an object through its public contract should be moved outside the object in question. ---
How to decide between C# static and non-static methods?
[ "", "c#", "oop", "class-design", "" ]
I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: ``` class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # create one a.m = "?" # here is a PROBLEM ``` But after running this simple code, I get a very strange error: ``` Traceback (most recent call last): File "test.py", line 8, in <module> a.m = "?" AttributeError: 'test' object attribute 'm' is read-only ``` Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?
When you declare instance variables using `__slots__`, Python creates a [descriptor object](https://docs.python.org/2/howto/descriptor.html) as a class variable with the same name. In your case, this descriptor is overwritten by the class variable `m` that you are defining at the following line: ``` m = None # my attribute ``` Here is what you need to do: Do not define a class variable called `m`, and initialize the instance variable `m` in the `__init__` method. ``` class MyClass(object): __slots__ = ("m",) def __init__(self): self.m = None a = MyClass() a.m = "?" ``` As a side note, tuples with single elements need a comma after the element. Both work in your code because `__slots__` accepts a single string or an iterable/sequence of strings. In general, to define a tuple containing the element `1`, use `(1,)` or `1,` and not `(1)`.
You are completely misusing `__slots__`. It prevents the creation of `__dict__` for the instances. This only makes sense if you run into memory problems with many small objects, because getting rid of `__dict__` can reduce the footprint. This is a hardcore optimization that is not needed in 99.9% of all cases. If you need the kind of safety you described then Python really is the wrong language. Better use something strict like Java (instead of trying to write Java in Python). If you couldn't figure out yourself why the class attributes caused these problems in your code then maybe you should think twice about introducing language hacks like this. It would probably be wiser to become more familiar with the language first. Just for completeness, here is the [documentation link for slots](https://docs.python.org/2/reference/datamodel.html#slots).
python, __slots__, and "attribute is read-only"
[ "", "python", "exception", "descriptor", "readonly-attribute", "" ]
We are running tomcat, and we are generating pdf files on the fly. I do not have the file size before hand, so I cannot direcly link to a file on the server. So I directly send the output. ``` response.setContentType("application/force-download"); OutputStream o = response.getOutputStream(); ``` And then I directly output to this OutputStream. The only problem is that the receiver does not get the filesize, so they do not know how long the download will take. Is there a way to tell the response how large the file is? **EDIT** I do know the filesize, I just cant tell the STREAM how big the file is.
The response object should have a [setContentLength](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletResponse.html#setContentLength(int)) method: ``` // Assumes response is a ServletResponse response.setContentLength(sizeHere); ```
Serialize the PDF byte stream to a file or in a byte array calculate its size, set the size and write it to the output stream.
Jsp download file size
[ "", "java", "html", "jsp", "tomcat", "download", "" ]
[**Update**: *Format specifiers are not the same thing as format strings; a format specifier is a piece of a custom format string, where a format string is 'stock' and doesn't provide customization. My problem is with specifiers not formats*] I've been trying to perform roundtrip DateTime conversions with a format string that uses 'zzz' format specifier, which I know is bound to local time. So, if I attempt to round trip with a UTC date time it throws a DateTimeInvalidLocalFormat exception, which it should, with this text: *A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output. **In that case, either use the 'Z' format specifier, which designates a UTC time**, or use the 'o' format string, which is the recommended way to persist a DateTime in text. This can also occur when passing a DateTime to be serialized by XmlConvert or DataSet. If using XmlConvert.ToString, pass in XmlDateTimeSerializationMode.RoundtripKind to serialize correctly. If using DataSet, set the DateTimeMode on the DataColumn object to DataSetDateTime.Utc.* Based on this suggestion, all I need to do to get my code to work is to replace 'zzz' with 'ZZZ' so I can stand in a UTC format. The problem is, 'Z' isn't found anywhere in the documentation and any 'Z' format combination I try, i.e. 'Z', 'ZZ', 'ZZZ', always just converts the DateTime instance with those Z's treated like literals. Did someone forget to implement 'Z' without telling the exception message author, or am I missing how to swap out a valid local time offset with "+0000" without hacking? **Code Example:** ``` // This is the format with 'zzzzz' representing local time offset const string format = "ddd MMM dd HH:mm:ss zzzzz yyyy"; // create a UTC time const string expected = "Fri Dec 19 17:24:18 +0000 2008"; var time = new DateTime(2008, 12, 19, 17, 24, 18, 0, DateTimeKind.Utc); // If you're using a debugger this will rightfully throw an exception // with .NET 3.5 SP1 because 'z' is for local time only; however, the exception // asks me to use the 'Z' specifier for UTC times, but it doesn't exist, so it // just spits out 'Z' as a literal. var actual = time.ToString(format, CultureInfo.InvariantCulture); Assert.AreEqual(expected, actual); ```
Maybe the "K" format specifier would be of some use. This is the only one that seems to mention the use of capital "Z". "Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 datetime standard for UTC times. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time. This probably creates a few problems for the date format library in .NET, since it's actually a literal, rather than a format specifier.
When you use DateTime you are able to store a date and a time inside a variable. The date can be a local time or a UTC time, it depend on you. For example, I'm in Italy (+2 UTC) ``` var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00 var dt2 = dt1.ToUniversalTime() // store 2011-06-27 10:00:00 ``` So, what happen when I print dt1 and dt2 including the timezone? ``` dt1.ToString("MM/dd/yyyy hh:mm:ss z") // Compiler alert... // Output: 06/27/2011 12:00:00 +2 dt2.ToString("MM/dd/yyyy hh:mm:ss z") // Compiler alert... // Output: 06/27/2011 10:00:00 +2 ``` dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset. **So where the "+2" come from if it's not contained in the dt1 and dt2 variable?** It come from your machine clock setting. The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + **"TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type)** and it will use the offset of the server machine that it's executing the code. The compiler tell you "Warning: the output of your code is dependent on the machine clock offset" If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "**+2**" it will write "**+1**" ``` ... dt1.ToString("MM/dd/yyyy hh:mm:ss z") // Output: 06/27/2011 12:00:00 +1 dt2.ToString("MM/dd/yyyy hh:mm:ss z") // Output: 06/27/2011 10:00:00 +1 ``` The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version
Where's the DateTime 'Z' format specifier?
[ "", "c#", "datetime", "format", "utc", "" ]
I've been using RMI for a project I am currently working on and I want to bind from multiple hosts to a single RMI registry. However when I attempt to do so I get an error saying java.rmi.AccessException: Registry.Registry.bind disallowed; origin / 192.168.0.9 is non-local host I did so googling and it seems that RMI stops remote hosts from binding by default, what I want to know is there some way of overriding or bypassing this? If anyone any suggestions on how to get past this issue they would be highly appreciated, i've tried using different policy files and overriding the security manger but none seem to work.
Thanks for everyones answers the solution I came up with in the end was to use the [Cajo Framework](https://cajo.dev.java.net/) this gives a very flexible system for distribution and it allowed for me to handle the registry as I saw fit. It can also work behind NATs, firewalls, and HTTP proxies, which is very useful. I believe that the method of proxying suggested by rndm.buoy will work in some cases but its may be troublesome on some system. RMI seems to have some issues with associating to the wrong Network Interface I particularly had this issue when running on Debian based Linux distributions.
There's a way to get around the limitation but it is what it is: a work-around. Anyway, feel free to try it out. It works for us. On the host that is running the central RMI registry run a small service which will bind a remote object with just one remote method: proxyRebind. The implementation of this method simply binds the object that is supplied to it in the central registry (this would not fail because the registry is on the same machine as this service). All other hosts would simply lookup this remote object and invoke proxyRebind with their own remote objects. This works because look-up on remotely hosted registries is allowed. Your original attempt failed because binding on remotely hosted registries is not allowed. Let me know if you need any further clarity on this. /RS
Using single RMI Registry
[ "", "java", "exception", "networking", "distributed", "rmi", "" ]
I want a string with one additional attribute, let's say whether to print it in red or green. Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying. Can multiple inheritence help? I never used that. Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself. Or is there a way to forward them, like Ruby's missing\_method? I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?
str can be inherited unless you are using a very old python version, for example : ``` >>> class A(str): ... def __new__(cls, color, *args, **kwargs): ... newobj = str.__new__(cls, *args, **kwargs) ... newobj.color = color ... return newobj >>> a = A("#fff", "horse") >>> a.color '#fff' >>> a 'horse' >>> a.startswith("h") True ```
``` import UserString class mystr(UserString.MutableString): ... ``` It's generally best to use immutable strings & subclasses thereof, but if you need a mutable one this is the simplest way to get it.
How to bestow string-ness on my class?
[ "", "python", "string", "multiple-inheritance", "immutability", "" ]
I updated my python version on windows 2003 server from 2.4 to 2.5. In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this: ``` import sub1 ``` as long as the calling script main.py that lives in c:\application was started like this: ``` c:\application\subdir>python ..\main.py ``` But in 2.5 it no longer works for me: ``` C:\application\subdir>python ..\main.py Traceback (most recent call last): File "main.py", line 3, in <module> import sub1 ImportError: No module named sub1 ``` Now I can put an empty file ``` __init__.py ``` into subdir and import like this: ``` import subdir.sub1 as sub1 ``` Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives. [edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]
You need to make the following changes: * turn `subdir` into a package by adding an empty `__init__.py` file to the directory * change the import to: `from subdir import sub1`
to import sub.py you need to: ``` import sub # not sub1 ```
Current working directory no longer inherited from calling process from python 2.5 onwards?
[ "", "python", "import", "" ]
I need an attribute that handles authorization for my controllers. This is for a Facebook application and there are a few hurdles surrounding the problem. What I really need is the equivalent to a `server.transfer` but of course that is not an option in ASP.NET MVC. A redirect will not work because of the way Facebook consumes the application. Is there an a way I can re-route from within an `ActionFilterAttribute`? ``` public class FbAuthorize : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!Service.SignedIn()) RouteToAction("Account", "Index"); // Fictional method (I wish it existed) } } ```
Here is your "Server.Transfer()" or kind of: ``` public static class ServerHelper { public static void Transfer(ActionExecutingContext filterContext, string url) { // Rewrite path HttpContext.Current.RewritePath(GetPath(filterContext, url), false); IHttpHandler httpHandler = new System.Web.Mvc.MvcHttpHandler(); // Process request httpHandler.ProcessRequest(HttpContext.Current); filterContext.HttpContext.Response.End(); } private static string GetPath(ActionExecutingContext filterContext, string url) { HttpRequestBase request = filterContext.HttpContext.Request; UriBuilder uriBuilder = new UriBuilder(request.Url.Scheme, request.Url.Host, request.Url.Port, request.ApplicationPath); uriBuilder.Path += url; return filterContext.HttpContext.Server.UrlDecode(uriBuilder.Uri.PathAndQuery); } } ``` Now, in your filter, just call: ``` ServerHelper.Transfer(filterContext, "Account/Index"); ``` Cheers
If you're using the facebook developer's toolkit you can implement the basepagehelper's LoadFBMLPage method in an ActionFiler's OnActionExecuting method. (otherwise you'll have to emit the fb:redirect tag yourself). Here's a brief writeup: <http://onishimura.com/2009/04/13/facebook-and-aspnet-mvc/>
How to write a custom MVC ActionFilterAttribute that redirects a Facebook application
[ "", "c#", "asp.net-mvc", "facebook", "fbml", "" ]
Probably an easy-to-answer question. I have this procedure: ``` CREATE PROCEDURE [dbo].[AccountExists] @UserName nvarchar(16) AS IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName) SELECT 1 ELSE SELECT 0 ``` When I have ADO.NET code that calls this procedure and does this: ``` return Convert.ToBoolean(sproc.ExecuteScalar()); ``` Either true or false is returned. When I change the stored procedure to RETURN 1 or 0 instead of SELECT: ``` ALTER PROCEDURE [dbo].[AccountExists] @UserName nvarchar(16) AS IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName) RETURN 1 ELSE RETURN 0 ``` sproc.ExecuteScalar() returns null. If I try sproc.ExecuteNonQuery() instead, -1 is returned. **How do I get the result of a stored procedure with a RETURN in ADO.NET?** I need AccountExists to RETURN instead of SELECT so I can have another stored procedure call it: ``` --another procedure to insert or update account DECLARE @exists bit EXEC @exists = [dbo].[AccountExists] @UserName IF @exists=1 --update account ELSE --insert acocunt ```
Add a parameter, using `ParameterDirection.ReturnValue`. The return value will be present in the paramter after the execution.
Also, to retrieve the result (or any other output parameter for that matter) from ADO.NET you have to loop through all returned result sets first (or skip them with NextResult) This means that if you have a procedure defined like this: ``` CREATE PROC Test(@x INT OUT) AS SELECT * From TestTable SELECT @x = 1 ``` And try to do this: ``` SqlCommand cmd = connection.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Test" cmd.Parameters.Add("@x", SqlDbType.Int).Direction = ParameterDirection.Output; cmd.Parameters.Add("@retval", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; cmd.Execute(); int? x = cmd.Parameters["@x"].Value is DBNull ? null : (int?)cmd.Parameters["@x"].Value; ``` Then x will contain null. To make it work, you have to execute the procedure like: ``` using (var rdr = cmd.ExecuteReader()) { while (rdr.Read()) MaybeDoSomething; } int? x = cmd.Parameters["@x"].Value is DBNull ? null : (int?)cmd.Parameters["@x"].Value; ``` In the latter case, x will contain 1 as expected.
How to get Return Value of a Stored Procedure
[ "", "sql", "t-sql", "stored-procedures", "ado.net", "" ]
I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa. Is there a straightforward way to open up the files using the correct file encoding?
Use the [chardet](http://chardet.feedparser.org/) library to detect the encoding.
You can check for the [BOM](http://en.wikipedia.org/wiki/Byte-order_mark "BOM") at the beginning of the file to check whether it's UTF. Then [unicode.decode](http://docs.python.org/library/stdtypes.html#str.decode) accordingly (using one of the [standard encodings](http://docs.python.org/library/codecs.html#standard-encodings)). **EDIT** Or, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDecodeError, then decode it as 'utf\_16\_le'.
Best way for Parsing ANSI and UTF-16LE files using Python 2/3?
[ "", "python", "encoding", "ansi", "utf-16", "" ]
I'm using Django, and I have the following error: > Exception Type: SyntaxError > Exception Value: invalid syntax (views.py, **line 115**) My viws.py code looks like this: ``` def myview(request): try: [...] except MyExceptionClass, e: [...] finally: render_to_response('template.html', {}, context_instance = RequestContext(request)) ``` Where MyExceptionClass is a class extending Exception, and **line 115** is the 'finally' clause line. If I remove finally clause, (lines 115-116), works fine. Any idea? Thanks a lot!
What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block. You can work around this by nesting try blocks. ``` def myview(request): try: try: [...] except MyExceptionClass, e: [...] finally: render_to_response( 'template.html', {}, context_instance = RequestContext(request) ) ```
Nadia is right, so if you're stuck with Python 2.4 or earlier, use *two* try blocks: ``` try: try: [...] except MyExceptionClass, e: [...] finally: render_to_response(...) ```
SyntaxError in finally (Django)
[ "", "python", "django", "" ]
I'd like to study some good C/C++ code. The code should: 1. be good in style and structure, presenting best practices 2. be a real life program (not an example or toy) 3. not too big so it doesn't takes ages to analyse it 4. Windows and/or Unix I know there are 1000s of open source projects out there. But I'd like to hear your suggestions. I am Java programmer and I am curious how good project in c/c++ is structured (files), granularity of classes/functions/files, documentation/comments, build tools etc. Multiple suggestions are welcomed e.g. this is good windows example, that is good pure C etc.
I would specifically mention [memcached.](http://www.danga.com/memcached/) It's a great example of fairly short, readable code with a clear purpose. Second, I would recommend the [Apache web server](http://httpd.apache.org/). It's a fantastically well-run open source project that you'll learn a lot from, both about the language, as well as general design practices and networking/threading.
I'd vote for nginx: <http://sysoev.ru/en/> as an example of a very good C programming style
Suggestions of excellent examples of real C/C++ code
[ "", "c++", "c", "" ]
in my app i need to send an javascript Array object to php script via ajax post. Something like this: ``` var saveData = Array(); saveData["a"] = 2; saveData["c"] = 1; alert(saveData); $.ajax({ type: "POST", url: "salvaPreventivo.php", data:saveData, async:true }); ``` Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work. Ideas? Thanks in advance
Don't make it an Array if it is not an Array, make it an object: ``` var saveData = {}; saveData.a = 2; saveData.c = 1; // equivalent to... var saveData = {a: 2, c: 1} // equivalent to.... var saveData = {}; saveData['a'] = 2; saveData['c'] = 1; ``` Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by [Paolo Bergantino](https://stackoverflow.com/users/16417/paolo-bergantino) ``` var saveData = Array(); saveData["a"] = 2; saveData["c"] = 1; //creating a json object var jObject={}; for(i in saveData) { jObject[i] = saveData[i]; } //Stringify this object and send it to the server jObject= YAHOO.lang.JSON.stringify(jObject); $.ajax({ type:'post', cache:false, url:"salvaPreventivo.php", data:{jObject: jObject} }); // reading the data at the server <?php $data = json_decode($_POST['jObject'], true); print_r($data); ?> //for jObject= YAHOO.lang.JSON.stringify(jObject); to work, //include the follwing files //<!-- Dependencies --> //<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script> //<!-- Source file --> //<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script> ``` Hope this helps
Convert js Array() to JSon object for use with JQuery .ajax
[ "", "javascript", "jquery", "arrays", "json", "" ]
Before asking this question I have Googled for this problem and I have looked through all StackOverflow related questions. The problem is pretty simple I have a string "North Atlantic Treaty Organization" I have a pattern "a.\*z", at moment it would match north ATLATIC TREATY ORGANIZation But I need it to match complete words only (orgANIZation for example) I have tried "\ba*z\b" and "\Ba*z\B" as pattern, but I think I don't quite get it How should I change my pattern in order to match complete words that string contains (without matching multiple words) The patterns are generated on the fly, user enteres a\*z and my application translates it into pattern that matches parts of complete words in string. My problem is that I don't know what user is going to search for. Ideally I would preppend some regexp to user's expression. Thank You!
ANIZ in orgANIZation is **not** a complete word -- it's a part of a word. Your pattern btw is not what you wrote -- `a*z` would not match as you describe; you're probably using `a.*z` instead, which would. So, try `a[^ ]*z` so it won't match spaces. If there are other characters besides spaces that you don't want to match, e.g. some kinds of punctuation, stick them in the `[^...]` construct as well, of course.
``` "a[^\s]*z" ``` This means an 'a' followed by any number of non-whitespace characters, followed by a 'z'. *EDIT:* You seem to want '`*`' to be interpreted as a wildcard character. The user is thus not to enter a regex, but a string with certain wildcards. You can translate these wildcard characters to regex by reasoning over the intended meaning. Let's say that '`*`' should mean "zero or more characters that are not whitespace". You replace this character, then, with the corresponding regex: ``` [^\s]* `-.-´| Character class-----´ `---Zero or more of these '\s': "Whitespace" Inside Character class: if it starts with '^': "not" ``` You might also want to define '?' as matching exactly a single non-whitespace character. This is the same character class, but you omit the '\*' at the end. So, what you do is regex-replace "`*`" with "`[^\s]*`" and "`?`" with "`[^\s]`".
C# regex match only parts of complete words in string
[ "", "c#", ".net", "regex", "" ]
When accessing instance variables or properties of a class from within the class itself, do you prepend them with "`this.`"?
No. I consider it visual noise. I think the this variable is a crutch to bad naming styles. Within my type I should be able to manage the naming of the fields, properties and methods. There is absolutely no good reason to name your backing field "myfield", the parameter to the constructor as "myField" and the property to be "myField". ``` public class TestClass { private string myField; public TestClass(string myField) { this.myField = myField; } public string MyField {get { return myField;} set {myField = value}} } ``` Personally, I always add a prefix of \_ to all my private backing fields. ``` public class TestClass { private string _myField; public TestClass(string myField) { _myField = myField; } public string MyField {get { return _myField;} set {_myField = value}} } ``` and now with automatic properties in C# ``` public class TestClass { private string MyField {get; set;} public TestClass(string myField) { MyField = myField; } } ``` Other than the above maybe the only other time you type this. is because you want to see the intellisense for your current type. If you need to do this then I submit that your type is too big and probably not following the [Single Responsibility Principle](http://en.wikipedia.org/wiki/Single_responsibility_principle). And lets say you are. Why keep the this. around after you actually make the call. Refactor it out.
I only ever use a `this.` prefix in constructors or setters, primarily in the case where the passed parameters have the same name as the relevant member variables.
Do you use 'this' in front of instance variables?
[ "", "c#", "coding-style", "" ]
When i add a listview to my form and in form load event i write below code , items added in the same row not in separated rows , how can i add them to separated rows ``` listView1.MultiSelect = true; listView1.CheckBoxes = true; listView1.Items.Add("Item 1"); listView1.Items.Add("Item 22"); listView1.Items.Add("Item 333"); ```
try this out ``` listView1.View = View.List; ```
Taking a stab at this, I'd suggest that it's because your ListView is defaulting to small icons or tiles. Try adding this line anywhere there: ``` listView1.View = View.Details; ```
Add item in separated rows in listview
[ "", "c#", "winforms", "listview", "" ]
I have a string which follows **literally**: ``` "lt;img src=quot;http://www.news.gov.tt/thumbnail.php?file=Hon__Jerry_Narace_Minister__Of_Health_599152837.jpgamp;size=summary_mediumquot;gt;lt;pgt;Fifty-eight people have been tested for Influenza A/H1N1 virus, commonly called swine flu, in Trinidad and Tobago. \r\nThe tests have all come back negative, Health Minister Jerry Narace said yesterday. \r\n\r\n" ``` I would like to get the url between the 'quot;' strings, ie, ``` http://www.news.gov.tt/thumbnail.php?file=Hon__Jerry_Narace_Minister__Of_Health_599152837.jpgamp;size=summary_medium ``` using a regex in .NET. Any ideas?
``` ^\"lt;img\s+src\=quot;(.+)quot; ``` Given the following input: ``` "lt;img src=quot;http://www.news.gov.tt/thumbnail.php?file=Hon__Jerry_Narace_Minister__Of_Health_599152837.jpgamp;size=summary_mediumquot;gt;lt;pgt;Fifty-eight people have been tested for Influenza A/H1N1 virus, commonly called swine flu, in Trinidad and Tobago. \r\nThe tests have all come back negative, Health Minister Jerry Narace said yesterday. \r\n\r\n" ``` this regex returns the following: ``` http://www.news.gov.tt/thumbnail.php?file=Hon__Jerry_Narace_Minister__Of_Health_599152837.jpgamp;size=summary_medium ``` which I believe is exactly what you required. Hope this helps, Ryan
``` Regex r = new Regex("(?<=img src=&quot;).*?(?=&quot;)"); ``` Should do the trick for you, assuming there aren't any ampersands hiding out there somewhere. EDIT: After posting this answer, I noticed ampersands I saw before in your string were no longer present.
I need a regex to get the src attribute of an img tag
[ "", "c#", "regex", "" ]
I roamed the site for this question using the search engine, and I don't think it's out there. If it is, apologies in advance and feel free to point me to it. Here is my scenario: I am setting up a web application, Moodle if anyone is familiar with it, with Apache, MySQL, and php on Windows. Moodle supports enabling SSL for login, but then reverts to regular http after login is established. This is running on an internal network with no connection to the outside world, so no Internet access through this network. All users who use the network have logins, however there are some generic guest type logins with certain restricted privilages. Currently the MySQL database is not encrypted. My question is this: If my users do an SSL login, and the system then reverts back to http for the remainder of their session, how vulnerable is the data that is transferred back and forth between the browser interface and the database? I would perhaps prefer to have all the data encrypted, but I am not sure how bad the performance hit would be to do that, so any suggestions concerning that would be appreciated too. Although I will be extending the functionality in Moodle, I don't necessarily want to have to change it to encrypt everything if already does. I am new to the world of IT security, and my DBA skills are rusty, so if you give me an answer, type slowly so I can understand! ;) Thanks in advance! Carvell
A few things. 1. The fact that the data in the DB server is not encrypted in no way is a factor in the communication between the User and the Web Server. It is a concern obviously for communications between the web server and the database server. 2. Your risk point between user and web server is in that packets could be sniffed if a person was able to interject in the middle of the communication chain. However, this risk is mitigated by the fact that your on an internal network. Therefore, unless you are VERY concerned about the other people in your organization, you are more than likely ok. However, if it is really sensitive data, you might do ALL communications via SSL to ensure that it is transmitted securely. IF you are this concerned, then I would also look at the security of the DB and the communications from DB to webserver.
My concern would be how your authenticated sessions are propagated. Generally a session works by setting a cookie or appending a session id to any URLs presented by the web site. Once a log-in has been established, often the credentials aren't needed any more, as a session is then linked to the user and deemed to be authenticated, and the existence of the session itself is proof of a successful authentication. However, as previous posters have mentioned, local network traffic can be available for sniffing. If someone sniffed a session id, they could recreate the cookie or urls using the session id, and simply access the site as that session user, even changing the user's password if that option was available. I would say that your decision here rests on the security of your sessions. If you have some mitigating factors in place to make sessions difficult to replicate even if a session id is compromised (ie. comparison to ip addresses, etc), or your user accounts are relatively secure from a compromised session (eg. require current password to change account settings), then perhaps SSL after login isn't required. However, if you have doubts and can afford the performance hit, then having SSL throughout the site will guarantee that your sessions can't be compromised (as far as you can guarantee SSL, anyway).
SSL to log in, regular http after that... how vulnerable is the data transferred from the database?
[ "", "php", "mysql", "database", "security", "" ]
What's the best way to call a class constructor that can have lots of parameters associated with it? For instance, if I want to develop a component to automatically log exceptions in an application; let's call it 'ExceptionLogger' ExceptionLogger has 3 ways of of writing the errors generated by the application that references it. ``` ToLogFile (takes 2 parameters) ToDatabase (takes 2 parameters) ToEmail (take 4 parameters) ``` Each of these 3 methods are private to ExceptionLogger and the calling application needs to 'turn on' these methods through the class constuctor; also supplying the parameters if required. The calling app would simply use a 'publish' method to have ExceptionLogger write the information to the relevant storage. To add a clarification; it's my intenttion for a single ExceptionLogger instance to be able to do multiple writes
It seems like this might be a good place to use inheritance instead. You could have a FileLogger, DatabaseLogger, and EmailLogger each of which derives from a base ExceptionLogger class and has a single appropriate constructor.
You might want to consider using the [Named Constructor](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8) paradigm or three separate classes in a hierarchy. It sounds like you have three different classes each with it's own set of requirements on the constructor. If the data in the constructor parameters are required for the instance to operate, then they have to be parameters of the constructor or else you end up with an instance that is missing data. The other approach is to use [Named Parameters](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.18) to represent truly optional parameters. I believe that boost offers a framework for implementing named parameters as well.
Class constructor with multiple parameters
[ "", "c#", "" ]
I am trying to integrate some OpenCV functionality into my application. Currently I have code set up with DirectShow to get a video feed from my camera, which is then showed in an MFC window. This code cannot be changed or removed. The code runs completely fine, but regardless of the location i place the following line of code: ``` IplImage *img = cvLoadImage("C:/well.jpg"); ``` The webcam fails to initialize correctly and breaks the program. more directly, i get a FAILED HRESULT at: ``` CoInitializeEx(NULL, COINIT_APARTMENTTHREADED) ``` More specifically, at some point in my code i Call CDialog::doModal(), which then hits CoInitializeEx(), and thus makes the program fail. would anyone know what is going on here?
CoInitialize will fail if the thread was previously initialized as a different apartment, i.e., if there was a previous CoInitializeEx(NULL, COINIT\_MULTITHREADED) I would guess that OpenCV calls CoInitializeEx(NULL, COINIT\_MULTITHREADED), causing your subsequent calls to CoInitializeEx to fail. You can confirm this by checking the return of CoInitializeEx - it'll be RPC\_E\_CHANGED\_MODE in this case. There is no straightforward fix, the most straightforward will be to move the OpenCV calls into a separate thread.
In addition to what Michael said check also for external dependent DLL's, if one is missing CoInitialize will also fail.
CoInitializeEx fails when calling OpenCV method cvLoadImage()
[ "", "c++", "windows", "mfc", "opencv", "directshow", "" ]
I am attempting to declare and use an interface like this: ``` public interface IItem<T> { string Name { get; set; } T Value { get; set; } } ``` This works fine until I attempt to create a list of these items. This fails to compile: ``` public interface IThing { string Name { get; } IList<IItem<T>> ThingItems { get; } } ``` so I am not certain where the issue is. The items value is not defined until runtime, and I need to have collections of the items. I figure that this is a fairly standard pattern, but I can not see where I am falling down.
You're falling down because the compiler wants to know what kind of items are in your list. So if you don't know yet, just create a non-generic base interface, and derive a generic more specific interface: Maybe this helps you out: ``` public interface IItem { string Name { get; set; } } public interface IItem<T>: IItem { T Value { get; set; } } public interface IThing { string Name { get; } IList<IItem> Items { get; } } public interface IThing<T>: IThing { string Name { get; } IList<IItem<T>> Items { get; } } ```
Your class needs to be generic too (`Thing<T>`) or else the list can't know what type to use. ``` public interface Thing<T> { string Name { get; } IList<IItem<T>> thingItems { get; } } ``` **EDIT** It compiles now. **EDIT** It seems you want your `IItem<T>` to be in terms of any type. This won't work in C#. You could create IList> here, but that is less than ideal, since you loose your typing when you want to get the items out.
Trouble defining an IList<T> where T is an generic interface
[ "", "c#", "generics", "" ]
I have 2 classes named Order and Orderrow. I use NHibernate to get a join on it. When running NUnit to test the query, I got an ADOException: ``` Logica.NHibernate.Tests.NHibernateTest.SelectAllOrdersFromSupplierNamedKnorrTest: NHibernate.ADOException : could not execute query [ SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM Order this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId ] [SQL: SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM Order this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId] ----> System.Data.SqlClient.SqlException : Incorrect syntax near the keyword 'Order'. ``` When analyzing the SQL that has been created by NHibernate, I notice that the Order class is corrupting the SQL statement, because ORDER BY is an internal keyword in SQL. This is the created SQL in NHibernate: ``` SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM Order this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId ``` I altered it in SQL Server 2008 Management studio like this: ``` SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM [Order] this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId` ``` I added brackets to the table name Order (like this: [Order]) and it is fixed. But how do I get this fixed in NHibernate ? Is there a mapping XML file instruction for it to get this done ? (using VS2008 SP1, SQL Server 2008 SP1, NHibernate 2.0.1 GA)
I think if you put the quotes ("[" and "]" in SQL Server, or whatever quotes your DB supports) in your mapping file, hibernate will quote the object names when it generates queries. (Maybe post your mapping file, so we can take a look)
See [this](https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/mapping.html), section "5.3. SQL quoted identifiers". Yoo basically need this: ``` <class name="Order" table="`Order`"> ```
NHibernate SQL creation causes error
[ "", "c#", "nhibernate", "" ]
I have a table that looks like this: ``` ProductId, Color "1", "red, blue, green" "2", null "3", "purple, green" ``` And I want to expand it to this: ``` ProductId, Color 1, red 1, blue 1, green 2, null 3, purple 3, green ``` Whats the easiest way to accomplish this? Is it possible without a loop in a proc?
I arrived this question 10 years after the post. SQL server 2016 added STRING\_SPLIT function. By using that, this can be written as below. ``` declare @product table ( ProductId int, Color varchar(max) ); insert into @product values (1, 'red, blue, green'); insert into @product values (2, null); insert into @product values (3, 'purple, green'); select p.ProductId as ProductId, ltrim(split_table.value) as Color from @product p outer apply string_split(p.Color, ',') as split_table; ```
Take a look at this function. I've done similar tricks to split and transpose data in Oracle. Loop over the data inserting the decoded values into a temp table. The convent thing is that MS will let you do this on the fly, while Oracle requires an explicit temp table. [MS SQL Split Function](http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648) [Better Split Function](http://www.devx.com/tips/Tip/20009) **Edit by author:** This worked great. Final code looked like this (after creating the split function): ``` select pv.productid, colortable.items as color from product p cross apply split(p.color, ',') as colortable ```
How do I expand comma separated values into separate rows using SQL Server 2005?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I'm evaluating Cruise (NOTE! Not CruiseControl but Cruise (commercial)) for doing CI with an unmanaged MSVC++ 2008 project. I use GoogleTest framework for my unit test. I know that GTest can output its result as an JUnit XML or XML format. My question is, does Cruise support JUnit/XML format? How would Cruise know whether or not my unit test fail? More information from Thoughtworks [here](http://studios.thoughtworks.com/cruise-continuous-integration/1.2/help/concepts_in_cruise.html):
According to the documentation, yes it does support the JUnit xml format. See the bottom of the page. Second to last section called "Publishing tests" <http://studios.thoughtworks.com/cruise-continuous-integration/1.2/help/managing_artifacts_and_reports.html>
Another option for when your test results are large or ugly is to translate the results into html (by xslt for example) then include the html as a new tab on the cruise build. We do this with ncover to good effect.
Thoughtworks Cruise: Unit Testing?
[ "", "c++", "unit-testing", "continuous-integration", "thoughtworks-go", "" ]
I have the following classes: ``` abstract class DTO{ } class SubscriptionDTO extends DTO { } ``` and the following generic method: ``` protected void fillList(ResultSet rs, ArrayList<? extends DTO> l) throws BusinessLayerException { SubscriptionDTO bs; try { while (rs.next()){ //initialize bs object... l.add(bs); //compiler error here } } catch (SQLException e) { e.printStackTrace(); } } ``` I can't seem to understand why you can't create a generic method for filling DTO subtypes. Am I doing something wrong or is this by design? If so, is there any workaround? Thanks in advance.
You should be using `<? super DTO>` (or `<? super SubscriptionDTO>`, as [Tom Hawtin - tackline](https://stackoverflow.com/users/4725/tom-hawtin-tackline) points out) as the generic parameter of the `ArrayList`. From item 28 of [*Effective Java*](http://java.sun.com/docs/books/effective/) (page 28 of the [sample chapter](http://java.sun.com/docs/books/effective/generics.pdf) [pdf]): > Here is a mnemonic to help you remember which wildcard type to use: > > **PECS stands for producer-extends, consumer-super.** > > In other words, if a parameterized type represents a `T` producer, use `<? extends T>`; > if it represents a `T` consumer, use `<? super T>`. In this case, `l` is a consumer (you are passing objects to it), so the `<? super T>` type is appropriate.
Imagine the following situation, with `Foo extends Bar` and `Zoo extends Bar` ``` List<Foo> fooList = new ArrayList<Foo>(); fooList.addAll(aBunchOfFoos()); aMethodForBarLists(fooList); ``` then we have the method itself: ``` void aMethodForBarLists (List<? extends Bar> barList) { barList.add(new Zoo()); } ``` What happens here, is that, even though Zoo does extend Bar, you're trying to add a Zoo in a `List<Foo>`, which is explicitly made for, and only for, Foos. *This* is why the Java spec disallows adding stuff into a `<? extends Something>` Collection - it can't be sure that, while the syntax *seems* right, the actual objects would allow adding stuff into the Collection.
Why it is not possible to create a generic fill method in Java?
[ "", "java", "generics", "" ]
I have an existing program deployed where some customer databases have a field set to not null, while others are nullable. I need to run a patch to correct the database so that the column is nullable but do not need to run it against all databases, just ones where it is incorrect. Is there a simple method that can be used in SQL Server to perform this check? Preferably something that can be run as part of a SQL script.
Look into the INFORMATION\_SCHEMA views. For example: ``` SELECT IS_NULLABLE FROM My_DB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'My_Table' AND COLUMN_NAME = 'My_Column' ``` IS\_NULLABLE will be either "YES" or "NO".
``` select Table_Name, Column_Name, Is_Nullable from information_schema.columns ``` Will get you that info
How to determine if a field is set to not null?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm writing an automated test to determine whether or not rtf files are successfully opened by MS Word. So far I looping through all the rtfs within a given directory and opening them. Later I will have to catch exceptions to generate a report (log the file name that crashed word). I am processing a large number of files. My application is currently opening a new instance of Word for each file. Can someone tell me how to close Word? ``` public class LoadRTFDoc { private object FileName; private object ReadOnly; private object isVisible; private object Missing; private ApplicationClass WordApp; private object Save; private object OrigFormat; private object RouteDoc; public LoadRTFDoc(object filename) { this.WordApp = new ApplicationClass(); this.FileName = filename; ReadOnly = false; isVisible = true; Missing = System.Reflection.Missing.Value; Save = System.Reflection.Missing.Value; OrigFormat = System.Reflection.Missing.Value; RouteDoc = System.Reflection.Missing.Value; } public void OpenDocument() { WordApp.Visible = true; WordApp.Documents.Open(ref FileName, ref Missing, ref ReadOnly, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref isVisible, ref Missing, ref Missing, ref Missing, ref Missing); WordApp.Activate(); } public void CloseDocument() { WordApp.Documents.Close(ref Save, ref OrigFormat, ref RouteDoc); } } ``` I am executing the CloseDocument() method after each document is opened. Anyone have some insight for me on this?
``` WordApp.Quit() ``` will exit the application. However, the safest way is to get a handle to the process and kill the winword process. In C# the following code would do that: ``` foreach (Process p in Process.GetProcessesByName("winword")) { if (!p.HasExited) { p.Kill(); } } ``` The reason is that it will happen frequently (I assume, especially since you are testing documents created not by Word) that Word will hang with an open message box, e.g. a repair dialog. In that case killing the process is the easiest way to close the application. I would suggest that you first try to close Word using `Application.Quit`. If this does not work it indicates a problem with your input file (most likely because a repair dialog is blocking Word). You should record this as an error in your log and then proceed killing the winword process. Another problem you might face is Word's document recovery feature blocking the application on startup (and thus preventing a document from being opened until the recovery dialog box is clicked away). Document recovery can be disabled by deleting the following registry key under both HKCU and HKLM prior to starting Word (replace 12.0 with 11.0 for Word 2003 and 10.0 for Word XP): ``` Software\Microsoft\Office\12.0\Word\Resiliency ``` It goes without saying that killing Word is a rather rude approach, however, it is simple and rather robust. The code above will just kill any instance of Word for a user. If you want to kill only a specific instance things get more difficult. You would have to retrieve the process id of a specific Word instance. Typically this can be done by searching for the window title of the instance, e.g. using WinAPI functions like `FindWindowByCaption` and `GetWindowThreadProcessId`.
`WordApp.Quit` followed by `ReleaseComObect` as said by dance2die.
Close MS Office C# Console
[ "", "c#", "interop", "automation", "ms-word", "ms-office", "" ]
First, [here's a sample](http://java.sun.com/docs/books/tutorial/essential/concurrency/deadlock.html): ``` public class Deadlock { static class Friend { private final String name; public Friend(String name) { this.name = name; } public String getName() { return this.name; } public synchronized void bow(Friend bower) { System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); } public synchronized void bowBack(Friend bower) { System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName()); } } public static void main(String[] args) { final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); new Thread(new Runnable() { public void run() { alphonse.bow(gaston); } }).start(); new Thread(new Runnable() { public void run() { gaston.bow(alphonse); } }).start(); } } ``` What I don't get is *how* the blockage occurs. The main function initiates two threads that each begin their own bows. What exactly does 'synchronized' block? The same function running for the same object (as I originally thought)? The same function for all objects of the same class? All synchronized functions for the same object? All synchronized functions for all objects of the same class? Help me out here.
In Java, each `Object` provides the ability for a Thread to `synchronize`, or lock, on it. When a method is synchronized, the method uses its object instance as the lock. In your example, the methods `bow` and `bowBack` are both `synchronized`, and both are in the same class `Friend`. This means that any Thread executing these methods will synchronize on a `Friend` instance as its lock. A sequence of events which will cause a deadlock is: 1. The first Thread started calls `alphonse.bow(gaston)`, which is `synchronized` on the `alphonse` `Friend` object. This means the Thread must acquire the lock from this object. 2. The second Thread started calls `gaston.bow(alphonse)`, which is `synchronized` on the `gaston` `Friend` object. This means the Thread must acquire the lock from this object. 3. The first thread started now calls `bowback` and waits for the lock on `gaston` to be released. 4. The second thread started now calls `bowback` and waits for the lock on `alphonse` to be released. To show the sequence of events in much more detail: 1. `main()` begins to execute in the main Therad (call it Thread #1), creating two `Friend` instances. So far, so good. 2. The main Thread starts its first new Thread (call it Thread #2) with the code `new Thread(new Runnable() { ...`. Thread #2 calls `alphonse.bow(gaston)`, which is `synchronized` on the `alphonse` `Friend` object. Thread #2 thus acquires the "lock" for the `alphonse` object and enters the `bow` method. 3. A time slice occurs here and the original Thread gets a chance to do more processing. 4. The main Thread starts a second new Thread (call it Thread #3), just like the first one. Thread #3 calls `gaston.bow(alphonse)`, which is synchronized on the `gaston` `Friend` object. Since no-one has yet acquired the "lock" for the `gaston` object instance, Thread #3 successfully acquires this lock and enters the `bow` method. 5. A time slice occurs here and Thread #2 gets a chance to do more processing. 6. Thread #2 now calls `bower.bowBack(this);` with `bower` being a reference to the instance for `gaston`. This is the logical equivalent of a call of `gaston.bowBack(alphonse)`. Thus, this method is `synchronized` on the `gaston` instance. The lock for this object has already been acquired and is held by another Thread (Thread #3). Thus, Thread #2 has to wait for the lock on `gaston` to be released. The Thread is put into a waiting state, allowing Thread #3 to execute further. 7. Thread #3 now calls `bowback`, which in this instance is logically the same as the call `alphonse.bowBack(gaston)`. To do this, it needs to acquire the lock for the `alphonse` instance, but this lock is held by Thread #2. This Thread is now put into a waiting state. And you are now in a position where neither Thread can execute. Both Thread #2 and Thread #3 are waiting for a lock to be released. But neither lock can be released without a Thread making progress. But neither thread can make progress without a lock being released. Thus: Deadlock! Deadlocks very often depend on a specific sequence of events occurring, which can make then difficult to debug since they can be difficult to reproduce.
[Synchronized has two effects](http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html): * First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. * Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. So in short, it blocks any invocations of synchronised methods on the same object.
How does synchronized work in Java
[ "", "java", "multithreading", "deadlock", "" ]
I've been using a drupal 4.7 installation for many years, and have had a recent problem crop up. That is, the rewritten URLs are now displaying these characters: ?q= in every drupal generated URL as follows: <http://sitename.com/?q=path/alias> , where before it would be: <http://sitename.com/path/alias> . My best guess as to why this might be happening, is that I recently began using some PHP code to add context-specific link styling within a few sideblocks. Here's the code: ``` <?php $alias= $_GET['q']; ?> <a <?php $pos=strpos($alias,"1234"); // node number if(!$pos == false) { echo 'style="color:black"'; } ?> href="internal/link/alias">Internal Link</a> ``` Or more recently: ``` <?php $path = isset($_GET['q']) ? $_GET['q'] : '<front>'; $alias = url($path, array('absolute' => TRUE)); ?> <a <?php $pos=strpos($alias,"internal/link/alias"); if(!$pos == false) { echo 'style="color:black"'; } ?> href="internal/link/alias">Internal Link</a> ``` Could this be the problem? If so, any ideas about fixes?
I don't think your snippet is causing it. It only reads from the database; it does not make changes to URLs. Is mod\_rewrite still enabled? This may be caused by a recent change to the server config. Check the output of `phpinfo()`. By the way, the option `$absolute` for `url()` is [passed as a separate argument](http://api.drupal.org/api/function/url/4.7) in Drupal 4.7, not in the `$options` array. Your call should be: ``` url($path, $absolute=TRUE); ```
I'm thinking that your clean urls are just broken. When you don't have clean URLs turned on, all your URLs will look like `http://example.com/?q=/foo/bar/baz`. The rewrite rules translate requests from `http://example.com/foo/bar/baz` **into** `http://example.com/?q=/foo/bar/baz` to be processed internally. You need to go back and make sure that your rewrite rules still work (can you even go to `http://example.com/foo/bar/bazz` ?) and that Drupal has clean URLs turned on.
Mod rewrite / clean urls problem
[ "", "php", "drupal", "" ]
I'm trying to determine whether an object is already contained within a `std::set`. According to msdn (and other sources) the set::find function is supposed to return `end()` if it doesn't find the element you asked for. However when I implement code like the following, `set::find` returns junk (`0xbaadf00d`) instead. ``` set<Cell*> cellSet; Cell* cell = new Cell(); if (cellSet.find(cell) == cellSet.end()) { ... } ``` Am I using this correctly? I'm working in Visual C++ 2005.
Your code as posted will always execute the code within the `if`, and `0xbaadf00d` **is** the implementation's "one-past-the-end" marker.
When using stl set I like to use the [count](http://cplusplus.com/reference/stl/set/count/) function to determine membership. I think this makes the code easier to read. ``` set<Cell*> cellSet; Cell* cell = new Cell(); if (cellSet.count(cell) == 0) { ... } ```
Determining whether an object is in a std::set
[ "", "c++", "stl", "set", "" ]
When using std::map in c++, is it possible to store inherited classes as their "base class" in the map and still being able to call their overloaded methods? See this example: ``` #include <iostream> #include <map> class Base { public: virtual void Foo() { std::cout << "1"; } }; class Child : public Base { public: void Foo() { std::cout << "2"; } }; int main (int argc, char * const argv[]) { std::map<std:string, Base> Storage; Storage["rawr"]=Child(); Storage["rawr"].Foo(); return 0; } ``` This following code writes "1". Which somehow tells me that polymorphism doesn't work when you use std::map.
Polymorphism doesn't work in that case because the std::map stores the Base as a value type, so the [objects get sliced](http://en.wikipedia.org/wiki/Object_slicing). If you want to have polymorphism on stored objects, you need to store pointers or use one of the [boost ptr containers](http://www.boost.org/doc/libs/1_38_0/libs/ptr_container/doc/tutorial.html) to effect the same. This means you need to remember to delete the memory afterwards (please don't put pointers to stack objects into the map)
Its case of [Object Slicing](http://en.wikipedia.org/wiki/Object_slicing). Try to insert with pointers. In the presence of inheritance copying leads to slicing. That is, if you create a map of base class objects and you try to insert derived class objects into it, the derivedness of the objects will be removed as the objects are copied (via the base class copy constructor) into the map. Hence, it is recommended to use pointers rather than copies itself.
std::map unable to handle polymorphism?
[ "", "c++", "" ]
Imagine I have a service that looks like this: ``` public interface MyAccountService { boolean create( String user ); } ``` The method create performs several changes, namely (for discussion sake): 1. adds a message into a Queue 2. adds a row into several tables 3. creates a LDAP account etc... Currently I collapse all the error messages into a single boolean return value. Now internally if there is an error, I will log these for the support team. e.g. a typical log of a failed user creation creation of "alistair" account in the following (strict) order: * add to table Foo: success * add to table Bar: success * add to LDAP: failed * add to queue: success This way, the tech support folks can decide how to repair the account. What is the best practice for designing systems such that we can easily trace the success/failure of a transaction (and repair it manually) ? Is returning boolean & swallowing all exceptions a good design ? **EDIT** : By *swallowing exceptions*, I meant not throwing them up the the caller. However I do log the exceptions, and translate them to a false/true return value.
You have 2 options on this one in my opinion: 1. Throw a custom exception with the list of the successes, thus the client of the API can catch the exception and see what failed and then decide which action to perform. 2. Return an ENUM in which you reflect all the possible results of the outcome, thus again the client of the API can decide which action he will perform. Any way you must log all the problems your method encounters so it can be traced... Exception and problem swallowing is a very bad practice. I like more the custom Exception method, for the ENUM is more C like API..
I like the approach described in the article [presented here](http://www.oracle.com/technetwork/java/effective-exceptions-092345.html), there is a discussion about it [here](http://www.theserverside.com/news/thread.tss?thread_id=43820)... The idea is to consider to kind of exceptions, and to handle them differently: > One type of exception is a contingency, which means that a process was executed that cannot succeed because of a known problem (the example he uses is that of a checking account, where the account has insufficient funds, or a check has a stop payment issued.) These problems should be handled by way of a distinct mechanism, and the code should expect to manage them. > > The other type of exception is a > fault, such as the IOException. A > fault is typically not something that > is or should be expected, and > therefore handling faults should > probably not be part of a normal > process.
How to handle errors for a facade method that performs many disparate background changes?
[ "", "java", "api", "oop", "exception", "" ]
When using an XMLHTTPRequest in javascript, I want to send it to an external website, rather than the one where the .js file is hosted. To send it to test.php on the current server, I would use ``` request.open("POST", "test.php", true); ``` but for the second arguemnt, how do I send it to another website. "example.com/test.php" looks for a file on the current server, and "<http://example.com/test.php>" justseems to outright fail.
You can't for security reasons. See the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) for JavaScript. There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended. The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
This sounds like a bad case of [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy), my friend :)
How to specify an external website for XMLHTTPRequest
[ "", "javascript", "http", "xmlhttprequest", "" ]
I have a vector of pointers that are not owned by the container. How do I use algorithms on the targets of the pointers. I tried to use boost's ptr\_vector, but it tries to delete the pointers when it goes out of scope. Here is some code that needs to work: ``` vector<int*> myValues; // ... myValues is populated bool consistent = count(myValues.begin(), myValues.end(), myValues.front()) == myValues.size(); auto v = consistent ? myValues.front() : accumulate(myValues.begin(), myValues.end(), 0) / myValues.size(); fill(myValues.begin(), myValues.end(), v); // etc. ``` I realize that for loops would work, but this happens in a bunch of places, so some kind of unary adapter? I wasn't able to find one. Thanks in advance!
You could use [Boost Indirect Iterator](http://www.boost.org/doc/libs/1_38_0/libs/iterator/doc/indirect_iterator.html). When dereferenced (with `operator*()` ), it applies *an extra* dereference, so you end up with the value pointed by the pointer referenced by the iterator. For more information, you can also see [this question about a dereference iterator](https://stackoverflow.com/questions/352152/is-there-a-dereferenceiterator-in-the-stl). Here's a simple example: ``` std::vector<int*> vec; vec.push_back(new int(1)); vec.push_back(new int(2)); std::copy(boost::make_indirect_iterator(vec.begin()), boost::make_indirect_iterator(vec.end()), std::ostream_iterator<int>(std::cout, " ")); // Prints 1 2 ```
``` bool consistent = count_if(myValues.begin(), myValues.end(), bind2nd(ptr_fun(compare_ptr), *myValues.front())) == myValues.size(); int v = consistent ? *myValues.front() : accumulate( myValues.begin(), myValues.end(), 0, sum_int_ptr) / myValues.size(); for_each(myValues.begin(), myValues.end(), bind1st(ptr_fun(assign_ptr),v)); ``` Fill can't take assign function (so that it would dereference pointers). Therefore for\_each() was used. For optimization it would be wise to add if(!consistent) before running for\_each(). Functions used in above STL one liners: ``` int sum_int_ptr(int total, int * a) { return total + *a; } void assign_ptr(int v, int *ptr) { *ptr = v; } bool compare_ptr(int* a, int pattern) { return *a == pattern; } ```
how do I use STL algorithms with a vector of pointers
[ "", "c++", "stl", "boost", "lambda", "c++11", "" ]
If I want to allocate a char array (in C) that is guaranteed to be large enough to hold any valid absolute path+filename, how big does it need to be. On Win32, there is the MAX\_PATH define. What is the equivalent for Unix/linux?
There is a `PATH_MAX`, but it is a bit problematic. From the bugs section of the [realpath(3)](http://man7.org/linux/man-pages/man3/realpath.3.html) man page: > The POSIX.1-2001 standard version of this function is broken by > design, since it is impossible to determine a suitable size for the > output buffer, *resolved\_path*. According to POSIX.1-2001 a buffer of > size **PATH\_MAX** suffices, but **PATH\_MAX** need not be a defined > constant, and may have to be obtained using [pathconf(3)](http://man7.org/linux/man-pages/man3/pathconf.3.html). And > asking [pathconf(3)](http://man7.org/linux/man-pages/man3/pathconf.3.html) does not really help, since, on the one hand > POSIX warns that the result of [pathconf(3)](http://man7.org/linux/man-pages/man3/pathconf.3.html) may be huge and > unsuitable for mallocing memory, and on the other hand > [pathconf(3)](http://man7.org/linux/man-pages/man3/pathconf.3.html) may return -1 to signify that **PATH\_MAX**is not > bounded.
The other answers so far all seem right on point about the \*nix side of things, but I'll add a warning about it on Windows. You've been lied to (by omission) by the documentation. `MAX_PATH` is indeed defined, and probably even applies to files stored on FAT or FAT32. However, any path name can be prefixed by `\\?\` to tell the Windows API to ignore `MAX_PATH` and let the file system driver make up its own mind. After that, the definitions get fuzzy. Add to the mix the fact that path names are actually Unicode (well, UTS-16) and that when the "ANSI" API is used the conversion to and from the internal Unicode name is dependent on a bunch of factors including the current code page, and you have a recipe for confusion. A good description of the rules for Windows is at [MSDN](http://msdn.microsoft.com/en-us/library/aa365247.aspx). The rules are much more complicated than I've summarized here. **Edit:** I changed `\\.\` to `\\?\` in the above thanks to the comment from KitsuneYMG. Windows paths and namespaces are complicated. Some might even argue they are too complicated. One source of complexity is that the Win32 (and now Win64) API is a subsystem that lays on top of the Windows NT native system. A path without any prefix is compatible across the widest range of Windows platforms. If it is restricted to 7-bit ASCII characters, then it is compatible with 16-bit DOS since version 2.0 or so (whenever subdirectories were introduced, which might actually have been in DOS 3; but DOS 1.0 only had root directories and the `\` character had no special meaning). The `\\?\` prefix causes the balance of the path name to be passed on verbatim to the appropriate file system driver, which is what produces the effect of dropping the restriction to `MAX_PATH` characters. If the long path name is also on a network share, then you can use an extended UNC name for it with the prefix `\\?\UNC\server\share\` instead of the normal UNC name `\\server\share\`. Using this prefix restricts portability to Win32 and later Windows platforms, but unless you require support for 16-bit Windows on legacy hardware, that isn't a big issue. The `\\.\` prefix is a different animal. It allows access to device objects beyond the set of specially named devices that are automatically mapped by Windows as special file names into every file folder. Those special names include CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Note that all of those names are special whether or not an extension is used, or in any mix of upper or lower case. But it is possible that you have 10 or more COM ports installed. This happens quickly if you play with USB modems, or USB serial port adapters, since each unique USB-based serial port will be assigned a distinct COMn name. If you need to access the 50th serial port, then you can only do so with the name `\\.\COM50` because COM50 is *not* a special name like COM1 is. The MSDN page I cited above had the distinction right, I simply typed the incorrect prefix in my original answer.
Is there an equivalent to WinAPI's MAX_PATH under linux/unix?
[ "", "c++", "c", "linux", "unix", "posix", "" ]
Is it possible to redefine a C# keyword like `int` to use Int64 instead of Int32? If not, how can one do this? I want to have the flexibility to redefine the int I use, so later I could change it to int64 if I wanted, instead of going around to replace all the int values manually.
No it's not possible and you really should not be doing this. Redefining keywords to custom values will only serve to make your code less readable and maintainable. People getting introduced to your code base would have to forget everything they know about C# defaults and learn *your* defaults. This is not a good way to make a maintainable code base. What you should consider though is creating a new type name and using a "using alias" to redirect that type within your code base. ``` using FexibleInt = System.Int32; ```
Add ``` using MyIntType = System.Int64; ``` after the `namespace` declaration.
Redefining C# keywords?
[ "", "c#", ".net", "" ]
I'm building an app that given another app mainWindowhandle it collects information about the window state. I have no problem collecting information about child windows, but I can not access the other open windows of an application or even the menus. Is there any way of getting all window handles of an application?
You could do what `Process.MainWindowHandle` appears to do: use P/Invoke to call the [`EnumWindows`](http://pinvoke.net/default.aspx/user32/EnumWindows.html) function, which invokes a callback method for every top-level window in the system. In your callback, call [`GetWindowThreadProcessId`](http://pinvoke.net/default.aspx/user32/GetWindowThreadProcessId.html), and compare the window's process id with `Process.Id`; if the process ids match, add the window handle to a list.
First, you'll have to get the windowhandle of the application's mainwindow. ``` [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); IntPtr hWnd = (IntPtr)FindWindow(windowName, null); ``` Then, you can use this handle to get all childwindows: ``` [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); private List<IntPtr> GetChildWindows(IntPtr parent) { List<IntPtr> result = new List<IntPtr>(); GCHandle listHandle = GCHandle.Alloc(result); try { EnumWindowProc childProc = new EnumWindowProc(EnumWindow); EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle)); } finally { if (listHandle.IsAllocated) listHandle.Free(); } return result; } ```
Get Application's Window Handles
[ "", "c#", ".net", "winapi", "handle", "" ]
I want to define an interface MyList which is a list of interface MyThing. Part of the semantics of MyList is that its operations don't have any meaning on objects which do not implement the MyThing interface. Is this the right declaration? ``` interface MyList<E extends MyThing> extends List<E> { ... } ``` **edit:** (part 2) Now I have another interface that returns a MyList as one of its methods. ``` // I'm defining this interface // it looks like it needs a wildcard or template parameter interface MyPlace { MyList getThings(); } // A sample implementation of this interface class SpecificPlace<E extends MyThing> implements MyPlace { MyList<E> getThings(); } // maybe someone else wants to do the following // it's a class that is specific to a MyNeatThing which is // a subclass of MyThing class SuperNeatoPlace<E extends MyNeatThing> implements MyPlace { MyList<E> getThings(); // problem? // this E makes the getThings() signature different, doesn't it? } ```
Yes, at least that is how [`EnumSet`](http://java.sun.com/javase/6/docs/api/java/util/EnumSet.html) does it. > `public abstract class EnumSet<E extends Enum<E>> > extends AbstractSet<E>` --- **Edit in answer to Part 2:** I'm not sure why the return type of `getThings()` in the interface doesn't complain about raw types. I suspect that because of type erasure, warnings in interfaces would be useless even if they were there (there's no warning if you change the return type to `List`, either). For the second question, since `MyNeatThing` extends `MyThing`, `E` is within its bounds. That's sort of the point of using the `extends` bound in the generic parameter, isn't it?
For part 1, yes that looks right. For your part 2, I suggest something like the following. The method returns a `MyList` of something, which you don't know what it is (it is different for different implementations apparently), but you know it's a subtype of MyThing. ``` interface MyPlace { MyList<? extends MyThing> getThings(); } ```
generic interface: list of something specific
[ "", "java", "generics", "interface", "" ]
I'm trying to implement basic auditing with some of my models (like CreatedAt, UpdatedAt, CreatedBy and UpdatedBy). The date/time part is done. I'm throwing events on my models when a property is changed (implementing `INotifyPropertyChanging, INotifyPropertyChanged`) and can update the correspondent fields just fine. I just need to know how to get the current user name without having to pass it through the controller every time I instantiate or get an existing instance of a model.
> Referencing System.Web and using > HttpContext.Current.User.Identity.Name > worked like a charm. I didn't know about it. Thanks. I do it like this: ``` Membership.GetUser().UserName ``` Which way is quicker?
The abstract way of talking about identity is the "principal" - see [this thread](https://stackoverflow.com/questions/818891/819124#819124). I would hope that this code allows you to get the identity without having to know about the login implementation: ``` public static class SomeUtilityClass { public static string GetUsername() { IPrincipal principal = Thread.CurrentPrincipal; IIdentity identity = principal == null ? null : principal.Identity; return identity == null ? null : identity.Name; } } ... record.UpdatedBy = record.CreatedBy = SomeUtilityClass.GetUsername(); ```
Getting the username inside a model class
[ "", "c#", "asp.net-mvc", "model", "audit", "" ]
what if you have so many entries in a table, that 2^32 is not enough for your auto\_increment ID within a given period (day, week, month, ...)? What if the largest datatype MySQL provides is not enough? I'm wondering how should I solve a situation where I'm having so many entries added to my table which require unique ID, but I fill up my datatype within one period? How could I natively within, MySQL (or any other system), achieve unlimited amount of unique IDs or at least increase it exponentially? Ideally I would expect something like ``` > SELECT * FROM table; +---+------+ | a | b | +---+------+ | 1 | 1 | | 1 | 2 | | 1 | 3 | |...| .... | |...| .... | | 1 | 2^32 | | 2 | 1 | | 2 | 2 | +---+------+ ``` Which exponentially increases the amount of entries. How do you cope with such situations? Remember - requirement is to have unique ID for any entry.
You could use BIGINT for the primary key. This is a 64-bit number by default. Edit #2: Apparently what I said before about varying the BIGINT byte length was incorrect. BIGINT *is* fixed at an 8-byte limit.
Don't you think a `BIGINT UNSIGNED` would be sufficient? That's a range of 0 - 18.446.744.073.709.551.615, or one year with 50.539.024.859.478.223 entries per day (365 d/y), 2.105.792.702.478.259 entries per hour, 35.096.545.041.304 entries per minute or 584.942.417.355 per second. [With assumed 600 writes per second (without any reads)](http://dev.mysql.com/doc/refman/5.1/en/replication-faq.html#qandaitem-17-3-4-1-8) you could write entries 974.904.028 years at full write speed. That should be enough.
What if 2^32 is just not enough?
[ "", "sql", "mysql", "database", "primary-key", "large-data-volumes", "" ]
I need to remove a single character from a string, eg in the text block below I would need to be able to remove ONE of the j's. djriojnrwadoiaushd leaving: driojnrwadoiaushd
*You can also use str\_relpace with the $count parameter: $str = 'djriojnrwadoiaushd'; echo str\_replace('j', '', $str, 1);* Ups, sorry.. my bad. --- Here is a real way: ``` $str = 'djriojnrwadoiaushd'; $pos = strpos( $str, 'j' ); if( $pos !== FALSE ) { echo substr_replace( $str, '', $pos, 1 ); } ```
Just use substrings: ``` <?php $str = 'djriojnrwadoiaushd'; $remove = 'j'; $index = strpos($str, $remove); if ($index !== false) $str = substr($str, 0, $index) . substr($str, $index + 1); echo $str; ?> ```
PHP Remove a single letter from a long string only once?
[ "", "php", "string", "" ]
I was wondering, how in jquery am I able to hide a div after a few seconds? Like Gmail's messages for example. I've tried my best but am unable to get it working.
This will hide the div after 1 second (1000 milliseconds). ``` setTimeout(function() { $('#mydiv').fadeOut('fast'); }, 1000); // <-- time in milliseconds ``` ``` #mydiv{ width: 100px; height: 100px; background: #000; color: #fff; text-align: center; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mydiv">myDiv</div> ``` If you just want to hide without fading, use `hide()`.
You can try the `.delay()` ``` $(".formSentMsg").delay(3200).fadeOut(300); ``` call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well. <http://api.jquery.com/delay/>
Hide div after a few seconds
[ "", "javascript", "jquery", "timing", "" ]
I know all kinds of ostreams holds their own internal buffers. I have to know whether there is some kind of ostream which accept an instance std::string and write on that instance. (I want to avoid redundant copies) **Note:** My question is about the standard library, don't offer me other libraries that can do that, I know they exist. :) **Edit:** After a request to be more specific ... Here is what I want, consider the following code: ``` std::string str = "bla bla bla "; std::ospecialstream o(str); o << 34 << " bla bla"; std::cout << str; //console output : "bla bla bla 34 bla bla" ``` I want ospecialstream such that it won't copy str contents into some internal buffer but rather write to the same instance of str. **Edit #2** I need it for performece reasons , ostringstream will make a memcopy when created with a string and will also make a memcpy when the contents are retrieved.
If you are asking can you alter the buffering of ostreams, then the answer is yes. However, depending on what you actually want the buffer to do, this is not a particularly simple task. You will want to consult a book like [Langer & Kreft](http://www.angelikalanger.com/iostreams.html) for more info. L&K have an example of how to implement an unbuffered output stream - it begins on page 229 of the book. It's too long to reproduce here, but basically you need to redefine the overflow() method of a derived streambuf class. Note the book is not available on-line but the source code apparently is - see this [page](http://www.angelikalanger.com/IOStreams/examples.htm) for details.
[`std::ostringstream`](http://www.cplusplus.com/reference/iostream/ostringstream/) part of `sstream` header. How about this: ``` void appendStuff(string& in) { ostringstream os; os << 34 << " bla bla"; in += os.str(); } ```
Is there a way to use an "ostream" to write over an existing instance of std::string
[ "", "c++", "" ]
``` for (int v = 0; v <= WordChosen.length();v++) { if(Letter == WordChosen[v]) { WordChosenDuplicate.replace(v,1,Letter); } } ``` I get this error > "Error 4 error C2664: > 'std::basic\_string<\_Elem,\_Traits,\_Ax> > &std::basic\_string<\_Elem,\_Traits,\_Ax>::replace(\_\_w64 > unsigned int,\_\_w64 unsigned int,const > std::basic\_string<\_Elem,\_Traits,\_Ax> > &)' : cannot convert parameter 3 from > 'char' to 'const > std::basic\_string<\_Elem,\_Traits,\_Ax> > &' c:\documents and settings\main\my > documents\uni\2nd > year\tp2\hangman\hangman\hangman.cpp 147 > " I only got the error after putting this line in ``` WordChosenDuplicate.replace(v,1,Letter); ```
Or ``` WordChosenDuplicate.replace(v,1,std::string(Letter, 1)); ```
The `std::string::replace()` function's parameters are incorrect or you need to invoke a different overload of `replace`. Something like: ``` WordChosenDuplicate.replace(v, // substring begining at index v 1, // of length 1 1, // replace by 1 copy of Letter); // character Letter ```
error C2664: in c++?
[ "", "c++", "visual-c++", "" ]
I encounter a totally strange behavior of the Java compiler. I can't cast a supertype to a subtype when **cyclic generic type relation** is involved. **JUnit test case** to reproduce the problem: ``` public class _SupertypeGenericTest { interface ISpace<S extends ISpace<S, A>, A extends IAtom<S, A>> { } interface IAtom<S extends ISpace<S, A>, A extends IAtom<S, A>> { } static class Space implements ISpace<Space, Atom> { } static class Atom implements IAtom<Space, Atom> { } public void test() { ISpace<?, ?> spaceSupertype = new Space(); IAtom<?, ?> atomSupertype = new Atom(); Space space = (Space) spaceSupertype; // cast error Atom atom = (Atom) atomSupertype; // cast error } } ``` **Compiler error output:** ``` _SupertypeGenericTest.java:33: inconvertible types found : pinetag.data._SupertypeGenericTest.ISpace<capture#341 of ?,capture#820 of ?> required: pinetag.data._SupertypeGenericTest.Space Space space = (Space) spaceSupertype; ^ _SupertypeGenericTest.java:34: inconvertible types found : pinetag.data._SupertypeGenericTest.IAtom<capture#94 of ?,capture#48 of ?> required: pinetag.data._SupertypeGenericTest.Atom Atom atom = (Atom) atomSupertype; ^ 2 errors ``` Note: I'm using Netbeans latest trunk, bundled Ant, latest Java 6 release. I tried using Ant from command line (Netbeans generates a build.xml file) but it results in same errors. **What is wrong?** Is there an elegant way solve the problem? The strange thing is: Netbeans doesn't mark errors (not even warnings) in given code. **EDIT:** No, now I understand **nothing**! Eclipse 3.4.1 doesn't mark neither warnings nor errors, and compiles the code without trouble!!! How can this be? I thought, using Ant from command line along with build.xml provided by Netbeans' would be neutral. **Am I missing something?** **EDIT 2:** Using **JDK7** library and JDK7 code format, netbeans compiles without errors/warnings! **(I'm using 1.7.0-ea-b55)** **EDIT 3:** Changed title to indicate that we're dealing with a javac bug.
I don't claim to easily understand those complex generic types, but if you find some code that compiles in `javac` and doesn't in `ecj` (the eclipse compiler), then file a bug report with both [Sun](http://bugs.sun.com/) and [Eclipse](https://bugs.eclipse.org/bugs/) and describe the situations cleary (best if you also mention that you filed both bug reports and mention their respective URLs, although for Sun it may take a while before the bug is publicly accessible). I've done that in the past and got really good responses where 1. one of the teams figured out what the correct approach was (give compile error, warning or nothing) 2. and the faulty compiler was fixed Since both compilers implement the same spec, one of them is by definition wrong, if only one of them compiles the code. For the record: I tried to compile the sample code with `javac` (javac 1.6.0\_13) and `ecj` (Eclipse Java Compiler 0.894\_R34x, 3.4.2 release) and `javac` complained loudly and failed to produce any `.class` files, while `ecj` only complained about some unused variables (warnings) and produced all the expected `.class` files.
I've ended up using non-generics for this: ``` @Test public void test() { ISpace spaceSupertype = new Space(); IAtom atomSupertype = new Atom(); Space space = (Space) spaceSupertype; // ok Atom atom = (Atom) atomSupertype; // ok } ```
Java: Cyclic generic type relation doesn't allow cast from supertype (javac bug)
[ "", "java", "generics", "casting", "types", "" ]
I need a solution for **auto-adjusting** the `width` and `height` of an `iframe` to barely fit its content. The point is that the width and height can be changed after the `iframe` has been loaded. I guess I need an event action to deal with the change in dimensions of the body contained in the iframe.
``` <script type="application/javascript"> function resizeIFrameToFitContent( iFrame ) { iFrame.width = iFrame.contentWindow.document.body.scrollWidth; iFrame.height = iFrame.contentWindow.document.body.scrollHeight; } window.addEventListener('DOMContentLoaded', function(e) { var iFrame = document.getElementById( 'iFrame1' ); resizeIFrameToFitContent( iFrame ); // or, to resize all iframes: var iframes = document.querySelectorAll("iframe"); for( var i = 0; i < iframes.length; i++) { resizeIFrameToFitContent( iframes[i] ); } } ); </script> <iframe src="usagelogs/default.aspx" id="iFrame1"></iframe> ```
one-liner solution for embeds: starts with a min-size and increases to content size. no need for script tags. ``` <iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe> ```
Adjust width and height of iframe to fit with content in it
[ "", "javascript", "html", "iframe", "adjustment", "" ]
Q1 We can add assembly reference to a web project via *Website --> Add Reference* , and assembly will automatically be referenced by all pages in that web project. But I’ve read somewhere that even if we simply copy ( thus we don’t add it via *Website --> Add Reference* ) an assembly to the Bin directory of a web project, that it will still be automatically referenced by all pages in that project. But as far as I can tell, that is not the case?! Q2 A)Deployed web site project also generates PrecompiledApp.config and website1\_deploy.wdproy. Should these two files also be copied to the server? B) Deployed Web application project also generates WebApplication1.csproj and WebApplication1.csproj.user. * Should the two files also be copied to the server? If so, why? * I assume obj directory shouldn’t be copied to the Web server?! thanx
Q1: "add reference" in a web site project means more than just copying the dll to the bin directly. It also means to place a dependency in app.config and to place a hint file which helps Visual Studio to find the dll from the source. This path is used by visual studio to copy the dll back to the bin directly (if somehow it gets removed) and to provide the "update reference" functionality. Having the dll registered in the app.config is essential for the runtime to compile your code using the right version of the dll. Q2A: website1\_deploy.wdproy is not required. PrecompiledApp.config is. This file tells the runtime that the website was already precompiled and that the aspx files are just placeholders for IIS. Q2B: you don't have to copy all those files. The .csproj file is just for visual studio to keep track of all files in your project. The runtime doesn't do anything with it. The .csproj.user file has your settings, again the runtime doesn't do anything with it. It doesn't even understand it. The obj folder is the temporary directory for the compiler. Also not needed after compilation.
Q1 - copying to bin is a runtime thing. the Web Project is a develop-time thing. They are related but not the same.
I've read that assemblies manually placed inside Bin are also automatically referenced by
[ "", "c#", ".net", "asp.net", "assemblies", "" ]
Is there any alternative to doing the following line: ``` document.getElementById("btn").setAttribute("onclick", "save(" + id + ");"); ``` This line basically changes the `onclick()` event of a button to something like: `save(34); , save(35);` etc. However it fails in IE 7 and 6 but works in IE 8 and Firefox. I can use jquery for this as well.
If you can use jQuery, then: ``` $("#btn").click(function() { save(id); }) ```
**Plain old javascript:** ``` var myButton = document.getElementById("btn"); myButton.onclick = function() { save(id); //where does id come from? } ``` **jQuery:** ``` $(function(){ $("#btn").click(function(){ save(id); //where does id come from? }); }); ```
Alternative to document.getElementById().setAttribute() function
[ "", "javascript", "jquery", "" ]
How to prevent a webpage from navigating away using JavaScript?
Using `onunload` allows you to display messages, but will not interrupt the navigation (because it is too late). However, using `onbeforeunload` will interrupt navigation: ``` window.onbeforeunload = function() { return ""; } ``` Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden. In older browsers you could specify the message to display in the prompt: ``` window.onbeforeunload = function() { return "Are you sure you want to navigate away?"; } ```
The equivalent in a more modern and browser compatible way, using modern addEventListener APIs. ``` window.addEventListener('beforeunload', (event) => { // Cancel the event as stated by the standard. event.preventDefault(); // Chrome requires returnValue to be set. event.returnValue = ''; }); ``` Source: <https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload>
Prevent a webpage from navigating away using JavaScript
[ "", "javascript", "onbeforeunload", "" ]
I have a table that has grown to over 1 million records... today (all valid) I need to speed it up... would Table Partitioning be the answer? If so can i get some help on building the query? The table has 4 bigint value keys and thats all with a primary key indexed and a index desc on userid the other values are at max 139 (there is just over 10,000 users now) Any help or direction would be appreciated :)
you probably just need to tune your queries and/or indexes. 1 million records shouldn't be causing you problems. I have a table with several hundred million records & am able to maintain pretty high performance. I have found the SQL Server profiler to be pretty helpful with this stuff. It's available in SQL Server Management Studio (but not the express version, unfortunately). You can also do `Query > Include Actual Execution Plan` to see a diagram of where time is being spent during the query.
You should investigate your indexes and query workload before thinking about partitioning. If you have done a large number of inserts, your clustered index may be fragmented. Even though you are using SQL Server Express you can still profile using this free tool: [Profiler for Microsoft SQL Server 2005/2008 Express Edition](http://sqlprofiler.googlepages.com/)
SQL Server 2008 Slow Table, Table Partitioning
[ "", "sql", "sql-server-2008", "" ]
I have an application that interacts with another application using SendMessage (among other things). Everything works fine until the other application hangs (either because it has actually frozen or it is doing a long, blocking call). I would like to simulate an application hanging using a C# WinForms application. Is there any way to start a long running, blocking call? Or maybe a way to cause the application to actually freeze? Maybe something like WebClient.DownloadString(), but something that will never return.
``` while(true) { } // busy waiting Thread.Sleep(time); // blocking ```
If you want to simulate a long running task, use ``` Thread.Sleep(timeout); ``` and with `Timeout.Infinite` if you want to block forever. If you want to simulate heavy processor usage, too, use an infinite loop. ``` while (true) { } ```
Simulating a locked/hung application
[ "", "c#", ".net", "" ]
Our company is facing some difficulties with our CMS web application. This application was part-built by a contractor and we have been confronting some stability issues (crashing, having to put them in front of load balancers or caching mechanisms) when we think the application should be able to handle it. We put together a minimal standard measurement, but we don't know if these metrics are realistic. We were hoping to get in this forum feedback on what is a realistic expectation of a CMS system should handle independent of the technology that was built. So if the same application was to be built in .NET instead of Java (current) you will expect to perform the same. The metrics that we came up with are: * Number of concurrent requests/queue length: 100 Maximum * Time to serve a request: 2 s Minimum * Number of requests per hour: 150,000 * Minimum number of page views per hour: 5,000 Minimum HD Requirements: - 2 GB Ram - 2 Dual-Core 2.0 Ghz General Functionality: * Dynamic Cross Referencing (People to News,Events to People and News, Technical Cases, Etc) * Advanced Search Features * Highly Configurable without programming
It's not reasonable to make concrete performance & scalability expectations without any information about hardware, technology, load, usage, etc. "CMS" is very broad: * What does your server farm look like? * What are the terms of your SLA? * What does your typical user look like? E.g. many brief users or fewer users with long sessions and many requests? Other important questions to answer: * Do you want to measure "time to first byte" (I hate this but it's fairly common), or include network latency in your total "time to serve"? * How many editors are working against the system? * Do your editors work against the same data backing, or do they prepare content in an isolated environment and push batches of content updates? * What kind of caching mechanism can you support? Can the content be stale for minutes/hours? In our farm of several load-balanced 64-bit servers with ~32gb RAM (IIRC) and 4 CPUs each, we average just under 100k requests per hour with a peak load of several hundred requests/sec (uncommon). Total end-user load time (incl images and assets) must be under 5 sec. Our total CMS content database is just under 750,000 pages. We have massive amounts of cross-loaded content, querying, complex editor-configurable widgets, etc.
What you should start doing is tracking how people are using it. If you're keeping weblogs, you'll have requests over time and number of sessions active etc. You should then use those metrics to base what your load/stress testing should look like. How many users at a time, load test it at peak transaction levels - zeroing out for reads vs. writes.
What is a realistic measurement to load test a CMS web application?
[ "", "java", ".net", "web-applications", "content-management-system", "" ]
I have an app where I get a list of drives on the computer and when you select one I populate a tree control with the directories and files. I was thinking of trying this using linq to loop round each directory and get its child directories. Has anyone done anything like this before? Thanks
You can use LINQ no problem, although it's a simple enough task that the file system-related code is likely to be longer than the LINQ-related code: ``` private static TreeNode AddDirectory(DirectoryInfo directory) { DirectoryInfo[] subdirs = directory.GetDirectories(); FileInfo[] files = directory.GetFiles(); IEnumerable<TreeNode> subdirNodes = from subdir in subdirs select AddDirectory(subdir); IEnumerable<TreeNode> fileNodes = from file in files select new TreeNode(file.Name); return new TreeNode( directory.Name, subdirNodes.Concat(fileNodes).ToArray()); } ```
Here's an example of how to do just that: **[Using-LINQ-to-access-the-file-system](http://devlicio.us/blogs/derik_whittaker/archive/2008/03/30/using-linq-to-access-the-file-system.aspx)** Here's another one: [How-to-search-the-file-system-using-linq-queries](http://www.dev102.com/2008/07/15/how-to-search-the-file-system-using-linq-queries/)
Get Directory Structure using Linq?
[ "", "c#", ".net", "linq", "" ]
Let's say I have the following code: ``` <div id="link_other"> <ul> <li><a href="http://www.google.com/">google</a></li> <li> <div class="some_class"> dsalkfnm sladkfm <a href="http://www.yahoo.com/">yahoo</a> </div> </li> </ul> </div> ``` In this case, the JavaScript would add `target="_blank"` to all links within the div `link_other`. How can I do that using JavaScript?
``` /* here are two different ways to do this */ //using jquery: $(document).ready(function(){ $('#link_other a').attr('target', '_blank'); }); // not using jquery window.onload = function(){ var anchors = document.getElementById('link_other').getElementsByTagName('a'); for (var i=0; i<anchors.length; i++){ anchors[i].setAttribute('target', '_blank'); } } // jquery is prettier. :-) ``` You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect: ``` $('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.'); ```
Non-jquery: ``` // Very old browsers // var linkList = document.getElementById('link_other').getElementsByTagName('a'); // New browsers (IE8+) var linkList = document.querySelectorAll('#link_other a'); for(var i in linkList){ linkList[i].setAttribute('target', '_blank'); } ```
How do I add target="_blank" to a link within a specified div?
[ "", "javascript", "hyperlink", "external-links", "" ]
I'm about to write a "server" application that is responsible to talk with external hardware. The application shall handle requests from clients. The clients send a message to the server, and if the server is busy with doing stuff with the hardware the new messages shall be stored in a queue that will be processed later. The client shall also be able to cancel a request (if it is in the server's queue.). When the server application is finished with the hardware it shall be able to send the result back to the client that requested the job. The server and client applications may or may not be on the same PC. All development is done in .NET (C#) 2005. What is the best way to solve this communication problem? [MSMQ](https://en.wikipedia.org/wiki/Microsoft_Message_Queuing)? [SOAP](https://en.wikipedia.org/wiki/SOAP)? [WCF](https://en.wikipedia.org/wiki/Windows_Communication_Foundation)? [Remoting](https://en.wikipedia.org/wiki/.NET_Remoting)? Other?
[Remoting](http://en.wikipedia.org/wiki/.NET_Remoting) If all development is done in .NET 2005, Remoting is the best way to go.
Assuming you can use .NET 3.0 or greater then you probably want to WCF as the communications channel - the interface is consistent but it will allow you to use an appropriate transport mechanism depending on where the client and server are in relation to each other - so you can choose to use SOAP or MSMQ or a binary format or others as appropriate (and can roll your own if needed). It also covers the need for two way communication. Queuing the messages at the server should probably be regarded as a separate problem - especially given the need to remove queued messages.
Communication (interprocess) between applications
[ "", "c#", "client-server", "interprocess", "" ]
Why can't a compiler be written that *manages* what needs to be *managed* in C++ code (i.e. to make it "CLR compatible")? Maybe with some compromise, like prohibiting *void* pointers in some situations etc. But all these extra keywords etc. What's the problem that has to be solved by these additions? I have my thoughts about some aspects and what might be hard to solve, but a good solid explanation would be highly appreciated!
I'd have to disagree with the answers so far. The main problem to understand is that a C++ compiler creates code which is suitable for a very dumb environment. Even a modern CPU does not know about virtual functions, hell, even functions are a stretch. A CPU really doesn't care that exception handling code to unwind the stack is outside any function, for instance. CPU's deal in instruction sequences, with jumps and returns. Functions certainly do not have names as far as the CPU is concerned. Hence, everything that's needed to support the concept of a function is put there by the compiler. E.g. vtables are just arrays of the right size, with the right values from the CPUs viewpoint. `__func__` ends up as a sequence of bytes in the string table, the last one of which is 00. Now, there's nothing that says the target environment *has to be dumb*. You could definitely target the JVM. Again, the compiler has to fill in what's not natively offered. No raw memory? Then allocate a big byte array and use it instead. No raw pointers? Just use integer indices into that big byte array. The main problem is that the C++ program looks quite unrecognizable from the hosting environment. The JVM isn't dumb, it knows about functions, but it expects them to be class members. It doesn't expect them to have `<` and `>` in their name. You can circumvent this, but what you end up with is basically name mangling. And unlike name mangling today, this kind of name mangling isn't intended for C linkers but for smart environments. So, its reflection engine may become convinced that there is a class `c__plus__plus` with member function `__namespace_std__for_each__arguments_int_pointer_int_pointer_function_address`, and that's still a nice example. I don't want to know what happens if you have a `std::map` of strings to reverse iterators. The other way around is actually a lot easier, in general. Pretty much all abstractions of other languages can be massaged away in C++. Garbage collection? That's already allowed in C++ today, so you could support that even for `void*`. One thing I didn't address yet is performance. Emulating raw memory in a big byte array? That's not going to be fast, especially if you put doubles in them. You can play a whole lot of tricks to make it faster, but at which price? You're probably not going to get a commercially viable product. In fact, you might up with a language that combines the worst parts of C++ (lots of unusual implementation-dependent behavior) with the worst parts of a VM (slow).
Existing correct code, i.e. code written according to the C++ standard, must not change its behaviour inadvertently.
Why does C++ need language modifications to be "managed"?
[ "", "c++", ".net", "c++-cli", "clr", "managed-code", "" ]
I have a ListView control which is exhibiting an odd behaviour - rows are only partially updating after a postback. I'm hoping someone here can shed some light on why this might be occuring. My listview DataSource is bound to a List of items which is stored in the page session state. This is intentional, partially to timeout out-of-date views since multiple users view the data. On a plain resort operation, the sorting is handled on page via javascript, and the list/session data order is kept in sync via callbacks. Callback also checks for permissions levels. On a particular resort operation that is more complicated, the javascript on the page makes a postback to the page to handle the sorting logic. The List/Session is updated as in the callback, then the listview control is rebound to the data. The page loads again, and the rows show the new order. No problem, right? The problem is that ***some*** of the elements in the listview do not change value in accordance with the new order. While the hyperlinks and text that is processed on page (ie like <%# Eval("ProjectAbbrev") %>) are updated appropriately, checkboxes, literals, and dropdowns that have their values set via the OnItemDataBound event method are not - they stay "frozen" in place, even though stepping through the code reveals that the method is run during the postback, and that the controls SHOULD be set to their new values. If I go and manually truncate the list to say, half the original size, sure enough only those items are repopulated, but the checkboxes and such still retain their original values. So my question is: Why aren't these elements updating along with the rest of the listview control elements on the postback? I have the feeling that I'm either misunderstanding the page lifecycle in ASP.NET or that I've encountered a bug of some kind. At this point I'm thinking I will have to move the more complicated sorting operation to the page in javascript, but that will be rather tricky and I'd like to avoid doing so if possible. --- UPDATE: I have tried setting EnableViewState to false and it does not fix this. I couldn't use that tactic in any case because other parts of the page (save) rely on reading the viewstate in the end. --- UPDATE: I'm providing some code snippets in the hope that they might shed some light on this issue: Page: The HyperLink element will update properly after postback, but the CheckBox which has its value assigned in the OnQueueRepeater\_ItemDataBound method, will stay the same. ``` <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TextProcessorProjects.ascx.cs" Inherits="ETD.UI.Controls.TextProcessorProjects" %> <asp:ListView ID="QueueListView" runat="server" OnItemDataBound="OnQueueRepeater_ItemDataBound"> <ItemTemplate> <tr> <td><asp:HyperLink runat="server" ID="ProjectIDLink"><%# Eval("ProjectAbbrev") %></asp:HyperLink></td> <td><asp:CheckBox runat="server" ID="ScannedCheckBox" BorderStyle="None" /></td> </tr> </ItemTemplate> </asp:ListView> ``` Code behind: On postback, the following code executes: ``` protected List<Book> QueueDataItems { get { return (List<Book>)Session["Queue"]; } set { Session["Queue"] = value; } } else if (IsPostBack && !Page.IsCallback) { // resort QueueDataItems List appropriately ResortQueue(Request.Params) // rebind QueueListView.DataSource = QueueDataItems; QueueListView.DataBind(); } protected void OnQueueRepeater_ItemDataBound(object sender, ListViewItemEventArgs e) { // ... // ... other controls set CheckBox scannedCheckBox = e.Item.FindControl("ScannedCheckBox") as CheckBox; scannedCheckBox.Checked = book.Scanned; } ``` UPDATE: I've given up on getting this to work and moved my sorting logic to the client side with javascript. If anyone has any ideas as to why this odd behaviour was happening though, I'd still be very interested in hearing them!
out of interest, what point on the page are you databinding on? Page\_Load? Try it on OnPreRender - might help out.
Sounds like the ViewState is kicking in and repopulating the data. In any case, if you are Databinding in every postback anyways, you should probably set the EnableViewState of your ListView to false to reduce page size.
Listview not fully updating on databind() after postback
[ "", "c#", "asp.net", "data-binding", "listview", "postback", "" ]
I'm trying to learn Java but it just seem like there are too many parts to put together. You have JSP, Java EE, Java SE, Java ME etc.... I can get Netbeans to do basic but just taking a peek at spring framework it seem like a lot of work to get it to run in the ide from the numerous configuration . I want to get into web programming and maybe mobile. Any advice? Another programming language? Is java this complex or does it get easier?
It's not that Java-the-language is complex, it's that vast libraries and frameworks exist that can help you do your work. This is true for many programming languages. Look at CPAN for Perl, for example. What language to use depends in great part on what your goals are. You can start simple and work your way up to larger and larger projects. Java is by no means too complex for a one-man operation, but learning any form of full-formed web programming is a lot to learn when it's all new. If you were looking at .NET for the same purpose, there is a lot there too. Unless you are doing huge-enterprise applications, ignore all of J2EE except for JSP and JMS and a very few other components. The lion's share of J2EE is only useful in the context of an enterprise application that needs to scale, and in fact can be harmful when used in smaller applications. The frameworks such as Spring, Hibernate, Apache-\*, Web Services, and so on help you do your job, but are yet more things to learn to do your job. There is a lot to learn. Should you use Java? Well, quite a lot of development is done with LAMP (or WAMP): Linux (or Windows) + Apache-HTTPD + MySQL + PHP. With this, you don't need to worry about Java or .NET or any of those frameworks. LAMP/WAMP works very well for a wide class of applications. Java and .NET on the server are (sort of) more appropriate for larger services, but once you are familiar with them, they work just fine for smaller services as well. You have to decide what your exact goals are, then look at how people have implemented the kind of thing that you're looking at doing. This will help you figure out what technologies are the most necessary for the niches you're looking at going into.
Java as a language is certainly not too complicated. J2EE *in its entirety* is only just about feasible for a one-man team - but you rarely need the whole of J2EE. It's perfectly reasonable for a one-man team to implement a medium-sized web application. I'm not saying one person could write GMail on their own, but you shouldn't be too scared of the technology stack - find the bits you actually *need* and concentrate on those. On the other hand, that in itself takes a fair amount of experience - I wouldn't really want to be starting off on an enterprise app (even a small one) on my own as a *newcomer* to Java. Start small. Learn the core (the language, IO, collections) - and then start with small projects. Work out whether you want to be in mobile, desktop, server or whatever - don't try all of them simultaneously. Gradually you'll build up your experience.
Is Java too complex a programming language for a beginner one man programming team?
[ "", "java", "" ]
I use the following code to Invoke and access properties on my from from a different thread. ``` public static void PFA(Action<frmain> action) { var form = Form.ActiveForm as frmain; if (form != null) { form.PerformAction(action); } } public void PerformAction(Action<frmain> action) { if (InvokeRequired) Invoke(action, this); else action(this); } ``` My Question: If I call `PFA(form => form.Richbox1.Text = "Test")` - I want PFA() to check if the action is (Richbox1.Text) and if so then Add "\n" to the text("Test"). The Idea is to call ``` PFA(form => form.Richbox1.Text = "Test"); ``` instead of ``` PFA(form => form.Richbox1.Text = "Test\n"); ``` In other words I want to add a new line automaticly if the action is "Richbox1.Text =" How I do that? I never worked with actions before.
What if you did: ``` PFA(form => UpdateTextBox(form.Richbox1,"Test")); public void UpdateTextBox(RichTextBox box,string text) { if (box.Name=="Richbox1") { text+="\n"; } box.AppendText(text); } ``` Your not going to be able to look inside the action and determine it's using a specific cotnrol from outside of the action. So either you need to add the \n before you call PFA, or have PFA call a function which will do what you want, or have PFA implement the logic.
You can add an extension method to do the trick. Try the following. ``` public static void AddNewLineIfMatch(this RichTextBox rtb, string toMatch) { if ( rtb.Text == toMatch ) { rtb.AppendText("\n"); } } PFDA(() => form.Richbox1.AddNewLineIfMatch("Test")); ``` **EDIT** Used the AppendText method instead of Text+=
C#: How to get the assigned value from an action?
[ "", "c#", "action", "" ]
While writing a game for J2ME we ran into an issue using java.lang.Integer.parseInt() We have several constant values defined as hex values, for example: ``` CHARACTER_RED = 0xFFAAA005; ``` During the game the value is serialized and is received through a network connection, coming in as a string representation of the hex value. In order to parse it back to an int we unsuccesfully tried the following: ``` // Response contains the value "ffAAA005" for "characterId" string hexValue = response.get("characterId"); // The following throws a NumberFormatException int value = Integer.parseInt(hexValue, 16); ``` Then I ran some tests and tried this: ``` string hexValue = Integer.toHexString(0xFFAAA005); // The following throws a NumberFormatException int value = Integer.parseInt(hexValue, 16); ``` This is the exception from the actual code: ``` java.lang.NumberFormatException: ffaaa005 at java.lang.Integer.parseInt(Integer.java:462) at net.triadgames.acertijo.GameMIDlet.startMIDlet(GameMIDlet.java:109) ``` This I must admit, baffled me. Looking at the parseInt code the NumberFormatException seems to be thrown when the number being parsed "crosses" the "negative/positive boundary" (perhaps someone can edit in the right jargon for this?). Is this the expected behavior for the Integer.parseInt function? In the end I had to write my own hex string parsing function, and I was quite displeased with the provided implementation. In other words, was my expectation of having Integer.parseInt() work on the hex string representation of an integer misguided? EDIT: In my initial posting I wrote 0xFFFAAA005 instead of 0xFFAAA005. I've since corrected that mistake.
The `String` you are parsing is too large to fit in an `int`. In Java, an `int` is a signed, 32-bit data type. Your string requires at least 36 bits. --- Your (positive) value is still too large to fit in a *signed* 32-bit `int`.
Do realize that your input (4289372165) overflows the maximum size of an `int` (2147483647)? Try parsing the value as a `long` and trim the leading `"0x"` off the string before you parse it: ``` public class Program { public static void main(String[] args) { String input = "0xFFFAAA005"; long value = Long.parseLong(input.substring(2), 16); System.out.print(value); } } ```
Is J2ME's Integer.parseInt() broken?
[ "", "java", "java-me", "parseint", "" ]
I try to compile a webtools project for Java5/Tomcat 5.5 in ubuntu (with manually installed eclipse 3.4). I set the installed jre to java-1.5.0-sun-1.5.0.18 and the compiler compliance level to 1.5. When I export this to a .war file, and try to deploy it in Tomcat (Windows XP, Tomcat 5.5.27, Java 1.5.0\_18) , I get the following error: ``` SEVERE: Error deploying web application archive Jdbc2Ei.war java.lang.UnsupportedClassVersionError: Bad version number in .class file at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) ... ``` Anybody knows how to solve this?
Compiled it under windows, and it works! Some bug somewhere... there will be a time that this problem will be fixed.
> java.lang.UnsupportedClassVersionError: Bad version number in .class file check that *all your jars* are compiled for java5.
How to compile .war for Java 5/Tomcat 5.5 in Ubuntu?
[ "", "java", "web-services", "tomcat", "war", "" ]
I'm using ADO to save data to an MS Access database. It was taking quite a while to save the data to file (about 7 seconds - which is too long for our purposes). I looked at the number of SQL queries being run, and it's about 4200; although there isn't a whole heap of data. The database connection seems to be the bottleneck. Do you know of any way to decrease the amount of time this takes; either by somehow combining multiple statements into one to reduce overhead, or some ADO/MS-Access trick? Can you, for instance, insert multiple rows into a table at once, and would this be noticeably faster? **Extra info:** One reason we have so many queries is that we insert a row, and then have another query to retrieve its autoincremented ID; then use this ID to insert several more rows, linking them to the first In response to several comments and responses: I am leaving the connection open the entire time, and performing it as a single transaction with BeginTransaction() and CommitTransaciton()
Some folk have posted that `@@IDENTITY` would be fast, so here’s a proof (using VBA) of how my `INSERT INTO` two tables at once via a `VIEW` trick is about three times faster than doing two INSERTS and grabbing the `@@IDENTITY` values each time... which is hardly surprising because the latter involves three `Execute` statements and the former only involves one :) On my machine for the 4200 iterations, the `VIEW` trick took 45 seconds and the `@@IDENTITY` approach took 127 seconds: ``` Sub InitInerts() On Error Resume Next Kill Environ$("temp") & "\DropMe.mdb" On Error GoTo 0 Dim cat Set cat = CreateObject("ADOX.Catalog") With cat .Create _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ Environ$("temp") & "\DropMe.mdb" With .ActiveConnection Dim Sql As String Sql = _ "CREATE TABLE TableA" & vbCr & "(" & vbCr & " ID IDENTITY NOT" & _ " NULL UNIQUE, " & vbCr & " a_col INTEGER NOT NULL" & vbCr & ")" .Execute Sql Sql = _ "CREATE TABLE TableB" & vbCr & "(" & vbCr & " ID INTEGER NOT" & _ " NULL UNIQUE" & vbCr & " REFERENCES TableA (ID)," & _ " " & vbCr & " b_col INTEGER NOT NULL" & vbCr & ")" .Execute Sql Sql = _ "CREATE VIEW TestAB" & vbCr & "(" & vbCr & " a_ID, a_col, " & vbCr & " " & _ " b_ID, b_col" & vbCr & ")" & vbCr & "AS " & vbCr & "SELECT A1.ID, A1.a_col," & _ " " & vbCr & " B1.ID, B1.b_col" & vbCr & " FROM TableA AS" & _ " A1" & vbCr & " INNER JOIN TableB AS B1" & vbCr & " " & _ " ON A1.ID = B1.ID" .Execute Sql End With Set .ActiveConnection = Nothing End With End Sub Sub TestInerts_VIEW() Dim con Set con = CreateObject("ADODB.Connection") With con .Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ Environ$("temp") & "\DropMe.mdb" Dim timer As CPerformanceTimer Set timer = New CPerformanceTimer timer.StartTimer Dim counter As Long For counter = 1 To 4200 .Execute "INSERT INTO TestAB (a_col, b_col) VALUES (" & _ CStr(counter) & ", " & _ CStr(counter) & ");" Next Debug.Print "VIEW = " & timer.GetTimeSeconds End With End Sub Sub TestInerts_IDENTITY() Dim con Set con = CreateObject("ADODB.Connection") With con .Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ Environ$("temp") & "\DropMe.mdb" Dim timer As CPerformanceTimer Set timer = New CPerformanceTimer timer.StartTimer Dim counter As Long For counter = 1 To 4200 .Execute "INSERT INTO TableA (a_col) VALUES (" & _ CStr(counter) & ");" Dim identity As Long identity = .Execute("SELECT @@IDENTITY;")(0) .Execute "INSERT INTO TableB (ID, b_col) VALUES (" & _ CStr(identity) & ", " & _ CStr(counter) & ");" Next Debug.Print "@@IDENTITY = " & timer.GetTimeSeconds End With End Sub ``` What this shows is the the bottleneck now is the overhead associated with executing multiple statements. What if we could do it in just one statement? Well, guess what, using my contrived example, we can. First, create a Sequence table of unique integers, being a standard SQL trick (every database should have one, IMO): ``` Sub InitSequence() Dim con Set con = CreateObject("ADODB.Connection") With con .Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ Environ$("temp") & "\DropMe.mdb" Dim sql As String sql = _ "CREATE TABLE [Sequence]" & vbCr & "(" & vbCr & " seq INTEGER NOT NULL" & _ " UNIQUE" & vbCr & ");" .Execute sql sql = _ "INSERT INTO [Sequence] (seq) VALUES (-1);" .Execute sql sql = _ "INSERT INTO [Sequence] (seq) SELECT Units.nbr + Tens.nbr" & _ " + Hundreds.nbr + Thousands.nbr AS seq FROM ( SELECT" & _ " nbr FROM ( SELECT 0 AS nbr FROM [Sequence] UNION" & _ " ALL SELECT 1 FROM [Sequence] UNION ALL SELECT 2 FROM" & _ " [Sequence] UNION ALL SELECT 3 FROM [Sequence] UNION" & _ " ALL SELECT 4 FROM [Sequence] UNION ALL SELECT 5 FROM" & _ " [Sequence] UNION ALL SELECT 6 FROM [Sequence] UNION" & _ " ALL SELECT 7 FROM [Sequence] UNION ALL SELECT 8 FROM" & _ " [Sequence] UNION ALL SELECT 9 FROM [Sequence] ) AS" & _ " Digits ) AS Units, ( SELECT nbr * 10 AS nbr FROM" & _ " ( SELECT 0 AS nbr FROM [Sequence] UNION ALL SELECT" & _ " 1 FROM [Sequence] UNION ALL SELECT 2 FROM [Sequence]" & _ " UNION ALL SELECT 3 FROM [Sequence] UNION ALL SELECT" & _ " 4 FROM [Sequence] UNION ALL SELECT 5 FROM [Sequence]" & _ " UNION ALL SELECT 6 FROM [Sequence] UNION ALL SELECT" & _ " 7 FROM [Sequence] UNION ALL SELECT 8 FROM [Sequence]" & _ " UNION ALL SELECT 9 FROM [Sequence] ) AS Digits )" & _ " AS Tens, ( SELECT nbr * 100 AS nbr FROM ( SELECT" & _ " 0 AS nbr FROM [Sequence] UNION ALL SELECT 1 FROM" & _ " [Sequence] UNION ALL SELECT 2 FROM [Sequence] UNION" sql = sql & _ " ALL SELECT 3 FROM [Sequence] UNION ALL SELECT 4 FROM" & _ " [Sequence] UNION ALL SELECT 5 FROM [Sequence] UNION" & _ " ALL SELECT 6 FROM [Sequence] UNION ALL SELECT 7 FROM" & _ " [Sequence] UNION ALL SELECT 8 FROM [Sequence] UNION" & _ " ALL SELECT 9 FROM [Sequence] ) AS Digits ) AS Hundreds," & _ " ( SELECT nbr * 1000 AS nbr FROM ( SELECT 0 AS nbr" & _ " FROM [Sequence] UNION ALL SELECT 1 FROM [Sequence]" & _ " UNION ALL SELECT 2 FROM [Sequence] UNION ALL SELECT" & _ " 3 FROM [Sequence] UNION ALL SELECT 4 FROM [Sequence]" & _ " UNION ALL SELECT 5 FROM [Sequence] UNION ALL SELECT" & _ " 6 FROM [Sequence] UNION ALL SELECT 7 FROM [Sequence]" & _ " UNION ALL SELECT 8 FROM [Sequence] UNION ALL SELECT" & _ " 9 FROM [Sequence] ) AS Digits ) AS Thousands;" .Execute sql End With End Sub ``` Then use the Sequence table to enumerate the values from 1 to 42000 and construct rows in a single INSERT INTO..SELECT statement: ``` Sub TestInerts_Sequence() Dim con Set con = CreateObject("ADODB.Connection") With con .Open _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ Environ$("temp") & "\DropMe.mdb" Dim timer As CPerformanceTimer Set timer = New CPerformanceTimer timer.StartTimer .Execute "INSERT INTO TestAB (a_col, b_col) " & _ "SELECT seq, seq " & _ "FROM Sequence " & _ "WHERE seq BETWEEN 1 AND 4200;" Debug.Print "Sequence = " & timer.GetTimeSeconds End With End Sub ``` That executes on my machine in 0.2 of a second!
More recent versions of Access support the @@IDENTITY variable. You can use this to retrieve the identity column after an insert, without doing a query. ``` INSERT INTO mytable (field1,field2) VALUES (val1,val2); SELECT @@IDENTITY; ``` See this [knowledge base article](http://support.microsoft.com/kb/815629).
SQL queries taking too long
[ "", "sql", "ms-access", "optimization", "ado", "" ]
I have this piece of Javascript code, which takes about 600 ms on every call in Internet Explorer. The time taken in other browsers is negligble. ``` var _nvs_currentTab; var _nvs_zoomfield; var _nvs_centerfield; var _nvs_globsearch; var _nvs_category; var _nvs_favsonly; var _nvs_wishonly; var _nvs_friendfavsonly; var _nvs_newitemsonly; var _nvs_globsearchOld; var _nvs_catOld; var _nvs_favsonlyOld; var _nvs_wishonlyOld; var _nvs_friendFavsonlyOld; var _nvs_newItemsOnlyOld; function saveState() { if (!_nvs_currentTab) { var f = document.getElementById; _nvs_currentTab = f('currentTab'); _nvs_zoomfield = f('zoomfield'); _nvs_centerfield = f('centerfield'); _nvs_globsearch = f("globsearch"); _nvs_category = f("category"); _nvs_favsonly = f("favsonly"); _nvs_wishonly = f("wishonly"); _nvs_friendfavsonly = f("friendfavsonly"); _nvs_newitemsonly = f("newitemsonly"); _nvs_globsearchOld = f("globsearchOld"); _nvs_catOld = f("categoryOld"); _nvs_favsonlyOld = f("favsonlyOld"); _nvs_wishonlyOld = f("wishonlyOld"); _nvs_friendFavsonlyOld = f("friendFavsonlyOld"); _nvs_newItemsOnlyOld = f("newItemsOnlyOld"); } // get all state vars var navState= new Object(); navState.page = currentPage; navState.currentTab = _nvs_currentTab.value; navState.zoomfield = _nvs_zoomfield.value; navState.centerfield = _nvs_centerfield.value; navState.globsearch = _nvs_globsearch.value; navState.category = _nvs_category.value; navState.favsonly = _nvs_favsonly.checked; navState.wishonly = _nvs_wishonly.checked; navState.friendfavsonly = _nvs_friendfavsonly.checked; navState.newitemsonly = _nvs_newitemsonly.checked; navState.globsearchOld = _nvs_globsearchOld.value; navState.catOld = _nvs_catOld.value; navState.favsonlyOld = _nvs_favsonlyOld.value; navState.wishonlyOld = _nvs_wishonlyOld.value; navState.friendFavsonlyOld = _nvs_friendFavsonlyOld.value; navState.newItemsOnlyOld = _nvs_newItemsOnlyOld.value; // build new url with state var url = new StringBuffer(); url.append("#"); for (var i in navState) { if (i != "page") url.append("&"); url.append(i).append("=").append(navState[i]); } // set it window.location.href = url.toString(); } ``` This is what the call tree looks like, from the IE8 profiler: ``` saveState 1 615,00 ms f 15 1,00 ms String.split 1 0,00 ms Array 1 0,00 ms Object 1 0,00 ms StringBuffer 1 0,00 ms append 64 0,00 ms Array.push 64 0,00 ms toString 1 0,00 ms Array.join 1 0,00 ms Object.valueOf 63 0,00 ms Function.toString 63 0,00 ms ``` The StringBuffer implementation I'm using: ``` function StringBuffer() { this.buffer = []; } StringBuffer.prototype.append = function append(string) { this.buffer.push(string); return this; }; StringBuffer.prototype.toString = function toString() { return this.buffer.join(""); }; ``` **Edit:** Updated code, takes 397 ms on average to run. ``` var _nvs_currentTab; var _nvs_zoomfield; var _nvs_centerfield; var _nvs_globsearch; var _nvs_category; var _nvs_favsonly; var _nvs_wishonly; var _nvs_friendfavsonly; var _nvs_newitemsonly; var _nvs_globsearchOld; var _nvs_catOld; var _nvs_favsonlyOld; var _nvs_wishonlyOld; var _nvs_friendFavsonlyOld; var _nvs_newItemsOnlyOld; function saveState() { if (!_nvs_currentTab) { var _f = document.guideForm; _nvs_currentTab = _f.currentTab; _nvs_zoomfield = _f.zoomfield; _nvs_centerfield = _f.centerfield; _nvs_globsearch = _f.globsearch; _nvs_category = _f.category; _nvs_favsonly = _f.favsonly; _nvs_wishonly = _f.wishonly; _nvs_friendfavsonly = _f.friendfavsonly; _nvs_newitemsonly = _f.newitemsonly; _nvs_globsearchOld = _f.globsearchOld; _nvs_catOld = _f.categoryOld; _nvs_favsonlyOld = _f.favsonlyOld; _nvs_wishonlyOld = _f.wishonlyOld; _nvs_friendFavsonlyOld = _f.friendFavsonlyOld; _nvs_newItemsOnlyOld = _f.newItemsOnlyOld; } // build new url with state var url = new StringBuffer(); url.append("#"); url.append('currentPage=').append(currentPage); url.append('&currentTab=').append(_nvs_currentTab.value); url.append('&zoomfield=').append(_nvs_zoomfield.value); url.append('&centerfield=').append(_nvs_centerfield.value); url.append('&globsearch=').append(_nvs_globsearch.value); url.append('&category=').append(_nvs_category.value); url.append('&favsonly=').append(_nvs_favsonly.checked); url.append('&wishonly=').append(_nvs_wishonly.checked); url.append('&friendfavsonly=').append(_nvs_friendfavsonly.checked); url.append('&newitemsonly=').append(_nvs_newitemsonly.checked); url.append('&globsearchOld=').append(_nvs_globsearchOld.value); url.append('&catOld=').append(_nvs_catOld.value); url.append('&favsonlyOld=').append(_nvs_favsonlyOld.value); url.append('&wishonlyOld=').append(_nvs_wishonlyOld.value); url.append('&friendFavsonlyOld=').append(_nvs_friendFavsonlyOld.value); url.append('&newItemsOnlyOld=').append(_nvs_newItemsOnlyOld.value); // set it window.location.href = url.toString(); } ```
Okay, you're not going to believe this. I just tried removing the following line: `window.location.href = url.toString();` And it reduced the average runtime to two third of a millisecond. I know from profiling the toString call is very fast, so apparently setting the window.location.href is ultra slow (couple of hundred ms!!!). Bah, I hate IE. Note: This is a clean install of Internet Explorer, and I have no crazy toolbars slowing down my browser.
Seems that you store fields from some form. Instead of using `document.getElementById()` to get each element of form try to get value of form elements directly: `navState.currentTab = document.formName.currentTab.value;` where `formName` is value of `name` attribute of `form` tag and `currentTab` is value of `name` attribute of form element (i.e. input, checkbox). **EDIT:** When I was using IE5 and IE5.5 in 2000 even change (store reference to form element in variable) from: ``` for (i = 0; i < document.form.elements.length; i++) { values[i] = document.form.elements[i].value; } ``` to: ``` var form = document.form; for (i = 0; i < form.elements.length; i++) { values[i] = form.elements[i].value; } ``` made big difference. I am afraid nothing has changed during last 10 years :(.
Why is this piece of Javascript code so slow?
[ "", "javascript", "profiling", "performance", "" ]
I'm trying generics for the first time and am having a problem. I have a dll that sends messages in batches * there is a "Message" class and a "Batch" class in that dll * on the batch class, I have some public properties * on of the batch class's public properties is a property called "Messages" which is a list of the "Message" class as follows: ``` public List<Message> Messages {get;set;} ``` **Method 1** I then have a test exe where I want to set the properties on the "Batch" class as follows: ``` Batch myBatch = new Batch() myBatch.Messages.Add( new MyNameSpace.Message(txtToAddress.Text, txtMessage.Text)); ``` When I run the app, I get: "Object reference not set to an instance of an object." **Method 2** After playing around a bit, I see that I can successfully do the following in the test exe: ``` List<MyNameSpace.Message> myMessages = new List<MyNameSpace.Message>(); myBatch.Messages.Add( new MyNameSpace.Message(txtToAddress.Text, txtMessage.Text)); myBatch.Messages = myMessages; ``` I'd like to get it working in the first way because other programmers will be using the dll and it seems more intutive to use the first approach. What am I missing to get the first method to work?
Normally, collections are initialized by the parent object: ``` public List<Message> Messages {get; private set;} public Batch() { // constructor Messages = new List<Message>(); } ``` Now it should work as expected. Note that if you are using `XmlSerializer` you'll need to keep the public set too... In some ways, the long-hand property code is easier here: ``` private List<Message> messages = new List<Message>(); public List<Message> Messages { get {return messages; } } ``` (no messing with constructors, etc)
You need to instantiate your list first. Add this to your contstructor ``` Messages = new List<Message>(); ```
C# generics list of objects used as a property - can't add values
[ "", "c#", "generics", "properties", "" ]
I'm using ``` [DllImport("Oleacc.dll")] static extern int AccessibleObjectFromWindow( int hwnd, uint dwObjectID, byte[] riid, ref Excel.Window ptr); ``` to get an Excel Instance using his handle, which I get from the process ID of the excel instance. This is how it looks like when I use these function ``` const uint OBJID_NATIVEOM = 0xFFFFFFF0; Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); Excel.Window ptr = null; int hr = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), ref ptr); Object objApp = ptr.Application; ``` This peace of code works great but the only problem is that I had to add a reference to the Office 2003 Primary Interop Assemblies. As you can see, the last param in the function is the reason why I needed to add the reference to the Pias, so my question is if there is a way of avoiding the use of Interop Assemblies, I have tried with late binding but perhaps I've been doing it wrong because I haven't been able to make it work.
First: Late binding in C# is quite a pain. It's best to avoid it. Second: Late binding in C# is a pain. Use the PIA! Ok, that being said, here is what you need to do in order to use late binding: Remove the reference to the Office 2003 PIAs and instead add a COM import of the interface required by `AccessibleObjectFromWindow`, i.e. the `Excel.Window` interface: ``` [Guid("00020893-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ExcelWindow { } ``` You can retrieve this interface using a tool like [Reflector](https://www.red-gate.com/products/dotnet-development/reflector/) (or by simply pressing F12 on the type `Excel.Window` while the reference to the Excel PIA is still in your project) That being done you will have to modify the signature of `AccessibleObjectFromWindow` to match the imported `ExcelWindow` interface: ``` [DllImport("Oleacc.dll")] static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out ExcelWindow ptr); ``` Finally, you must use reflection to get the `Excel.Application` object from the `ExcelWindow` object: ``` object xlApp = ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null); ``` If your code is going to make a lot of calls into Excel's OM it might be easier to use VB with `Option Strict` turned off (or wait for C#4.0 ;-). Or, if you don't want to change from C#, it might be a good idea to create a wrapper class for the late binding calls. --- **Full Sample** Here is a fully functional sample (based on an [article](https://web.archive.org/web/20151228071923/http://blogs.msdn.com:80/b/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx) by Andrew Whitechapel): ``` using System; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; namespace ExcelLateBindingSample { /// <summary> /// Interface definition for Excel.Window interface /// </summary> [Guid("00020893-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ExcelWindow { } /// <summary> /// This class is needed as a workaround to http://support.microsoft.com/default.aspx?scid=kb;en-us;320369 /// Excel automation will fail with the follwoing error on systems with non-English regional settings: /// "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))" /// </summary> class UILanguageHelper : IDisposable { private CultureInfo _currentCulture; public UILanguageHelper() { // save current culture and set culture to en-US _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); } public void Dispose() { // reset to original culture System.Threading.Thread.CurrentThread.CurrentCulture = _currentCulture; } } class Program { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("Oleacc.dll")] static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out ExcelWindow ptr); public delegate bool EnumChildCallback(int hwnd, ref int lParam); [DllImport("User32.dll")] public static extern bool EnumChildWindows(int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam); [DllImport("User32.dll")] public static extern int GetClassName(int hWnd, StringBuilder lpClassName, int nMaxCount); public static bool EnumChildProc(int hwndChild, ref int lParam) { StringBuilder buf = new StringBuilder(128); GetClassName(hwndChild, buf, 128); if (buf.ToString() == "EXCEL7") { lParam = hwndChild; return false; } return true; } static void Main(string[] args) { // Use the window class name ("XLMAIN") to retrieve a handle to Excel's main window. // Alternatively you can get the window handle via the process id: // int hwnd = (int)Process.GetProcessById(excelPid).MainWindowHandle; // int hwnd = (int)FindWindow("XLMAIN", null); if (hwnd != 0) { int hwndChild = 0; // Search the accessible child window (it has class name "EXCEL7") EnumChildCallback cb = new EnumChildCallback(EnumChildProc); EnumChildWindows(hwnd, cb, ref hwndChild); if (hwndChild != 0) { // We call AccessibleObjectFromWindow, passing the constant OBJID_NATIVEOM (defined in winuser.h) // and IID_IDispatch - we want an IDispatch pointer into the native object model. // const uint OBJID_NATIVEOM = 0xFFFFFFF0; Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); ExcelWindow ptr; int hr = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), out ptr); if (hr >= 0) { // We successfully got a native OM IDispatch pointer, we can QI this for // an Excel Application using reflection (and using UILanguageHelper to // fix http://support.microsoft.com/default.aspx?scid=kb;en-us;320369) // using (UILanguageHelper fix = new UILanguageHelper()) { object xlApp = ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null); object version = xlApp.GetType().InvokeMember("Version", BindingFlags.GetField | BindingFlags.InvokeMethod | BindingFlags.GetProperty, null, xlApp, null); Console.WriteLine(string.Format("Excel version is: {0}", version)); } } } } } } } ``` And this would be the same solution without PIAs in VB (Note that OM call are much more readable; however, the code to get access to the OM would be the same): ``` Option Strict Off Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Text Module ExcelLateBindingSample ''' <summary> ''' Interface definition for Excel.Window interface ''' </summary> <Guid("00020893-0000-0000-C000-000000000046"), _ InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _ Public Interface ExcelWindow End Interface ''' <summary> ''' This class is needed as a workaround to http://support.microsoft.com/default.aspx?scid=kb;en-us;320369 ''' Excel automation will fail with the follwoing error on systems with non-English regional settings: ''' "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))" ''' </summary> Class UILanguageHelper Implements IDisposable Private _currentCulture As CultureInfo Public Sub New() ' save current culture and set culture to en-US _currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US") End Sub Public Sub Dispose() Implements System.IDisposable.Dispose 'reset to original culture System.Threading.Thread.CurrentThread.CurrentCulture = _currentCulture End Sub End Class <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _ Private Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr End Function <DllImport("Oleacc.dll")> _ Private Function AccessibleObjectFromWindow(ByVal hwnd As Integer, ByVal dwObjectID As UInt32, ByVal riid() As Byte, ByRef ptr As ExcelWindow) As Integer End Function Public Delegate Function EnumChildCallback(ByVal hwnd As Integer, ByRef lParam As Integer) As Boolean <DllImport("User32.dll")> _ Public Function EnumChildWindows(ByVal hWndParent As Integer, ByVal lpEnumFunc As EnumChildCallback, ByRef lParam As Integer) As Boolean End Function <DllImport("User32.dll")> _ Public Function GetClassName(ByVal hWnd As Integer, ByVal lpClassName As StringBuilder, ByVal nMaxCount As Integer) As Integer End Function Public Function EnumChildProc(ByVal hwndChild As Integer, ByRef lParam As Integer) As Boolean Dim buf As New StringBuilder(128) GetClassName(hwndChild, buf, 128) If buf.ToString() = "EXCEL7" Then lParam = hwndChild Return False End If Return True End Function Sub Main() ' Use the window class name ("XLMAIN") to retrieve a handle to Excel's main window. ' Alternatively you can get the window handle via the process id: ' Dim hwnd As Integer = CInt(Process.GetProcessById(excelPid).MainWindowHandle); ' Dim hwnd As Integer = CInt(FindWindow("XLMAIN", Nothing)) If hwnd <> 0 Then Dim hwndChild As Integer = 0 ' Search the accessible child window (it has class name "EXCEL7") Dim cb As New EnumChildCallback(AddressOf EnumChildProc) EnumChildWindows(hwnd, cb, hwndChild) If hwndChild <> 0 Then ' We call AccessibleObjectFromWindow, passing the constant OBJID_NATIVEOM (defined in winuser.h) ' and IID_IDispatch - we want an IDispatch pointer into the native object model. ' Const OBJID_NATIVEOM As UInteger = &HFFFFFFF0& Dim IID_IDispatch As New Guid("{00020400-0000-0000-C000-000000000046}") Dim ptr As ExcelWindow Dim hr As Integer = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), ptr) If hr >= 0 Then ' We successfully got a native OM IDispatch pointer, we can QI this for ' an Excel Application using reflection (and using UILanguageHelper to ' fix http://support.microsoft.com/default.aspx?scid=kb;en-us;320369) ' Using fixCrash As New UILanguageHelper Console.WriteLine(String.Format("Excel version is: {0}", ptr.Application.Version)) End Using End If End If End If End Sub End Module ```
Use this definition of AccessibleObjectFromWindow instead: ``` [DllImport("Oleacc.dll")] private static extern int AccessibleObjectFromWindow( int hwnd, uint dwObjectID, byte[] riid, [MarshalAs(UnmanagedType.IUnknown)]ref object ptr); ```
How to use use late binding to get excel instance?
[ "", "c#", "excel", "" ]
``` interface IFolderOrItem<TFolderOrItem> where TFolderOrItem : FolderOrItem {} abstract class FolderOrItem {} class Folder : FolderOrItem {} abstract class Item : FolderOrItem {} class Document : Item {} ``` now i'm trying to do sth like this: ``` class Something { IFolderItemOrItem<Item> SelectedItem { get; set; } void SomeMagicMethod() { this.SelectedItem = (IFolderOrItem<Item>)GetMagicDocument(); // bad bad bad ... ?? } IFolderOrItem<Document> GetMagicDocument() { return someMagicDocument; // which is of type IFolderOrItem<Document> } } ``` is there any possibility to get this working?
If I read it correctly... then the problem is that just because `Foo : Bar`, that does **not** mean that `ISomething<Foo> : ISomething<Bar>`... In some cases, variance in C# 4.0 may be an option. Alternatively, there are sometimes things you can do with generic methods (not sure it will help here, though). --- The closest you can do in C# 3.0 (and below) is probably a non-generic base interface: ``` interface IFolderOrItem {} interface IFolderOrItem<TFolderOrItem> : IFolderOrItem where TFolderOrItem : FolderOrItem { } ``` commonly, the base-interface would have, for example, a `Type ItemType {get;}` to indicate the real type under consideration. Then usage: ``` IFolderOrItem SelectedItem { get; set; } ... public void SomeMagicMethod() { this.SelectedItem = GetMagicDocument(); // no cast needed // not **so** bad } ``` --- From the spec, this relates to §25.5.6 (ECMA 334 v4): > 25.5.6 Conversions > > Constructed types follow the same conversion rules (§13) > as do non-generic types. When applying > these rules, the base classes and > interfaces of constructed types shall > be determined as described in §25.5.3. > > No special conversions exist between > constructed reference types other than > those described in §13. In particular, > unlike array types, constructed > reference types do not permit > co-variant conversions (§19.5). This > means that a type `List<B>` has no > conversion (either implicit or > explicit) to `List<A>` even if `B` is > derived from `A`. Likewise, no > conversion exists from `List<B>` to > `List<object>`. > > [Note: The rationale for > this is simple: if a conversion to > `List<A>` is permitted, then apparently, > one can store values of type `A` into > the list. However, this would break > the invariant that every object in a > list of type `List<B>` is always a value > of type `B`, or else unexpected failures > can occur when assigning into > collection classes. end note] The same applies to interfaces. This changes a *bit* in C# 4.0, but only in some cases.
As far as the compiler is concerened, `IFolderOrItem<Document>` & `IFolderOrItem<Item>` are two completely different types. `Document` may inherit `Item`, but `IFolderOrItem<Document>` does not inherit `IFolderOrItem<Item>` I'm relying on Marc or Jon to post links to the relevant portions of the C# spec.
Why is this cast not possible?
[ "", "c#", "generics", "oop", "" ]
I'm trying to use the jQuery UI Dialog to display a confirmation prior to executing the action...in this case navigating to the selected link....but in another case, I might like to use AJAX delete. I thought I could pass the action as parameter of the custom\_confirm function: ``` $("a.edit").click(function(e){ e.preventDefault(); custom_confirm('Please Note:', function(){ location.href = $(this).attr('href'); } ); }); function custom_confirm(prompt, action, title){ if (title === undefined) title = "Are you sure?"; if ($("#confirm").length == 0){ $("#main div.inner").append('<div id="confirm" title="' + title + '">' + prompt + '</div>'); $("#confirm").dialog({buttons: {'Proceed': function(){ $(this).dialog('close'); action; }, Cancel: function(){ $(this).dialog('close'); }}}); } else { $("#confirm").html(prompt); $("#confirm").dialog('open'); } } ``` It's not working. Is there another way to accomplish this? --- Thanks for the quick responses guys. I tried your suggestion, but it's still not executing function that is passed as parameter. ``` $("a.edit").click(function(e){ e.preventDefault(); var href = $(this).attr('href'); custom_confirm('Please Note:', function(){ console.log(href); location.href = href; } ); }); ``` --- Cleaned up the custom\_confirm function, added the close option: ``` function custom_confirm(prompt, action, title){ if (title === undefined) title = "Are you sure?"; $("#main div.inner").append('<div id="confirm" title="' + title + '">' + prompt + '</div>'); $("#confirm").dialog({position: 'top', width: 700, modal: true, resizable: false, show: "fold", hide: "blind", buttons: {'Proceed': function(){ $(this).dialog('close'); action(); }, Cancel: function(){ $(this).dialog('close'); }}, close: function(ev, ui) { $(this).remove();}}); } ```
Figured it out. If you are passing a function as a parameter to another function, you need to call the parameter as a funciton ``` action() ``` Instead of as a variable ``` action ``` Hope that helps ``` $("a.edit").click(function(e){ e.preventDefault(); var href = $(this).attr('href'); custom_confirm('Please Note:', function(){ location.href = href; } ); }); function custom_confirm(prompt, action, title){ if (title === undefined) title = "Are you sure?"; if ($("#confirm").length == 0){ $("#main div.inner").append('<div id="confirm" title="' + title + '">' + prompt + '</div>'); $("#confirm").dialog({buttons: {'Proceed': function(){ $(this).dialog('close'); action(); }, Cancel: function(){ $(this).dialog('close'); }}}); } else { $("#confirm").html(prompt); $("#confirm").dialog('open'); } } ```
You need to pass in the `this` variable with a closure. [See this example.](http://jsbin.com/ikeha) (improved) ``` $("a.edit").click(function(e){ e.preventDefault(); custom_confirm('Please Note:', (function (element) { return function(element){ location.href = $(element).attr('href'); })(this) ); }); ``` But what you're trying to do could be done with the following probably just as easy: ``` $("a.edit").each(function() { $(this).click(function() { if (!confirm("Are you sure about that?")) e.preventDefault(); }); }); ```
jQuery UI Dialog confirmation
[ "", "javascript", "jquery", "" ]
Merely out of interrest: do you think Java would have been a better language if static variables would have been excluded, effectively replacing Singletons with singletons? [Definition here.](http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html) If you think so: could you elaborate on what motivation there might have been for including it in the language?
The same article that you cite has the following statement: > The other kind of Singletons, which are semi-acceptable are those which don't effect the execution of your code, They have no "side effects" ... and then the article explains about logging. Another typical example is Printing. So that are arguments for Singletons even in the article that calls for "let's-get-rid-of-all-singletons". The argument the author provides is interesting. He states that having global state is the real problem with Singletons, and as long as there is a one-way communication between your program and the Singleton you are in the clear. And definitively Java would be a worse language if it had no static variables, as it is a feature that is required in several use cases. I mean, you could program in a procedural way in Java if you really wanted... and that is not evil per-se. The abuse of static variables and Singletons doesn't necessarily mean that we need to get rid of them.
> do you think Java would have been a better language if static variables would have been > excluded, effectively replacing Singletons with singletons? No, sometimes you *really* want to have variables or constants that are common to all objects. Of course **static** is not necessary evil. > Could you elaborate on what motivation there might have been for including it in the > language? **static** is a shorthand for objects or methods that are not necessary bounded to data, it models behaviour without instance data.
Java without singletons
[ "", "java", "design-patterns", "" ]
Is there any practical difference between a `Set` and `Collection` in Java, besides the fact that a `Collection` can include the same element twice? They have the same methods. (For example, does `Set` give me more options to use libraries which accept `Set`s but not `Collection`s?) **edit:** I can think of at least 5 different situations to judge this question. Can anyone else come up with more? I want to make sure I understand the subtleties here. 1. designing a method which accepts an argument of `Set` or `Collection`. `Collection` is more general and accepts more possibilities of input. (if I'm designing a specific class or interface, I'm being nicer to my consumers and stricter on my subclassers/implementers if I use `Collection`.) 2. designing a method which returns a `Set` or `Collection`. `Set` offers more guarantees than `Collection` (even if it's just the guarantee not to include one element twice). (if I'm designing a specific class or interface, I'm being nicer to my consumers and stricter on my subclassers/implementers if I use `Set`.) 3. designing a class that implements the interface `Set` or `Collection`. Similar issues as #2. Users of my class/interface get more guarantees, subclassers/implementers have more responsibility. 4. designing an interface that extends the interface `Set` or `Collection`. Very similar to #3. 5. writing code that uses a `Set` or `Collection`. Here I might as well use `Set`; the only reasons for me to use `Collection` is if I get back a `Collection` from someone else's code, or if I have to handle a collection that contains duplicates.
[`Collection`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html) is also the supertype of `List`, `Queue`, `Deque`, and others, so it gives you more options. For example, I try to use `Collection` as a parameter to library methods that shouldn't explicitly depend on a certain type of collection. Generally, you should use the right tool for the job. If you don't want duplicates, use `Set` (or `SortedSet` if you want ordering, or `LinkedHashSet` if you want to maintain insertion order). If you want to allow duplicates, use `List`, and so on.
I think you already have it figured out- use a `Set` when you want to specifically exclude duplicates. `Collection` is generally the lowest common denominator, and it's useful to specify APIs that accept/return this, which leaves you room to change details later on if needed. However if the details of your application require **unique entries**, use `Set` to enforce this. Also worth considering is whether order is important to you; if it is, use `List`, or `LinkedHashSet` if you care about order *and* uniqueness.
when to use Set vs. Collection?
[ "", "java", "collections", "" ]
Something I have found strange since I started working on GWT is how few open source projects there are in this technology. Initially I was surprised to discover this mainly because GWT itself is open source. But after puzzling over this, my suspicion is that it is mainly used for internal projects by large corporations who already use Java and are using GWT for their RIAs instead of Flex or Rails. My understanding is that large corporations that use Java would tend to have lower contributions to open source because their focus is mainly on internal or commercial applications. Does this sound like an accurate interpretation or does anyone have a different explanation for this phenomenon?
It actually seems quite reasonable to me that corporations, particularly those who use closed source, would favor GWT more than open-source developers, for exactly the reasons related to those mentioned in the question: * They already use Java, and in particular have experienced Java developers * There is a perceived (and sometimes real) higher cost in supporting multiple languages * Management is reluctant to add either another bullet point on job postings (must know Javascript) or send developers to training Open-source developers, on the other hand, are often hobbyists (though not always), and hobbyists tend to be more interested in picking up new technologies "for the fun of it." Thus a hobbyist would be more open to writing Javascript directly, probably with the aid of a Javascript framework that doesn't involve translating from some other source language. Specifically concerning source language translation, it's a [leaky abstraction](http://www.joelonsoftware.com/articles/LeakyAbstractions.html). Eventually you're probably going to want to drop down into "raw" Javascript, and it's easier to do in an environment where you're already writing JS than one in which you're writing Java that gets translated.
I think you are right, but you might want to add in a couple more factors: GWT is fairly young OpenSource programmers work in their language of choice, and for small 1-person projects, Java can be a little uncomfortable if you don't already know it (I'm the biggest Java fan around, but everything has it's limitations). Java isn't really a great choice for web front-ends, so even though GWT is a great solution for that, it wouldn't ever be more attractive than rails to a very small development team.
Why are there so few open source GWT apps?
[ "", "java", "open-source", "gwt", "" ]
I'm wondering what the declaration of the data type in [`bindParam()`](http://php.net/manual/en/pdostatement.bindparam.php) (or [`bindValue()`](http://php.net/manual/en/pdostatement.bindvalue.php)) is used for... I mean, I thought that if I define an integer argument (`PDO::PARAM_INT`), the argument must be converted to an integer, something like ``` $delete->bindParam(1, $kill, PDO::PARAM_INT); // should work like $delete->bindParam(1, (int)$kill); ``` or at least throw an error if the argument is not of the declared type. But this is not the case. Googling around, I found that in the php.net archive: > Hi all, > > I am currently working on PDO. Exactly > on the bindParam() function. The third > parameter data\_type seems to be here > to force the type of the value ? But > when I try : > > ``` > $sql = "INSERT INTO produit (idproduit, nom, marque) VALUES (NULL, :nom, :marque)"; > $stmt = $dbh->prepare($sql); > $nom = 'Testarossa'; $marque = 'Ferrari' ; > $stmt->BindValue(':marque',$marque) ; > $stmt->BindParam(':nom',$nom,PDO::PARAM_INT) ; > > $stmt->execute(); $nom = '250 GTO' ; > $stmt->execute(); ?> > ``` > > I was expecting to have either a PHP > error or an interger in my database. > But in my DB I have : > > 22 Testarossa Ferrari 23 250 GTO > Ferrari > > It mean that it didn't change if I > have the third parameter or not. Or > perhaps I miss something. Can someone > tole me more ? Or just can someone > told me where I can find information > about it. > > Regards, > > Cyruss That is exactly my situation. Where are my thoughts going wrong?
It can be used for things like making sure PDO is doing the proper escaping for in-lining values (for drivers that don't support proper bound parameters) and improving network efficiency by making sure numbers are binary packed appropriately (given protocol support). It looks like in base PDO, it doesn't do much. ``` if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_STR && param->max_value_len <= 0 && !Z_ISNULL_P(parameter)) { if (!try_convert_to_string(parameter)) { return 0; } } else if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_INT && (Z_TYPE_P(parameter) == IS_FALSE || Z_TYPE_P(parameter) == IS_TRUE)) { convert_to_long(parameter); } else if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL && Z_TYPE_P(parameter) == IS_LONG) { convert_to_boolean(parameter); } ``` So, if you say it is a string (or if you say nothing at all as that is the default) and your data's type is something other than a NULL then it will convert it into a string. If you say it's an int but you bind a bool then it will convert it to an integer. If you say it's a bool but you bind a number then it will convert it to a true boolean. When emulation mode is turned on, the type hint is used to determine how to inject it into the SQL string. Additionally, PDO provides this information to the database drivers, which can then be used to bind the data most optimally or correctly, depending on the particular DB's requirements.
So I decided to dive into the PHP source code and this is what I found. `static int really_register_bound_param` in ext/pdo/pdo\_stmt.c on line 329 of version 8.3.0 ``` if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_STR && param->max_value_len <= 0 && !Z_ISNULL_P(parameter)) { if (!try_convert_to_string(parameter)) { return 0; } } else if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_INT && (Z_TYPE_P(parameter) == IS_FALSE || Z_TYPE_P(parameter) == IS_TRUE)) { convert_to_long(parameter); } else if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL && Z_TYPE_P(parameter) == IS_LONG) { convert_to_boolean(parameter); } ``` These are the conversions PDO does during binding. * PDO::PARAM\_STR converts whatever you give it to a string except null. * PDO::PARAM\_INT converts bools into integers * PDO::PARAM\_BOOL converts longs into bools That's it. Nothing else is converted. PDO uses the PARAM flags to format SQL not to cast data types.
PHP PDO::bindParam() data types.. how does it work?
[ "", "php", "types", "pdo", "prepared-statement", "" ]
I am building a Winforms C# 2.0 application. I have successfully been able to connect to my SLQ Server database using the following: m\_connexion = new SqlConnection("server=192.168.xxx.xxx;uid=...;pwd=...;database=..."); Because my company wanted to be able to use any database, I went on to use the Odbc driver and my commands went on like this: m\_connexion = new OdbcConnection("server=192.168.xxx.xxx;uid=...;pwd=...;database=..."); However, this throws out a System.InvalidOperationException. Any idea why? I'm also trying to use a DSN, but the commend OdbcConnection connection = new OdbcConnection("DSN=MyDataSourceName"); suggested [here](https://stackoverflow.com/questions/754302/how-to-get-odbc-connection-by-name) but it likewise throws my a System.InvalidOperationException
The connection string needs a Provider= so that the ODBC drivers know which server you're connecting to. In this case Provider=SQLSERVER I believe. **UPDATE:** Should have been Provider=SQLOLEDB
I think you need to specify a driver. Look here for details: <http://connectionstrings.com/sql-server-2005#21>
Why does this OdbcConnection throw me a System.InvalidOperationException?
[ "", "c#", ".net", "sql-server", "ado.net", "" ]
Are there any open source frameworks to help build a .NET GUI? I would also be fine with free frameworks.
There are quite a few of them. Most of the larger ones are [listed here](http://mono-project.com/Gui_Toolkits).
[OpenWinforms](http://feeds.feedburner.com/Openwinforms) has a variety of open source controls and some various articles. If you are just looking for some free controls, the [Krypton Toolkit](https://github.com/ComponentFactory/Krypton) is a really nice library has a free library of a lot of common controls, but no source is available.
Open Source .NET Desktop UI Frameworks
[ "", "c#", "open-source", "" ]
I've got a `shared` class (`static` in C#) which mostly carries some settings data that any class in the application can read and sometimes write. Also there are some static properties which holds some internal states. Now I want to revert this class to initial stage of it. With all default variables etc. *Assume that the user want to reset the current state and start over without restarting the application.* In a singleton model I'd simply renew it with something like this : ``` Public Sub Reset() _Instance = New MyClass() End Sub ``` However this is not possible in a `Shared` class. Is there any idea about how can I accomplish this? Or should I switch **back** to Singleton?
There is no way to do it in the same way the singleton model you just pointed out. The reason being that there is no backing data store to "reset". What you could do though is simulate this by using an explicit method to initialize all of our data. ``` Public Module MyClass Public Sub Reset() Field1 = 42 Field2 = "foo" End Sub Public Shared Field1 As Integer Public Shared Field2 As String End Module ``` Version with a class vs. a module ``` Public Class MyClass Shared Sub New() Reset End Sub Private Sub New() ' Prevent instantiation of the class End Sub Public Sub Reset() Field1 = 42 Field2 = "foo" End Sub Public Shared Field1 As Integer Public Shared Field2 As String End Class ```
You can't do this in a static class, since there is no instance of a static class. The two options would be to switch (back) to a singleton. Alternatively, you could have a method which resets each of the static members of the class.
Can I reset a static/shared class?
[ "", "c#", ".net", "vb.net", "static", "shared", "" ]
I'm using sql 2008 express edition and I'm trying to do a multiple row insert thru my C# application. I've got around 100000 records that needs to be inserted. Okay all goes well for the first 1000 records then I'm getting the error: "The number of row value expressions in the INSERT statement exceeds the maximum allowed number of 1000 row values." I looked at my column data type -> int, so that shouldn't be the problem. I checked my code and I'm inserting in steps of 500 records. So I googled it but couldn't find anything useful. Can somebody explain why I get this error and if possible how to solve it.
You can use the [SQLBulkCopy](http://msdn.microsoft.com/en-us/library/7ek5da1a.aspx) class. Which supports batching, transactions and is more efficient than standard insert statements.
this is how my code handles the multi insert ``` var count = "SELECT COUNT(*) as rowcount FROM table_mysql GROUP BY id"; var countReader = Retrieve(count); var countRows = 0; try { while (countReader.Read()) { countRows += int.Parse(countReader.GetValue(0).ToString()); } } catch (Exception ex) { Log.LogMessageToFile("Import.cs -> table_mssql: " + ex.StackTrace + " /n" + ex.Message); } finally { if (countReader != null) { countReader.Close(); _crud.close_conn(); } } for (var a = 0; a < countRows; ) { var sql = "SELECT id, traffic_id, dow, uu, imps, impsuu, otsw, otsm FROM table_mysql LIMIT " + a + ", " + (a + 500) + ""; var reader = Retrieve(sql); try { var builder = new StringBuilder(); builder.Append( "SET IDENTITY_INSERT table_mssql ON;INSERT INTO table_mssql(id, traffic_id, dow, uu, imps, impsuu, otsw, otsm) VALUES "); while (reader.Read()) { Application.DoEvents(); try { builder.Append("(" + reader.GetValue(0) + ", " + reader.GetValue(1) + ", " + reader.GetValue(2) + ", " + reader.GetValue(3) + ", " + reader.GetValue(4) + ", " + reader.GetValue(5) + ", " + reader.GetValue(6) + ", " + reader.GetValue(7) + "), "); } catch (Exception ex) { Log.LogMessageToFile("Import.cs -> table_mssql: " + ex.StackTrace + " /n" + ex.Message); } } var sqlDB = builder.ToString(0, builder.Length - 2); sqlDB += ";SET IDENTITY_INSERT table_mssql OFF;"; if (!InsertDB(sqlDB)) { Log.LogMessageToFile("Import.cs -> table_mssql: No insert happend!"); } } catch (Exception ex) { Log.LogMessageToFile("Import.cs -> table_mssql: " + ex.StackTrace + " /n" + ex.Message); return false; } finally { if (reader != null) { reader.Close(); _crud.close_conn(); } } a = a + 500; } ``` I'm going to check the sqlbulkcopy. Maybe that is a better solution.
Multiple row insert -> statement exceeds the maximum allowed number of 1000 row values
[ "", "c#", "sql-server", "" ]
I have worked with SQL for several years now, primarily MySQL/PhpMyAdmin, but also Oracle/iSqlPlus and PL/SQL lately. I have programmed in PHP, Java, ActionScript and more. I realise SQL isn't an imperative programming language like the others - but why do the error messages seem so much less specific in SQL? In other environments I'm pointed straight to the root of the problem. More often that not, MySQL gives me errors like "error AROUND where u.id = ..." and prints the whole query. This is even more difficult with stored procedures, where debugging can be a complete nightmare. Am I missing a magic tool/language/plugin/setting that gives better error reporting or are we stuck with this? I want a debugger or language which gives me the same amount of control that Eclipse gives me when setting breakpoints and stepping trough the code. Is this possible?
I think the answer lies in the fact that SQL is a set-based language with a few procedural things attached. Since the designers were thinking in set-based terms, they didn't think that the ordinary type of debugging that other languages have is important. However, I think some of this is changing. You can set breakpoints in SQL Server 2008. I haven't used it really as you must have SQL Server 2008 databases before it will work and most of ours are still SQL Server 2000. But it is available and it does allow you to step through things. You still are going to have problems when your select statement is 150 lines long and it knows that the syntax isn't right but it can't point out exactly where as it is all one command. Personally when I am writing a long procedural SP, I build in a test mode that includes showing me the results of things I do, the values of key variables at specific points I'm interested in, and print staments that let me know what steps have been completed and then rolling the whole thing back when done. That way I can see what would have happened if it had run for real, but not have hurt any of the data in the database if I got it wrong. I find this very useful. It can vastly increase the size of your proc though. I have a template I use that has most of the structure I need set up in it, so it doesn't really take me too long to do. Especially since I never add an insert. update or delete to a proc without first testing the associated select to ensure I have the records I want.
I think the explanation is that "regular" languages have much smaller individual statements than SQL, so that single-statement granularity points to a much smaller part of the code in them than in SQL. A single SQL statement can be a page or more in length; in other languages it's usually a single line. I don't think that makes it impossible for debuggers / IDEs to more precisely identify errors, but I suspect it makes it harder.
Is there a better way to debug SQL?
[ "", "sql", "debugging", "" ]
I'm trying to load an html document into a WebBrowser control, but I'm at my wits end. Here's a sample: ``` public void Button_Click(object sender, EventArgs e) { webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_c); webBrowser1.DocumentText = "<html>foo</html>"; // The documenttext property is NOT what was set above. // No exception is thrown. It's always "<html></html>\0", however. // This line setting the title throws a HRESULT COM error. webBrowser1.Document.Title = "foobar!"; } ``` The wb\_c event handler is never called, either. The webbrowser control is defined as a control on the form. The form itself consists of only the browser and the button. Does anyone have any ideas? I've used this class before without any issues, but this time the .Net gods are denying me! My end goal is to print the rendered document, but right now I can't even get it to accept my HTML. Maybe I need some holy water or something. Edit: If the Title line is removed above, the wb\_c event handler is never getting triggered. It's as though there's something wrong with the COM component itself, or something. Edit 2: By popular demand, here is a complete blob of my code. ``` public partial class Form2 : Form { [STAThread] public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form2()); } public Form2() { InitializeComponent(); webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_c); } void wb_c(object sender, WebBrowserDocumentCompletedEventArgs e) { throw new Exception("The method or operation is not implemented."); } private void button1_Click(object sender, EventArgs e) { webBrowser1.DocumentText = "<html>foo</html>"; } } partial class Form2 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.webBrowser1 = new System.Windows.Forms.WebBrowser(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // webBrowser1 // this.webBrowser1.Location = new System.Drawing.Point(12, 12); this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser1.Name = "webBrowser1"; this.webBrowser1.Size = new System.Drawing.Size(117, 99); this.webBrowser1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(90, 165); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 1; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form2 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.button1); this.Controls.Add(this.webBrowser1); this.Name = "Form2"; this.Text = "Form2"; this.Load += new System.EventHandler(this.Form2_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser webBrowser1; private System.Windows.Forms.Button button1; } ``` This is a .Net 2.0 project running in VS 2005. System.Windows.Forms.dll is v2.0.50727. EDIT 3: Adding this line to the end of the Form2 constructor: ``` webBrowser1.Navigate("about:blank"); ``` *Does* trigger the event handler, but it doesn't otherwise affect the behavior of the code when setting the document text. Setting a breakpoint after the webBrowser1.Document.Text line still gives the same "\0" string, and trying to set the title still gives a COM HERROR.
Try moving the line: ``` webBrowser1.Document.Title = "foobar!"; ``` into your wb\_c method. I think the problem is that when you're calling it, the Document property isn't completley set yet, and you're getting a null reference exception. If you wait till the page is loaded, you should be ok. **UPDATE:** Tried your sample, and your event handler IS getting called, however I suspect it's being called from another thread. Therefore, it gets to the line where the Exception is thrown, but you're never actually seeing it, because it's in another thread. Take out the line that throws the exception, and replace it with: ``` webBrowser1.Document.Title = "foobar!"; ``` That should do the trick.
Before you can manipulate the Document you need to execute the navigate command. To use the WebBrowser to construct a HTML page from scratch just navigate to *"about:blank"* like so: ``` WebBrowser browser = new WebBrowser(); browser.Navigate("about:blank"); browser.Document.Write(html); ``` Then use the InnerHtml on the root element and not the DocumentText property to apply Html as you are.
webbrowser not loading document
[ "", "c#", "webbrowser-control", "" ]
I have a database which is 6GB in size, with a multitude of tables however smaller queries seem to have the most problems, and want to know what can be done to optimise them for example there is a Stock, Items and Order Table. The Stock table is the items in stock this has around 100,000 records within with 25 fields storing ProductCode, Price and other stock specific data. The Items table stores the information about the items there are over 2,000,000 of these with over 50 fields storing Item Names and other details about the item or product in question. The Orders table stores the Orders of Stock Items, which is the when the order was placed plus the price sold for and has around 50,000 records. Here is a query from this Database: ``` SELECT Stock.SKU, Items.Name, Stock.ProductCode FROM Stock INNER JOIN Order ON Order.OrderID = Stock.OrderID INNER JOIN Items ON Stock.ProductCode = Items.ProductCode WHERE (Stock.Status = 1 OR Stock.Status = 2) AND Order.Customer = 12345 ORDER BY Order.OrderDate DESC; ``` Given the information here what could be done to improve this query, there are others like this, what alternatives are there. The nature of the data and the database cannot be detailed further however, so if general optmisation tricks and methods are given these will be fine, or anything which applies generally to databases. The Database is MS SQL 2000 on Windows Server 2003 with the latest service packs for each. DB Upgrade / OS Upgrade are not options for now. --- **Edit** Indices are Stock.SKU, Items.ProductCode and Orders.OrderID on the tables mentioned. Execution plan is 13-16 seconds for a Query like this 75% time spent in Stock --- Thanks for all the responses so far - Indexing seems to be the problem, all the different examples given have been helpful - dispite a few mistakes with the query, but this has helped me a lot some of these queries have run quicker but combined with the index suggestions I think I might be on the right path now - thanks for the quick responses - has really helped me and made me consider things I did not think or know about before! --- Indexes ARE my problem added one to the Foriegn Key with Orders (Customer) and this has improved performance by halfing execution time! Looks like I got tunnel vision and focused on the query - I have been working with DBs for a couple of years now, but this has been very helpful. However thanks for all the query examples they are combinations and features I had not considered may be useful too!
The most important (if not already done): define your primary keys for the tables (if not already defined) and add indexes for the foreign keys and for the columns you are using in the joins.
is your code correct??? I'm sure you're missing something ``` INNER JOIN Batch ON Order.OrderID = Orders.OrderID ``` and you have a ) in the code ... --- you can always test some variants against the execution plan tool, like ``` SELECT s.SKU, i.Name, s.ProductCode FROM Stock s, Orders o, Batch b, Items i WHERE b.OrderID = o.OrderID AND s.ProductCode = i.ProductCode AND s.Status IN (1, 2) AND o.Customer = 12345 ORDER BY o.OrderDate DESC; ``` and you should return just a fraction, like TOP 10... it will take some milliseconds to just choose the TOP 10 but you will save plenty of time when binding it to your application.
Slow but simple Query, how to make it quicker?
[ "", "sql", "sql-server", "database", "optimization", "" ]
What is the cleanest way to create a comma-separated list of string values from an `IList<string>` or `IEnumerable<string>`? `String.Join(...)` operates on a `string[]` so can be cumbersome to work with when types such as `IList<string>` or `IEnumerable<string>` cannot easily be converted into a string array.
**.NET 4+** ``` IList<string> strings = new List<string>{"1","2","testing"}; string joined = string.Join(",", strings); ``` **Detail & Pre .Net 4.0 Solutions** `IEnumerable<string>` can be converted into a string array *very* easily with LINQ (.NET 3.5): ``` IEnumerable<string> strings = ...; string[] array = strings.ToArray(); ``` It's easy enough to write the equivalent helper method if you need to: ``` public static T[] ToArray(IEnumerable<T> source) { return new List<T>(source).ToArray(); } ``` Then call it like this: ``` IEnumerable<string> strings = ...; string[] array = Helpers.ToArray(strings); ``` You can then call `string.Join`. Of course, you don't *have* to use a helper method: ``` // C# 3 and .NET 3.5 way: string joined = string.Join(",", strings.ToArray()); // C# 2 and .NET 2.0 way: string joined = string.Join(",", new List<string>(strings).ToArray()); ``` The latter is a bit of a mouthful though :) This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) [this one](https://stackoverflow.com/questions/219519/whats-the-c-method-syntax-for-converting-an-array-to-a-simple-string). As of .NET 4.0, there are more overloads available in [`string.Join`](http://msdn.microsoft.com/en-us/library/system.string.join), so you can actually just write: ``` string joined = string.Join(",", strings); ``` Much simpler :)
FYI, the .NET 4.0 version of `string.Join()` has some [extra overloads](http://msdn.microsoft.com/en-us/library/system.string.join.aspx), that work with `IEnumerable` instead of just arrays, including one that can deal with any type `T`: ``` public static string Join(string separator, IEnumerable<string> values) public static string Join<T>(string separator, IEnumerable<T> values) ```
Creating a comma separated list from IList<string> or IEnumerable<string>
[ "", "c#", "string", "" ]
I asked a general Spring question: [Auto-cast Spring Beans](https://stackoverflow.com/questions/812178/auto-cast-spring-beans) and had multiple people respond that calling Spring's `ApplicationContext.getBean()` should be avoided as much as possible. Why is that? How else should I gain access to the beans I configured Spring to create? I'm using Spring in a non-web application and had planned on accessing a shared `ApplicationContext` object [as described by LiorH](https://stackoverflow.com/questions/812178/auto-cast-spring-beans/812291#812291). **Amendment** I accept the answer below, but here's an alternate take by Martin Fowler who [discusses the merits of Dependency Injection vs. using a Service Locator](http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection) (which is essentially the same as calling a wrapped `ApplicationContext.getBean()`). In part, Fowler states, "*With service locator the application class asks for it [the service] explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control. Inversion of control is a common feature of frameworks, but it's something that comes at a price. It tends to be hard to understand and leads to problems when you are trying to debug. So on the whole I prefer to avoid it [Inversion of Control] unless I need it. This isn't to say it's a bad thing, just that I think it needs to justify itself over the more straightforward alternative.*"
I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have *none of your classes know or care how they get the objects they depend on*. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes *simpler* and more focused on their core responsibility. Calling `ApplicationContext.getBean()` is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container. Everywhere you want to say: ``` MyClass myClass = applicationContext.getBean("myClass"); ``` you should instead, for example, declare a method: ``` public void setMyClass(MyClass myClass) { this.myClass = myClass; } ``` And then in your configuration: ``` <bean id="myClass" class="MyClass">...</bean> <bean id="myOtherClass" class="MyOtherClass"> <property name="myClass" ref="myClass"/> </bean> ``` Spring will then automatically inject `myClass` into `myOtherClass`. Declare everything in this way, and at the root of it all have something like: ``` <bean id="myApplication" class="MyApplication"> <property name="myCentralClass" ref="myCentralClass"/> <property name="myOtherCentralClass" ref="myOtherCentralClass"/> </bean> ``` `MyApplication` is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your `main` method, you can call `applicationContext.getBean("myApplication")` but you should not need to call `getBean()` anywhere else!
Reasons to prefer Service Locator over Inversion of Control (IoC) are: 1. Service Locator is much, much easier for other people to following in your code. IoC is 'magic' but maintenance programmers must understand your convoluted Spring configurations and all the myriad of locations to figure out how you wired your objects. 2. IoC is terrible for debugging configuration problems. In certain classes of applications the application will not start when misconfigured and you may not get a chance to step through what is going on with a debugger. 3. IoC is primarily XML based (Annotations improve things but there is still a lot of XML out there). That means developers can't work on your program unless they know all the magic tags defined by Spring. It is not good enough to know Java anymore. This hinders less experience programmers (ie. it is actually poor design to use a more complicated solution when a simpler solution, such as Service Locator, will fulfill the same requirements). Plus, support for diagnosing XML problems is far weaker than support for Java problems. 4. Dependency injection is more suited to larger programs. Most of the time the additional complexity is not worth it. 5. Often Spring is used in case you "might want to change the implementation later". There are other ways of achieving this without the complexity of Spring IoC. 6. For web applications (Java EE WARs) the Spring context is effectively bound at compile time (unless you want operators to grub around the context in the exploded war). You can make Spring use property files, but with servlets property files will need to be at a pre-determined location, which means you can't deploy multiple servlets of the same time on the same box. You can use Spring with JNDI to change properties at servlet startup time, but if you are using JNDI for administrator-modifiable parameters the need for Spring itself lessens (since JNDI is effectively a Service Locator). 7. With Spring you can lose program Control if Spring is dispatching to your methods. This is convenient and works for many types of applications, but not all. You may need to control program flow when you need to create tasks (threads etc) during initialization or need modifiable resources that Spring didn't know about when the content was bound to your WAR. Spring is very good for transaction management and has some advantages. It is just that IoC can be over-engineering in many situations and introduce unwarranted complexity for maintainers. Do not automatically use IoC without thinking of ways of not using it first.
Why is Spring's ApplicationContext.getBean considered bad?
[ "", "java", "spring", "" ]
How can I rewrite the query "**select col1 from tbl1**" so it splits the results into three columns - each column sorting the results vertically? So if the data I'm getting back is: ``` aaa bbb ccc ddd eee fff ggg ``` I need the query to return it as: ``` aaa ddd ggg bbb eee ccc fff ``` Is this possible? Thanks
In truth, this should not be done in SQL. Unless the pairing of aaa, ddd, and ggg has some meaning then this is client-side formatting and shouldn't be done on the server. EDIT: In the interests of an intellectual exercise, something like this seems to work. ``` select f1.data, f2.data, f3. data from (select data, ROW_NUMBER() over (order by data) as row_num from your_table) f1 left join (select data, ROW_NUMBER() over (order by data) as row_num from your_table) f2 on f2.row_num = f1.row_num + (select CEILING(COUNT(1) / 3) + 1 from your_table) left join (select data, ROW_NUMBER() over (order by data) as row_num from your_table) f3 on f3.row_num = f1.row_num + (select CEILING(COUNT(1) / 3) + 1 from your_table) * 2 where f1.row_num between 1 and FLOOR((select COUNT(1) from your_table) / 3) + 1 ``` But, again, I suspect that this is really something that should be done client-side, NOT in SQL.
That seems like something that you should handle in the front end of your application. Unless there is a specific reason as to why you can't do that, I would suggest that you handle it there.
Return sql query results in separate columns sorted vertically
[ "", "sql", "sql-server", "t-sql", "" ]
I want a string of text to change color from default to #c30 when I click a button somewhere on the page, and it changes back to default when I click the button again. My code looks like this: ``` $("#button").click(function() { var anno = $(#text); if (anno.css('color') == '#c30') { anno.css('color', ''); } else { anno.css('color', '#c30'); } }); ``` But it doesn't seem to work on FF3. Works in IE though. Any idea?
I would try to separate the presentational details as much as possible, i.e. change the classes to which the element belongs, and leave the colour information in a separate stylesheet. ``` $("#button").click(function() { $("#text").toggleClass('somethingDescriptive'); }); ```
If you use named colors, this will work. ``` $("#button").click(function(){ $("#text").css('color', $("#text").css('color') == 'white' ? 'black' : 'white'); }); ``` Hex values do not. This is a bad way to do it anyways, I agree with the most voted up answer here. So I have updated my answer after some research. ``` <style type="text/css"> .color1 { color:#fff; } .color2 { color:#000; } </style> <script> $("#button").click(function(){ $("#text").toggleClass('color1').toggleClass('color2'); }); </script? <div class="color1">Text</div> ```
How to switch between 2 CSS colors with jQuery?
[ "", "javascript", "jquery", "" ]
If I am building a string using a StringBuilder object in a method, would it make sense to: Return the StringBuilder object, and let the calling code call ToString()? ``` return sb; ``` OR Return the string by calling ToString() myself. ``` return sb.ToString(); ``` I guess it make a difference if we're returning small, or large strings. What would be appropriate in each case? Thanks in advance. Edit: I don't plan on further modifying the string in the calling code, but good point Colin Burnett. Mainly, is it more efficient to return the StringBuilder object, or the string? Would a reference to the string get returned, or a copy?
Return the StringBuilder if you're going to further modify the string, otherwise return the string. This is an API question. Regarding efficiency. Since this is a vague/general question without any specifics then I think mutable vs. immutable is more important than performance. Mutability is an API issue of letting your API return modifiable objects. String length is irrelevant to this. That said. If you look at StringBuilder.ToString with Reflector: ``` public override string ToString() { string stringValue = this.m_StringValue; if (this.m_currentThread != Thread.InternalGetCurrentThread()) { return string.InternalCopy(stringValue); } if ((2 * stringValue.Length) < stringValue.ArrayLength) { return string.InternalCopy(stringValue); } stringValue.ClearPostNullChar(); this.m_currentThread = IntPtr.Zero; return stringValue; } ``` You can see it may make a copy but if you modify it with the StringBuilder then it will make a copy then (this is what I can tell the point of m\_currentThread is because Append checks this and will copy it if it mismatches the current thread). I guess the end of this is that if you do not modify the StringBuilder then you do not copy the string and length is irrelevant to efficiency (unless you hit that 2nd if). **UPDATE** System.String is a class which means it is a reference type (as opposed to value type) so "string foo;" is essentially a pointer. (When you pass a string into a method it passes the pointer, not a copy.) System.String is mutable inside mscorlib but immutable outside of it which is how StringBuilder can manipulate a string. So when ToString() is called it returns its internal string object by reference. At this point you cannot modify it because your code is not in mscorlib. By setting the m\_currentThread field to zero then any further operations on the StringBuilder will cause it to copy the string object so it can be modified **and** not modify the string object it returned in ToString(). Consider this: ``` StringBuilder sb = new StringBuilder(); sb.Append("Hello "); string foo = sb.ToString(); sb.Append("World"); string bar = sb.ToString(); ``` If StringBuilder did not make a copy then at the end foo would be "Hello World" because the StringBuilder modified it. But since it did make a copy then foo is still just "Hello " and bar is "Hello World". Does that clarify the whole return/reference thing?
I don't think performance should be a factor in this question. Either way someone is going to call sb.ToString() so your going to take the hit someplace. The more important question is what is the intention of the method and the purpose. If this method is part of a builder you might return the string builder. Otherwise I would return a string. If this is part of a public API I would lean towards returning a string instead of the builder.
String or StringBuilder return values?
[ "", "c#", "string", "return-value", "stringbuilder", "return-type", "" ]
I've recently run into a rather nasty bug, wherein the code was loading a `<select>` dynamically via JavaScript. This dynamically loaded `<select>` had a pre-selected value. In IE6, we already had code to fix the selected `<option>`, because sometimes the `<select>`'s `selectedIndex` value would be out of sync with the selected `<option>`'s `index` attribute, as below: ``` field.selectedIndex = element.index; ``` However, this code wasn't working. Even though the field's `selectedIndex` was being set correctly, the wrong index would end up being selected. However, if I stuck an `alert()` statement in at the right time, the correct option would be selected. Thinking this might be some sort of timing issue, I tried something random that I'd seen in code before: ``` var wrapFn = (function() { var myField = field; var myElement = element; return function() { myField.selectedIndex = myElement.index; } })(); setTimeout(wrapFn, 0); ``` And this worked! I've got a solution for my problem, but I'm uneasy that I don't know exactly why this fixes my problem. Does anyone have an official explanation? What browser issue am I avoiding by calling my function "later" using `setTimeout()`?
In the question, there existed a [race condition](https://en.wikipedia.org/wiki/Race_condition) between: 1. The browser's attempt to initialize the drop-down list, ready to have its selected index updated, and 2. Your code to set the selected index Your code was consistently winning this race and attempting to set drop-down selection before the browser was ready, meaning that the bug would appear. This race existed because JavaScript has a [single thread of execution](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop) that is shared with page rendering. In effect, running JavaScript blocks the updating of the DOM. Your workaround was: ``` setTimeout(callback, 0) ``` Invoking `setTimeout` with a callback, and zero as the second argument will schedule the callback to be run **asynchronously**, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy. The OP's solution, therefore was to delay by about 10ms, the setting of the selected index. This gave the browser an opportunity to initialize the DOM, fixing the bug. Every version of Internet Explorer exhibited quirky behaviors and this kind of workaround was necessary at times. Alternatively it might have been a genuine bug in the OP's codebase. --- See Philip Roberts talk ["What the heck is the event loop?"](https://www.youtube.com/watch?v=8aGhZQkoFbQ) for more thorough explanation.
***Preface:*** Some of the other answers are correct but don't actually illustrate what the problem being solved is, so I created this answer to present that detailed illustration. As such, I am posting a **detailed walk-through of what the browser does and how using `setTimeout()` helps**. It looks longish but is actually very simple and straightforward - I just made it very detailed. **UPDATE:** I have made a JSFiddle to live-demonstrate the explanation below: <http://jsfiddle.net/C2YBE/31/> . Many **thanks** to @ThangChung for helping to kickstart it. **UPDATE2:** Just in case JSFiddle web site dies, or deletes the code, I added the code to this answer at the very end. --- **DETAILS**: Imagine a web app with a "do something" button and a result div. The `onClick` handler for "do something" button calls a function "LongCalc()", which does 2 things: 1. Makes a very long calculation (say takes 3 min) 2. Prints the results of calculation into the result div. Now, your users start testing this, click "do something" button, and the page sits there doing seemingly nothing for 3 minutes, they get restless, click the button again, wait 1 min, nothing happens, click button again... The problem is obvious - you want a "Status" DIV, which shows what's going on. Let's see how that works. --- So you add a "Status" DIV (initially empty), and modify the `onclick` handler (function `LongCalc()`) to do 4 things: 1. Populate the status "Calculating... may take ~3 minutes" into status DIV 2. Makes a very long calculation (say takes 3 min) 3. Prints the results of calculation into the result div. 4. Populate the status "Calculation done" into status DIV And, you happily give the app to users to re-test. They come back to you looking very angry. And explain that when they clicked the button, **the Status DIV never got updated with "Calculating..." status!!!** --- You scratch your head, ask around on StackOverflow (or read docs or google), and realize the problem: The browser places all its "TODO" tasks (both UI tasks and JavaScript commands) resulting from events into a **single queue**. And unfortunately, re-drawing the "Status" DIV with the new "Calculating..." value is a separate TODO which goes to the end of the queue! Here's a breakdown of the events during your user's test, contents of the queue after each event: * Queue: `[Empty]` * Event: Click the button. Queue after event: `[Execute OnClick handler(lines 1-4)]` * Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: `[Execute OnClick handler(lines 2-4), re-draw Status DIV with new "Calculating" value]`. **Please note that while the DOM changes happen instantaneously, to re-draw the corresponding DOM element you need a new event, triggered by the DOM change, that went at the end of the queue**. * **PROBLEM!!!** **PROBLEM!!!** Details explained below. * Event: Execute second line in handler (calculation). Queue after: `[Execute OnClick handler(lines 3-4), re-draw Status DIV with "Calculating" value]`. * Event: Execute 3rd line in handler (populate result DIV). Queue after: `[Execute OnClick handler(line 4), re-draw Status DIV with "Calculating" value, re-draw result DIV with result]`. * Event: Execute 4th line in handler (populate status DIV with "DONE"). Queue: `[Execute OnClick handler, re-draw Status DIV with "Calculating" value, re-draw result DIV with result; re-draw Status DIV with "DONE" value]`. * Event: execute implied `return` from `onclick` handler sub. We take the "Execute OnClick handler" off the queue and start executing next item on the queue. * NOTE: Since we already finished the calculation, 3 minutes already passed for the user. **The re-draw event didn't happen yet!!!** * Event: re-draw Status DIV with "Calculating" value. We do the re-draw and take that off the queue. * Event: re-draw Result DIV with result value. We do the re-draw and take that off the queue. * Event: re-draw Status DIV with "Done" value. We do the re-draw and take that off the queue. Sharp-eyed viewers might even notice "Status DIV with "Calculating" value flashing for fraction of a microsecond - **AFTER THE CALCULATION FINISHED** So, the underlying problem is that the re-draw event for "Status" DIV is placed on the queue at the end, AFTER the "execute line 2" event which takes 3 minutes, so the actual re-draw doesn't happen until AFTER the calculation is done. --- To the rescue comes the `setTimeout()`. How does it help? Because by calling long-executing code via `setTimeout`, you actually create 2 events: `setTimeout` execution itself, and (due to 0 timeout), separate queue entry for the code being executed. So, to fix your problem, you modify your `onClick` handler to be TWO statements (in a new function or just a block within `onClick`): 1. Populate the status "Calculating... may take ~3 minutes" into status DIV 2. **Execute `setTimeout()` with 0 timeout and a call to `LongCalc()` function**. `LongCalc()` function is almost the same as last time but obviously doesn't have "Calculating..." status DIV update as first step; and instead starts the calculation right away. So, what does the event sequence and the queue look like now? * Queue: `[Empty]` * Event: Click the button. Queue after event: `[Execute OnClick handler(status update, setTimeout() call)]` * Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: `[Execute OnClick handler(which is a setTimeout call), re-draw Status DIV with new "Calculating" value]`. * Event: Execute second line in handler (setTimeout call). Queue after: `[re-draw Status DIV with "Calculating" value]`. The queue has nothing new in it for 0 more seconds. * Event: Alarm from the timeout goes off, 0 seconds later. Queue after: `[re-draw Status DIV with "Calculating" value, execute LongCalc (lines 1-3)]`. * Event: **re-draw Status DIV with "Calculating" value**. Queue after: `[execute LongCalc (lines 1-3)]`. Please note that this re-draw event might actually happen BEFORE the alarm goes off, which works just as well. * ... Hooray! The Status DIV just got updated to "Calculating..." before the calculation started!!! --- --- Below is the sample code from the JSFiddle illustrating these examples: <http://jsfiddle.net/C2YBE/31/> : **HTML code:** ``` <table border=1> <tr><td><button id='do'>Do long calc - bad status!</button></td> <td><div id='status'>Not Calculating yet.</div></td> </tr> <tr><td><button id='do_ok'>Do long calc - good status!</button></td> <td><div id='status_ok'>Not Calculating yet.</div></td> </tr> </table> ``` **JavaScript code: (Executed on `onDomReady` and may require jQuery 1.9)** ``` function long_running(status_div) { var result = 0; // Use 1000/700/300 limits in Chrome, // 300/100/100 in IE8, // 1000/500/200 in FireFox // I have no idea why identical runtimes fail on diff browsers. for (var i = 0; i < 1000; i++) { for (var j = 0; j < 700; j++) { for (var k = 0; k < 300; k++) { result = result + i + j + k; } } } $(status_div).text('calculation done'); } // Assign events to buttons $('#do').on('click', function () { $('#status').text('calculating....'); long_running('#status'); }); $('#do_ok').on('click', function () { $('#status_ok').text('calculating....'); // This works on IE8. Works in Chrome // Does NOT work in FireFox 25 with timeout =0 or =1 // DOES work in FF if you change timeout from 0 to 500 window.setTimeout(function (){ long_running('#status_ok') }, 0); }); ```
Why is setTimeout(fn, 0) sometimes useful?
[ "", "javascript", "dom", "event-loop", "" ]
is there a way to create my own custom superglobal variables like $\_POST and $\_GET?
Static class variables can be referenced globally, e.g.: ``` class myGlobals { static $myVariable; } function a() { print myGlobals::$myVariable; } ```
Yes, it is possible, but not with the so-called "core" PHP functionalities. You have to install an extension called [runkit7](https://www.php.net/manual/en/book.runkit7.php): [Installation](https://www.php.net/manual/en/runkit7.installation.php) After that, you can set your custom superglobals in php.ini as documented here: [ini.runkit.superglobal](https://www.php.net/manual/en/runkit7.configuration.php#ini.runkit.superglobal)
create superglobal variables in php?
[ "", "php", "" ]
I need to construct and send a zip to a user. I've seen examples doing one or the other, but not both, and am curious if there are any 'best practices' or anything. Sorry for the confusion. I'm going to generating the zip on the fly for the web user, and sending it to them in the HTTP response. Not in an email. Mark
I would second the vote for [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/) to create the Zip file. Then you'll want to append a response header to the output to force the download dialog. <http://aspalliance.com/259> should give you a good starting point to achieve that. You basically need to add a response header, set the content type and write the file to the output stream: ``` Response.AppendHeader( "content-disposition", "attachment; filename=" + name ); Response.ContentType = "application/zip"; Response.WriteFile(pathToFile); ``` That last line could be changed to a Response.Write(filecontents) if you don't want to save to a temp file.
[DotNetZip](http://dotnetzip.codeplex.com) lets you do this easily, without ever writing to a disk file on the server. You can write a zip archive directly out to the Response stream, which will cause the download dialog to pop on the browser. [Example ASP.NET code for DotNetZip](http://cheeso.members.winisp.net/DotNetZipHelp/Example-ASPNET.htm) [More example ASP.NET code for DotNetZip](http://code.msdn.microsoft.com/DotNetZip/Wiki/View.aspx?title=ASP.NET%20Example) snip: ``` Response.Clear(); Response.BufferOutput = false; // false = stream immediately System.Web.HttpContext c= System.Web.HttpContext.Current; String ReadmeText= String.Format("README.TXT\n\nHello!\n\n" + "This is text for a readme."); string archiveName= String.Format("archive-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + archiveName); using (ZipFile zip = new ZipFile()) { zip.AddFiles(f, "files"); zip.AddFileFromString("Readme.txt", "", ReadmeText); zip.Save(Response.OutputStream); } Response.Close(); ``` or in VB.NET: ``` Response.Clear Response.BufferOutput= false Dim ReadmeText As String= "README.TXT\n\nHello!\n\n" & _ "This is a zip file that was generated in ASP.NET" Dim archiveName as String= String.Format("archive-{0}.zip", _ DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")) Response.ContentType = "application/zip" Response.AddHeader("content-disposition", "filename=" + archiveName) Using zip as new ZipFile() zip.AddEntry("Readme.txt", "", ReadmeText, Encoding.Default) '' filesToInclude is a string[] or List<String> zip.AddFiles(filesToInclude, "files") zip.Save(Response.OutputStream) End Using Response.Close ```
How do I generate and send a .zip file to a user in C# ASP.NET?
[ "", "c#", "asp.net", "file", "zip", "" ]
When I first learned Python, I got used to doing this: ``` print "text", lineNumber, "some dictionary", my_dict ``` When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this: ``` def error(*args): print ERR_PREFIX, for _x in args: print _x, print "\r\n", error("text", lineNumber, "some dictionary", my_dict) ``` Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this: ``` error("text %d some dictionary %s" % (lineNumber, my_dict)) ``` Or, I could do something really silly like this: ``` error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict)))) ``` The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier? As a follow-up question, can you think of a way to override the Logger class to perform this?
I would suggest that it would be better to update the existing logging messages to the style that the logging module expects as it will be easier for other people looking at your code as the logging module will not longer function as they expect. That out of the way, the following code will make the logging module behave as you desire. ``` import logging import types class ExtendedLogRecord(logging.LogRecord): def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ if not hasattr(types, "UnicodeType"): #if no unicode support... msg = str(self.msg) else: try: msg = str(self.msg) except UnicodeError: msg = self.msg #Defer encoding till later if self.args: msg +=' '+' '.join(map(str,self.args)) return msg #Patch the logging default logging class logging.RootLogger.makeRecord=lambda self,*args: ExtendedLogRecord(*args) some_dict={'foo':14,'bar':15} logging.error('text',15,'some dictionary',some_dict) ``` Output: ``` ERROR:root:text 15 some dictionary {'foo': 14, 'bar': 15} ```
Patching the logging package (as one answer recommended) is actually a bad idea, because it means that *other* code (that you didn't write, e.g. stuff in the standard library) that calls logging.error() would no longer work correctly. Instead, you can change your existing error() function to call logging.error() instead or print: ``` def error(*args): logging.error('%s', ' '.join(map(str, args))) ``` (If there might be unicode objects you'd have to be a bit more careful, but you get the idea.)
Why does python logging package not support printing variable length args?
[ "", "python", "logging", "" ]
I have added above code in my WPF from which include animated GIF image, the problem is whenever form load I don't find any of the Image displayed on form, any suggestions ??? ``` <Image Name="imgScan" Source="Images\Pre_Scan_RealImage.gif" /> ``` I even tried Image element shown above
I fond UserControl [here](http://www.solidrockstable.com/blogs/PragmaticTSQL/Lists/Posts/Post.aspx?ID=37) for showing Animated GIFs, and guess what work just works as simple as Image control. And thank you all Here's the [same article](http://web.archive.org/web/20120413012735/http://www.solidrockstable.com/blogs/PragmaticTSQL/Lists/Posts/Post.aspx?ID=37) (web post captured by the Wayback Machine)
**Use XAML below** ``` <MediaElement Height="30" Width="30" LoadedBehavior="Play" Source="Images\loading.gif" /> ``` **Set properties of loading.gif** 1. **BuildAction** : None 2. **Copy to Output Directory** : Copy always It should work.
Animated GIF problem in WPF
[ "", "c#", "wpf", ".net-3.5", "" ]
Is they say that sun's java is opensource now - then can I compile all the patform from sources ? I used gentoo and I found a great performance inmrovement wnen I compiled the system myself, so can it be done with java (both vm runtime and library classes ) ? Is it possible to do under windows/linux ? Did anyone do it ? Does it make any sense ?
yes, that should be possible now -- and no, it will not give you any benefits unless you have a compiler that produces better byte code from the same source input. Given the simple nature of translating java to bytecode and the fact that most optimizations are done at runtime, that seems unlikely.
Yes you can. Prebuilt binaries, source code etc. are available in the OpenJDK project from Sun: <http://openjdk.java.net/> Whether it makes a difference to performance is hard to tell. It might, but usually the difference is not great.
Can I compile java myself?
[ "", "java", "performance", "" ]
I wrote a Java program to download a HTML page. But CPU usage is near to 100%, while network usage is lower than 3%. It seems like that CPU became my bottleneck. How do I cut my CPU usage?
Use a profiler (I like [VisualVM](https://visualvm.dev.java.net/)), identify the bottleneck and fix it!
If you have a continuous while loop, give your program some [sleep](http://java.sun.com/docs/books/tutorial/essential/concurrency/sleep.html) time between iterations. Downloading the web pages alone should not cause that much resource utilization though, you may want to look into a profiler to find out whats bottlenecking you. Perhaps posting the code here would let us help you a bit more.
Are there any suggestions about cutting CPU usage in Java?
[ "", "java", "cpu-usage", "" ]