Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I usually, almost without thinking anymore, use forward declarations so that I won't have to include headers. Something along this example: ``` //----------------------- // foo.h //----------------------- class foo { foo(); ~foo(); }; //----------------------- // bar.h //----------------------- class foo; // ...
Just use a smart pointer - you can even use auto\_ptr in this case. ``` //----------------------- // bar.h //----------------------- #include <memory> class foo; // Not enough given the way we declare "foo_object".. class bar { public: bar(); ~bar(); foo &foo_object() { return *foo_ptr; } const fo...
You can't. The compiler needs to know the size of the object when declaring the class. References are an alternative, although they have to be instantiated at construction time, so it's not always feasible. Another alternative are smart pointers, but I suppose that's technically still a pointer. It would be good to ...
Alternative to forward declarations when you don't want to #include
[ "", "c++", "physical-design", "forward-declaration", "" ]
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen(). If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
You can use [**atexit**](http://docs.python.org/library/atexit.html) for this, and register any clean up tasks to be run when your program exits. **atexit.register(func[, \*args[, \*\*kargs]])** In your cleanup process, you can also implement your own wait, and kill it when a your desired timeout occurs. ``` >>> imp...
On \*nix's, maybe using process groups can help you out - you can catch subprocesses spawned by your subprocesses as well. ``` if __name__ == "__main__": os.setpgrp() # create new process group, become its leader try: # some code finally: os.killpg(0, signal.SIGKILL) # kill all processes in my group ``` ...
Ensuring subprocesses are dead on exiting Python program
[ "", "python", "subprocess", "kill", "zombie-process", "" ]
I wrote a simple javascript image rotator which picks a random image on each page load. The issue is that if i use a default image, that default image will show up for a second before the javascript loads and replaces it. Obviously if someone has javascript disabled i want them to see an image. How can i have a default...
It sounds like you want to change the page HTML before window.onload fires (because at that point the default image has been displayed already). You need to attach your javascript function to a "DOMContentLoaded" or commonly called domready event. Dean Edwards provided us a fantastic cross-browser implementation <http...
If you hide the default image as the first thing you do when the page loads, there probably won't be a chance for the users to see the image. You can then install an onload handler on the image and change its source to your random image. When the image loads, you can unhide the image. ``` window.onload = function () {...
javascript image rotator issue, default image
[ "", "javascript", "image", "" ]
Is there a simple attribute or data contract that I can assign to a function parameter that prevents `null` from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal `null` isn't being used anywhere for it and at run-time throw `ArgumentNullException`. Currently I write somet...
There's nothing available at compile-time, unfortunately. I have a bit of a [hacky solution](https://web.archive.org/web/20081231232311/http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/non-nullable-reference-types.aspx) which I posted on my blog recently, which uses a new struct and conversions. In .NET 4.0 with ...
I know I'm incredibly late to this question, but I feel the answer will become relevant as the latest major iteration of C# comes closer to release, then released. In C# 8.0 a major change will occur, C# will assume *all* types are considered not null. According to Mads Torgersen: > The problem is that null reference...
Mark parameters as NOT nullable in C#/.NET?
[ "", "c#", ".net", "parameters", "null", "" ]
**SpousesTable** *SpouseID* **SpousePreviousAddressesTable** *PreviousAddressID*, *SpouseID*, FromDate, AddressTypeID What I have now is updating the most recent for the whole table and assigning the most recent regardless of SpouseID the AddressTypeID = 1 I want to assign the most recent SpousePreviousAddress.Addre...
Presuming you are using SQLServer 2005 (based on the error message you got from the previous attempt) probably the most straightforward way to do this would be to use the ROW\_NUMBER() Function couple with a Common Table Expression, I think this might do what you are looking for: ``` WITH result AS ( SELECT ROW_N...
Here's one way to do it: ``` UPDATE spa1 SET spa1.AddressTypeID = 1 FROM SpousePreviousAddresses AS spa1 LEFT OUTER JOIN SpousePreviousAddresses AS spa2 ON (spa1.SpouseID = spa2.SpouseID AND spa1.FromDate < spa2.FromDate) WHERE spa1.CountryID = 181 AND spa2.SpouseID IS NULL; ``` In other words, update the row ...
Sql Server Query Selecting Top and grouping by
[ "", "sql", "sql-server", "database-partitioning", "" ]
## Background We are developing some in-house utilities using ASP.NET 2.0. One of which is extracting some information from databases and building an Excel workbook containing a number of spreadsheets with data based on queries into the database. ## Problem The proof-of-concept prototype (a simple ASP.NET page that ...
Can the user that the ASP.NET Application Pool runs under have access to the application? Try logging in as that user (or change the Application Pool to run as that user) and opening Excel. If that works try running a WinForms application on the server as that user with the code that is failing. Not sure but I think t...
Consider working with **XLSX files** (new in Office 2007, but there is a plugin for Office 2003), which are just ZIP files containing XML files which you can manipulate without the need for Excel. The (XML-based) SpreadsheetML is well documented and not too complicated to program against (you might even find a LINQ to ...
Automating Excel using ASP.NET
[ "", "c#", "asp.net", "excel", "interop", "pia", "" ]
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult. I'd like to be a...
Here's an except from MVC RC1 release notes - Jan 2009 **IsMvcAjaxRequest Renamed to IsAjaxRequest** > The IsMvcAjaxRequest method been > renamed to IsAjaxRequest. As part of > this change, the IsAjaxRequest method > was updated to recognize the > X-Requested-With HTTP header. This is > a well known header sent by th...
**See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.** The way the `IsMvcAjaxRequest` extension method currently works is that it checks `Request["__MVCASYNCPOST"] == "true"`, and it only works when the method is a HTTP POST request. If you are making HTTP PO...
Is there a Request.IsMvcAjaxRequest() equivalent for jQuery?
[ "", "javascript", "jquery", "asp.net-mvc", "ajax", "" ]
Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields? ``` SYSTEMTIME sysTime; GetLocalTime( &sysTime ); char buf[80]; for (int i = 0; i < 100000; i++) { sprintf(buf, "%4d-%02d-%02d %02d:%0...
If you were writing your own function to do the job, a lookup table of the string values of 0 .. 61 would avoid having to do any arithmetic for everything apart from the year. edit: Note that to cope with leap seconds (and to match [`strftime()`](http://en.cppreference.com/w/c/chrono/strftime)) you should be able to p...
You could try filling each char in the output in turn. ``` buf[0] = (sysTime.wYear / 1000) % 10 + '0' ; buf[1] = (sysTime.wYear / 100) % 10 + '0'; buf[2] = (sysTime.wYear / 10) % 10 + '0'; buf[3] = sysTime.wYear % 10 + '0'; buf[4] = '-'; ``` ... etc... Not pretty, but you get the picture. If nothing else, it may hel...
How can I improve/replace sprintf, which I've measured to be a performance hotspot?
[ "", "c++", "c", "performance", "printf", "strftime", "" ]
I need to determine the number of pages in a specified PDF file using C# code (.NET 2.0). The PDF file will be read from the file system, and not from an URL. Does anyone have any idea on how this could be done? Note: Adobe Acrobat Reader is installed on the PC where this check will be carried out.
You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist. **iTextSharp Example** You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application. ``` using System; using System.Collections.Gene...
This should do the trick: ``` public int getNumberOfPdfPages(string fileName) { using (StreamReader sr = new StreamReader(File.OpenRead(fileName))) { Regex regex = new Regex(@"/Type\s*/Page[^s]"); MatchCollection matches = regex.Matches(sr.ReadToEnd()); return matches.Count; } } ``...
Determine number of pages in a PDF file
[ "", "c#", "pdf", ".net-2.0", "" ]
Inside my code I'm generating hashes of URLs, (which are practically of unbounded length). I'm currently using sha1(), which I know has a tiny chance of a collision, but I have up to 255 bytes to store the hash in so feel that I might as well use that available space to lower the chance of collision even further. Is t...
> Or, is sha1's 20-byte has good enough for anything and I should stop worrying about it? Exactly. Hashtables, Pigeonholes, and Birthdays <http://www.codinghorror.com/blog/archives/001014.html>
Let see... <http://www.cryptography.com/cnews/hash.html> > Q: How hard would it be to find > collisions in SHA-1? > A: The reported > attacks require an estimated work > factor of 2^69 (approximately 590 > billion billion) hash computations Looks like the risk is quite low... ^\_^
A PHP hash function with a long output length?
[ "", "php", "hash", "" ]
I have heard a few developers recently say that they are simply polling stuff (databases, files, etc.) to determine when something has changed and then run a task, such as an import. I'm really against this idea and feel that utilising available technology such as [Remoting](http://en.wikipedia.org/wiki/.NET_Remoting)...
Polling is not "wrong" as such. A lot depends on how it is implemented and for what purpose. If you really care about immedatly notification of a change, it is very efficient. Your code sits in tight loop, constantly polling (asking) a resource whether it has changed / updated. This means you are notified as soon as y...
Examples of things that use polling in this day and age: * Email clients poll for new messages (even with IMAP). * RSS readers poll for changes to feeds. * Search engines poll for changes to the pages they index. * StackOverflow users poll for new questions, by hitting 'refresh' ;-) * Bittorrent clients poll the track...
What is wrong with polling?
[ "", "c#", ".net", "asp.net", "polling", "" ]
What is the C# equivalent of Delphi's `FillChar`?
If I understand FillChar correctly, it sets all elements of an array to the same value, yes? In which case, unless the value is 0, you probably have to loop: ``` for(int i = 0 ; i < arr.Length ; i++) { arr[i] = value; } ``` For setting the values to the type's 0, there is `Array.Clear` Obviously, with the loop ...
I'm assuming you want to fill a byte array with zeros (as that's what FillChar is mostly used for in Delphi). .NET is guaranteed to initialize all the values in a byte array to zero on creation, so generally FillChar in .NET isn't necessary. So saying: ``` byte[] buffer = new byte[1024]; ``` will create a buffer of...
What is a equivalent of Delphi FillChar in C#?
[ "", "c#", "delphi", "" ]
I'd like to have some of the ScriptManager features in the new Asp.net MVC model: 1- Script combining 2- Resolving different paths for external Javascript files 3- Minify and Gzip Compression [Here](http://www.codeproject.com/KB/aspnet/HttpCombine.aspx) is what I found, but I'm not sure is the best way for MVC ap...
Maybe you could just create a new 'Scripts' controller with different actions serving different combinations of compressed JS files. Since MVC is designed with a resource oriented approach, i.e. URLs are now at the center of your programming model, why not define simple URIs for your Javascripts too ? In your views, f...
Try this: <http://www.codeplex.com/MvcScriptManager> > MvcScriptManager is aimed to port certain key features available in AjaxControlToolkit's ToolkitScriptManager into the current ASP.NET MVC Framework. You will be able to use it as a control in your ASP.NET MVC application. > > ### Features > > 1. Script combinatio...
Scriptmanager Asp.Net Mvc
[ "", "javascript", "jquery", "asp.net-mvc", "performance", "gzip", "" ]
I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example.... ``` @Entity @Table(name="widget") public class Widget { private Integer id; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer ...
From a performance and design perspective, using annotations on getters is a better idea than member variables, because the getter setters are called using reflection if placed on the field, than a method. Also if you plan to use validation and other features of hibernate, you'll have all the annotations at one place, ...
You got me on the right track toolkit. Thanks. Here's the deal... Of course, my contrived example didn't include the whole story. My Widget class was actually much larger than the example I gave. I have several extra fields/getters and I was ***MIXING*** my annotations. So I was annotating the @Id on the field but othe...
Hibernate Annotation Placement Question
[ "", "java", "hibernate", "annotations", "" ]
I currently don't know any thing about web services, except that they are used to allow an application to share its functions. * Where & how to start? * Does any book on web services work with me if I use PHP as my programming language? * Does anyone know any IRC channel for help? * Does anyone know of a directory for...
I've used two good books in the past that focus on web services and PHP. [Professional Web APIs with PHP](https://rads.stackoverflow.com/amzn/click/com/0764589547) is good if you want to quickly get started *using* 3rd party APIs (like Amazon, Google, eBay, etc.). It has tons of example PHP code to get you started. [Pr...
Web services are not hard to learn. If you already have PHP experience then you know most of what you need to do a web service. This [article](http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html) might start you off creating your first web service in php.
Can anyone show me a good source to learn web services?
[ "", "php", "web-services", "" ]
I've written some C# code that checks whether a device is present on any SerialPort by issuing a command on the port and listening for a reply. When I just set the port speed, open the port, get the serial stream and start processing, it works 100% of the time. However, some of our devices work at different speeds and ...
Having written Windows drivers for one of these sort of device once, my advice would be not to waste your time with WinDbg trying to prove what you already know - i.e. that the driver you're using is buggy. If you can find a more up-to-date driver from the PL2302, then try that, but my recommendation is that if you ha...
You can also disable "Automatic Restart" under System Properties\Advanced\Start and Recovery\Settings. Once you disable that, you can see the BSOD and look for the error message, e.g. IRQL\_LESS\_OR\_EQUAL, by searching for that error name, you can usually narrow down to the source of the problem. Btw, not many notebo...
SerialPort and the BSOD
[ "", "c#", "concurrency", "serial-port", "bsod", "" ]
Does anyone have a recommendation about web service security architecture in Java (preferably under JBoss)? Any recommended reading? I want to expose a fairly rich web service to the world but the data are sensitive and it requires authentication from the current client (Flex), accessed via RPC. I definitely do not wa...
For web services security in JBoss, I would start by reading [8.4 WS-Security](http://jbossws.jboss.org/mediawiki/index.php?title=User_Guide#WS-Security) of the [JBossWS User Guide](http://jbossws.jboss.org/mediawiki/index.php?title=User_Guide).
You could try: [![SOA Security](https://www.manning.com/kanneganti/kanneganti_cover150.jpg)](http://www.manning.com/kanneganti/)
How to go about web service security in Java
[ "", "java", "web-services", "security", "jboss", "" ]
In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences. If this code: ``` Console.WriteLine(someString); ``` produces: ``` Hello World! ``` I want this code: ``` Console.WriteLine(ToLiteral(someString)); ```...
There's a method for this in [Roslyn](https://en.wikipedia.org/wiki/.NET_Compiler_Platform)'s [Microsoft.CodeAnalysis.CSharp](https://www.nuget.org/packages/Microsoft.CodeAnalysis.CSharp/) package on NuGet: ``` private static string ToLiteral(string valueTextForCompiler) { return Microsoft.CodeAnalysis.CSharp.Symb...
A long time ago, I found this: ``` private static string ToLiteral(string input) { using (var writer = new StringWriter()) { using (var provider = CodeDomProvider.CreateProvider("CSharp")) { provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null); ...
Can I convert a C# string value to an escaped string literal?
[ "", "c#", "string", "escaping", "" ]
I need to pull some BLOB data from a SQL Server 2005 database and generate a SQL script to insert this same data in another database, in another server. I am only allowed to do this using SQL scripts, I can't use any other utility or write a program in Java or .NET to do it. The other big restriction I have is that I...
TEXTCOPY was a sample application included in SQL Server 7.0 and 2000 but no longer available in SQL Server 2005. However, googling for TEXTCOPY in SQL Server 2005, I found this alternative that might do the trick: <http://sequelserver.blogspot.com/2007/01/texcopy-sql-server-2005.html> It relies on writing and readi...
This article "[Copy Text or Image into or out of SQL Server](http://www.databasejournal.com/features/mssql/article.php/1443521/Copy-Text-or-Image-into-or-out-of-SQL-Server.htm)" could help: You could integrate the TEXTCOPY command line tool in a stored procedure: ``` CREATE PROCEDURE sp_textcopy ( @srvname varc...
Copying BLOB values between databases with pure SQL in SQL Server
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "blob", "" ]
I have a form containing a web browser control. This browser control will load some HTML from disk and display it. I want to be able to have a button in the HTML access C# code in my form. For example, a button in the HTML might call the Close() method on the form. Target platform: C# and Windows Forms (any version)
Look at the [WebBrowser.ObjectForScripting](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx) property. Managed to get Google Maps talking to a windows forms application using this.
I've implemeted this in a few applications in the past, here's how: (NB: the example below is not production ready and should be used as a guide only). First create a normal .NET class (public) that contains public methods that you wish to call from Javasvcipt running in your web browser control. Most importantly it ...
WinForms - How do I execute C# application code from inside WebBrowser control?
[ "", "c#", "winforms", "webbrowser-control", "" ]
I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g. ``` def analyser(testFunc): print testFunc.__name__, 'belongs to the class, ... ``` I thought ``` testFunc.__class__ ``` would solve my problems, but that just tells ...
``` testFunc.im_class ``` <https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy> > `im_class` is the class of `im_self` for > bound methods or the class that asked > for the method for unbound methods
From python 3.3, `.im_class` is gone. You can use `.__qualname__` instead. Here is the corresponding PEP: <https://www.python.org/dev/peps/pep-3155/> ``` class C: def f(): pass class D: def g(): pass print(C.__qualname__) # 'C' print(C.f.__qualname__) # 'C.f' print(C.D.__qualname__) #'C.D' print(C.D.g...
In Python, how can you get the name of a member function's class?
[ "", "python", "reflection", "metaprogramming", "" ]
I am wondering if it is possible to have a sort of thumbnail image gallery, in which clicking on a thumbnail would show the full image in a layer. I was wondering if it was possible to load all layers and respective images and use javascript to change the z index or something similar to avoid having to reload or leave ...
Yes, you can do it without a framework: ``` <div id='big' style='width:500px;height:500px'></div> <a href="javascript://load big image" onclick="document.getElementById('big').style.backgroundImage='url(Big.gif)'"><img border="0" src="images/Thumb.gif" /></a> ``` Here is a simple example using the [Prototype](http://...
There are plenty of thumbnail image gallerys around to bother writing one yourself unless you have a specific need. such as <http://www.huddletogether.com/projects/lightbox/>
manipulating css layers with javascript
[ "", "javascript", "html", "css", "" ]
While looking at a micro-optimization question that I asked yesterday ([here](https://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer)), I found something strange: an `or` statement in Java is running *slightly* faster than looking up a boolean value in an array of b...
Loading some random piece of data is generally slower than a little non-branching code. It all depends upon processor architecture, of course. Your first if statement could be implemented as four instructions. The second may potentially need null pointer checking, bounds checking as well as the load and compare. Also ...
I would *guess* that the issues is that range checking for the array and if the array lookup is implemented as a method call. That would certainly overshadow 4 straight int compares. Have you looked at the byte code?
Why is this code with several "or" statements slightly faster than using a lookup table in Java?
[ "", "java", "optimization", "" ]
I want to create a trace on a database server from my C# app, like what you do in SQL Server Profiler. I have found stored procedures (sys.sp\_trace\_create etc...) that dont seem to work for my SQL management studio. I was wondering if anyone could help with the coding, or where i would start to do this?!
Are you wanting this to be real-time, just like the Profiler itself? That'd be tough to do. You'd basically be re-creating the profiler. If that is not a requirement, I would recommend simply calling the sp\_trace\_create stored procs that you found to start a server-side trace, then use your application to open up th...
If you are still interested, found this code ``` public void FileToTable() { TraceServer reader = new TraceServer(); ConnectionInfoBase ci = new SqlConnectionInfo("localhost"); ((SqlConnectionInfo)ci).UseIntegratedSecurity = true; reader.InitializeAsReader(ci, @"Standard.tdf"); int eventNumber =...
Imitating SQL Server Profiler in a C# app?
[ "", "c#", "sql-server", "trace", "smo", "sql-server-profiler", "" ]
I'm a .NET developer, and worked with VB6 before that. I've become very familiar with those environments, and working in the context of garbage collected languages. However, I now wish to bolster my skillset with native C++ and find myself a bit overwhelmed. Ironically, it's not what I'd imagine is the usual stumbling ...
I know you say you've got a good grasp of pointers and memory management, but I'd still like to explain an important trick. As a general rule of thumb, *never* have new/delete in your user code. Every resource acquisition (whether it's a synchronization lock, a database connection or a chunk of memory or anything else...
I'll not repeat what others have said about libraries and such, but if you're serious about C++, do yourself a favor and pick up Bjarne Stroustrup's "The C++ Programming Language." It took me years of working in C++ to finally pick up a copy, and once I did, I spent an afternoon slapping my forehead saying "of course!...
C++ for a C# developer
[ "", "c++", "" ]
I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection? For example: ``` public string[] Items { get; set; } ``` My method so far: ``` public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new() { T to = new T(); Type...
``` if (propertyInfo.GetIndexParameters().Length > 0) { // Property is an indexer } ```
What you want is the `GetIndexParameters()` method. If the array that it returns has more than 0 items, that means it's an indexed property. See [the MSDN documentation](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getindexparameters.aspx) for more details.
C# Reflection Indexed Properties
[ "", "c#", "reflection", "clone", "" ]
I'm using a repeater control and I'm trying to pass a parameter as such: ``` <%# SomeFunction( DataBinder.Eval(Container.DataItem, "Id") ) %> ``` It's basically calling: ``` public string SomeFunction(long id) { return "Hello"; } ``` I'm not able to achieve this as I get an error: error CS1502: The b...
You need to cast the result to a long, so: ``` <%# SomeFunction( (long)DataBinder.Eval(Container.DataItem, "Id") ) %> ``` The alternative is to do something like this: ``` <%# SomeFunction(Container.DataItem) %> ``` and... ``` public string SomeFunction(object dataItem) { var typedDataItem = (TYPED_DATA_ITEM_T...
I think you should cast the DataBinder.Eval(Container.DataItem, "Id") as long.
How do you pass a Container.DataItem as a parameter?
[ "", "c#", "asp.net", "" ]
If I have a vector of pairs: ``` std::vector<std::pair<int, int> > vec; ``` Is there and easy way to sort the list in **increasing** order based on the second element of the pair? I know I can write a little function object that will do the work, but is there a way to use existing parts of the *STL* and `std::less` ...
**EDIT**: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type `auto`. **This is my current favorite solution** ``` std::sort(v.begin(), v.end(), [](auto &left, auto &right) { return left.second < right.second; }); ``` --- **ORIGINAL ANSWER**: Just use a cu...
You can use boost like this: ``` std::sort(a.begin(), a.end(), boost::bind(&std::pair<int, int>::second, _1) < boost::bind(&std::pair<int, int>::second, _2)); ``` I don't know a standard way to do this equally short and concise, but you can grab `boost::bind` it's all consisting of headers.
How do I sort a vector of pairs based on the second element of the pair?
[ "", "c++", "stl", "stdvector", "" ]
In a C# application I am working on I have a very long identifier as follows:- ``` foo.bar.bwah.blah.whatever.very.very.huge ``` Whenever I to reference this object it's an absolute nightmare, and unfortunately I do need to reference it a lot:- ``` var something = foo.bar.bwah.blah.whatever.very.very.huge.a; var som...
One way out is to use one or a pair of lambdas. For example: ``` Func<string> getter = () => blah_de_blah; Action<string> setter = x => blah_de_blah = x; ``` Now, you can use getter and setter to read and write the long identifier. However, since your dots are member accessors, the easiest way of going about it is ...
I would use namespace alias. ``` using myAlias = foo.bar.bwah.blah.whatever.very.very ``` then inside your method you just had to type: `myAlias.huge.a = "hello";`
SAFE Pointer to a pointer (well reference to a reference) in C#
[ "", "c#", ".net", "" ]
I'm looking to setup video uploads for users on a site and want to have them viewed through a Flash player. The site is already partially built (by someone else) and I'm wondering what kind of technologies there are to deal with the video files, specifically in PHP. I'm thinking the files need to be converted to an FL...
[ffmpeg](http://ffmpeg.mplayerhq.hu/) is the tool for you. It's a major opensource video encoding library that a lot of other tools are based on. It's a bit tricky to use directly, but I think there are a few wrappers around.
In adition to Daniels answer, I recommend you to check [ffmpeg-php](http://ffmpeg-php.sourceforge.net/), is a wrapper library for PHP that adds an object-oriented API for accessing and retrieving information from video and audio files using [ffmpeg](http://ffmpeg.mplayerhq.hu/). You can do a lot of things, from conver...
Add dynamic video content (YouTube like) (PHP)
[ "", "php", "flash", "mp3", "flv", "" ]
I am trying to do positioning in JavaScript. I am using a cumulative position function based on the [classic quirksmode function](http://www.quirksmode.org/js/findpos.html "Find position") that sums `offsetTop` and `offsetLeft` for each `offsetParent` until the top node. However, I am running into an issue where the e...
If the document hasn't finished loading then offsetParent can be null
I have made [a test of 2,304 divs](http://jsfiddle.net/XEHZV/3/) with unique combinations of values for `position`, `display`, and `visibility`, nested inside unique combinations of each of those values, and determined that: an otherwise-valid element that is a descendant of `<body>` will not have an `offsetParent...
What would make offsetParent null?
[ "", "javascript", "html", "positioning", "" ]
I can't seem to find an answer to this problem, and I'm wondering if one exists. Simplified example: Consider a string "nnnn", where I want to find all matches of "nn" - but also those that overlap with each other. So the regex would provide the following 3 matches: 1. **nn**nn 2. n**nn**n 3. nn**nn** I realize this...
Update 2016: To get `nn`, `nn`, `nn`, [SDJMcHattie](https://stackoverflow.com/users/772095/sdjmchattie) proposes in [the comments](https://stackoverflow.com/questions/320448/overlapping-matches-in-regex/320478?noredirect=1#comment57488084_320478) [`(?=(nn))` (see regex101)](https://regex101.com/r/ET6Rvs/1/). ``` (?=(...
Using a lookahead with a capturing group works, at the expense of making your regex slower and more complicated. An alternative solution is to tell the Regex.Match() method where the next match attempt should begin. Try this: ``` Regex regexObj = new Regex("nn"); Match matchObj = regexObj.Match(subjectString); while (...
Overlapping matches in Regex
[ "", "c#", "regex", "overlap", "" ]
Something is eluding me ... it seems obvious, but I can't quite figure it out. I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list. An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ... ...
Using straight DOM and Javascript you would want to modify the InnterHtml property of a DOM object which will contain the text boxes...most likely a div. So it would look something like: ``` var container = document.getElementById("myContainerDiv"); var html; for(var i = 0; i < selectedRooms; i++) { html = html + ...
for your select list of rooms, add an onchange event handler that will show/hide the text boses. ``` <script> //swap $ with applicable lib call (if avail) function $(id){ return document.getElementById(id); } function adjustTexts(obj){ var roomTotal = 4; var count = obj.selectedIndex; //show/hi...
Add HTML control(s) via javascript
[ "", "javascript", "html", "controls", "" ]
I have downloaded Privoxy few weeks ago and for the fun I was curious to know how a simple version of it can be done. I understand that I need to configure the browser (client) to send request to the proxy. The proxy send the request to the web (let say it's a http proxy). The proxy will receive the answer... but how ...
You can build one with the [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) class to listen for incoming requests and the [`HttpWebRequest`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) class to relay the requests.
I wouldn't use HttpListener or something like that, in that way you'll come across so many issues. Most importantly it'll be a huge pain to support: * Proxy Keep-Alives * SSL won't work (in a correct way, you'll get popups) * .NET libraries strictly follows RFCs which causes some requests to fail (even though IE, FF ...
How to create a simple proxy in C#?
[ "", "c#", ".net", ".net-2.0", "proxy", "" ]
We have a large management software that is producing big reports of all kinds, based on numerous loops, with database retrievals, objects creations (many), and so on. On PHP4 it could run happily with a memory limit of 64 MB - now we have moved it on a new server and with the same database - same code, the same repor...
A big problem we have run into was circular references between objects stopping them from freeing memory when they become out of scope. Depending on your architecture you may be able to use \_\_destruct() and manually unset any references. For our problem i ended up restructuring the classes and removing the circular ...
When I need to optimize resources on any script, I try always to analyze, profile and debug my code, I use [xDebug](http://www.xdebug.org/), and the [xDebug Profiler](http://www.xdebug.org/docs/profiler), there are other options like [APD](http://php.net/apd), and [Benchmark Profiler](http://pear.php.net/package/Benchm...
Strategies for handling memory consumption in PHP5?
[ "", "php", "memory", "" ]
Is there a way (in C#) to access the systray? I am not talking about making a notify icon. I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my o...
How do you feel about Win32 interop? I found [C/Win32 code](http://skyscraper.fortunecity.com/gigo/311/winprog/shellico.txt "this C/Win32 code") that might do the trick for you. (Actually, it looks like an interesting problem so I might try to tackle it myself, just not now). The magic appears to be that he gets a han...
Mathias Rauen's madCollection (for Delphi not c#) can list [Tray Icons](http://help.madshi.net/TrayIcons.htm). And there is a commandline tool: [Windows System Tray Scan Utility](http://exodusdev.com/products/windows-system-tray-scan-utility) I have also written (not released) my own program in Delphi (not Delphi.NET...
Systray Access
[ "", "c#", ".net", "" ]
Why does the following behave unexpectedly in Python? ``` >>> a = 256 >>> b = 256 >>> a is b True # This is an expected result >>> a = 257 >>> b = 257 >>> a is b False # What happened here? Why is this False? >>> 257 is 257 True # Yet the literal numbers compare properly ``` I am using Py...
Take a look at this: ``` >>> a = 256 >>> b = 256 >>> id(a) == id(b) True >>> a = 257 >>> b = 257 >>> id(a) == id(b) False ``` Here's what I found in the documentation for ["Plain Integer Objects"](https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong): > The current implementation keeps an array of integer obj...
> # Python's “is” operator behaves unexpectedly with integers? In summary - let me emphasize: ***Do not use `is` to compare integers.*** This isn't behavior you should have any expectations about. Instead, use `==` and `!=` to compare for equality and inequality, respectively. For example: ``` >>> a = 1000 >>> a ==...
"is" operator behaves unexpectedly with integers
[ "", "python", "int", "operators", "identity", "python-internals", "" ]
i want the result of an equation rounded to the nearest integer. e.g. ``` 137 * (3/4) = 103 ``` Consider the following incorrect code. ``` int width1 = 4; int height1 = 3; int width2 = 137; int height2 = width2 * (height1 / width1); ``` What is the proper way to perform "integer" math in C#? Do i really have to d...
As said above, you should do the multiplication before the division. Anyway you could write your expression with casting only the divisor: ``` int height2 = (int)Math.Round(width2 * (height1 / (float)width1)); ```
``` int height2 = (width2 * height1) / width1; ```
C#: How do I do simple math, with rounding, on integers?
[ "", "c#", "math", "rounding", "" ]
I occasionally see the list slice syntax used in Python code like this: ``` newList = oldList[:] ``` Surely this is just the same as: ``` newList = oldList ``` Or am I missing something?
Like NXC said, Python variable names actually point to an object, and not a specific spot in memory. `newList = oldList` would create two different variables that point to the same object, therefore, changing `oldList` would also change `newList`. However, when you do `newList = oldList[:]`, it "slices" the list, and...
`[:]` [Shallow copies](http://en.wikipedia.org/wiki/Deep_copy#Shallow_copy) the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists s...
Python list slice syntax used for no obvious reason
[ "", "python", "list", "shallow-copy", "" ]
I have an entity that maps to an external oracle table which is one of the primary data sources of my application. This entity is modelled using hibernate. The oracle table now has a complex function defined the calculates some special values. I need to call this function somehow - almost as another accessor on the en...
I have a solution using the @Formula annotation
In order to keep the decoupling from your database, provided by Hibernate, I would rely on Oracle to invoke this function, using triggers or views. The main advantage of this approach is that it is totally seamless to your Hibernate implementation.
Hibernate and Oracle native functions
[ "", "java", "oracle", "hibernate", "" ]
Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI. For example: ``` typedef std::bitset<16> WordSet; ``` Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler spec...
It's not possible in general to pick arbitrary template parameters. However, the usual way you do it is this: ``` template<int N> struct foo { static const int value = N; }; ``` and for types ``` template<typename T> struct foo { typedef T type; }; ``` You can access it then as `foo<39>::value` or `foo<int...
You can easily do this in C++11 using argument deduction and unevaluated contexts (note that demo uses C++14's variable template feature for convenience). ``` #include <type_traits> #include <iostream> template<int> struct foo {}; template<int arg_N> struct val { static constexpr auto N = arg_N; }; template<tem...
Extract C++ template parameters
[ "", "c++", "templates", "rtti", "" ]
Nested If or single if with And operator, which is better approach? **Single If with And** ``` if (txtPackage.Text != string.Empty && txtPackage.Text == "abc") { // } ``` **Nested If** ``` if (txtPackage.Text != string.Empty) { if (txtPackage.Text == "abc") { // } } ```
Are you going to do something different in the 'nested if' example if, in fact, txtPackage.Text isn't empty but contains something other than "abc"? If you aren't, I'd ask why are you checking for string.empty at all? You could just write: ``` if (txtPackage.Text == "abc") { // } ``` and be done with it. Totally...
I wasn't going to chime in, but seeing that some answers here seem to be about "I like my code to *look* like this"... I feel that I should say something :) "Better" means the code will execute faster, or it's more readable / extendable. You **would** want to nest your if's in the case that you would possibly have mul...
Which is better apply two conditions in nested If or using single with And?
[ "", "c#", "vb.net", "" ]
I'm a self-taught developer and my experience is all in small applications that I've developed. I'm currently working on an application that I've made public, and I've realized that I need to start doing good unit testing to catch regressions and generally make sure everything works. I've read up on a [previous quest...
You don't specify which [flavor of VS2008](http://msdn.microsoft.com/en-us/subscriptions/subscriptionschart.aspx) you are using. If it is Pro or above, then MSTest is bundled, but a lot of people have issues with it - it isn't always very intuitive, and it takes far too much setup to do simple things like coverage / fi...
<http://www.asp.net/learn/mvc-videos/> Storefront and the Pair Programming videos involve a lot of TDD (Test Driven Development)
Beginners introduction to unit testing in Visual Studio 2008
[ "", "c#", "visual-studio-2008", "unit-testing", "" ]
I currently have Apache HTTP Server, but I'm guessing I'll need Tomcat (and then have to configure it in a way that makes it not open to the public), a Java JDK (which I already have, but should probably update), and an IDE (I have Eclipse). But what else should I have or know before starting?
Lets see... you'll need: 1. A JDK. Preferably the [Standard Edition](http://java.sun.com/javase/downloads/index.jsp), unless you plan on using GlassFish as a J2EE server. If you do use the standard edition, you need to include the jars from your servlet container/J2EE stack to access J2EE libraries. 2. A Servlet conta...
I'd recommend having a database server installed as well- you can go pretty far with the various pure Java implementations, but anything significant will probably benefit from having a copy of MySQL around. I'd also get some sort of version control going- tortoiseSVN works really well for windows. Even if you're just ...
What do I need to write Java-based web applications and test them on my personal computer?
[ "", "java", "" ]
I need to test a url that it **does not** end with `.asp` So `test`, `test.html` and `test.aspx` should match, but `test.asp` should not match. Normally you'd test if the url **does** end with .asp and negate the fact that it matched using the NOT operator in code: ``` if(!regex.IsMatch(url)) { // Do something } ```...
The trick is to use [negative lookbehind](http://www.regular-expressions.info/lookaround.html). If you need just a yes/no answer: ``` (?<!\.asp)$ ``` If you need to match the whole URL: ``` ^.*(?<!\.asp)$ ``` These regexes will work with any URL where the file name occurs at the end of the URL (i.e. URLs without a...
Not a regexp, but c# String.EndsWith method which could easily do the job. ie ``` string test1 = "me.asp" ; string test2 = "me.aspx" ; test1.EndsWith(".asp") // true; test2.EndsWith(".asp") // false ; ```
Regular expression to match a string (1+ characters) that does NOT end in .ext (extension)
[ "", "c#", ".net", "asp.net-mvc", "regex", "" ]
I'm working on a school project and I'm getting some weird errors from Xcode. I'm using TextMate's Command+R function to compile the project. Compilation seems to work okay but linking fails with an error message I don't understand. ld output: > ld: duplicate symbol text\_field(std::basic\_istream >&)in /path/final/b...
My first thought was that you're including it twice on the linker command but it appears to be complaining about having the same function in `main.o` and `generics.o`. So it looks like you're including the `io_functions.cpp` file into the `main.cpp` and `generics.cpp` which is a bad idea at the best of times. You sho...
It sounds like io\_functions.cpp is being included twice (once by generics.cpp, once by main.cpp).
ld: duplicate symbol
[ "", "c++", "xcode", "linker", "" ]
I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to the x and the y axis, that is all of their edges will have slopes of 0 or infinity. I've tried to implement what is men...
``` if (RectA.Left < RectB.Right && RectA.Right > RectB.Left && RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top ) ``` or, using Cartesian coordinates (With X1 being left coord, X2 being right coord, **increasing from left to right** and Y1 being Top coord, and Y2 being Bottom coord, **increasing from bottom...
``` struct rect { int x; int y; int width; int height; }; bool valueInRange(int value, int min, int max) { return (value >= min) && (value <= max); } bool rectOverlap(rect A, rect B) { bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) || valueInRange(B.x, A.x, A.x + A.width...
Determine if two rectangles overlap each other?
[ "", "c++", "algorithm", "geometry", "overlap", "rectangles", "" ]
When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided. I know how to do this with Win32 functions (the `WNet*` family from `mpr.dll`), but would like to do it with .Net (2.0) functionality. What options are avail...
You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error): ``` using (n...
I liked [Mark Brackett](https://stackoverflow.com/users/2199/mark-brackett)'s answer so much that I did my own quick implementation. Here it is if anyone else needs it in a hurry: ``` public class NetworkConnection : IDisposable { string _networkName; public NetworkConnection(string networkName, Netw...
How to provide user name and password when connecting to a network share
[ "", "c#", ".net", "winapi", "networking", "passwords", "" ]
I've tried the following, but I was unsuccessful: ``` ALTER TABLE person ALTER COLUMN dob POSITION 37; ```
"[Alter column position](http://wiki.postgresql.org/wiki/Alter_column_position)" in the PostgreSQL Wiki says: > PostgreSQL currently defines column > order based on the `attnum` column of > the `pg_attribute` table. The only way > to change column order is either by > recreating the table, or by adding > columns and r...
In PostgreSQL, while adding a field it would be added at the end of the table. If we need to insert into particular position then ``` alter table tablename rename to oldtable; create table tablename (column defs go here); ### with all the constraints insert into tablename (col1, col2, col3) select col1, co...
How do I alter the position of a column in a PostgreSQL database table?
[ "", "sql", "database", "postgresql", "alter-table", "" ]
Does anyone know of a definitive list of LINQ to SQL query limitations that are not trapped at compile time, along with (where possible) workarounds for the limitations? The list we have so far is: * Calling methods such as `.Date` on `DateTime` + no workaround found * `string.IsNullOrEmpty` + simple, just use `=...
Basically, that list is huge... it is everything outside of the relatively [small set of things that **are** handled](http://msdn.microsoft.com/en-us/library/bb386970.aspx). Unfortunately, the [Law Of Leaky Abstractions](http://www.joelonsoftware.com/articles/LeakyAbstractions.html) kicks in, and each provider has diff...
LINQ is the language. LINQ-to-SQL compiles your LINQ command down into a SQL query. Thus, it is limited by the normal limitations of the TSQL syntax, or rather the items that can easily be converted into it. As others have said, the lists of what you cannot do would be enormous. It is a much smaller list of what you c...
"Cannot call methods on DateTime", and other limitations
[ "", ".net", "sql", "linq", "linq-to-sql", "" ]
This SQL query was generated by Microsoft Access 2003, and works fine when run, but fails when trying to run from a Macro. Is there any obvious error within the query, or any reason it would not work? ``` SELECT tblAuction.article_no, tblAuction.article_name, tblAuction.subtitle, tblAuction.current_bid, tblAuction.sta...
Did you mean from a Access Macro or from VBScript or from VBA? If you have a macro that is invoking an action then my recommendation would be to convert it to a VBA statement. I assume when you say it works fine when run you mean run as an Access query. You don't specify whether the database is local or is a remote one...
[This article](http://support.microsoft.com/kb/931407) is for Access 2007, but perhaps you're experiencing this as well. What's the security level you're using in Access? (Open an MDB, then go to Tools\Macro\Security...). Try lowering the security level and see if that helps.
sql query causing error 2950
[ "", "sql", "ms-access", "macros", "" ]
I am attempting to integrate an existing payment platform into my webshop. After making a succesful transaction, the payment platform sends a request to an URL in my application with the transaction ID included in the query parameters. However, I need to do some post-processing like sending an order confirmation, etc....
Many thanks for all the replies. [Smazurov's answer](https://stackoverflow.com/questions/325836/how-to-re-initialize-a-session-in-php#326915) got me thinking and made me overlook my PHP configuration once more. PHP's default behaviour is not to encrypt the session-related data, which *should* make it possible to read...
Not really what you ask for, but don't you need to persist the order into database before you send the customer to the payment-service? It's better to rely on persisted data in your post-processing of the order when you receive the confirmation of the payment. Relying on sessions is not reliable since you will have no...
How to re-initialize a session in PHP?
[ "", "php", "session", "" ]
Consider the following piece of Java code. ``` int N = 10; Object obj[] = new Object[N]; for (int i = 0; i < N; i++) { int capacity = 1000 * i; obj[i] = new ArrayList(capacity); } ``` Because in Java, all objects live on the Heap, the array does not contain the objects themselves, but references to the object...
For an array of ArrayList objects: ``` ArrayList obj[10]; ``` The objects will be default initialised, which is fine for user-defined types, but may not be what you want for builtin-types. Consider also: ``` std::vector<ArrayList> obj(10, ArrayList()); ``` This initialises the objects by copying whatever you pass ...
Simply declaring ``` Object array_of_objects[10]; ``` in C++ creates 10 default-constructed objects of type Object on the stack. If you want to use a non-default constructor, that's not so easy in C++. There might be a way with placement new but I couldn't tell you off the top of my head. **EDIT: Link to other ques...
C++: how to create an array of objects on the stack?
[ "", "c++", "arrays", "stack", "oop", "" ]
I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app? In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things): ``` class Movie(models.Model): title = models.CharField(max_length=255) ``...
According to the docs, your second attempt should work: > To refer to models defined in another application, you must instead explicitly specify the application label. For example, if the Manufacturer model above is defined in another application called production, you'd need to use: ``` class Car(models.Model): ...
It is also possible to pass the class itself: ``` from django.db import models from production import models as production_models class Car(models.Model): manufacturer = models.ForeignKey(production_models.Manufacturer) ```
Foreign key from one app into another in Django
[ "", "python", "django", "django-models", "" ]
My code runs inside a JAR file, say **foo.jar**, and I need to know, in the code, in which folder the running **foo.jar** is. So, if **foo.jar** is in `C:\FOO\`, I want to get that path no matter what my current working directory is.
``` return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation() .toURI()).getPath(); ``` Replace "MyClass" with the name of your class. Obviously, this will do odd things if your class was loaded from a non-file location.
Best solution for me: ``` String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); ``` This should solve the problem with spaces and special characters.
How to get the path of a running JAR file?
[ "", "java", "path", "jar", "executable-jar", "" ]
Does anyone know of a good, extensible source code analyzer that examines JavaScript files?
In the interest of keeping this question up-to-date, there is a fork of JSLint called [JSHint](http://jshint.com/). An explanation of why JSHint was created can be found [here](http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/), but to summarize: > JSHint is a fork of JSLint, the tool > written and m...
[JSLint](http://www.jslint.com/) has historically been the main tool for this, but several more now exist: * [JSHint](http://jshint.com/) - a fork of JSLint that is said to be a little less opinionated * [Closure Linter](https://developers.google.com/closure/utilities/) - a linter that checks against the [Google Javas...
JavaScript Source Code Analyzer
[ "", "javascript", "code-analysis", "" ]
I have a linq to sql database. Very simplified we have 3 tables, Projects and Users. There is a joining table called User\_Projects which joins them together. I already have a working method of getting `IEnumberable<Project>` for a given user. ``` from up in User_Projects select up.Project; ``` Now I want to get the...
Linq to Sql doesn't understand how to work with an arbitrary in-memory sequence of objects. You need to express this in relational terms, which works on IDs: ``` var userProjectIds = from project in GetProjects() select project.ProjectId; var nonUserProjects = from project in db.Projects where !userPr...
You could try something simple like ``` User u = SomeUser; from up in User_Projects where up.User != u select up.Project; ```
IEnumerable.Except wont work, so what do I do?
[ "", "c#", "linq", "" ]
I need a 2d political map of the world on which I will draw icons, text, and lines that move around. Users will interact with the map, placing and moving the icons, and they will zoom in and out of the map. The Google Maps interface isn't very far from what I need, but this is NOT web related; it's a Windows MFC appli...
Perhaps: <http://www.codeplex.com/SharpMap> ESRI MapObjects <http://www.esri.com/software/mapobjects/index.html> ESRI MapObjects LT <http://www.esri.com/software/mapobjectslt/index.html> See <http://www.esri.com/software/mapobjectslt/about/mo_vs_lt.html> for a comparison of the two MapObjects feature sets. ESRI may ...
You might want to try the [Mapnik C++/Python GIS Toolkit](http://www.mapnik.org/). You can take a look at the [Marble Widget](http://edu.kde.org/marble/#developers), which is part of KDE's Marble project. There are Windows binaries for this, too, but they might be dependent on Qt.
Need a client-side interactive 2D world map: best map package? Or best C++ graphics/canvas library to make one?
[ "", "c++", "graphics", "google-maps", "canvas", "sdl", "" ]
I am working on a Windows Forms app for quite some time now, and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code. What I mean becomes apparent if you watch the ComboBox control that accepts some vague "object" as it's item. Then you go off and may display some D...
While the criticism of "didn't use generics" can't be fairly applied to controls developed before their existence... one must wonder about WPF controls (new in .NET 3.0, after generics in .NET 2.0). I checked out the [AddChild](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.addchild.aspx)...
I dont think you're missing anything. It's just that these classes were created back in the pre-Generics days, and WinForms is simply not cutting edge enough for MS to spend a lot of time changing or extending the API.
Strongly Typed Controls in .NET
[ "", "c#", ".net", "winforms", "generics", "" ]
I'm trying to find out the most efficient (best performance) way to check date field for current date. Currently we are using: ``` SELECT COUNT(Job) AS Jobs FROM dbo.Job WHERE (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0) AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1)...
``` WHERE DateDiff(d, Received, GETDATE()) = 0 ``` Edit: As lined out in the comments to this answer, that's not an ideal solution. Check the other answers in this thread, too.
If you just want to find all the records where the Received Date is today, and there are records with future Received dates, then what you're doing is (very very slightly) wrong... Because the Between operator allows values that are equal to the ending boundary, so you could get records with Received date = to midnight...
Best way to check for current date in where clause of sql query
[ "", "sql", "t-sql", "stored-procedures", "performance", "" ]
I use an SQL statement to remove records that exist on another database but this takes a very long time. Is there any other alternative to the code below that can be faster? Database is Access. email\_DB.mdb is from where I want to remove the email addresses that exist on the other database (table Newsletter\_Subscri...
I would use **WHERE Subscriber\_Email IN (Email, Email0)** as the WHERE clause ``` SQLRemoveDupes = "DELETE FROM Newsletter_Subscribers WHERE EXISTS " & _ (select * from [" & strDBPath & "Customers].Customers where Subscriber_Email IN (Email, EmailO)" ``` I have found from experience that using an OR predicate in a ...
Assuming there's an ID-column present in the Customers table, the following change in SQL should give better performance: "DELETE FROM Newsletter\_Subscribers WHERE ID IN (select ID from [" & strDBPath & "Customers].Customers where Subscriber\_Email = Email or Subscriber\_Email = EmailO)" PS. The ideal solution (judg...
Improve asp script performance that takes 3+ minutes to run
[ "", "sql", "asp-classic", "" ]
> Write a class ListNode which has the following properties: > > * int value; > * ListNode \*next; > > Provide the following functions: > > * ListNode(int v, ListNode \*l) > * int getValue(); > * ListNode\* getNext(); > * void insert(int i); > * bool listcontains(int j); > > Write a program which asks the user to enter...
What unwind and ckarmann say. Here is a hint, i implement listcontains for you to give you the idea how the assignment could be meant: ``` class ListNode { private: int value; ListNode * next; public: bool listcontains(int v) { // does this node contain the value? if(value == v) return tr...
I think you misunderstood the requested design. The ListNode class is supposed to be a node, not a list containing nodes. I would advise you not to put several commands on a single ligne, like this: ``` cout << "Please input integer number " << intNode << ": "; cin >> intInput; ``` This is simply confusing.
C++ Pointers / Lists Implementation
[ "", "c++", "list", "pointers", "" ]
I query all security groups in a specific domain using ``` PrincipalSearchResult<Principal> results = ps.FindAll(); ``` where ps is a PrincipalSearcher. I then need to iterate the result (casting it to a GroupPrincipal first ) and locate the ones that contains a specific string in the notes field. But the Notes fie...
I have been returning to this challange over and over again, but now I have finally given up. It sure looks like that property is inaccessible.
You can access the 'notes' field of a directory entry as such: ``` // Get the underlying directory entry from the principal System.DirectoryServices.DirectoryEntry UnderlyingDirectoryObject = PrincipalInstance.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry; // Read the content of the 'notes' pr...
How to access the notes field on a GroupPrincipal object
[ "", "c#", "active-directory", "" ]
I've been working a little with DevExpress CodeRush and Refactor! Pro this week, and I picked up a commentor plug-in that will automatically generate comments as you type code. I don't want to go into how good a job it does of picking out basic meaning (pretty good, actually) but it's default implementation does raise...
I think comments like that are useless, unless of course the code is awful. With proper formatting of code it's not difficult to see where a block starts and where a block ends because usually those blocks are indented. Edit: If a procedure is so big that is not readily apparent what block of code is being closed by a...
I find the idea of a plugin that genrates comments from code rather useless. If it can be inferred by the machine then it can also be inferred by anybody reading it. The comments are extremely likely to be totally redundant. I feel that those closing brace comment is messy, it gives information that is better provided...
C# comments on closing {}
[ "", "c#", "devexpress", "comments", "" ]
Say I have 2 tables: Customers and Orders. A Customer can have many Orders. Now, I need to show any Customers with his latest Order. This means if a Customer has more than one Orders, show only the Order with the latest Entry Time. This is how far I managed on my own: ``` SELECT a.*, b.Id FROM Customer a INNER JOIN ...
I don't think you do want to use MAX() as you don't want to group the OrderID. What you need is an ordered sub query with a SELECT TOP 1. ``` select * from Customers inner join Orders on Customers.CustomerID = Orders.CustomerID and OrderID = ( SELECT TOP 1 subOrders.OrderID ...
Something like this should do it: ``` SELECT X.*, Y.LatestOrderId FROM Customer X LEFT JOIN ( SELECT A.Customer, MAX(A.OrderID) LatestOrderId FROM Order A JOIN ( SELECT Customer, MAX(EntryTime) MaxEntryTime FROM Order GROUP BY Customer ) B ON A.Customer = B.Customer AND A.EntryTime = B.MaxEntryTime GROUP...
SQL Statement Help - Select latest Order for each Customer
[ "", "sql", "sql-server-2005", "" ]
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible and also not to conflict with different lib/version that is already on my system. L.E.: Sorry i forgot to specify. I will be doing this on linux. And I'm not referring in making my app a installable file lik...
You can have your users run the system from a startup script, and that script can fix the pythonpath ahead of time to put your versions first. For example if you put CherryPy, SQLAlchemy, etc. in an "external" subdirectory, you could try: ``` # startproj.sh script_path=`dirname $0` export PYTHONPATH=${script_path}/ext...
You could try `freeze.py`, see <http://wiki.python.org/moin/Freeze> for more details.
How to pack python libs I'm using so I can distribute them with my app and have as few dependencies as possible
[ "", "python", "linux", "deployment", "" ]
I'm quite confused about the basic concepts of a Hash table. If I were to code a hash how would I even begin? What is the difference between a Hash table and just a normal array? Basically if someone answered this question I think all my questions would be answered: If I had 100 randomly generated numbers (as keys), h...
The answers so far have helped to define hash tables and explain some theory, but I think an example may help you get a better feeling for them. *What is the difference between a hash table and just a normal array?* A hash table and an array are both structures that allow you to store and retrieve data. Both allow yo...
First, you have to understand a what a hash function is. A hash function is a function that takes a key (for example, an string of arbritrary length) and returns a number *as unique as possible*. The same key must always return the same hash. A really simple string hashing function in java might look like ``` public i...
The fundamentals of Hash tables?
[ "", "java", "hashtable", "" ]
I'm looking for a PHP (with MYSQL) nested sets class with all needed functions. For example: createLeftNode, createRightNode,createRootNode, createSubNode,deleteNode and **moveTree**. Not only 1 left, 1 right, 1 up and 1 down but also a part of a tree in a nother tree. Thanks!
Well nested sets are great if you are working with hierarchical data. It's much more complex to implement it only with php arrays especially if you want to save these information in a database. you could try this on. Never used it but after a short code screening it looks almost complete. <http://www.edutech.ch/contr...
look at the [nested behavior](http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/behaviors.html#nesting-behaviors) of Doctrine
Searching for the best PHP nested sets class (PEAR class excluded)
[ "", "php", "class", "nested", "set", "nested-sets", "" ]
I was really looking at the differences between pass by value and how Java allocates objects and what java does to put objects on the stack. Is there anyway to access objects allocated on the heap? What mechanisms does java enforce to guarantee that the right method can access the right data off the heap? It seems li...
There is no instruction in the JVM instruction set that gives arbitrary access to the heap. Hence, bytecode manipulation will not help you here. The JVM also has a verifier. It checks the code of every method (as a class is being loaded) to verify that the method does not try to pop more values off the execution stack...
All objects in Java are located on the heap. I'm not quite sure what you mean by "access objects from the heap". The only things stored on the stack are the list of functions which called into the current context and their local variables and parameters. All local variables and parameters are either primitive types or ...
General Question: Java has the heap and local stack. Can you access any object from the heap?
[ "", "java", "jvm", "stack", "heap-memory", "" ]
I have some HTML and jQuery that slides a `div` up and down to show or hide` it when a link is clicked: ``` <ul class="product-info"> <li> <a href="#">YOU CLICK THIS TO SHOW/HIDE</a> <div class="toggle"> <p>CONTENT TO SHOW/HIDE</p> </div> </li> </ul> ``` ``` $('div.toggle').hide(); $('ul.product...
Try something like: ``` $('div.toggle').hide(); $('ul.product-info li a').click(function(event) { event.preventDefault(); $(this).next('div').slideToggle(200); }); ``` Here is the page about that in the [jQuery documentation](http://learn.jquery.com/events/event-basics/#preventdefault)
Set the **`href`** attribute as `href="javascript:;"` ``` <ul class="product-info"> <li> <a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a> <div class="toggle"> <p>CONTENT TO SHOW/HIDE</p> </div> </li> </ul> ```
preventDefault() on an <a> tag
[ "", "javascript", "jquery", "" ]
Is there any way to direct C# to ignore `NullReferenceException` (or any specific exception for that matter) for a set of statements. This is useful when trying to read properties from a deserialized object that may contain many null objects in it. Having a helper method to check for null could be one way but I'm looki...
now I'm using delegate and NullReferenceException handling ``` public delegate string SD();//declare before class definition string X = GetValue(() => Message.instance[0].prop1.prop2.ID); //usage //GetValue defintion private string GetValue(SD d){ try { return d(); } catch...
In short: no. Null-check the reference before trying to use it. One useful trick here might be C# 3.0 extension methods... they allow you to *appear to* invoke something on a null reference without error: ``` string foo = null; foo.Spooky(); ... public static void Spooky(this string bar) { Console.WriteLine("boo!"...
Ignore NullReferenceException when reading object properties
[ "", "c#", ".net", "exception", "language-features", "serialization", "" ]
I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices. If not, how do I detect a mobile device? My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device. ...
I'm not sure how the IPhone/iPod Touch declare themselves when requesting the stylesheet, but for most, using ``` <style type="text/css"> @media handheld { /* handheld styles */ } </style> ``` should do the trick. It works in the same way @media print does (or doesn't). For a complete list of media...
Mobile browsers are a real hodge-podge in terms of what they support, whether they follow the "media" attribute on your styles, etc. I would say aim for [progressive enhancement](http://www.alistapart.com/articles/progressiveenhancementwithcss) (that's one of a series of articles) and make sure that if the browser onl...
Web Site Designing for Mobile
[ "", "c#", "css", "mobile", "" ]
I have this code ``` <?php session_start(); if (isset($_GET["cmd"])) $cmd = $_GET["cmd"]; else die("You should have a 'cmd' parameter in your URL"); $pk = $_GET["pk"]; $con = mysql_connect("localhost","root","geheim"); if(!$con) { die('Connection failed because of' .mysql_error()); } mysql_select_db("ebay",$con);...
It should be: ``` echo "<img src=\"".$row['PIC_URL']."\">"; ```
`<style ty</td>` looks like the problem to me.
cant display image from database outside of table in php
[ "", "php", "html", "" ]
I'm having trouble trying to optimize the following query for sql server 2005. Does anyone know how could I improve it. Each one of the tables used there have about 40 million rows each. I've tried my best trying to optimize it but I manage to do the exact opposite. Thanks ``` SELECT cos , SIN FROM ...
It seems that the query is just combining the separated history tables into a single result set containing all the data. In that case the query is already optimal.
Another approach would be to tackle the problem of why do you need to have all the 160 million rows? If you are doing some kind of reporting can you create separate reporting tables that already have some of the data aggregated. Or do you actually need a data warehouse to support your reporting needs.
Optimizing unions
[ "", "sql", "sql-server-2005", "optimization", "" ]
I have the following problem: I open the dialog, open the SIP keyboard to fill the form and then minimize the SIP. Then when I close the current dialog and return to the main dialog the SIP keyboard appears again. Does anyone know how could I show/hide SIP keyboard programatically or better what could be done to solve...
We use [SHSipPreference](http://msdn.microsoft.com/en-us/library/aa458034.aspx) to control the display of the SIP in our applications. I know it works with MFC and it sets the state of the SIP for the window so you can set it once and you know the SIP state will be restored to your set state every time the window is sh...
You'll want to call **SipShowIM**() in coredll. See this MSDN article: <http://msdn.microsoft.com/en-us/library/ms838341.aspx>
how to show/hide SIP on Pocket PC
[ "", "c++", "windows-mobile", "pocketpc", "" ]
I am using the following code to set a tray icon in Windows and Linux. It works wonderful in Windows and works okay in Linux. In Linux (Ubuntu) I have my panel set to be (somewhat) transparent and when I add a GIF (with a transparent background) the background of the icon shows up all grey and ugly (see image, green di...
Chances are this problem cannot be resolved. It depends on wether Java is doing a good job in creating the tray subwindow in Linux or not. If Jave does it wrong, transparency is already lost when the image is drawn. 1. What is the real background value of the icon you are using? Is it the gray tone shown above? Set it...
The problem lies in the sun.awt.X11.XTrayIconPeer.IconCanvas.paint() method! Before painting, the icon background is amateurishly cleared by simply drawing a rectangle of IconCanvas’ background color, to allow image animations. ``` public void paint(Graphics g) { if (g != null && curW > 0 && curH > 0) { B...
java TrayIcon using image with transparent background
[ "", "java", "linux", "panel", "gnome", "tray", "" ]
What's the best way to do it in .NET? I always forget what I need to `Dispose()` (or wrap with `using`). EDIT: after a long time using `WebRequest`, I found out about customizing `WebClient`. Much better.
Following Thomas Levesque's comment [here](https://stackoverflow.com/questions/1469805/c-canonical-http-post-code/1474861#1474861), there's a simpler and more generic solution. We create a `WebClient` subclass with timeout support, and we get all of [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webcli...
Syncronous Way: ``` var request = HttpWebRequest.Create("http://www.contoso.com"); request.Timeout = 50000; using (var response = request.GetResponse()) { //your code here } ``` You can also have the asynchronous way: ``` using System; using System.Net; using System.IO; using System.Text; using System.Threading;...
C#: Downloading a URL with timeout
[ "", "c#", "httpwebrequest", "timeout", "webrequest", ".net-3.0", "" ]
So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on. I would like to use generics to create a general class for this scenario. Something like: ``` Adder<Double> adder = new Adder<Double>();...
Uh oh---generics are not C++ templates. Because of type erasure, the `Double` in your example won't even show through to the runtime system. In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g., `double add(double, double)`, `float add(float, fload)...
I *think* you can do what you want, but I'm not sure, given the information you provided. It sounds as if you want some variation of the following: ``` public class Foob<T extends Number> { public T doSomething(T t1, T t2) { return null; } } ```
Java: Using generics to implement a class that operates on different kinds of numbers
[ "", "java", "generics", "" ]
It's hard to put this into the title, so let me explain. I have an application that uses Direct3D to display some mesh and directshow(vmr9 + allocator) to play some video, and then send the video frame as texture to the Direct3D portion to be applied onto the mesh. The application needs to run 24/7. At least it's allo...
Yes you can do this with Direct3D 9Ex. This only works with Vista and you must use a Direct3DDevice9Ex. You can read about sharing [resources here.](http://msdn.microsoft.com/en-us/library/bb219800(VS.85).aspx)
> Now the problem is that directshow seems to be giving problem after a few hours of playback, either due to the codec, video driver or video file itself. At which point the application simply refuse playing anymore video. Why not just fix this bug instead?
Pass texture using pointer across process
[ "", "c#", ".net", "directx", "directshow", "direct3d", "" ]
Use case: 3rd party application wants to programatically monitor a text file being generated by another program. Text file contains data you want to analyze as it's being updated. I'm finding a lot of answers to this question wrapped around FileSystemWatcher but let's say you are writing an application for a Windows m...
You can monitor a directory with [FindFirstChangeNotification](http://msdn.microsoft.com/en-us/library/aa364417.aspx) works on any windows. It's efficent if you know where the file is - otherwise you can use the virtual driver/Filemon described below to check for changes anywhere on the system. Example code [here](h...
A simpler solution could be to check the last modified time stamp of the file. If you use the \_stat64() function to do this, it becomes a cross-platform solution. Example code: ``` struct __stat64 fileinfo; if(-1 != _stat64(filename, &fileinfo) return fileinfo.st_mtime; ```
How do I Monitor Text File Changes with C++? Difficulty: No .NET
[ "", "c++", "file", "monitoring", "" ]
In an interview for a SQL DBA position a while back, I mentioned I prefer the SQL 2005 Management Studio app vs. the old 2000 versions of Enterprise Manager / Query Analyzer. The DBA who was interviewing me said that they had experienced some sort of database corruption in their 2000 databases when making changes from ...
It sounds like he was just was using that as an excuse for lack of experience with SQL 2005 Management Studio. DBAs hate change.
I have never encountered this, in almost three years of using SQL Management Studio 2005 to manage SQL 2000 databases. There are a few tasks I still bounce back into EntMan for, but I've never had a database encounter even the minutest bit of corruption. (And background: As a consultant, I'm managing about 45 different...
Is there danger of corruption in SQL Server 2000 databases when using SQL Server 2005 Management Studio?
[ "", "sql", "sql-server", "ssms", "" ]
I need a standard, Microsoft delivered, encryption library that works for both .NET 2.0 and C++. What would you suggest? We find that AES is only offered in .NET 3.5 (and available in C++) We find that Rijndael is used in .NET 2.0 but not available in the standard C++ libraries. If I am wrong (very good chance), can...
We successfully do a similar thing that I hope might help you: ### C++ CryptoAPI * [CryptoAPI](http://msdn.microsoft.com/en-us/library/aa380239(VS.85).aspx) is pure Win32 (c/c++), native to all Microsoft OS's. * Use [Enhanced Cryptographic Provider](http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx) (`MS_E...
AES and Rijndael are essentially the same algorithm with a restriction on block size and cipher mode. So as long as you can live with the [restrictions](http://blogs.msdn.com/shawnfa/archive/2006/10/09/The-Differences-Between-Rijndael-and-AES.aspx) (which are not onerous) you can use them interchangeably.
Encryption algorithm/library for .NET 2.0 + C++
[ "", "c++", "encryption", ".net-2.0", "aes", "rijndael", "" ]
Delegates look like such a powerful language feature, but I've yet to find an opportunity to use them in anger (apart from in DALs I must say). How often do you use them, and under what circumstances do you find them most useful?
Funcs and Actions are newish "types" of delegates and I use them a lot with Linq and really other odd situations. For Linq they are nice because personally I'd rather have a descriptive name than a lambda expression: ``` someList.Select(item => item.Name); ``` Where with a Func I can: ``` Func<Item, String> itemName...
I use C# Delegate the most of time with Event. ``` public delegate void MyDelegate(object sender, EventArgs e, string otherParameterIWant); //...Inside the class public event MyDelegate myEvent; //...Inside a method if (myEvent != null) myEvent(this, new EventArgs(), "Test for SO"); ```
C# Delegates - How Often Do You Use Them, And When?
[ "", "c#", "delegates", "" ]
Thanks for reading this. I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and ...
`$(this)` is only relevant within the scope of the function. outside of the function though, it loses that reference: ``` $('.classSelect').one("click", function() { $(this); // refers to $('.classSelect') $.ajax({ // content $(this); // does not refer to $('.classSelect') }); }); ``` a better way ...
I believe that this is because the function attached to the success event doesn't know what 'this' is as it is run independently of the object you're calling it within. (I'm not explaining it very well, but I think it's to do with closures.) I think if you added the following line before the $.ajax call: ``` var _thi...
jQuery: Referencing the calling object(this) when the bind/click event is for a class
[ "", "javascript", "jquery", "" ]
Is there an elegantish way in Swing to find out if there are any tooltips currently being displayed in my frame? I'm using custom tooltips, so it would be very easy to set a flag in my `createToolTip()` method, but I can't see a way to find out when the tooltip is gone. `ToolTipManager` has a nice flag for this, tipS...
It appears that the isEnabled() property of the hideTipAction is directly tied to the tipShowing boolean. You could try this: ``` public boolean isTooltipShowing(JComponent component) { AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip"); return hideTipAction.isEnabled(); }...
It looks like that is going to require looping over all of the components to see if they have a tooltip. I'm looking for a global value. It may be that a loop is doable, but it seems inefficient.
Can Swing tell me if there is an active tooltip?
[ "", "java", "swing", "tooltip", "" ]
I've added a weakly named assembly to my [Visual Studio 2005](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005) project (which is strongly named). I'm now getting the error: > "Referenced assembly 'xxxxxxxx' does not have a strong name" Do I need to sign this third-party assembly?
To avoid this error you could either: * Load the assembly dynamically, or * Sign the third-party assembly. You will find instructions on signing third-party assemblies in *[.NET-fu: Signing an Unsigned Assembly (Without Delay Signing)](https://dzone.com/articles/net-fu-zero-delay-signing-of-a)*. ### Signing Third-Pa...
Expand the project file that is *using* the project that does not "have a strong name key" and look for the `.snk` file (.StrongNameKey). Browse through to this file in [Windows Explorer](http://en.wikipedia.org/wiki/Windows_Explorer) (just so that you know where it is). Back in Visual Studio in the project that does...
How to fix "Referenced assembly does not have a strong name" error
[ "", "c#", "visual-studio", "visual-studio-2005", "assemblies", "strongname", "" ]
What's a better way to start a thread, `_beginthread`, `_beginthreadx` or `CreateThread`? I'm trying to determine what are the advantages/disadvantages of `_beginthread`, `_beginthreadex` and `CreateThread`. All of these functions return a thread handle to a newly created thread, I already know that CreateThread provi...
`CreateThread()` is a raw Win32 API call for creating another thread of control at the kernel level. `_beginthread()` & `_beginthreadex()` are C runtime library calls that call `CreateThread()` behind the scenes. Once `CreateThread()` has returned, `_beginthread/ex()` takes care of additional bookkeeping to make the C...
There are several differences between `_beginthread()` and `_beginthreadex()`. `_beginthreadex()` was made to act more like `CreateThread()` (in both parameters and how it behaves). As [Drew Hall](https://stackoverflow.com/questions/331536/windows-threading-beginthread-vs-beginthreadex-vs-createthread-c#331567) mentio...
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
[ "", "c++", "c", "multithreading", "winapi", "" ]
What is the correct syntax for this: ``` IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse(); ``` What am I messing up? What does TSource mean?
The problem is that you're calling `List<T>.Reverse()` which returns `void`. You could either do: ``` List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>(); names.Reverse(); ``` or: ``` IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>(); ``` The latter is more expensive, as reve...
I realize that this question is quite old, but I had a similar problem, except my string had spaces included in it. For those that need to know how to separate a string with more than just commas: ``` string str = "Tom, Scott, Bob"; IList<string> names = str.Split(new string[] {","," "}, StringSplitOptions.RemoveE...
C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order
[ "", "c#", "generics", "syntax", "ilist", "" ]
My code is like the following: ``` URLConnection cnx = address.openConnection(); cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); InputStream is = cnx.getInputStream(); ``` Is it ok if I set the headers...
The headers **must** be set prior to getting the `InputStream` to have any affect - an `IllegalStateException` will be thrown if the connection is already open. As far as the `User-Agent` header specifically, it should be sent if it has been set. See the [URLConnection](http://docs.oracle.com/javase/6/docs/api/java/n...
To answer the question, the code is correct. The moment getInputStream(), an HTTP get is sent to the target server. A side-note on user-agent, if you don't set it, URLConnection will send the default one anyway, which is: ``` User-Agent: Java/1.6.0_24 (varies depending on your java version) ```
What is the proper way of setting headers in a URLConnection?
[ "", "java", "header", "urlconnection", "" ]
I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products. **...
Try this ``` SELECT inv_t.product_id, inventory_total-nvl(sales_total,0) FROM (SELECT product_id, sum(quantity) as inventory_total FROM inventory GROUP BY product_id) inv_t LEFT OUTER JOIN (SELECT product_id, count(*) AS sales_total FROM sales GROUP BY product_id) sale_t ON (inv_t.product_id = sal...
``` SELECT product AS prd, SUM(quantity) - IFNULL((SELECT COUNT(*) FROM sells WHERE product = prd GROUP BY product), 0) AS stock FROM bought GROUP BY product; ``` This one also works when quantity sold is 0.
Finding difference in row count of two tables in MySQL
[ "", "mysql", "sql", "count", "sum", "" ]
When I discovered [`boost::lexical_cast`](http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm) I thought to myself "why didn't I know about this sooner!" - I hated having to write code like ``` stringstream ss; ss << anIntVal; mystring = ss.str(); ``` Now I write ``` mystring = boost::lexical_cast<...
Probably the most used part of boost for me is [boost::shared\_ptr](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm).
[BOOST\_FOREACH](http://www.boost.org/doc/libs/1_39_0/doc/html/foreach.html) makes life worthwhile again. (Why has nobody mentioned this? The question was asked 8 months ago!)
Most used parts of Boost
[ "", "c++", "boost", "" ]
I want to create maintainable code, but this inheritance situation is causing me problems. The issue is with my 2nd database helper class named **InitUserExtension**. Since UserExtension inherits from User, I have to make sure that I **mirror** any changes in my InitUser helper to InitUserExtension. I really don't l...
How about moving the processing of Name etc into a method (accepting either a User or a T : User), and call that from both? ``` private static void InitUser(User user, SqlDataReader dr) { // could also use an interface here, or generics with T : User user.Name = Convert.ToString(dr["name"]); user.Age ... } publi...
Why don't you call `InitUser` from the `InitUserExtension` method. Let the base initialization handle the base class properties and let the extended initializer handled the extension class properties.
Inherited class quagmire, how to make this maintainable code
[ "", "c#", "coding-style", "" ]
I'm working on a webservice + AJAX interface, and I'm worried about authentication. This moment I'm passing username and password to the webservice as arguments, but I fear that this approach is highly insecure. I was told that ssl could solve my problem, but I want more alternatives. My webservice is written in php a...
AJAX request are no different to normal request. Since you have an AJAX interface I guess you can have a page where users log-in. When they log-in store a cookie at the browser. This cookie can then be sent back with every AJAX request. Your PHP script can "authenticate" the AJAX request using the cookie exactly as i...
There are various standards like ws-trust, ws-security, ws-federation etc. which you could rely upon to secure your webservices. You can also sign your soap headers containing security information. The following blog details out various authentication mechanism for webservices using php. <http://phpwebservices.blogsp...
Webservice Authentication
[ "", "php", "html", "ajax", "web-services", "authentication", "" ]
I need to create an `XmlDocument` with a root element containing multiple namespaces. Am using C# 2.0 or 3.0 Here is my code: ``` XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("JOBS", "http://www.example.com"); doc.AppendChild(root); XmlElement job = doc.CreateElement("JOB", "http://www.ex...
The following will generate the desired output that you requested above: ``` XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("JOBS"); root.SetAttribute("xmlns:JOBS", "http://www.example.com"); root.SetAttribute("xmlns:JOB", "http://www.example.com"); doc.AppendChild(root); XmlElement job = d...
You can explicitly create namespace prefix attributes on an element. Then when you add descendant elements that are created with both the same namespace and the same prefix, the XmlDocument will work out that it doesn't need to add a namespace declaration to the element. Run this example to see how this works: ``` ...
How do I add multiple namespaces to the root element with XmlDocument?
[ "", "c#", ".net", "xml", "namespaces", "xmldocument", "" ]
How do I retrieve an item at random from the following list? ``` foo = ['a', 'b', 'c', 'd', 'e'] ```
Use [`random.choice()`](https://docs.python.org/library/random.html#random.choice): ``` import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) ``` For [cryptographically secure](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) random choices (e.g., for generating...
If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using `random.sample` instead. ``` import random group_of_items = {'a', 'b', 'c', 'd', 'e'} # a sequence or set will work here. num_to_select = 2 # set the number to select here. list_o...
How can I randomly select (choose) an item from a list (get a random element)?
[ "", "python", "list", "random", "" ]
I am really new to Python and I have been looking for an example on how to write a Web Service (XML - SOAP) in Python with Google App Engine with no luck. Can anyone point me to an article or give me an example on how to do this?
I was curious about this myself and not finding anything I decided to try to get something to work. The short answer is that it turns out a SOAP service can actually be done using the latest alpha [ZSI library](http://pywebsvcs.sourceforge.net/zsi.html). However it isn't simple and I didn't do much more than a simple r...
If you want to do something with App Engine specifically, there are libraries that will make it much faster on your end. I'd recommend looking at the XML-RPC and REST examples. <http://appengine-cookbook.appspot.com/recipe/xml-rpc-server-using-google-app-engine/> <http://github.com/fczuardi/gae-rest/tree/master>
How to write a Web Service for Google App Engine?
[ "", "python", "xml", "web-services", "google-app-engine", "soap", "" ]
I don't have too much experience with C# so if someone could point me in the right direction I would greatly appreciate it. I have a foreach loop that references a variable of an object. I wish to make another foreach loop inside the main one that compares (or performs actions on) the current variable to the rest of th...
Each time you execute foreach, (even while nesting them) the internal Enumerator should "new" up a new iterator for you, there should not be any issue with that. The issues come about when you are adding, or removing items from the collection while you are still iterating... Remember, in the inner foreach, to check to...
IMHO it should be possible, although you should really consider Kibbee's suggestion. Maybe you can optimize it that way too (for example, like this:) ``` int l = doc.Bodies.Count; for ( int i = 0; i < l; i++ ) for ( int j = i + 1; j < l; j++ ) // Do stuff ```
C# foreach within a foreach loop
[ "", "c#", "" ]
I am currently starting my Java VM with the **`com.sun.management.jmxremote.*`** properties so that I can connect to it via JConsole for management and monitoring. Unfortunately, it listens on all interfaces (IP addresses) on the machine. In our environment, there are often cases where there is more than one Java VM r...
If anyone else will be losing his nerves with this ... After 10 years, they finally fixed it! Since Java 8u102 `-Dcom.sun.management.jmxremote.host` binds to the selected IP see: <https://bugs.openjdk.java.net/browse/JDK-6425769>
Fernando already provided a link to [my blog post](http://vafer.org/blog/20061010091658) :) ..it's not trivial. You have to provide your own RMIServerSocketFactoryImpl that creates sockets on the wanted address. If internal/external interfaces are the problem and you have local access setting up a local firewall might...
How to have JMX bind to a specific interface?
[ "", "java", "rmi", "jmx", "jconsole", "" ]
I'm looking for the fastest way to determine if a `long` value is a perfect square (i.e. its square root is another integer): 1. I've done it the easy way, by using the built-in [`Math.sqrt()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#sqrt(double)) function, but I'm wondering...
I figured out a method that works ~35% faster than your 6bits+Carmack+sqrt code, at least with my CPU (x86) and programming language (C/C++). Your results may vary, especially because I don't know how the Java factor will play out. My approach is threefold: 1. First, filter out obvious answers. This includes negative...
![](https://i.stack.imgur.com/UDUNr.png) I'm pretty late to the party, but I hope to provide a better answer; shorter and (assuming my [benchmark](https://www.dropbox.com/s/ad4r6oxfcilqkch/IsSquareBenchmark.java?dl=0) is correct) also much [faster](https://microbenchmarks.appspot.com/runs/185f228a-fd9b-44b4-8a7a-48d12...
Fastest way to determine if an integer's square root is an integer
[ "", "java", "math", "optimization", "perfect-square", "" ]
I have a nice and lovely Django site up and running, but have noticed that my `error.log` file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like `http://mysite.com/...
Um, perhaps, use [logrotate](http://linuxcommand.org/man_pages/logrotate8.html) to rotate and compress the logs periodically, if it isn't being done already.
If you can find a pattern in UserAgent string, you may use `DISALLOWED_USER_AGENT` setting. Mine is: ``` DISALLOWED_USER_AGENTS = ( re.compile(r'Java'), re.compile(r'gigamega'), re.compile(r'litefinder'), ) ``` See the description in [Django docs](http://docs.djangoproject.com/en/dev/ref/settings/#disallo...
Spambots are cluttering my log file [Django]
[ "", "python", "django", "apache", "spam-prevention", "" ]