source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
177,514 | I was hoping to implement a simple XMPP server in Java. What I need is a library which can parse and understand xmpp requests from a client. I have looked at Smack (mentioned below) and JSO. Smack appears to be client only so while it might help parsing packets it doesn't know how to respond to clients. Is JSO maintained it looks very old. The only promising avenue is to pull apart Openfire which is an entire commercial (OSS) XMPP server. I was just hoping for a few lines of code on top of Netty or Mina, so I could get started processing some messages off the wire. Joe - Well the answer to what I am trying to do is somewhat long - I'll try to keep it short. There are two things, that are only loosely related: 1) I wanted to write an XMPP server because I imagine writing a custom protocol for two clients to communicate. Basically I am thinking of a networked iPhone app - but I didn't want to rely on low-level binary protocols because using something like XMPP means the app can "grow up" very quickly from a local wifi based app to an internet based one... The msgs exchanged should be relatively low latency, so strictly speaking a binary protocol would be best, but I felt that it might be worth exploring if XMPP didn't introduce too much overhead such that I could use it and then reap benefits of it's extensability and flexability later. 2) I work for Terracotta - so I have this crazy bent to cluster everything. As soon as I started thinking about writing some custom server code, I figured I wanted to cluster it. Terracotta makes scaling out Java POJOs trivial, so my thought was to build a super simple XMPP server as a demonstration app for Terracotta. Basically each user would connect to the server over a TCP connection, which would register the user into a hashmap. Each user would have a LinkedBlockingQueue with a listener thread taking message from the queue. Then any connected user that wants to send a message to any other user (e.g. any old chat application) simply issues an XMPP message (as usual) to that user over the connection. The server picks it up, looks up the corresponding user object in a map and places the message onto the queue. Since the queue is clustered, regardless of wether the destination user is connected to the same physical server, or a different physical server, the message is delivered and the thread that is listening picks it up and sends it back down the destination user's tcp connection. So - not too short of a summary I'm afraid. But that's what I want to do. I suppose I could just write a plugin for Openfire to accomplish #1 but I think it takes care of a lot of plumbing so it's harder to do #2 (especially since I was hoping for a very small amount of code that could fit into a simple 10-20kb Maven project). | http://xmpp.org/xmpp-software/libraries/ has a list of software libraries for XMPP. Here is an outdated snapshot of it: ActionScript as3xmpp C iksemel libstrophe Loudmouth C++ gloox Iris oajabber C# / .NET / Mono agsXMPP SDK jabber-net Erlang Jabberlang Flash XIFF Haskell hsxmpp Java Echomine Feridian Jabber Stream Objects (JSO) Smack JavaScript strophe.js xmpp4js Lisp cl-xmpp Objective-C xmppframework Perl AnyEvent::XMPP PHP Lightr xmpphp Python jabber.py pyxmpp SleekXMPP Twisted Words xmpp-psn xmpppy Ruby XMPP4R Tcl JabberLib | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19013/"
]
} |
177,538 | Every time I need to do something N times inside an algorithm using C# I write this code for (int i = 0; i < N; i++){ ...} Studying Ruby I have learned about method times() which can be used with the same semantics like this N.times do ...end Code fragment in C# looks more complex and we should declare useless variable i . I tried to write extension method which returns IEnumerable , but I am not satisfied with the result because again I have to declare a cycle variable i . public static class IntExtender{ public static IEnumerable Times(this int times) { for (int i = 0; i < times; i++) yield return true; }}...foreach (var i in 5.Times()){ ...} Is it possible using some new C# 3.0 language features to make N times cycle more elegant? | A slightly briefer version of cvk's answer : public static class Extensions{ public static void Times(this int count, Action action) { for (int i=0; i < count; i++) { action(); } } public static void Times(this int count, Action<int> action) { for (int i=0; i < count; i++) { action(i); } }} Use: 5.Times(() => Console.WriteLine("Hi"));5.Times(i => Console.WriteLine("Index: {0}", i)); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
]
} |
177,569 | I have Eclipse 3.3.2 with PDT doing PHP development.All projects that I create, even SVN projects have code completion.Now I just opened another SVN project and it has no code completion or PHP templates (CTRL-space does nothing in that project).However, I can open the other projects and code completion all work in them. Why would code completion and templates be "off" in just one project and how can I turn it back on? | Maybe Eclipse doesn't understand the project has a "PHP nature".Try comparing the .project file on both projects to look for differences. It should contain something like: <natures> <nature>org.eclipse.php.core.PHPNature</nature> </natures> The .project file will be in your workspace under the project directories. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
} |
177,628 | What is the differences and similarities between Domain Specific Languages (DSL) and Domain Driven Design (DDD)? | Domain Driven Design (DDD) is a way of thinking and communicating about the problems and its solutions. Domain Specific Language (DSL) is a way of writing code. They're similar because they both start with the word "domain". That's it, I guess. :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11135/"
]
} |
177,673 | I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items. I'd like them to be able to define the ClientId on creation, but not edit, and this to be reflected in the UI. To this end, I have the following line: <%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new { @readonly = (ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 ? "readonly" : "false") } )%> It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive. Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required? | Tough problem... However, if you want to define only the readonly attribute, you can do it like this: <%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 ? new { @readonly = "readonly" } : null) %> If you want to define more attributes then you must define two anonymous types and have multiple copies of the attributes. For example, something like this (which I don't like anyway): ClientId.Length > 0 ? (object)new { @readonly = "readonly", @class = "myCSS" } : (object)new { @class = "myCSS" } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
]
} |
177,719 | I'm trying to get a case-insensitive search with two strings in JavaScript working. Normally it would be like this: var string="Stackoverflow is the BEST";var result= string.search(/best/i);alert(result); The /i flag would be for case-insensitive. But I need to search for a second string; without the flag it works perfect: var string="Stackoverflow is the BEST";var searchstring="best";var result= string.search(searchstring);alert(result); If I add the /i flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working): var string="Stackoverflow is the BEST";var searchstring="best";var result= string.search(/searchstring/i);alert(result); How can I achieve this? | Yeah, use .match , rather than .search . The result from the .match call will return the actual string that was matched itself, but it can still be used as a boolean value. var string = "Stackoverflow is the BEST";var result = string.match(/best/i);// result == 'BEST';if (result){ alert('Matched');} Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf like this: matchString = 'best';// If the match string is coming from user input you could do// matchString = userInput.toLowerCase() here.if (string.toLowerCase().indexOf(matchString) != -1){ alert('Matched');} | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/177719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25741/"
]
} |
177,752 | I'm migrating a TSQL stored procedure to PL/SQL and have encountered a problem - the lack of a CONTINUE keyword in Oracle 10g. I've read that Oracle 11g has this as a new feature, but upgrading is not an option unfortunately. Is there any alternative to CONTINUE in 10g? I don't believe it's practical to restructure the logic of the SP as a work-around, because I have an outer loop, an IF, then a nested IF, then the CONTINUE at the end of a statement block within that IF. Any help would be greatly appreciated, cheers. | You can simulate a continue using goto and labels . DECLARE done BOOLEAN;BEGIN FOR i IN 1..50 LOOP IF done THEN GOTO end_loop; END IF; <<end_loop>> -- not allowed unless an executable statement follows NULL; -- add NULL statement to avoid error END LOOP; -- raises an error without the previous NULLEND; | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827/"
]
} |
177,762 | Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work DECLARE @MyBoolean bit;SET @MyBoolean = 0;SET @MyBoolean = NOT @MyBoolean;SELECT @MyBoolean; Instead, I am getting more successful with DECLARE @MyBoolean bit;SET @MyBoolean = 0;SET @MyBoolean = 1 - @MyBoolean;SELECT @MyBoolean; Yet, this looks a bit a twisted way to express something as simple as a negation. Am I missing something? | Use the ~ operator: DECLARE @MyBoolean bitSET @MyBoolean = 0SET @MyBoolean = ~@MyBooleanSELECT @MyBoolean | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/177762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
]
} |
177,764 | I'm reading the book "The Software Architect's Profession" by Marc and Laura Sewell ( Amazon link ) and it got me wondering whether a software architect is a part of the old non-agile BDUF approach. Is there a place for software architects in an agile approach? I'm especially interested in Scrum. BTW I currently am the Unix Application Architect for a major company. cheers, Rob | My role as architect in Scrum includes the following. Technical spikes -- proofs of concept -- how will we do that. ("It would be simpler if you'd simply using the SMTP library directly, it already wraps the existing SMTP libraries; writing your own wrapper around our wrapper doesn't help much. We can add the method you want.") Coordination among the developers to fit the intended architecture. ("Ummm... why are you using your own properties file?" Working with users to prioritize the backlog appropriately. ("These three are related, if we do one, we get the other two at almost zero extra cost.") Working with managers to cost the backlog. (No, a project manager can't do this; they don't have the technical depth. No, the programmers can't do this, they don't have the overview.) Articulating why the package names are that way, and why the data model has those features. Finding the things we're missing and reprioritizing the backlog on technical grounds ("We're going to need this additional sprint to integrate [X], upgrade [Y] and replace [Z] or we'll never get those sprints done.") | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974/"
]
} |
177,778 | I am trying to set the background color for a double spin box, and I am not sure what function I should use. I saw some function called SetBackgroundRole which accepts a Qt::ColorRole , but I am not sure how to use this one as well. Kindly let me know, what's the simple way to change the background color of a QComboBox or QDoubleSpinBox ? | Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine. To make sure your background color will be correct, I would suggest to use the Qt Style Sheet . Here is what I did to change the background color of a QComboBox : myComboBox->setStyleSheet("QComboBox { background-color: blue; }"); I haven't specifically tried for a QSpinBox , but I guess it'll work the same ! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11212/"
]
} |
177,815 | I am changing a GET to a POST. Currently I have .jsp?id=a,b,c,d. When changing this to a post I am still sitting the id parameter a,b,c,d . This is not working for me. Can I submit a comma separated list to a post parameter? | Am I wrong or most of the answers are beside the point? To answer precisely your question, yes, you can submit a comma separated list to a POST parameter. To be honest, I just did a quick try with a PHP script, but I don't see why Java would behave differently. One point with POST requests is precisely that you have much less constraints on syntax (no need to escape = & or such). So if you explain more in details what "doesn't work", perhaps we can help you more. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
177,856 | I would like to be able to trap Ctrl + C in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this? | See MSDN: Console.CancelKeyPress Event Article with code samples: Ctrl-C and the .NET console application | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/177856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
]
} |
177,863 | I am using the next class (simplified for the sake of understandability) to download images in a struts web application. It is working fine in every browser but firefox, which cuts names containing spaces. That it is to say: file with spaces.pdf gets downloaded in firefox as: file while in chrome, IE7 IE6 is downloaded as file with spaces.pdf . public class Download extends Action { private static final int BUFFER_SIZE = 4096; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = "file with spaces.pdf"; File file = ... // variable containing the file; response.setStatus(HttpServletResponse.SC_OK); response.setContentType(getMimeType(request, file)); response.setHeader("Content-Type", getMimeType(request, file)); response.setHeader("Content-Disposition","attachment; filename="+ filename); InputStream is = new FileInputStream(file); sendFile(is, response); return null; } protected String getMimeType(HttpServletRequest request, File file) { ServletContext application = super.servlet.getServletContext(); return application.getMimeType(file.getName()); } protected void sendFile(InputStream is, HttpServletResponse response) throws IOException { BufferedInputStream in = null; try { int count; byte[] buffer = new byte[BUFFER_SIZE]; in = new BufferedInputStream(is); ServletOutputStream out = response.getOutputStream(); while(-1 != (count = in.read(buffer))) out.write(buffer, 0, count); out.flush(); } catch (IOException ioe) { System.err.println("IOException in Download::sendFile"); ioe.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } }} Does anyone know about what is going on here? Note i am using firefox 3.0.3 under Windows Vista. | The filename should be a quoted string. (According to Section 19.5.1 of RFC 2616 ) response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
177,867 | I need to copy data values from one element to another, but jQuery's clone() method doesn't clone the data. And I can't iterate over the data either: element.data().each because data() is a function and not a jQuery object. It seems I have to keep a separate list of attribute names and reference those but that seems too hacky. So how can I do either of these: a) Iterate over data items OR b) clone() an element with its data. | To really only copy the data-*, this is quite straightforward: $(destination).data( $(source).data() ); This is because using .data() no arguments will return a key-value object of all pieces of data and vice versa you can also update multiple pieces data at once using a key-value object. UPDATE 25th May 2017 A clever alternative in JavaScript without jQuery appears to be: Object.assign(destination.dataset, source.dataset); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896/"
]
} |
177,883 | is it possible to include a servlet in a jsp page? if so how? | To really only copy the data-*, this is quite straightforward: $(destination).data( $(source).data() ); This is because using .data() no arguments will return a key-value object of all pieces of data and vice versa you can also update multiple pieces data at once using a key-value object. UPDATE 25th May 2017 A clever alternative in JavaScript without jQuery appears to be: Object.assign(destination.dataset, source.dataset); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24481/"
]
} |
177,901 | LAMP is a well-known acronym for the software/technology bundle/stack representing Linux , Apache , MySQL , PHP . There are a few passing references on the Web that use the acronym WISC to speak of the other (supposedly Microsoft-centric) software/technology bundle/stack in contrast to LAMP. There is, however, no Wikipedia entry on WISC at this time nor any relevant results from googling . Does the following seem like the right de-composition of the WISC acronym? W = Windows I = Internet Information Services (IIS) S = SQL Server C = C# If yes, is there a Web reference that coins the WISC acronym? If no, is there another acronym used to represent the Microsoft-centric stack when comparing with LAMP? P.S. First sighting of WISC at “ ASP.NET Caching vs. memcached: Seeking Efficient Data Partitioning, Lookup, and Retrieval ”. | Or WISA:Windows, IIS, SQL Server, ASP.net I don't know why anyone would want to call it WISC, as these people are essentially saying "We will never ever use VB.NET, IronPython, IronRuby, F# or any other .NET Language". Also calling it .NET (WISN) sounds a bit weird as well, since ASP.NET is the Web-Technology of .NET. But well, that's the good things about acronyms and standard. Everyone has its own. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6682/"
]
} |
177,945 | I would like to create XML Schema for this chunk of xml, I would like to restrict the values of "name" attribute, so that in output document on and only one instance of day is allowed for each week day: <a> <day name="monday" /> <day name="tuesday" /> <day name="wednesday" /></a> I have tried to use this: <xs:complexType name="a"> <xs:sequence> <xs:element name="day" minOccurs="1" maxOccurs="1"> <xs:complexType> <xs:attribute name="name" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="monday" /> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:element> <xs:element name="day" minOccurs="1" maxOccurs="1"> <xs:complexType> <xs:attribute name="name" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="tuesday" /> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:element> </xs:sequence></xs:complexType> but XML Schema validator in eclipse says error "Multiple elements with name 'day', with different types, appear in the model group.". Is there any other way? | You need something like this: <?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="day"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="day"> <xs:complexType> <xs:attribute name="name" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="monday"/> <xs:enumeration value="tuesday"/> <xs:enumeration value="wednesday"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:element></xs:schema> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/177945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10560/"
]
} |
177,956 | What is the best way to convert an int or null to boolean value in an SQL query, such that: Any non-null value is TRUE in the results Any null value is FALSE in the results | To my knowledge (correct me if I'm wrong), there is no concept of literal boolean values in SQL. You can have expressions evaluating to boolean values, but you cannot output them. This said, you can use CASE WHEN to produce a value you can use in a comparison: SELECT CASE WHEN ValueColumn IS NULL THEN 'FALSE' ELSE 'TRUE' END BooleanOutput FROM table | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/177956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
]
} |
177,970 | I need a select from table which does not have column that tells when row was inserted, only timestamp column (values like: 0x0000000000530278). Some data was imported to the table yesterday and now I need to find out what exactly was imported :( Is there a way to do it using only timestamp info? Here I found that: Timestamp is a 8 bytes sequential Hex number, that has nothing to do with neither the date nor the time. To get the current value of timestamp, use: @@DBTS. Perhaps there is a way to find what was timestamp value around specific time? That would help to form a select. Or maybe there is a well known solution? | The Transact-SQL timestamp data type is a binary data type with no time-related values. So to answer your question: Is there a way to get DateTime value from timestamp type column? The answer is: No | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23436/"
]
} |
177,974 | How can I test sending email from my application without flooding my inbox? Is there a way to tell IIS/ASP.NET how to deliver email to a local folder for inspection? | Yes there is a way. You can alter web.config like this so that when you send email it will instead be created as an .EML file in c:\LocalDir. <configuration> <system.net> <mailSettings> <smtp deliveryMethod="SpecifiedPickupDirectory"> <specifiedPickupDirectory pickupDirectoryLocation="c:\LocalDir"/> </smtp> </mailSettings> </system.net> </configuration> You can also create an instance of the SmtpClient class with these same settings, if you don't want to/can't change the web.config. In C# that looks something like this: var smtpClient = new SmtpClient();smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;var emailPickupDirectory = HostingEnvironment.MapPath("~/EmailPickup");if (!Directory.Exists(emailPickupDirectory)) { Directory.CreateDirectory(emailPickupDirectory)}smtpClient.PickupDirectoryLocation = emailPickupDirectory; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/177974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
]
} |
178,026 | We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException. Is there a reason why "null" has even been included in the language? After all, if there were no "null", I would have no bug, right? In other words, what feature in the language couldn't work without null? | Anders Hejlsberg, "C# father", just spoke about that point in his Computerworld interview : For example, in the type system we do not have separation between value and reference types and nullability of types. This may sound a little wonky or a little technical, but in C# reference types can be null, such as strings, but value types cannot be null. It sure would be nice to have had non-nullable reference types, so you could declare that ‘this string can never be null, and I want you compiler to check that I can never hit a null pointer here’. 50% of the bugs that people run into today, coding with C# in our platform, and the same is true of Java for that matter, are probably null reference exceptions. If we had had a stronger type system that would allow you to say that ‘this parameter may never be null, and you compiler please check that at every call, by doing static analysis of the code’. Then we could have stamped out classes of bugs. Cyrus Najmabadi, a former software design engineer on the C# team (now working at Google) discuss on that subject on his blog: ( 1st , 2nd , 3rd , 4th ).It seems that the biggest hindrance to the adoption of non-nullable types is that notation would disturb programmers’ habits and code base. Something like 70% of references of C# programs are likely to end-up as non-nullable ones. If you really want to have non-nullable reference type in C# you should try to use Spec# which is a C# extension that allow the use of "!" as a non-nullable sign. static string AcceptNotNullObject(object! s){ return s.ToString();} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25781/"
]
} |
178,128 | Let's say I have to implement a piece of T-SQL code that must return a table as result. I can implement a table-valued function or else a stored procedure that returns a set of rows. What should I use? In short, what I want to know is: Which are the main differences between functions and stored procedures? What considerations do I have to take into account for using one or the other? | If you're likely to want to combine the result of this piece of code with other tables, then obviously a table-valued function will allow you to compose the results in a single SELECT statement. Generally, there's a hierarchy (View < TV Function < Stored Proc). You can do more in each one, but the ability to compose the outputs, and for the optimizer to get really involved decreases as the functionality increases. So use whichever one minimally allows you to express your desired result. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
]
} |
178,138 | I fear this is probably a bit of a dummy question, but it has me pretty stumped. I'm looking for the simplest way possible to pass a method of an object into a procedure, so that the procedure can call the object's method (e.g. after a timeout, or maybe in a different thread). So basically I want to: Capture a reference to an object's method. Pass that reference to a procedure. Using that reference, call the object's method from the procedure. I figure I could achieve the same effect using interfaces, but I thought there was another way, since this "procedure of object" type declaration exists. The following doesn't work, but might it help explain where I'm confused...? interface TCallbackMethod = procedure of object; TCallbackObject = class procedure CallbackMethodImpl; procedure SetupCallback; end;implementationprocedure CallbackTheCallback(const callbackMethod: TCallbackMethod);begin callbackMethod();end;procedure TCallbackObject.CallbackMethodImpl;begin // Do whatever.end;procedure TCallbackObject.SetupCallback;begin // following line doesn't compile - it fails with "E2036 Variable required" CallbackTheCallback(@self.CallbackMethodImpl);end; (Once the question is answered I'll remove the above code unless it aids the explanation somehow.) | Just remove the Pointer stuff. Delphi will do it for you: procedure TCallbackObject.SetupCallback;begin CallbackTheCallback(CallbackMethodImpl);end; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961/"
]
} |
178,147 | I have an application in C# (2.0 running on XP embedded) that is communicating with a 'watchdog' that is implemented as a Windows Service. When the device boots, this service typically takes some time to start. I'd like to check, from my code, if the service is running. How can I accomplish this? | I guess something like this would work: Add System.ServiceProcess to your project references (It's on the .NET tab). using System.ServiceProcess;ServiceController sc = new ServiceController(SERVICENAME);switch (sc.Status){ case ServiceControllerStatus.Running: return "Running"; case ServiceControllerStatus.Stopped: return "Stopped"; case ServiceControllerStatus.Paused: return "Paused"; case ServiceControllerStatus.StopPending: return "Stopping"; case ServiceControllerStatus.StartPending: return "Starting"; default: return "Status Changing";} Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs. Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first. Reference: ServiceController object in .NET. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/178147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
]
} |
178,199 | In PHP I can name my array indices so that I may have something like: $shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'), 1 => Array('id' => 2, 'name' => 'Dora The Explorer')); Is this possible in Python? | This sounds like the PHP array using named indices is very similar to a python dict: shows = [ {"id": 1, "name": "Sesaeme Street"}, {"id": 2, "name": "Dora The Explorer"},] See http://docs.python.org/tutorial/datastructures.html#dictionaries for more on this. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
178,215 | We are using log4j behind a selfmade wrapper. We plan to use much more features of it now. Should we update to logback ? (I mean the framework not a facade like SLF4J) | Logback natively implements the SLF4J API. This means that if you are using logback, you are actually using the SLF4J API. You could theoretically use the internals of the logback API directly for logging, but that is highly discouraged. All logback documentation and examples on loggers are written in terms of the SLF4J API. So by using logback, you'd be actually using SLF4J and if for any reason you wanted to switch back to log4j, you could do so within minutes by simply dropping slf4j-log4j12.jar onto your class path. When migrating from logback to log4j, logback specific parts, specifically those contained in logback.xml configuration file would still need to be migrated to its log4j equivalent, i.e. log4j.properties . When migrating in the other direction, log4j configuration, i.e. log4j.properties , would need to be converted to its logback equivalent. There is an on-line tool for that. The amount of work involved in migrating configuration files is much less than the work required to migrate logger calls disseminated throughout all your software's source code and its dependencies. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
178,247 | I have minified my javascript and my css. Now, Which is better? <script type="text/javascript"><? $r = file_get_contents('min.js'); if($r) echo $r;?></script> OR <script type="text/javascript" src="min.js"></script> Same question for CSS. If the answer is 'sometimes because browsers fetch files simultaneously?' Which browsers, and what are examples of the times in either scenario. | <script type="text/javascript" src="min.js"></script> ...is better, as the user's browser can cache the file. Adding a parameter to the src such as the file's last modified timestamp is even better, as the user's browser will cache the file but will always retrieve the most up to date version when the file is modified. <script type="text/javascript" src="min.js?version=20081007134916"></script> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
]
} |
178,257 | Huge files take forever to load and work with in vim, due to syntax-highlighting. I'm looking for a way to limit size of highlighted files, such that files larger than (say) 10MB will be colorless. | Adding the following line to _vimrc does the trick, with a bonus: it handles gzipped files, too (which is a common case with huge files): autocmd BufWinEnter * if line2byte(line("$") + 1) > 1000000 | syntax clear | endif | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6984/"
]
} |
178,263 | I am testing a web app that writes cookies to subdomain.thisdomain.com and several subfolders within that. I'm looking for JavaScript that I can put into a bookmarklet that will delete all cookies under that subdomain, regardless of the folder in which they exist. Any ideas? | Derived from my answer here : javascript:new function(){var c=document.cookie.split(";");for(var i=0;i<c.length;i++){var e=c[i].indexOf("=");var n=e>-1?c[i].substr(0,e):c[i];document.cookie=n+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";}}(); return void(0); Due to browser security issues, this will only work when executed while on a page that has access to all the cookies you want to delete. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335036/"
]
} |
178,265 | Today at work we came across the following code (some of you might recognize it): #define GET_VAL( val, type ) \ { \ ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); \ val = ( *((type *&)(pIP))++ ); \ } Basically we have a byte array and a pointer. The macro returns a reference to a variable of type and advance the pointer to the end of that variable. It reminded me of the several times that I needed to "think like a parser" in order to understand C++ code. Do you know of other code examples that caused you to stop and read it several times till you managed to grasp what it was suppose to do? | The inverse square root implementation in Quake 3: float InvSqrt (float x){ float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x;} Update: How this works (thanks ryan_s) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361/"
]
} |
178,320 | When you're passing variables through your site using GET requests, do you validate (regular expressions, filters, etc.) them before you use them? Say you have the URL http://www.example.com/i=45&p=custform . You know that "i" will always be an integer and "p" will always contain only letters and/or numbers. Is it worth the time to make sure that no one has attempted to manipulate the values and then resubmit the page? | Yes. Without a doubt. Never trust user input. To improve the user experience, input fields can (and IMHO should) be validated on the client. This can pre-empt a round trip to the server that only leads to the same form and an error message. However, input must always be validated on the server side since the user can just change the input data manually in the GET url or send crafted POST data. In a worst case scenario you can end up with an SQL injection , or even worse, a XSS vulnerability. Most frameworks already have some builtin way to clean the input, but even without this it's usually very easy to clean the input using a combination of regular exceptions and lookup tables. Say you know it's an integer, use int.Parse or match it against the regex "^\d+$". If it's a string and the choices are limited, make a dictionary and run the string through it. If you don't get a match change the string to a default. If it's a user specified string, match it against a strict regex like "^\w+$" | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444511/"
]
} |
178,325 | How do I toggle the visibility of an element using .hide() , .show() , or .toggle() ? How do I test if an element is visible or hidden ? | Since the question refers to a single element, this code might be more suitable: // Checks CSS content for display:[none|block], ignores visibility:[true|false]$(element).is(":visible");// The same works with hidden$(element).is(":hidden"); It is the same as twernt's suggestion , but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ . We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false. | {
"score": 14,
"source": [
"https://Stackoverflow.com/questions/178325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
]
} |
178,326 | I have an MFC app which I have been working on for a few weeks now, I want to manually set the dimensions of the main frame when it is loaded, can someone give me a hand with this, specifically where to put the code as well? Thanks! | You can also set the size (with SetWindowPos() ) from within CMainFrame::OnCreate() , or in the CWinApp -derived class' InitInstance . Look for the line that says pMainFrame->ShowWindow() , and call pMainFrame->SetWindowPos() before that line. That's where I always do it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
]
} |
178,328 | In PHP, function parameters can be passed by reference by prepending an ampersand to the parameter in the function declaration, like so: function foo(&$bar){ // ...} Now, I am aware that this is not designed to improve performance, but to allow functions to change variables that are normally out of their scope. Instead, PHP seems to use Copy On Write to avoid copying objects (and maybe also arrays) until they are changed. So, for functions that do not change their parameters, the effect should be the same as if you had passed them by reference. However, I was wondering if the Copy On Write logic maybe is shortcircuited on pass-by-reference and whether that has any performance impact. ETA: To be sure, I assume that it's not faster, and I am well aware that this is not what references are for. So I think my own guesses are quite good, I'm just looking for an answer from someone who really knows what's definitely happening under the hood. In five years of PHP development, I've always found it hard to get quality information on PHP internals short from reading the source. | In a test with 100 000 iterations of calling a function with a string of 20 kB, the results are: Function that just reads / uses the parameter pass by value: 0.12065005 secondspass by reference: 1.52171397 seconds Function to write / change the parameter pass by value: 1.52223396 secondspass by reference: 1.52388787 seconds Conclusions Pass the parameter by value is always faster If the function change the value of the variable passed, for practical purposes is the same as pass by reference than by value | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
178,333 | Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability. For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that: public interface IFirst { void FirstMethod(); }public interface ISecond { void SecondMethod(); }public class First:IFirst { public void FirstMethod() { Console.WriteLine("First"); } }public class Second:ISecond { public void SecondMethod() { Console.WriteLine("Second"); } }public class FirstAndSecond: IFirst, ISecond{ First first = new First(); Second second = new Second(); public void FirstMethod() { first.FirstMethod(); } public void SecondMethod() { second.SecondMethod(); }} Every time I add a method to one of the interfaces I need to change the class FirstAndSecond as well. Is there a way to inject multiple existing classes into one new class like it is possible in C++? Maybe there is a solution using some kind of code generation? Or it may look like this (imaginary c# syntax): public class FirstAndSecond: IFirst from First, ISecond from Second{ } So that there won't be a need to update the class FirstAndSecond when I modify one of the interfaces. EDIT Maybe it would be better to consider a practical example: You have an existing class (e.g. a text based TCP client based on ITextTcpClient) which you do already use at different locations inside your project. Now you feel the need to create a component of your class to be easy accessible for windows forms developers. As far as I know you currently have two ways to do this: Write a new class that is inherited from components and implements the interface of the TextTcpClient class using an instance of the class itself as shown with FirstAndSecond. Write a new class that inherits from TextTcpClient and somehow implements IComponent (haven't actually tried this yet). In both cases you need to do work per method and not per class. Since you know that we will need all the methods of TextTcpClient and Component it would be the easiest solution to just combine those two into one class. To avoid conflicts this may be done by code generation where the result could be altered afterwards but typing this by hand is a pure pain in the ass. | Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel , IBrakable implies a property of type BrakePedal , etc. Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg: public interface ISteerable { SteeringWheel wheel { get; set; } }public interface IBrakable { BrakePedal brake { get; set; } }public class Vehicle : ISteerable, IBrakable{ public SteeringWheel wheel { get; set; } public BrakePedal brake { get; set; } public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }}public static class SteeringExtensions{ public static void SteerLeft(this ISteerable vehicle) { vehicle.wheel.SteerLeft(); }}public static class BrakeExtensions{ public static void Stop(this IBrakable vehicle) { vehicle.brake.ApplyUntilStop(); }}public class Main{ Vehicle myCar = new Vehicle(); public void main() { myCar.SteerLeft(); myCar.Stop(); }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
]
} |
178,342 | I need to edit the web.config file on a live Sharepoint environment, but I'm unsure what will happen if I do (I want to output custom errors). Will this cause the IIS6 worker process to recycle? Will active users lose their session state because of this? Or can I safely edit the file? | The application pool will restart and session state will be lost. Imagine each ASP.NET application (as defined in IIS) is a program on the desktop. Saving web.config will do something similar to closing the program and reopening it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22702/"
]
} |
178,396 | OK, another road bump in my current project. I have never had form elements in both my master and content pages, I tend to have all the forms in the content where relevant. In the current project however, we have a page where they want both. A login form at the top right, and a questions form in the content. Having tried to get this in, I have run in to the issue of ASP.NET moaning about the need for a single form element in a master page. TBH, I really dont get why this is a requirement on ASP.NET's part, but hey ho. Does anyone know if/how I can get the master and content pages to contain form elements that work independantly? If not, can you offer advice on how to proceed to get the desired look/functionality? | Thought I would review some of my outstanding questions and see if I can close some of them off. This one was an interesting one. I outright refused to believe you can only have one form on an ASP.NET page. This to me made no sense. I have seen plenty of webpages that have more than one form on a web page, why should an ASP.NET page be any different? So, it got me thinking. Why does a ASP.NET page need a form element? ASP.NET pages try to emulate the WinForms environment, by provided state persistance through the PostBack model. This provides an element of state to a stateless environment. In order to do this, the runtime needs to be able to have the ability to maintain this state within each "form". It does this by posting back data to itself. It's important to note that: There is nothing really fancy about a PostBack. It uses a HTTP form and POST, the same as any other form, from any other stack. Just because it looks like it might be doing something special, its not, all that happens is it POST's back with some info about what caused it, so you can do things like handle client-side events, in server-side code. So why only one? This to me was the million pound question (I am British). I understand that ASP.NET needs this, especially if you are using ASP.NET server controls, but why the hell can't I make my own additional forms? So, I thought screw it, just make your own form! And I did. I added a bog-standard, simple form with a submit action of "#". This then performs a POST to the current page, with the Form data for the given form in the request. Guess what? It all worked fine. So I ended up with: A master page, with a HTML form in This form posts back to the current page (basically the page using the master). In the Page_Load code-behind for the master, I then added code to check the request to see what data was passed in the request. If it contains data (say a hidden field) then I know the post was sourced from the Form on the master page, if not, then it is most liekly a PostBack from content, and can be ignored. I then surrounded the Content tags with <form runat="server" id="aspNetForm"...> </form> tags. This meant that all content pages automatically had a form to work with. This provided me with a relatively simple, clean solution to my problem. My login form works fine in tandem with all the content forms created, some of which are complex forms, others use lots of server controls and many PostBacks, and so on. I hope this helps others. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
]
} |
178,407 | Say I have the following: <ul> <li>First item</li> <li>Second item</li> <li>Third item</li></ul> How would I select all the child elements after the first one using jQuery? So I can achieve something like: <ul> <li>First item</li> <li class="something">Second item</li> <li class="something">Third item</li></ul> | You should be able to use the "not" and "first child" selectors. $("li:not(:first-child)").addClass("something"); http://docs.jquery.com/Selectors/not http://docs.jquery.com/Selectors/firstChild | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
]
} |
178,434 | Objective-C has no namespaces; it's much like C, everything is within one global namespace. Common practice is to prefix classes with initials, e.g. if you are working at IBM, you could prefix them with "IBM"; if you work for Microsoft, you could use "MS"; and so on. Sometimes the initials refer to the project, e.g. Adium prefixes classes with "AI" (as there is no company behind it of that you could take the initials). Apple prefixes classes with NS and says this prefix is reserved for Apple only. So far so well. But appending 2 to 4 letters to a class name in front is a very, very limited namespace. E.g. MS or AI could have an entirely different meanings (AI could be Artificial Intelligence for example) and some other developer might decide to use them and create an equally named class. Bang , namespace collision. Okay, if this is a collision between one of your own classes and one of an external framework you are using, you can easily change the naming of your class, no big deal. But what if you use two external frameworks, both frameworks that you don't have the source to and that you can't change? Your application links with both of them and you get name conflicts. How would you go about solving these? What is the best way to work around them in such a way that you can still use both classes? In C you can work around these by not linking directly to the library, instead you load the library at runtime, using dlopen(), then find the symbol you are looking for using dlsym() and assign it to a global symbol (that you can name any way you like) and then access it through this global symbol. E.g. if you have a conflict because some C library has a function named open(), you could define a variable named myOpen and have it point to the open() function of the library, thus when you want to use the system open(), you just use open() and when you want to use the other one, you access it via the myOpen identifier. Is something similar possible in Objective-C and if not, is there any other clever, tricky solution you can use resolve namespace conflicts? Any ideas? Update: Just to clarify this: answers that suggest how to avoid namespace collisions in advance or how to create a better namespace are certainly welcome; however, I will not accept them as the answer since they don't solve my problem. I have two libraries and their class names collide. I can't change them; I don't have the source of either one. The collision is already there and tips on how it could have been avoided in advance won't help anymore. I can forward them to the developers of these frameworks and hope they choose a better namespace in the future, but for the time being I'm searching a solution to work with the frameworks right now within a single application. Any solutions to make this possible? | Prefixing your classes with a unique prefix is fundamentally the only option but there are several ways to make this less onerous and ugly. There is a long discussion of options here . My favorite is the @compatibility_alias Objective-C compiler directive (described here ). You can use @compatibility_alias to "rename" a class, allowing you to name your class using FQDN or some such prefix: @interface COM_WHATEVER_ClassName : NSObject@end@compatibility_alias ClassName COM_WHATEVER_ClassName// now ClassName is an alias for COM_WHATEVER_ClassName@implementation ClassName //OK//blah@endClassName *myClass; //OK As part of a complete strategy, you could prefix all your classes with a unique prefix such as the FQDN and then create a header with all the @compatibility_alias (I would imagine you could auto-generate said header). The downside of prefixing like this is that you have to enter the true class name (e.g. COM_WHATEVER_ClassName above) in anything that needs the class name from a string besides the compiler. Notably, @compatibility_alias is a compiler directive, not a runtime function so NSClassFromString(ClassName) will fail (return nil )--you'll have to use NSClassFromString(COM_WHATERVER_ClassName) . You can use ibtool via build phase to modify class names in an Interface Builder nib/xib so that you don't have to write the full COM_WHATEVER_... in Interface Builder. Final caveat: because this is a compiler directive (and an obscure one at that), it may not be portable across compilers. In particular, I don't know if it works with the Clang frontend from the LLVM project, though it should work with LLVM-GCC (LLVM using the GCC frontend). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15809/"
]
} |
178,456 | Is it better to do this: try{ ...}catch (Exception ex){ ... throw;} Or this: try{ ...}catch (Exception ex){ ... throw ex;} Do they do the same thing? Is one better than the other? | You should always use the following syntax to rethrow an exception. Else you'll stomp the stack trace: throw; If you print the trace resulting from throw ex , you'll see that it ends on that statement and not at the real source of the exception. Basically, it should be deemed a criminal offense to use throw ex . If there is a need to rethrow an exception that comes from somewhere else (AggregateException, TargetInvocationException) or perhaps another thread, you also shouldn't rethrow it directly. Rather there is the ExceptionDispatchInfo that preserves all the necessary information. try{ methodInfo.Invoke(...);}catch (System.Reflection.TargetInvocationException e){ System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); throw; // just to inform the compiler that the flow never leaves the block} | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/178456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
]
} |
178,479 | What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement , which is not supported for multiple values due to SQL injection attack security issues: One ? placeholder represents one value, rather than a list of values. Consider the following SQL statement: SELECT my_column FROM my_table where search_column IN (?) Using preparedStatement.setString( 1, "'A', 'B', 'C'" ); is essentially a non-working attempt at a workaround of the reasons for using ? in the first place. What workarounds are available? | An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's Batching Select Statements in JDBC entry on JavaRanch Journal. The suggested options are: Prepare SELECT my_column FROM my_table WHERE search_column = ? , execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful. Prepare SELECT my_column FROM my_table WHERE search_column IN (?,?,?) and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious. Prepare SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ... and execute it. [Or use UNION ALL in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than WHERE search_column IN (?,?,?) , so I don't know why the blogger even suggested it. Use a stored procedure to construct the result set. Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6) . Any decent server will optimize out the duplicate values before running the query. None of these options are ideal. The best option if you are using JDBC4 and a server that supports x = ANY(y) , is to use PreparedStatement.setArray as described in Boris's anwser . There doesn't seem to be any way to make setArray work with IN-lists, though. Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query: query=SELECT * FROM table t WHERE t.column IN (?) Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run: sql = any( sql, count ); For example: /** * Converts a SQL statement containing exactly one IN clause to an IN clause * using multiple comma-delimited parameters. * * @param sql The SQL statement string with one IN clause. * @param params The number of parameters the SQL statement requires. * @return The SQL statement with (?) replaced with multiple parameter * placeholders. */public static String any(String sql, final int params) { // Create a comma-delimited list based on the number of parameters. final StringBuilder sb = new StringBuilder( String.join(", ", Collections.nCopies(possibleValue.size(), "?"))); // For more than 1 parameter, replace the single parameter with // multiple parameter placeholders. if (sb.length() > 1) { sql = sql.replace("(?)", "(" + sb + ")"); } // Return the modified comma-delimited list of parameters. return sql;} For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow = ? into the faster IN (?) clause condition, which can then be expanded by calling the any method. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/178479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15816/"
]
} |
178,482 | For a school project, I need to create a way to create personnalized queries based on end-user choices. Since the user can choose basically any fields from any combination of tables, I need to find a way to map the tables in order to make a join and not have extraneous data (This may lead to incoherent reports, but we're willing to live with that). For up to two tables, I already managed to design an algorithm that works fine. However, when I add another table, I can't find a way to path through my database. All tables available for the personnalized reports can be linked together so it really all falls down to finding which path to use. | An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's Batching Select Statements in JDBC entry on JavaRanch Journal. The suggested options are: Prepare SELECT my_column FROM my_table WHERE search_column = ? , execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful. Prepare SELECT my_column FROM my_table WHERE search_column IN (?,?,?) and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious. Prepare SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ... and execute it. [Or use UNION ALL in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than WHERE search_column IN (?,?,?) , so I don't know why the blogger even suggested it. Use a stored procedure to construct the result set. Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6) . Any decent server will optimize out the duplicate values before running the query. None of these options are ideal. The best option if you are using JDBC4 and a server that supports x = ANY(y) , is to use PreparedStatement.setArray as described in Boris's anwser . There doesn't seem to be any way to make setArray work with IN-lists, though. Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query: query=SELECT * FROM table t WHERE t.column IN (?) Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run: sql = any( sql, count ); For example: /** * Converts a SQL statement containing exactly one IN clause to an IN clause * using multiple comma-delimited parameters. * * @param sql The SQL statement string with one IN clause. * @param params The number of parameters the SQL statement requires. * @return The SQL statement with (?) replaced with multiple parameter * placeholders. */public static String any(String sql, final int params) { // Create a comma-delimited list based on the number of parameters. final StringBuilder sb = new StringBuilder( String.join(", ", Collections.nCopies(possibleValue.size(), "?"))); // For more than 1 parameter, replace the single parameter with // multiple parameter placeholders. if (sb.length() > 1) { sql = sql.replace("(?)", "(" + sb + ")"); } // Return the modified comma-delimited list of parameters. return sql;} For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow = ? into the faster IN (?) clause condition, which can then be expanded by calling the any method. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/178482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25818/"
]
} |
178,519 | I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue? | I usually put separate folders at the root level, so I end up with a directory structure like this: /system/css/js/img Seems to work for me - when you use site_url(url) , the URL it generates is from the root, so you can use site_url('css/file.css') to generate URLs to your stylesheets etc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
} |
178,524 | I recently read this Phil Haack post ( The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse ) from last year, and thought I'd see if anyone has any additions to the list. | People tend to use the following which is ugly and bound to fail: string path = basePath + "\\" + fileName; Better and safer way: string path = Path.Combine(basePath, fileName); Also I've seen people writing custom method to read all bytes from file.This one comes quite handy: byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine As TheXenocide pointed out, same applies for File.ReadAllText() and File.ReadAllLines() | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624/"
]
} |
178,539 | How can I round a decimal number (floating point) to the nearest integer? e.g. 1.2 = 11.7 = 2 | Output of perldoc -q round Does Perl have a round() function? What about ceil() and floor()?Trig functions? Remember that int() merely truncates toward 0 . For rounding to a certain number of digits, sprintf() or printf() is usually the easiestroute. printf("%.3f", 3.1415926535); # prints 3.142 The POSIX module (part of the standard Perl distribution) implements ceil() , floor() , and a number of other mathematical and trigonometricfunctions. use POSIX; $ceil = ceil(3.5); # 4 $floor = floor(3.5); # 3 In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex module. With 5.004, the Math::Trig module (part of the standard Perldistribution) implements the trigonometric functions. Internally ituses the Math::Complex module and some functions can break out from thereal axis into the complex plane, for example the inverse sine of 2. Rounding in financial applications can have serious implications, andthe rounding method used should be specified precisely. In thesecases, it probably pays not to trust whichever system rounding is beingused by Perl, but to instead implement the rounding function you needyourself. To see why, notice how you'll still have an issue on half-way-pointalternation: for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i} 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0 Don't blame Perl. It's the same as in C. IEEE says we have to dothis. Perl numbers whose absolute values are integers under 2**31 (on32 bit machines) will work pretty much like mathematical integers.Other numbers are not guaranteed. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/178539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12850/"
]
} |
178,561 | I have the following VB.net interface that I need to port to C#. C# does not allow enumerations in interfaces. How can I port this without changing code that uses this interface? Public Interface MyInterface Enum MyEnum Yes = 0 No = 1 Maybe = 2 End Enum ReadOnly Property Number() As MyEnumEnd Interface | In short, you can't change that interface without breaking code, because C# can't nest types in interfaces. When you implement the VB.NET versions's interface, you are specifying that Number will return a type of MyInterface.MyEnum: class TestClass3 : TestInterfaces.MyInterface{ TestInterfaces.MyInterface.MyEnum TestInterfaces.MyInterface.Number { get { throw new Exception("The method or operation is not implemented."); } }} However, since C# can't nest types inside interfaces, if you break the enumerator out of the interface, you will be returning a different data type: in this case, MyEnum. class TestClass2 : IMyInterface{ MyEnum IMyInterface.Number { get { throw new Exception("The method or operation is not implemented."); } }} Think about it using the fully qualified type name. In the VB.NET interface, you have a return type of MyProject.MyInterface.MyEnum In the C# interface, you have: MyProject.MyEnum. Unfortunately, code that implements the VB.NET interface would have to be changed to support the fact that the type returned by MyInterface.Number has changed. IL supports nesting types inside interfaces, so it's a mystery why C# doesn't: .class public interface abstract auto ansi MyInterface { .property instance valuetype TestInterfaces.MyInterface/MyEnum Number { .get instance valuetype TestInterfaces.MyInterface/MyEnum TestInterfaces.MyInterface::get_Number() } .class auto ansi sealed nested public MyEnum extends [mscorlib]System.Enum { .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Maybe = int32(2) .field public static literal valuetype TestInterfaces.MyInterface/MyEnum No = int32(1) .field public specialname rtspecialname int32 value__ .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Yes = int32(0)} } If you have lots of code in other assemblies that make use of this interface, your best bet is to keep it inside a separate VB.NET assembly, and reference it from your C# projects. Otherwise, it's safe to convert it, but you'll have to change any code that uses it to return the different type. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25825/"
]
} |
178,562 | I got a bunch of servlet context listeners in my Java webapp, each of them gathering some information about the environment. Some of them depend on information which is gathered by another listener. But I can't determine the order in which the listeners are registered and called, so I have to duplicate code. I understand that the listeners are registered in the order their order in web.xml but this sounds a bit vague to me, too vague to rely on it. Do you have a hint how I can solve my problem? | All servlet containers and Java EE containers implement this part of the spec strictly. You can rely on the fact that the listeners are called in the order you specified in web.xml. You can have a Application LEVEL Data structure(HashMap) that will be updated by each Filter/Listener as it encounters the data from the requests. This will let each Listener update only what is essential. You can put the common code in a base Listener so that there is no code duplication. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17473/"
]
} |
178,572 | A large international company deploys a new web and MOTO (Mail Order and Telephone Order) handling system. Among other things you are tasked to design format for both order and customer identification numbers. What would be the best format in your opinion? Please list any assumptions and considerations. Accepted Answer Michael Haren's answer selected due to the most up votes, but please do read other answers and comments as they make Michael's answer more complete. | Go with all numbers or all letters. If you must mix it up, then make sure there are no ambiguous characters (Il1m, O0, etc.). When displayed/printed, put spaces in every 3-4 characters but make sure your systems can handle inputs without the spaces. Edit:Another thing to consider is having a built in way to distinguish orders, customers, etc. e.g. customers always start with 10, orders always start with 20, vendors always start with 30, etc. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22088/"
]
} |
178,600 | The project is ASP.NET 2.0, I have never been able to reproduce this myself, but I get emails informing me it happens to clients many times a week, often a few times in a row. Here is the full error: Exception Details: Microsoft.Reporting.WebForms.AspNetSessionExpiredException: ASP.NET session has expired Stack Trace: [AspNetSessionExpiredException: ASP.NET session has expired] at Microsoft.Reporting.WebForms.ReportDataOperation..ctor() at Microsoft.Reporting.WebForms.HttpHandler.GetHandler() at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Session Objects:75de8e1d65ff40d1ba666d940af5b118: Microsoft.Reporting.WebForms.ReportHierarchy 5210064be1fa4d6abf5dd5e56b262974: Microsoft.Reporting.WebForms.ReportHierarchy | We had the same problem. So far, we only found it when the session expired but they used the back button in a browser that does aggressive caching, which is fine. But the ReportViewer tried to to a refresh even though the main page did not. So, we just added some hacky Global.asax error handling: protected void Application_Error(object sender, EventArgs e){ Exception exc = Server.GetLastError().GetBaseException(); if (exc is Microsoft.Reporting.WebForms.AspNetSessionExpiredException) { Server.ClearError(); Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.PathAndQuery), true); }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21367/"
]
} |
178,633 | Does anyone know what would be the minimum rights I would need to grant to a domain user account in order to run a windows service as that user? For simplicity, assume that the service does nothing over and above starting, stopping, and writing to the "Application" event log - i.e. no network access, no custom event logs etc. I know I could use the built in Service and NetworkService accounts, but it's possible that I may not be able to use these due to network policies in place. | Two ways: Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24071/"
]
} |
178,645 | There is some magic going on with WCF deserialization. How does it instantiate an instance of the data contract type without calling its constructor? For example, consider this data contract: [DataContract]public sealed class CreateMe{ [DataMember] private readonly string _name; [DataMember] private readonly int _age; private readonly bool _wasConstructorCalled; public CreateMe() { _wasConstructorCalled = true; } // ... other members here} When obtaining an instance of this object via DataContractSerializer you will see that the field _wasConstructorCalled is false . So, how does WCF do this? Is this a technique that others can use too, or is it hidden away from us? | FormatterServices.GetUninitializedObject() will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes. I tested it using the sample code below and it looks like it works great: using System;using System.Reflection;using System.Runtime.Serialization;namespace NoConstructorThingy{ class Program { static void Main() { // does not call ctor var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); Console.WriteLine(myClass.One); // writes "0", constructor not called Console.WriteLine(myClass.Two); // writes "0", field initializer not called } } public class MyClass { public MyClass() { Console.WriteLine("MyClass ctor called."); One = 1; } public int One { get; private set; } public readonly int Two = 2; }} http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24874/"
]
} |
178,667 | I have the following code: import javax.swing.JEditorPane;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.ScrollPaneConstants;public class ScratchPad { public static void main(String args[]) throws Exception { String html ="<html>"+"<head>"+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/>"+ // this is the problem right here"<title>Error 400 BAD_REQUEST</title>"+"</head>"+"<body>"+"<h2>HTTP ERROR: 400</h2><pre>BAD_REQUEST</pre>"+"<p>RequestURI=null</p>"+"<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by jetty://</a></small></i></p>"+"</body>"+"</html>"; JFrame f = new JFrame(); JEditorPane editor = new JEditorPane(); editor.setEditable( false ); editor.getDocument().putProperty( "Ignore-Charset", "true" ); // this line makes no difference either way editor.setContentType( "text/html" ); editor.setText( html ); f.add( new JScrollPane(editor, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ); f.pack(); f.setVisible( true ); }} If you run it, you'll notice the frame is blank. However, if I remove the "; charset=ISO-8859-1" from the meta tag, the HTML shows up. Any ideas why and what I can do to prevent this (other than manually hacking the HTML string over which I have no control...). Edit #1 - putProperty( "Ignore-Charset", "true" ) makes no difference unfortunately. | Use the follow line before setText and after setContentType. editor.getDocument().putProperty("IgnoreCharsetDirective", Boolean.TRUE); This is one of the mystic undocumented features. setContentType create a new Document that it has no effect if you set it before. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
]
} |
178,669 | How can i make my flash applications in a browser in full screen mode? I know that the stage can be put in that mode, but when i run the application in any browser this doesn't work. So, this can be done, but how? | In the HTML including the Flash SWF, add the following parameter to your <object> tag: <param name="allowFullScreen" value="true" /> and the following attribute to your <embed> tag: allowFullScreen="true" Or, if you are using SWFObject (as you should be), add the allowFullscreen parameter to your embed code. See the SWFObject documentation for the various ways to this. In your Flash/Flex file, you need to provide the user a way to initiate fullscreen mode - you cannot force fullscreen without the user initiating it . Whatever you have the user do, include this code as a response to it: stage.displayState = StageDisplayState.FULL_SCREEN; //FlashsystemManager.stage.displayState = StageDisplayState.FULL_SCREEN; // Flex | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
]
} |
178,696 | I've got the following JavaScript on my web page... 64 var description = new Array();65 description[0] = "..."66 description[1] = "..."...78 function init() {79 document.getElementById('somedivid').innerHTML = description[0];80 }8182 window.onload = init(); In Microsoft Internet Explorer it causes the following error... A Runtime Error has occurred. Do you wish to debug? Line: 81 Error: Not implemented Line 79 executes as expected. If line 79 is commented out, it still throws the error. If I comment out line 82, then the function does not execute and there is no error. | Shouldn't line 82 read: window.onload = init; When you do "init()" it's a call to a function that returns void. You end up calling that function before the page loads. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
]
} |
178,704 | I always use unix timestamps for everything, but am wondering if there is a better way. What do you use to store timestamps and why? | However you choose to store a timestamp, it is important to avoid regional interpretation problems and time offset problems. A Unix timestamp is interpreted the same regardless of region, and is calculated from the same point in time regardless of time zone - these are good things. Beware storing timestamps as ambiguous strings such as 01/02/2008, since that can be interpreted as January 02, 2008 or February 01, 2008, depending on locale. When storing hours/minutes/seconds, it is important to know "which" hour/minute/second is being specified. You can do this by including timezone information (not needed for a Unix timestamp, since it is assumed to be UTC). However, note that Unix timestamps cannot uniquely represent some instants in time: when there is a leap second in UTC, the Unix timestamp does not change, so both 23:59:60 UTC and 00:00:00 the next day have the same Unix representation. So if you really need one second or better resolution, consider another format. If you prefer a more human readable format for storage than a Unix timestamp, consider ISO 8601 . One technique that helps keep things straight-forward is to store dates as UTC and only apply timezone or DST offsets when displaying a date to a user. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
]
} |
178,712 | I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull. I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this? | DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it. If DataRow.Table.Columns.Contains("column") Then MsgBox("YAY") End If | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/178712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21186/"
]
} |
178,738 | Is there a way to catch a click on a cell in VBA with Excel? I am not referring to the Worksheet_SelectionChange event, as that will not trigger multiple times if the cell is clicked multiple times. BeforeDoubleClick does not solve my problem either, as I do not want to require the user to double click that frequently. My current solution does work with the SelectionChange event, but it appears to require the use of global variables and other suboptimal coding practices. It also seems prone to error. | Clearly, there is no perfect answer. However, if you want to allow the user to select certain cells allow them to change those cells,and trap each click,even repeated clickson the same cell, then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event. One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own. If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows Private Sub Worksheet_SelectionChange(ByVal Target As Range) 'prevent Select event triggering again when we extend the selection below Application.EnableEvents = False Target.Resize(1, 2).Select Application.EnableEvents = TrueEnd Sub | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12002/"
]
} |
178,806 | What is the best way to graphically represent page flow, as applicable to an action oriented web application? What model do you use to represent page flows (page flow diagrams) encompassing pages (views), user actions on those views (events) and processes? These diagrams should act as a starting point for understanding between a business domain expert (say someone specifying an e-commerce web site), a technical analyst (someone responsible for designing the web application) and a web developer (someone responsible for implementing the solution) I am not looking for a software solution to help me draw those diagrams, nor am I looking for a web flow framework that will let me implement these page flows in software. I am, however looking for a good scheme for drawing out a page flow using pencil and paper For example, a good answer could be as follows Rectangle with label in CAPS represents page Arrow with label in lowercase represents user action Diamond with label in CAPS represents a process Entry points always from the left (arrows come into a page from the left) Exit points always from the right (arrows go out of a page to the right) If there is an accepted standard, or if this problem space is actually a specific case of a larger problem space for which there exists a standard, please highlight this. In the spirit of Stack Overflow, one scheme per answer please, and votes rather than duplicates | I have always liked Jesse James Garret's Visual Language. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
]
} |
178,836 | Should new projects use logback instead of log4j as a logging framework ? Or with other words :'Is logback better than log4j (leaving the SLF4J-'feature' of logback beside)?' | You should use SLF4J+Logback for logging. It provides neat features like parametrized messages and (in contrast to commons-logging) a Mapped Diagnostic Context (MDC, javadoc , documentation ). Using SLF4J makes the logging backend exchangeable in a quite elegant way. Additionally, SLF4J supports bridging of other logging frameworks to the actual SLF4J implementation you'll be using so logging events from third party software will show up in your unified logs - with the exception of java.util.logging that can't be bridged the same way that other logging frameworks are. Bridging jul is explained in the javadocs of SLF4JBridgeHandler. I've had a very good experience using the SLF4J+Logback combination in several projects and LOG4J development has pretty much stalled. SLF4J has the following remaining downsides: It does not support varargs to stay compatible with Java < 1.5 It does not support using both parametrized message and an exception at the same time. It does not contain support for a Nested Diagnostic Context (NDC, javadoc ) which LOG4J has. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
178,837 | I am looking for a regex that will find repeating letters. So any letter twice or more, for example: booooooot or abbott I won't know the letter I am looking for ahead of time. This is a question I was asked in interviews and then asked in interviews. Not so many people get it correct. | You can find any letter, then use \1 to find that same letter a second time (or more). If you only need to know the letter, then $1 will contain it. Otherwise you can concatenate the second match onto the first. my $str = "Foooooobar";$str =~ /(\w)(\1+)/;print $1;# prints 'o'print $1 . $2;# prints 'oooooo' | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/178837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
} |
178,846 | I installed the ReSharper evaluation version and uninstalled it. Afterwards Visual Studio's Intellisense stopped working. I have restarted computer but I still have this problem. Can anyone please help me here? I am using Visual Studio 2005. Thanks. | Try opening Visual Studio Command Prompt and entering: devenv.exe /ResetSettings | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20933/"
]
} |
178,899 | I have a collection of classes that I want to serialize out to an XML file. It looks something like this: public class Foo{ public List<Bar> BarList { get; set; }} Where a bar is just a wrapper for a collection of properties, like this: public class Bar{ public string Property1 { get; set; } public string Property2 { get; set; }} I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form. I want to get a nice XML representation like this: <?xml version="1.0" encoding="utf-8"?><Foo> <BarList> <Bar> <Property1>Value</Property1> <Property2>Value</Property2> </Bar> <Bar> <Property1>Value</Property1> <Property2>Value</Property2> </Bar> </Barlist></Foo> where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination. I've marked Foo with the attribute [XmlRoot("Foo")] and the list<Bar> with the attribute [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")] in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this: <?xml version="1.0" encoding="utf-8"?><Foo> <Barlist /></Foo> I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me. | Just to check, have you marked Bar as [Serializable]? Also, you need a parameter-less ctor on Bar, to deserialize Hmm, I used: public partial class Form1 : Form{ public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Foo f = new Foo(); f.BarList = new List<Bar>(); f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" }); XmlSerializer ser = new XmlSerializer(typeof(Foo)); using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create)) { ser.Serialize(fs, f); } }}public class Foo{ [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")] public List<Bar> BarList { get; set; }}[XmlRoot("Foo")]public class Bar{ public string Property1 { get; set; } public string Property2 { get; set; }} And that produced: <?xml version="1.0"?><Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <BarList> <Bar> <Property1>abc</Property1> <Property2>def</Property2> </Bar> </BarList></Foo> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4019/"
]
} |
178,904 | var something = {wtf: null,omg: null}; My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now. Except for this. I don't recall ever seeing this before. What is it? And where can I learn more about it? | It is an object literal with two properties. Usually this is how people create associative arrays or hashes because JS doesn't natively support that data structure. Though note that it is still a fully-fledged object, you can even add functions as properties: var myobj = { name: 'SO', hello: function() { alert(this.name); }}; And you can iterate through the properties using a for loop: for (i in myobj) { // myobj[i] // Using the brackets (myobj['name']) is the same as using a dot (myobj.name)} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19825/"
]
} |
178,915 | What do I need to do to save an image my program has generated (possibly from the camera, possibly not) to the system photo library on the iPhone? | You can use this function: UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo); You only need completionTarget , completionSelector and contextInfo if you want to be notified when the UIImage is done saving, otherwise you can pass in nil . See the official documentation for UIImageWriteToSavedPhotosAlbum() . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/178915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626/"
]
} |
178,934 | In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g. for ( int i=0; i < vecVector.size(); i++ ){..} Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please? | Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings. Genericity Iterators increase the genericity of your code. For example: typedef std::vector<int> Container ;void doSomething(Container & p_aC){ for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it) { int & i = *it ; // i is now a reference to the value iterated // do something with "i" }} Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code. Should you have used index-based code instead, it would have needed to be re-written. Access The iterator should be viewed like a kind of super pointer.It "points" to the value (or, in case of maps, to the pair of key/value). But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque). Algorithms Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/178934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
]
} |
178,936 | I am working on a build system. The build system posts the results as a zip file in a directory. Unfortunately I have no easy way to know the name of the zip file, because it is timestamped. For the next operation, I must decompress this zip file to some specific location and then do some more file operations. I guess I could change the build system so I specify the name of the result zip file from the command line, however, I though it might be easiest just to find out which one is the newest file and unzip it (if the previous process is successful). How can I issue an unzip command that will only take effect on the newest zip file in the directory, ignoring all others? EDIT: I decided to use the capabilities in ANT for this task instead. However, it is still a neat trick to have up the sleve... Thanks for the answer! | This should do it: FOR /F usebackq %%i IN (`DIR /B /O-D *.ZIP`) DO UNZIP %%i && GOTO DONE || GOTO DONE:DONE This works as follows: DIR /B /O-D *.ZIP lists all ZIP files in reverse date order in a "bare" - i.e. name only - format. FOR /F usebackq is used to loop over the output of the command. && GOTO DONE || GOTO DONE makes sure the UNZIP is only run for the first file. You need both && (and) and || (or) in case the unzip fails for some reason. You'll need to change UNZIP %%i for whatever unzip command you want to use. EDIT The above will work as long as the Zip filename doesn't contain any spaces. If you want to handle filenames with spaces, use the following variant: FOR /F "tokens=*" %%i IN ('DIR /B /O-D *.ZIP') DO UNZIP "%%i" && GOTO DONE || GOTO DONE:DONE The differences are: The "tokens=*" option returns the whole of the filename even if it contains spaces. The filename passed to UNZIP is quoted This variant uses single quotes for the DIR command so doesn't need the "usebackq" option. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309/"
]
} |
178,964 | JavaScript post request like a form submit shows you how to submit a form that you create via POST in JavaScript. Below is my modified code. var form = document.createElement("form");form.setAttribute("method", "post");form.setAttribute("action", "test.jsp");var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", "id");hiddenField.setAttribute("value", "bob");form.appendChild(hiddenField);document.body.appendChild(form); // Not entirely sure if this is necessary form.submit(); What I would like to do is open the results in a new window. I am currently using something like this to open a page in a new window: onclick = window.open(test.html, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no'); | Add <form target="_blank" ...></form> or form.setAttribute("target", "_blank"); to your form's definition. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/178964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
178,973 | I'm a big fan of log4net , but recently, some (in my department) have questioned its inclusion in our projects because of the seemingly heaviness of each logging method. I would argue that there are better techniques than others, but that's another question. I'm curious to know, what is the typical impact of a log4net DebugFormat-type call on your applications. I'm going to leave out variables like number of log statements per lines of code, etc, because I'm just looking for anything that you've seen in the real world. And, I am aware of the simple technique of adding a guard clause to long evaluation statements eg: if (log.IsDebug){ log.DebugFormat(...);} So, let's exclude that from consideration for now. | I am not familiar with log4net, or log.DebugFormat(...). But the cost of logging is really in two areas. The first is the logging call, and the second is the actual persisting of the log information. The guards help reduce the logging call to a minimum when the logging is not actually necessary. It tends to be very fast, since it's little more than a method call and a comparison of two scalars. However, when you don't use guards, the cost may well become the price of creating the actual logging arguments. For example, in log4j, this was a common idiom: log.debug("Runtime error. Order #" + order.getOrderNo() + " is not posted."); Here, the cost is the actual evaluation of the string expression making the message. This is because regardless of the logging level, that expression, and the resulting string are created. Imagine if instead you had something like: log.debug("Something wrong with this list: " + longListOfData); That could create a large and expensive string variable that, if the log level wasn't set for DEBUG, would simply be wasted. The guards: if (log.isDebug()) { log.debug(...);} Eliminate that problem, since the isDebug call is cheap, especially compared to the actual creation of the argument. In my code, I have written a wrapper for logging, and I can create logs like this: log.debug("Runtime error. Order # {0} is not posted.", order.getOrderNo()); This is a nice compromise. This relies on Java varargs, and my code checks the logging level, and then formats the message appropriately. This is almost as fast as the guards, but much cleaner to write. Now, log.DebugFormat may well do a similar thing, that I don't know. On top of this, of course, is the actual cost of logging (to the screen, to a file, to a socket, etc.). But that's just a cost you need to accept. My best practice for that, when practical, is to route the actual log messages to a queue, which is then reaped and output to the proper channel using a separate thread. This, at least, helps keep the logging out of line with the main computing, but it has expenses and complexity of its own. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/178973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
} |
179,004 | Every time I make a project I develop several generic routines/modules/libraries that I expect I'll be using with other projects. Due to the speed of development I don't spend a lot of time making these modules perfect - just good enough for this project, and well enough documented and isolatable that I can easily add them to another project. So far so good. Now when I use them in another project inevitably I improve them - either adding new features/functions, fixing bugs, making them more general, etc. At that point I have several problems: I need to maintain the changes in the module for the code I'm working on I need to maintain those same changes in a central "module" repository I need to make sure that the updated modules are available for, but not automatically used in older projects, or sometimes even existing projects I'm already working on. How do you manage this? How are these problems different when you have teams working on various modules in different projects? -Adam | If you're using Subversion for all your projects, you can simply use svn:externals : this allows one repository to reference another repository, optionally fixed at a particular revision. For example, svn://svn/sharedsvn://svn/project1 |- dir1 |- dir2 \- svn:externals "shared -r 3 svn://svn/shared"svn://svn/project2 |- dir3 \- svn:externals "shared -r 5 svn://svn/shared" Commit your changes to svn://svn/shared , and modify the svn:externals property in the individual projects when you're ready. Otherwise, using other VCS, you might simply keep a bunch of tags on shared , one for each project using shared , pointing to the version they use. Advance each tag to later versions when ready. This requires manually updating each project's copy of shared , though (one thing which makes svn:externals nice is that it happens automatically). If you're forking/branching shared for each individual project... well, that can work, but it takes manpower to maintain and merge changes. [Edit] Further references: See External Definitions in the svn book for a tutorial and more details on svn:externals , and git-submodule tutorial for a similar feature in the DVCS git . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
} |
179,014 | I am using PHP with Apache on Linux, with Sendmail. I use the PHP mail function. The email is sent, but the envelope has the Apache_user@localhostname in MAIL FROM (example [email protected]) and some remote mail servers reject this because the domain doesn't exist (obviously). Using mail , can I force it to change the envelope MAIL FROM ? EDIT: If I add a header in the fourth field of the mail () function, that changes the From field in the headers of the body of the message, and DOES NOT change the envelope MAIL FROM . I can force it by spawning sendmail with sendmail -t -odb -oi -frealname@realhost and piping the email contents to it. Is this a better approach? Is there a better, simpler, more PHP appropriate way of doing this? EDIT: The bottom line is I should have RTM. Thanks for the answers folks, the fifth parameter works and all is well. | mail() has a 4th and 5th parameter (optional). The 5th argument is what should be passed as options directly to sendmail. I use the following: mail('[email protected]','subject!','body!','From: [email protected]','-f [email protected]'); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/179014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13667/"
]
} |
179,024 | How do you add a JAR file to an already existing Java library in Eclipse? Note that this is not a user library. That is, if you look at the Java Build Path for a Java project and click on the Libraries tab, you will see the list of libraries used by the project. If you expand a given library, you will see a list of JAR files included in that library. I want to add an additional JAR file to one of these libraries. I am using Version 3.4.0 of Eclipse. | In eclipse Galileo : Open the project's properties Select Java Build Path Select Libraries tab From there you can Add External Jars | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/179024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
]
} |
179,026 | In Gmail, I have a bunch of labeled messages. I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is. c = imaplib.IMAP4_SSL('imap.gmail.com')c.list()('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])c.search(???) I'm not finding many examples for this sort of thing. | imaplib is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the IMAP specification . As you'll see in section "6.4.4. SEARCH Command", there are many things you can specify for search criterion. Note that you have to SELECT a mailbox (IMAP's name for a folder) before you can search for anything. (Searching multiple folders simultaneously requires multiple IMAP connections, as I understand it.) IMAP4.list will help you figure out what the mailbox identifiers are. Also useful in formulating the strings you pass to imaplib is "9. Formal Syntax" from the RFC linked to above. The r'(\HasNoChildren) "/"' is a mailbox flag on the root mailbox, / . See "7.2.6. FLAGS Response". Good luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17732/"
]
} |
179,085 | What is the difference between creating one index across multiple columns versus creating multiple indexes, one per column? Are there reasons why one should be used over the other? For example: Create NonClustered Index IX_IndexName On TableName(Column1 Asc, Column2 Asc, Column3 Asc) Versus: Create NonClustered Index IX_IndexName1 On TableName(Column1 Asc)Create NonClustered Index IX_IndexName2 On TableName(Column2 Asc)Create NonClustered Index IX_IndexName3 On TableName(Column3 Asc) | I agree with Cade Roux . This article should get you on the right track: Indexes in SQL Server 2005/2008 – Best Practices, Part 1 Indexes in SQL Server 2005/2008 – Part 2 – Internals One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits. Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused. e.g. imagine you search a table on three columns state, county, zip. you sometimes search by state only. you sometimes search by state and county. you frequently search by state, county, zip. Then an index with state, county, zip. will be used in all three of these searches. If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful. You could then create an index on Zip alone that would be used in this instance. By the way We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state' I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's. The article will help a lot. :-) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/179085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
179,102 | I want to get a System.Type given only the type name in a string . For instance, if I have an object: MyClass abc = new MyClass(); I can then say: System.Type type = abc.GetType(); But what if all I have is: string className = "MyClass"; | Type type = Type.GetType("foo.bar.MyClass, foo.bar"); MSDN . Make sure the name is Assembly Qualified . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
]
} |
179,105 | I recall reading somewhere that using references to smart pointers can cause memory corruption. Is this simply because of using the reference of the smart pointer after its been destroyed? Or does the reference counting get messed up? Thanks for clarifying | Assuming you are talking about shared_ptr here... Is this simply because of using the reference of the smart pointer after its been destroyed? This is a good answer. You may not know absolutely the lifetime of the pointer your reference refers too. To get around this, you'd want to look into boost::weak_ptr. It doesn't participate in reference counting. When you need to use it, it gives you a shared_ptr which goes away once your done with it. It will also let you know when the refered to pointer has been collected. From the weak_ptr documentation The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr. To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr constructor or the member function lock. When the last shared_ptr to the object goes away and the object is deleted, the attempt to obtain a shared_ptr from the weak_ptr instances that refer to the deleted object will fail: the constructor will throw an exception of type boost::bad_weak_ptr, and weak_ptr::lock will return an empty shared_ptr. Note the method expired() will also tell you if your ptr is still around. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16496/"
]
} |
179,119 | I am learning and using Emacs. What I found annoying is that Ctrl-Space input will be stolen by Windows XP to switch the language bar instead of setting the mark in Emacs. The "language bar" is the native input languages selection such as Chinese keyboard other than English keyboard. Is there a way to temporarily prevent XP from stealing it? I have disabled the language bar from "Regional and language options" from Control Panel but the problem still exists. It doesn't happen on my Windows 2000 desktop at office but it happens on my work Windows XP laptop. Thank you very much. | Found the solution to this problem as I just experienced it. So here goes even if the question is old. Applies to Windows 7 and maybe others. I had added Chinese, Japanese and Korean input languages as I needed these for some development. After that I removed them again via Control Panel "Change keyboards...". I removed them all in one go and closed the dialog.After this all the languages still showed in the Language bar and I had the Ctrl-Space problem. To fix it I did the following for each language one at a time:1. Open Control Panel applet "Change keyboards..."2. Add the keyboard for the language (i.e. chinese)3. Click OK and exit control panel4. Open applet again and remove the keyboard. The problem seems to be a bug that appears when removing multiple keyboards at the same time. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24020/"
]
} |
179,123 | I wrote the wrong thing in a commit message. How can I change the message? The commit has not been pushed yet. | Amending the most recent commit message git commit --amend will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with: git commit --amend -m "New commit message" …however, this can make multi-line commit messages or small corrections more cumbersome to enter. Make sure you don't have any working copy changes staged before doing this or they will get committed too. ( Unstaged changes will not get committed.) Changing the message of a commit that you've already pushed to your remote branch If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also need to force push the commit with: git push <remote> <branch> --force# Orgit push <remote> <branch> -f Warning: force-pushing will overwrite the remote branch with the state of your local one . If there are commits on the remote branch that you don't have in your local branch, you will lose those commits. Warning: be cautious about amending commits that you have already shared with other people. Amending commits essentially rewrites them to have different SHA IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether. Perform an interactive rebase Another option is to use interactive rebase.This allows you to edit any message you want to update even if it's not the latest message. In order to do a Git squash, follow these steps: // n is the number of commits up to the last commit you want to be able to editgit rebase -i HEAD~n Once you squash your commits - choose the e/r for editing the message: Important note about interactive rebase When you use git rebase -i HEAD~n there can be more than n commits. Git will "collect" all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + . Good tip: If you have to do it for more than a single branch and you might face conflicts when amending the content, set up git rerere and let Git resolve those conflicts automatically for you. Documentation git-commit(1) Manual Page git-rebase(1) Manual Page git-push(1) Manual Page | {
"score": 15,
"source": [
"https://Stackoverflow.com/questions/179123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
} |
179,128 | I'm starting a project which requires reading outlook msg files in c#. I have the specs for compound documents but am having trouble reading them in c#. Any pointers would be greatly appreciated. Thanks. | Here is my shot. This is an initial translation of this article . namespace cs_console_app{ using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; [ComImport] [Guid("0000000d-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumSTATSTG { // The user needs to allocate an STATSTG array whose size is celt. [PreserveSig] uint Next( uint celt, [MarshalAs(UnmanagedType.LPArray), Out] System.Runtime.InteropServices.ComTypes.STATSTG[] rgelt, out uint pceltFetched ); void Skip(uint celt); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumSTATSTG Clone(); } [ComImport] [Guid("0000000b-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IStorage { void CreateStream( /* [string][in] */ string pwcsName, /* [in] */ uint grfMode, /* [in] */ uint reserved1, /* [in] */ uint reserved2, /* [out] */ out IStream ppstm); void OpenStream( /* [string][in] */ string pwcsName, /* [unique][in] */ IntPtr reserved1, /* [in] */ uint grfMode, /* [in] */ uint reserved2, /* [out] */ out IStream ppstm); void CreateStorage( /* [string][in] */ string pwcsName, /* [in] */ uint grfMode, /* [in] */ uint reserved1, /* [in] */ uint reserved2, /* [out] */ out IStorage ppstg); void OpenStorage( /* [string][unique][in] */ string pwcsName, /* [unique][in] */ IStorage pstgPriority, /* [in] */ uint grfMode, /* [unique][in] */ IntPtr snbExclude, /* [in] */ uint reserved, /* [out] */ out IStorage ppstg); void CopyTo( /* [in] */ uint ciidExclude, /* [size_is][unique][in] */ Guid rgiidExclude, // should this be an array? /* [unique][in] */ IntPtr snbExclude, /* [unique][in] */ IStorage pstgDest); void MoveElementTo( /* [string][in] */ string pwcsName, /* [unique][in] */ IStorage pstgDest, /* [string][in] */ string pwcsNewName, /* [in] */ uint grfFlags); void Commit( /* [in] */ uint grfCommitFlags); void Revert(); void EnumElements( /* [in] */ uint reserved1, /* [size_is][unique][in] */ IntPtr reserved2, /* [in] */ uint reserved3, /* [out] */ out IEnumSTATSTG ppenum); void DestroyElement( /* [string][in] */ string pwcsName); void RenameElement( /* [string][in] */ string pwcsOldName, /* [string][in] */ string pwcsNewName); void SetElementTimes( /* [string][unique][in] */ string pwcsName, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pctime, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME patime, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pmtime); void SetClass( /* [in] */ Guid clsid); void SetStateBits( /* [in] */ uint grfStateBits, /* [in] */ uint grfMask); void Stat( /* [out] */ out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, /* [in] */ uint grfStatFlag); } [Flags] public enum STGM : int { DIRECT = 0x00000000, TRANSACTED = 0x00010000, SIMPLE = 0x08000000, READ = 0x00000000, WRITE = 0x00000001, READWRITE = 0x00000002, SHARE_DENY_NONE = 0x00000040, SHARE_DENY_READ = 0x00000030, SHARE_DENY_WRITE = 0x00000020, SHARE_EXCLUSIVE = 0x00000010, PRIORITY = 0x00040000, DELETEONRELEASE = 0x04000000, NOSCRATCH = 0x00100000, CREATE = 0x00001000, CONVERT = 0x00020000, FAILIFTHERE = 0x00000000, NOSNAPSHOT = 0x00200000, DIRECT_SWMR = 0x00400000, } public enum STATFLAG : uint { STATFLAG_DEFAULT = 0, STATFLAG_NONAME = 1, STATFLAG_NOOPEN = 2 } public enum STGTY : int { STGTY_STORAGE = 1, STGTY_STREAM = 2, STGTY_LOCKBYTES = 3, STGTY_PROPERTY = 4 } class Program { [DllImport("ole32.dll")] private static extern int StgIsStorageFile( [MarshalAs(UnmanagedType.LPWStr)] string pwcsName); [DllImport("ole32.dll")] static extern int StgOpenStorage( [MarshalAs(UnmanagedType.LPWStr)] string pwcsName, IStorage pstgPriority, STGM grfMode, IntPtr snbExclude, uint reserved, out IStorage ppstgOpen); static void Main(string[] args) { string filename = @"f:\temp\treta2.msg"; if (StgIsStorageFile(filename) == 0) { IStorage storage = null; if (StgOpenStorage( filename, null, STGM.DIRECT | STGM.READ | STGM.SHARE_EXCLUSIVE, IntPtr.Zero, 0, out storage) == 0) { System.Runtime.InteropServices.ComTypes.STATSTG statstg; storage.Stat(out statstg, (uint) STATFLAG.STATFLAG_DEFAULT); IEnumSTATSTG pIEnumStatStg = null; storage.EnumElements(0, IntPtr.Zero, 0, out pIEnumStatStg); System.Runtime.InteropServices.ComTypes.STATSTG[] regelt = { statstg }; uint fetched = 0; uint res = pIEnumStatStg.Next(1, regelt, out fetched); if (res == 0) { while (res != 1) { string strNode = statstg.pwcsName; bool bNodeFound = false; Console.WriteLine(strNode); if (strNode == "__substg1.0_0E04001E" || strNode == "__substg1.0_0E1D001E" || strNode == "__substg1.0_1000001E" || strNode == "__substg1.0_1013001E") { bNodeFound = true; } if (bNodeFound) { switch (statstg.type) { case (int) STGTY.STGTY_STORAGE: { IStorage pIChildStorage; storage.OpenStorage(statstg.pwcsName, null, (uint) (STGM.READ | STGM.SHARE_EXCLUSIVE), IntPtr.Zero, 0, out pIChildStorage); } break; case (int) STGTY.STGTY_STREAM: { IStream pIStream; storage.OpenStream(statstg.pwcsName, IntPtr.Zero, (uint)(STGM.READ | STGM.SHARE_EXCLUSIVE), 0, out pIStream); byte[] data = new byte[255]; pIStream.Read(data, 255, IntPtr.Zero); } break; } } if ((res = pIEnumStatStg.Next(1, regelt, out fetched)) != 1) { statstg = regelt[0]; } } } } } Console.ReadLine(); } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16834/"
]
} |
179,161 | Or would a conventional client-server VCS be more appropriate? I'm currently using TortoiseSVN, but I'm interested in a DVCS, but I'm not sure if it's even a good idea to try to use something like that solo. | Since you can still push to another machine also running Git/Mercurial/Bzr/etc you still have the multi-computer backup safety, which you'd hopefully have either way. However if you ever code while traveling, having full repository access can be a huge plus, then just resync to your server when you have a net connection again/get home/etc. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
179,173 | I have an XmlDocument that already exists and is read from a file. I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls? I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode. ex:Original XmlDoc: <MyXml> <Employee> </Employee></MyXml> and, I would like to add a Demographic (with several children) tag to Employee: <MyXml> <Employee> <Demographic> <Age/> <DOB/> </Demographic> </Employee></MyXml> | I suggest using XmlDocument.CreateDocumentFragment if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder. XmlDocument xdoc = new XmlDocument();xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";xdoc.DocumentElement.FirstChild.AppendChild(xfrag); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/179173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2871/"
]
} |
179,176 | Is there an easy way to create a table in SQL Server (2005) from an Excel spreadsheet. I'm thinking maybe some tool? Thanks in advance. | If the data is not that big and if it is a simple table, easiest way is to create and open the table in SQL Server Management Studio and copy paste the excel data into it. Other solutions are using DTS or using SSIS .. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24927/"
]
} |
179,213 | This is a multiple question for the same pre-processing instruction. 1 - <> or "" ? Apart from the info found in the MSDN: #include Directive (C-C++) 1.a: What are the differences between the two notations? 1.b: Do all compilers implement them the same way? 1.c: When would you use the <>, and when would you use the "" (i.e. what are the criteria you would use to use one or the other for a header include)? 2 - #include {TheProject/TheHeader.hpp} or {TheHeader.hpp} ? I've seen at least two ways of writing includes of one's project headers.Considering that you have at least 4 types of headers, that is: private headers of your project? headers of your project, but which are exporting symbols (and thus, "public") headers of another project your module links with headers of a compiler or standard library For each kind of headers: 2.a: Would you use <> or "" ? 2.b: Would you include with {TheProject/TheHeader.hpp}, or with {TheHeader.hpp} only? 3 - Bonus 3.a: Do you work on project with sources and/or headers within a tree-like organisation (i.e., directories inside directories, as opposed to "every file in one directory") and what are the pros/cons? | After reading all answers, as well as compiler documentation, I decided I would follow the following standard. For all files, be them project headers or external headers, always use the pattern: #include <namespace/header.hpp> The namespace being at least one directory deep, to avoid collision. Of course, this means that the project directory where the project headers are should be added as "default include header" to the makefile, too. The reason for this choice is that I found the following information: 1. The include "" pattern is compiler-dependent I'll give the answers below 1.a The Standard Source: C++14 Working Draft n3797 : https://isocpp.org/files/papers/N3797.pdf C++11, C++98, C99, C89 (the section quoted is unchanged in all those standards) In the section 16.2 Source file inclusion, we can read that: A preprocessing directive of the form #include <h-char-sequence> new-line searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. This means that #include <...> will search a file in an implementation defined manner. Then, the next paragraph: A preprocessing directive of the form #include "q-char-sequence" new-line causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read #include <h-char-sequence> new-line with the identical contained sequence (including > characters, if any) from the original directive. This means that #include "..." will search a file in an implementation defined manner and then, if the file is not found, will do another search as if it had been an #include <...> The conclusion is that we have to read the compilers documentation. Note that, for some reason, nowhere in the standards the difference is made between "system" or "library" headers or other headers. The only difference seem that #include <...> seems to target headers, while #include "..." seems to target source (at least, in the english wording). 1.b Visual C++: Source: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx #include "MyFile.hpp" The preprocessor searches for include files in the following order: In the same directory as the file that contains the #include statement. In the directories of any previously opened include files in the reverse order in which they were opened. The search starts from the directory of the include file that was opened last and continues through the directory of the include file that was opened first. Along the path specified by each /I compiler option. (*) Along the paths specified by the INCLUDE environment variable or the development environment default includes. #include <MyFile.hpp> The preprocessor searches for include files in the following order: Along the path specified by each /I compiler option. (*) Along the paths specified by the INCLUDE environment variable or the development environment default includes. Note about the last step The document is not clear about the "Along the paths specified by the INCLUDE environment variable" part for both <...> and "..." includes. The following quote makes it stick with the standard: For include files that are specified as #include "path-spec", directory searching begins with the directory of the parent file and then proceeds through the directories of any grandparent files. That is, searching begins relative to the directory that contains the source file that contains the #include directive that's being processed. If there is no grandparent file and the file has not been found, the search continues as if the file name were enclosed in angle brackets. The last step (marked by an asterisk) is thus an interpretation from reading the whole document. 1.c g++ Source: https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html https://gcc.gnu.org/onlinedocs/cpp/Include-Operation.html https://gcc.gnu.org/onlinedocs/cpp/Invocation.html https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html https://gcc.gnu.org/onlinedocs/cpp/Wrapper-Headers.html https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html The following quote summarizes the process: GCC [...] will look for headers requested with #include <file> in [system directories] [...] All the directories named by -I are searched, in left-to-right order, before the default directories GCC looks for headers requested with #include "file" first in the directory containing the current file, then in the directories as specified by -iquote options, then in the same places it would have looked for a header requested with angle brackets. #include "MyFile.hpp" This variant is used for header files of your own program. The preprocessor searches for include files in the following order: In the same directory as the file that contains the #include statement. Along the path specified by each -iquote compiler option. As for the #include <MyFile.hpp> #include <MyFile.hpp> This variant is used for system header files. The preprocessor searches for include files in the following order: Along the path specified by each -I compiler option. Inside the system directories. 1.d Oracle/Sun Studio CC Source: http://docs.oracle.com/cd/E19205-01/819-5265/bjadq/index.html Note that the text contradict itself somewhat (see the example to understand). The key phrase is: " The difference is that the current directory is searched only for header files whose names you have enclosed in quotation marks. " #include "MyFile.hpp" This variant is used for header files of your own program. The preprocessor searches for include files in the following order: The current directory (that is, the directory containing the “including” file) The directories named with -I options, if any The system directory (e.g. the /usr/include directory) #include <MyFile.hpp> This variant is used for system header files. The preprocessor searches for include files in the following order: The directories named with -I options, if any The system directory (e.g. the /usr/include directory) 1.e XL C/C++ Compiler Reference - IBM/AIX Source: http://www.bluefern.canterbury.ac.nz/ucsc%20userdocs/forucscwebsite/c/aix/compiler.pdf http://www-01.ibm.com/support/docview.wss?uid=swg27024204&aid=1 Both documents are titled "XL C/C++ Compiler Reference" The first document is older (8.0), but is easier to understand. The second is newer (12.1), but is a bit more difficult to decrypt. #include "MyFile.hpp" This variant is used for header files of your own program. The preprocessor searches for include files in the following order: The current directory (that is, the directory containing the “including” file) The directories named with -I options, if any The system directory (e.g. the /usr/vac[cpp]/include or /usr/include directories) #include <MyFile.hpp> This variant is used for system header files. The preprocessor searches for include files in the following order: The directories named with -I options, if any The system directory (e.g. the /usr/vac[cpp]/include or /usr/include directory) 1.e Conclusion The pattern "" could lead to subtle compilation error across compilers, and as I currently work both on Windows Visual C++, Linux g++, Oracle/Solaris CC and AIX XL, this is not acceptable. Anyway, the advantage of "" described features are far from interesting anyway, so... 2. Use the {namespace}/header.hpp pattern I saw at work ( i.e. this is not theory, this is real-life, painful professional experience ) two headers with the same name, one in the local project directory, and the other in the global include. As we were using the "" pattern, and that file was included both in local headers and global headers, there was no way to understand what was really going on, when strange errors appeared. Using the directory in the include would have saved us time because the user would have had to either write: #include <MyLocalProject/Header.hpp> or #include <GlobalInclude/Header.hpp> You'll note that while #include "Header.hpp" would have compiled successfully, thus, still hiding the problem, whereas #include <Header.hpp> would not have compiled in normal circonstances. Thus, sticking to the <> notation would have made mandatory for the developer the prefixing of the include with the right directory, another reason to prefer <> to "". 3. Conclusion Using both the <> notation and namespaced notation together removes from the pre-compiler the possibility to guess for files, instead searching only the default include directories. Of course, the standard libraries are still included as usual, that is: #include <cstdlib>#include <vector> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
]
} |
179,223 | I want to add my own member to the StringBuilder class, but when I go to create it IntelliSense doesn't bring it up. public class myStringBuilder() Inherits System.Text.[StringBuilder should be here] ....end class Is it even possible? thanks | StringBuilder is NotInheritable (aka sealed in C#) so you cannot derive from it. You could try wrapping StringBuilder in your own class or consider using extension methods instead. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
]
} |
179,238 | As I'm riding the wave of resurgence of Smalltalk (especially because many Ruby-on-Rails people are rediscovering Smalltalk and seeing Seaside as their next upgraded web framework), I get questions like "yeah, but how do I use my favorite editor to edit Smalltalk code?" or "Does Smalltalk still insist on living in a world of its own?". Now, having first experienced Smalltalk back in 1981 , I don't understand these questions very well. It seems rather natural that I'd want the editor and debugger to be savvy of my current code state, and integrate with the change control system that is Smalltalk-aware. Using an external editor or debugger or change control manager would seem very awkward. So what is it that scares you the most about not being able to edit the five-line methods in Smalltalk with your favorite editor, or use your favorite non-Smalltalk-aware change control system? | Everything's different. Want to go to the end of the line? It's not Ctrl - E . Want to jump a few words over, by word? It's not Meta-F.... Text editing is a fundamental programming activity . Messing with those inputs is messing with something deep in my mind. Edit: and here is someone asking for emacs key bindings on comp.lang.smalltalk in 1987 . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/179238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22483/"
]
} |
179,254 | Has anyone got this working in a web application? No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded. Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more performant solution. Update: By 'reloading' I mean refreshing ConfigurationManager.AppSettings without having to completely restart my ASP.NET application and having to incur the usual startup latency. | Make sure you are passing the correct case sensitive value to RefreshSection, i.e. ConfigurationManager.RefreshSection("appSettings"); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/179254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
]
} |
179,315 | I am sure there is a simple answer to this one. I have a docx file that I get an error when trying to download(document cannot be found).... .doc is fine .txt is also fine. I am sure this is just an iis setting, the permissions on the server are all the same for all files. | Yes, it's just an IIS setting: by default, it will only serve files for which the extension matches a defined MIME type . To allow .docx files to be downloaded, follow the steps from the KB article linked above: Open the IIS Microsoft Management Console (MMC), right-click the local computer name, and then click Properties. Click MIME Types. Click New. In the Extension box, type the file name extension that you want (in this case, .docx). In the MIME Type box, type application/vnd.openxmlformats-officedocument.wordprocessingml.document (thanks to @web developer for pointing out this MIME type, which supercedes the 'application/msword' from my original answer). Apply the new settings. Note that you must restart the World Wide Web Publishing Service or wait for the worker process to recycle for the changes to take effect. In this example, IIS now serves files with the .docx extension. Note that the KB article uses the generic application/octet-stream MIME type: although that generally should work, if a more specific MIME type exists, such as application/msword, it's always best to use that. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/179315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
179,337 | In c# double tmp = 3.0 * 0.05; tmp = 0.15000000000000002 This has to do with money. The value is really $0.15, but the system wants to round it up to $0.16. 0.151 should probably be rounded up to 0.16, but not 0.15000000000000002 What are some ways I can get the correct numbers (ie 0.15, or 0.16 if the decimal is high enough). | Use a fixed-point variable type, or a base ten floating point type like Decimal. Floating point numbers are always somewhat inaccurate, and binary floating point representations add another layer of inaccuracy when they convert to/from base two. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
]
} |
179,355 | How do you delete all the cookies for the current domain using JavaScript? | function deleteAllCookies() { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; var eqPos = cookie.indexOf("="); var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; }} Note that this code has two limitations: It will not delete cookies with HttpOnly flag set, as the HttpOnly flag disables Javascript's access to the cookie. It will not delete cookies that have been set with a Path value. (This is despite the fact that those cookies will appear in document.cookie , but you can't delete it without specifying the same Path value with which it was set.) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/179355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636/"
]
} |
179,369 | I have a simple Python script that I want to stop executing if a condition is met. For example: done = Trueif done: # quit/stop/exitelse: # do other stuff Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code. | To exit a script you can use, import syssys.exit() You can also provide an exit status value, usually an integer. import syssys.exit(0) Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero. import syssys.exit("aa! errors!") Prints "aa! errors!" and exits with a status code of 1. There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used. The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/179369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
179,415 | Assuming we always use a Sun JVM (say, 1.5+), is it always safe to cast a Graphics reference to Graphics2D? I haven't seen it cause any problems yet and, to my understanding, the Graphics class is legacy code but the Java designers didn't want to change the interfaces for Swing and AWT classes in order to preserver backwards compatibility. | According to the discussion here , it is always safe to cast from Graphics to Graphics2D . However I am not able to quickly find the official Sun statement on this. The reason it is valid to cast from Graphics to Graphics2D, is because Sun have said that all Graphics objects returned by the API in Java 1.2 or above will be a subclass of Graphics2D. Another hint here with the same conclusion. Graphics Object can always be cast Graphics2D g2d = (Graphics2D)g; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/179415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
]
} |
179,427 | Seems like the subtraction is triggering some kind of issue and the resulting value is wrong. double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d; 78.75 = 787.5 * 10.0/100d double netToCompany = targetPremium.doubleValue() - tempCommission; 708.75 = 787.5 - 78.75 double dCommission = request.getPremium().doubleValue() - netToCompany; 877.8499999999999 = 1586.6 - 708.75 The resulting expected value would be 877.85. What should be done to ensure the correct calculation? | To control the precision of floating point arithmetic, you should use java.math.BigDecimal . Read The need for BigDecimal by John Zukowski for more information. Given your example, the last line would be as following using BigDecimal. import java.math.BigDecimal;BigDecimal premium = BigDecimal.valueOf("1586.6");BigDecimal netToCompany = BigDecimal.valueOf("708.75");BigDecimal commission = premium.subtract(netToCompany);System.out.println(commission + " = " + premium + " - " + netToCompany); This results in the following output. 877.85 = 1586.6 - 708.75 | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/179427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25881/"
]
} |
179,439 | I checked out a project from SVN and did not specify the project type, so it checked out as a "default" project. What is the easiest way to quickly convert this into a "Java" project? I'm using Eclipse version 3.3.2. | Open the .project file and add java nature and builders. <projectDescription> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> </natures></projectDescription> And in .classpath, reference the Java libs: <classpath> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/></classpath> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/179439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917/"
]
} |
179,447 | I use Safari Books Online as a reference library and to evaluate book before I decide to buy a paper copy, but it doesn't include any Apress books. Is there a better alternative you would recommend? Edit: Safari Books Online now includes Apress titles which makes it the most complete reference library on the web in my opinion. | With my ACM membership , I get access to both Safari and Books24x7 (this includes Apress). The selection is reduced from the total offering of those sites (600 in Safari only available to professional members and 500 in Books24x7 available to both student and professional members), but I find it's well worth the ACM annual membership, especially when you factor in the other benefits. There is a discount for first year members: http://learnmore.acm.org/joinacm5.html Our local library ( nutrias.org ) does have ebooks for free also, but I haven't looked to see if they have technical books. In addition, they are term-limited with DRM (yuk). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22205/"
]
} |
179,448 | on KDE, there's a possibility to execute a command when some event happen.for example one can execute a script when kmail receives a mail or when a akregator fetches a new feed. I want to execute the script on a way I can retrieve the mail/feed subject in my script.is there a possibility to specify the program to execute: myprogram <SUBJECT> ? possibly specify it as an argument or an environment variable. | With my ACM membership , I get access to both Safari and Books24x7 (this includes Apress). The selection is reduced from the total offering of those sites (600 in Safari only available to professional members and 500 in Books24x7 available to both student and professional members), but I find it's well worth the ACM annual membership, especially when you factor in the other benefits. There is a discount for first year members: http://learnmore.acm.org/joinacm5.html Our local library ( nutrias.org ) does have ebooks for free also, but I haven't looked to see if they have technical books. In addition, they are term-limited with DRM (yuk). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65724/"
]
} |
179,452 | Can VBA code instantiate and use .NET objects? The specific class I'm interested in is System.IO.Compression.GZipStream. For Info GAC is the .NET Global Assembly Cache | I think Andy nailed this answer, but I'm not certain that the aspect regarding the CLR loading rules is exactly right. The .NET Assembly that holds the class acting as the wrapper for GZipStream would be exposed to COM and registered just like any other COM project library and class. In this regard, VBA would find the location of the COM-exposed .NET assembly via the registry. It might be smart to put the assembly in the GAC, so that it can't move (since moving the assembly would invalidate the registry info), but so long as the registry points to the right place, it should be fine. A good beginner's tutorial on the subject is here Hope this helps... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4023/"
]
} |
179,460 | If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do? For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements java.util.Map by wrapping some immutable object and exposing it's data as key/value pairs. In this case the methods put and putAll don't make sense as I have no way to modify the underlying object. So the question is what should those methods do? | Any method that cannot be implemented according to the semantics of the interface should throw an UnsupportedOperationException . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
]
} |
179,488 | Is there a list somewhere on common Attributes which are used in objects like Serializable ? Thanks Edit ~ The reason I asked is that I came across an StoredProcedure attribute in ntiers ORMS. | Yes, look msdn has you covered please look here . EDIT: This link only answer sucked. Here is a working extractor for all loadable types (gac) that have Attribute in the name. using System;using System.Collections.Generic;using System.Diagnostics;using System.Reflection;namespace ConsoleApp1{ class Program { static void Main(string[] args) { var process = new Process(); //your path may vary process.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\gacutil.exe"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.Arguments = "/l"; process.Start(); var consoleOutput = process.StandardOutput; var assemblyList = new List<string>(); var startAdding = false; while (consoleOutput.EndOfStream == false) { var line = consoleOutput.ReadLine(); if (line.IndexOf("The Global Assembly Cache contains the following assemblies", StringComparison.OrdinalIgnoreCase) >= 0) { startAdding = true; continue; } if (startAdding == false) { continue; } //add any other filter conditions (framework version, etc) if (line.IndexOf("System.", StringComparison.OrdinalIgnoreCase) < 0) { continue; } assemblyList.Add(line.Trim()); } var collectedRecords = new List<string>(); var failedToLoad = new List<string>(); Console.WriteLine($"Found {assemblyList.Count} assemblies"); var currentItem = 1; foreach (var gacAssemblyInfo in assemblyList) { Console.SetCursorPosition(0, 2); Console.WriteLine($"On {currentItem} of {assemblyList.Count} "); Console.SetCursorPosition(0, 3); Console.WriteLine($"Loading {gacAssemblyInfo}"); currentItem++; try { var asm = Assembly.Load(gacAssemblyInfo); foreach (Type t in asm.GetTypes()) { if (t.Name.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase)) { collectedRecords.Add($"{t.FullName} - {t.Assembly.FullName}"); } } } catch (Exception ex) { failedToLoad.Add($"FAILED to load {gacAssemblyInfo} - {ex}"); Console.SetCursorPosition(1, 9); Console.WriteLine($"Failure to load count: {failedToLoad.Count}"); Console.SetCursorPosition(4, 10); Console.WriteLine($"Last Fail: {gacAssemblyInfo}"); } } var fileBase = System.IO.Path.GetRandomFileName(); var goodFile = $"{fileBase}_good.txt"; var failFile = $"{fileBase}_failedToLoad.txt"; System.IO.File.WriteAllLines(goodFile, collectedRecords); System.IO.File.WriteAllLines(failFile, failedToLoad); Console.SetCursorPosition(0, 15); Console.WriteLine($"Matching types: {goodFile}"); Console.WriteLine($"Failures: {failFile}"); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
]
} |
179,492 | F# is derived from OCaml, but what major items are missing or added? Specifically I'm curious as to whether the resources available for learning OCaml are also useful to someone who wants to learn F#. | The main differences are that F# does not support: functors OCaml-style objects polymorphic variants the camlp4/5 preprocessor or extension points (ppx) In addition, F# has a different syntax for labeled and optional parameters. In theory, OCaml programs that don't use these features can be compiled with F#. Learning OCaml is a perfectly reasonable introduction to F# (and vice versa, I'd imagine). The complete list of differences is here (note: archive.org replacement of dead link). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/179492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16942/"
]
} |
179,500 | I've seen a lot of questions around that use improperly the expression "C/C++".The reasons in my opinion are: Newbie C and C++ programmers probably don't understand the difference between the two languages. People don't really care about it since they want a generic, quick and "dirty" answer While C/C++ could sometimes be interpreted as "either C or C++", I think it's a big error. C and C++ offer different approaches to programming, and even if C code can be easily implemented into C++ programs I think that referring to two separate languages with that single expression ( C/C++ ) is wrong. It's true that some questions can be considered either as C or C++ ones, anyway. What do you think about it? | C/C++ is a holdout from the early days of C++, where they were much more similar than they were today. It's something that wasn't really wrong at first, but is getting more-so all the time. The basic structure is similar enough that most simple questions do still work between the two, though. There is an entire Wikipedia article on this topic: http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B The biggest fallacy that comes from this is that because someone is well-versed in C, they will be equally good at C++. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/179500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23890/"
]
} |
179,510 | Is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely? | Do you mean the dotted outline of a target? Try: :focus { outline: 0;} This would remove all focus outlines. IT's essentially the same as onclick in JavaScript terms. You might prefer to apply this to a:focus . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/179510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.