Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to write a Mono C# daemon for linux.
I'd like to do a starts and stops of it when its done processing instead of just killing the process.
Does anyone have any examples of this?
Edit: I figured out how to use start-stop-daemon --background in debian, so I think I'll just use that for now.
Edit: I'm imple... | You should implement a service and use mono-service. Google for it and you'll find several examples. | To receive notifications in the Unix way, that is using signals, you want to use the [Mono.Unix.UnixSignal](http://mapsbkp.geolives.com/monodoc/monodoc.ashx?link=T%3aMono.Unix.UnixSignal) for each signal that you plan on receiving and then call UnixSignal.WaitAny () on an array of signals.
---
You would typically do ... | How do I code a Mono Daemon | [
"",
"c#",
"linux",
"mono",
"daemon",
"mono-service",
""
] |
I've seen second one in another's code and I suppose this length comparison have been done to increase code productivity. It was used in a parser for a script language with a specific dictionary: words are 4 to 24 letters long with the average of 7-8 lettets, alphabet includes 26 latin letters plus "@","$" and "\_".
L... | In your random test the strings might have been long enough to show the gain while in your real case you may deal with shorter strings and the constant factor of two comparison is not offset by any gain in not performing the string comparison part of the test. | If it mattered, assume that your library did it already. Don't mess up your code this way for micro-optimisations unless it really matters. | if(str1==str2) versus if(str1.length()==str2.length() && str1==str2) | [
"",
"c++",
"performance",
"stl",
"stdstring",
""
] |
I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail.
Something along these lines should work:
```
// filename examples: "test.avi", "test.dvr-ms"
// position is from 0 to 100 percent (0.0 to 1.0)
// returns a bitmap
byte[] GetVideoThumbnail(string file... | I ended up rolling my own stand alone class (with the single method I described), the source can be [viewed here](https://gist.github.com/2823028). [Media browser is](http://www.mediabrowser.tv) GPL but I am happy for the code I wrote for that file to be Public Domain. Keep in mind it uses interop from the [directshow.... | This project will do the trick for AVIs: <http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx>
Anything other formats, you might look into directshow. There are a few projects that might help:
<http://sourceforge.net/projects/directshownet/>
<http://code.google.com/p/slimdx/> | How do I get a Video Thumbnail in .Net? | [
"",
"c#",
".net",
"video-processing",
""
] |
I'm trying to understand the concepts behind DDD, but I find it hard to understand just by reading books as they tend to discuss the topic in a rather abstract way. I would like to see some good implementations of DDD in code, preferably in C#.
Are there any good examples of projects practicing DDD in the open source ... | Eric Evans and a Swedish consulting company have released a sample application based on the shipping example that Eric uses throughout the book. It's in Java, but the concepts are well documented on the project page.
<http://dddsample.sourceforge.net/>
However, be warned that DDD is more about the journey than the de... | I'm not sure how complete it is, but I found the [NDDD Sample](http://code.google.com/p/ndddsample/) on Google Code. | Are there any open source projects using DDD (Domain Driven Design)? | [
"",
"c#",
"architecture",
"open-source",
"domain-driven-design",
""
] |
What are ways to draw animations in C++? GDI+? OpenGL? Would you recommend a class pattern in particular to get the drawing and redrawing done?
Do you know of any open source project where animations are made so I can take a peek at the code?
Where would you start if you wanted to code geometrical animations? Do you ... | QT QGraphicsScene
It was specifically designed to make writing 2D games easy and effortless, with great support for animation.
QT is a very mature cross platform toolkit which also have an open source flavor. | I'm a developer of openframeworks (openframeworks.cc / openframeworks.cc/download) and also, I teach a course about animation in c++ in ny, there are some code examples up now (and more over the next few months):
<http://makingthingsmove.org/blog>
there is some example code in OF here too:
<http://wiki.openframework... | Animation in C++ | [
"",
"c++",
"animation",
""
] |
When indenting java code with annotations, vim insists on indenting like this:
```
@Test
public void ...
```
I want the annotation to be in the same column as the method definition but I can't seem to find a way to tell vim to do that, except maybe using an indent expression but I'm not sure if I can use that tog... | Edit: I cannot delete my own answer because it has already been accepted, but [@pydave's answer](https://stackoverflow.com/a/4414015/2844) seems to be the better (more robust) solution.
---
You should probably be using the indentation file for the java FileType (instead of using cindent) by setting `filetype plugin i... | You shouldn't modify the built-in vim settings. Your changes could disappear after a package upgrade. If you copy it to your .vim, then you won't get any java indent bug fixes.
Instead, put the following into a new file called `~/.vim/after/indent/java.vim`
```
function! GetJavaIndent_improved()
let theIndent = G... | How do I make vim indent java annotations correctly? | [
"",
"java",
"vim",
"annotations",
""
] |
Is there a documented max to the length of the string data you can use in the send method of an `XMLHttpRequest` for the major browser implementations?
I am running into an issue with a JavaScript `XMLHttpRequest` Post failing in FireFox 3 when the data is over approx 3k. I was assuming the Post would behave the same ... | I believe the maximum length depends not only on the browser, but also on the web server. For example, the Apache HTTP server has a [LimitRequestBody directive](http://httpd.apache.org/docs/2.0/mod/core.html#limitrequestbody) which allows anywhere from 0 bytes to 2GB worth of data. | You don't specify how it fails however your encoding is incorrect. You should use encodeURIComponent not encodeURI.
Default the maximum size of the request entity body on the client is likely only limited by the available memory. The server as has already been pointed out may reject entity bodies over a certain size. ... | Max length of send() data param on XMLHttpRequest Post | [
"",
"javascript",
"ajax",
"xmlhttprequest",
""
] |
Lets assume my classes are loaded from a compressed .war file or loaded elsewhere,
how can I discover all the resources in a given package? Enumerating files will not really work, since this is a war file. Most likely this will involve using the current classloader?
Is there a library out there that does something lik... | No, you can't list resources in a package because the JVM simply doesn't know what resources are in what package. See [this question](https://stackoverflow.com/questions/176527/how-can-i-enumerate-all-classes-in-a-package-and-add-them-to-a-list). | Yes. You can use `ClassLoader.getResources("")`;
Or you could use ferret API:
<https://www.ohloh.net/p/pureperfect-ferret>
This API allows you to scan the class path as well as arbitrary archives and directories using the Visitor pattern. | Can I list the resources in a given package? | [
"",
"java",
"list",
"resources",
"war",
""
] |
I have a django application that I'd like to add some rest interfaces to. I've seen <http://code.google.com/p/django-rest-interface/> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the rest... | I would look into using django-piston <http://bitbucket.org/jespern/django-piston/wiki/Home> application if security is your main concern.
I have used django-rest-interface in the past, its reliable and though simple can be quite powerful, however django-piston seems more flexible going forward. | Even with the Authentication parameter, you don't have fine-grained control over what people can do. The current implementation of the Django-REST interface doesn't track the user information, so you don't have this information available for doing fine-grained authorization checks.
See [Issue #32](http://code.google.c... | Using django-rest-interface | [
"",
"python",
"django",
"rest",
""
] |
I have a scenario in a system which I've tried to simplify as best as I can. We have a table of (lets call them) artefacts, artefacts can be accessed by any number of security roles and security roles can access any number of artefacts. As such, we have 3 tables in the database - one describing artefacts, one describin... | Since I was looking for this answer and found this thread on google (without an answer) I figured I'd post my solution to this. With three tables: Role, RolesToAccess(ManyToMany), Access.
Create the following mappings:
Access:
```
<bag name="Roles" table="RolesToAccess" cascade="none" lazy="false">
<key column=... | What you say here:
> The only way to successfully delete a role is to query for all artefacts that link to that role, remove the role from the artefact's role collection, update the artefacts and then delete the role - not very efficient or nice, especially when in the un-simplified system, roles can be associated wit... | Many to Many delete cascade in NHibernate | [
"",
"c#",
"nhibernate",
"many-to-many",
""
] |
I'm trying to host a PHP web site that was given to me. I see this warning:
> **Warning:** Unknown: Your script possibly
> relies on a session side-effect which
> existed until PHP 4.2.3. Please be
> advised that the session extension
> does not consider global variables as
> a source of data, unless
> register\_globa... | basically you have a variable with the same name as your session. ex:
```
$_SESSION['var1'] = null;
$var1 = 'something';
```
which will reproduce this error. you can stop PHP from trying to find existing variables and warning you about them by adding these lines to your script:
```
ini_set('session.bug_compat_warn',... | There seem to be a few problematic possibilities here:
[http://www.spiration.co.uk/post/1231/Your-script-possibly-relies-on-a-session-side-effect](http://www.spiration.co.uk/post/1231/Your-script-possibly-relies-on-a-session-side-effect "spiration.co.uk")
says that cases like this:
```
$_SESSION['firstname']=$_REQUE... | PHP session side-effect warning with global variables as a source of data | [
"",
"php",
"session",
"global-variables",
"session-variables",
""
] |
Is there a *portable* way of getting thread and/or process identifier (string, int, ...) with C++? | There is no portable way when portable means a way that works on **every** platform for that a C++ compiler exists. Such a way had to be part of the C++ standard, in which case it really would work everywhere (just like the other parts of the C++ standard work everywhere). Everything not in the standard is not guarante... | You have a few ways, but all imply the use of an external library abstracting the thread for you.
Among the popular choices, two are:
1. The [Boost.Thread](http://www.boost.org/doc/libs/1_36_0/doc/html/thread.html) library. This is the most portable but imply working with Boost, which is a HUGE library
2. The [Qt](ht... | C++ thread/process identifier | [
"",
"c++",
"multithreading",
"process",
""
] |
I'm using GDI+ in a C++/MFC application and I just can't seem to avoid flickering whenever the window is resized.
I have already tried these steps:
* returned TRUE on `OnEraseBkGnd()`;
* returned NULL on `OnCtlColor()`;
* used double buffering according to this code:
```
void vwView::OnDraw(CDC* pDC)
{
CRect rcC... | To completely avoid flicker, you would need to complete *all* drawing in the interval between screen updates. Windows does not provide any easy means of accomplishing this for normal window painting (Vista provides composite drawing via the [DWM](https://en.wikipedia.org/wiki/Desktop_Window_Manager), but this cannot be... | You might try using old-fashioned GDI rather than GDI+ to write to the DC, especially since you're already buffering the image. Use Bitmap::LockBits to access the raw bitmap data, create a BITMAPINFO structure, and use SetDIBitsToDevice to display the bitmap. | Reduce flicker with GDI+ and C++ | [
"",
"c++",
"windows",
"gdi+",
""
] |
I have created an item swapper control consisting in two listboxes and some buttons that allow me to swap items between the two lists. The swapping is done using javascript. I also move items up and down in the list. Basically when I move the items to the list box on the right I store the datakeys of the elements (GUID... | The first option will bring considerable overhead. I have defined my own custom listbox control derived from the listbox class and performed an override of the loadpostback data:
```
public class CustomListBox : ListBox
{
protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameV... | The problem is that the saved view state of the list and the data received on postback do not match. The event validation issue is most likely just one of the possible problems that might appear because of this approach. The architecture of webforms does not allow this kind of uses and, most likely, there will be more ... | ListBox elements rearranged with JavaScript causing event validation error on postback | [
"",
"asp.net",
"javascript",
"listbox",
"eventvalidation",
""
] |
I need a way to build C++ code from UML diagrams and vice versa.
Should be simple too hopefully. I don't mind paying too much. | You could try [Sparx Enterprise Architect](http://www.sparxsystems.com.au/products/ea/index.html) but the code quality would be average, not excellent.
I am not aware of any great automatic code generators for C++
Prices start from $135 | Visio is slow, and ate a whole weekend's worth of work one day. Don't use it for UML.
I've used [UMLStudio](http://www.pragsoft.com/) in the past -- it's cheap, and it did a decent job of reverse engineering my C++ code to make diagrams. It's a little wonky to use, but it's fast as hell once you get into the spirit of... | Simple C++ UML w/ reverse engineering | [
"",
"c++",
""
] |
I have the simple class using auto-implemented properies:
```
Public Class foo
{
public foo() { }
public string BarName {get; set;}
}
```
I obviously use the variable BarName throughout my class and now need to add logic when the property value is set (it must be all upper case, go figure). Does this mean ... | > Does this mean that I need to now
> create a private variable for BarName
Yes
> and change the current BarName
> variable used throughout my class
Do not change the rest of the code in your class to use the new private variable you create. *BarName*, as a property, is intended to hide the private variable (among o... | You don't need to change anything. Auto-implemented properties are just syntactic sugar. The compiler is generating the private variable and get/set logic for you, behind the scenes. If you add your own getter/setter logic the compiler will use your code instead of its auto-generated code, but as far as the *users* of ... | Learning about Auto-Implemented Properties | [
"",
"c#",
".net-3.5",
"properties",
"automatic-properties",
""
] |
I'm setting up an online ordering system but I'm in Australia and for international customers I'd like to show prices in US dollars or Euros so they don't have to make the mental effort to convert from Australian dollars.
Does anyone know if I can pull up to date exchange rates off the net somewhere in an easy-to-pars... | You can get currency conversions in a simple format from yahoo:
For example, to convert from GBP to EUR:
`http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&f=sl1d1t1ba&e=.csv` | This answer is VERY late, but there is a key bit of info missing from the above answers.
If you want to show accurate prices to your customers it is important to understand how foreign exchange rates work.
Most FX services only quote the spot rate (midway between the Bid and Ask). The spot is a kind of shorthand for ... | Programmatically access currency exchange rates | [
"",
"php",
"currency",
"finance",
""
] |
I'm writing an editor for large *archive files* (see below) of 4GB+, in native&managed C++.
For accessing the files, I'm using *file mapping* (see below) like any sane person. This is absolutely great for reading data, but a problem arises in actually editing the archive.
File mapping does not allow resizing a file wh... | What I do is to close view handle(s) and FileMapping handle, set the file size then reopen mapping / view handles.
```
// Open memory mapped file
HANDLE FileHandle = ::CreateFileW(file_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
size_t Size = ::GetFileSize(FileHandle, 0);
HANDLE MappingHa... | What do you mean by 'editor software'? If this is a text file, have you tried existing production-quality editors, before writing your own? If it's a file storing binary data, have you considered using an RDBMS and manipulating its contents using SQL statements?
If you absolutely have to write this from scratch, I'm n... | Design: Large archive file editor, file mapping | [
"",
"c++",
"visual-studio",
"winapi",
"file-io",
""
] |
I have a need to work with Windows executables which are made for x86, x64, and IA64. I'd like to programmatically figure out the platform by examining the files themselves.
My target language is PowerShell but a C# example will do. Failing either of those, if you know the logic required that would be great. | (from another Q, since removed)
Machine type: This is a quick little bit of code I based on some that gets the linker timestamp. This is in the same header, and it seems to work - it returns I386 when compiled -any cpu-, and x64 when compiled with that as the target platform.
The Exploring PE Headers (K. Stanton,MSDN... | If you have Visual Studio installed you can use `dumpbin.exe`. There's also the `Get-PEHeader` cmdlet in the [PowerShell Community Extensions](http://pscx.codeplex.com) that can be used to test for executable images.
Dumpbin will report DLLs as `machine (x86)` or `machine (x64)`
Get-PEHeader will report DLLs as eithe... | How can I determine for which platform an executable is compiled? | [
"",
"c#",
"powershell",
"cpu-architecture",
""
] |
Which other restrictions are there on names (beside the obvious uniqueness within a scope)?
Where are those defined? | From the [PDF of ECMA-335](https://www.ecma-international.org/publications/standards/Ecma-335.htm), Partition II, section 22:
> Metadata preserves name strings, as created by a compiler or code generator, unchanged. Essentially, it treats
> each string as an opaque blob. In particular, it preserves case. The CLI impos... | In addition to the other answers, the maximum identifier length that is accepted by the Microsoft Visual C# compiler is **511 characters**. This can be tested with the following code:
```
class Program
{
private static void Main(string[] args)
{
int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... | What is the maximum length of a C#/CLI identifier? | [
"",
"c#",
".net",
"clr",
"language-features",
"command-line-interface",
""
] |
I have some problems on a site with the concurrent access to a list. This list keeps a cart of items, and multiple deletes are crashing the site.
**Which is the best method to sync them?**
Is a lock enough?
The lock option seems to be ugly because the code is spread all over the place and is pretty messy.
Update:
This... | So is this in-memory list shared between requests? That sounds like a potential cause of problems even when you've got locking. Mutable shared collections should generally be avoided, IME.
Note that if you *do* decide to synchronize, you'll need to do things like locking the list for the whole course of iterating over... | Yes, you have to lock- using [List.SyncRoot](http://msdn.microsoft.com/en-us/library/bb356596.aspx) like this:
```
lock (myList.SyncRoot)
{
// Access the collection.
}
``` | How to synchronize the access to a List<T> used in ASP.NET? | [
"",
"c#",
"asp.net",
".net",
"multithreading",
"access-synchronization",
""
] |
How do I display a leading zero for all numbers with less than two digits?
```
1 → 01
10 → 10
100 → 100
``` | In Python 2 (and Python 3) you can do:
```
number = 1
print("%02d" % (number,))
```
Basically **%** is like `printf` or `sprintf` (see [docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)).
---
For Python 3.+, the same behavior can also be achieved with [`format`](https://docs.pyth... | You can use [`str.zfill`](https://docs.python.org/2/library/stdtypes.html#str.zfill):
```
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
```
prints:
```
01
10
100
``` | Display number with leading zeros | [
"",
"python",
"integer",
"string-formatting",
""
] |
I'm primarily interested in pgsql for this, but I was wondering if there is a way in any RDBMS to do an insert operation, *without* disabling and re-enabling any FOREIGN KEY or NOT NULL constraints, on two tables that refer to each other. (You might think of this as a chicken that was somehow born from its own egg.)
F... | I think that you answered your own question - you have to make a transaction block. In PostgreSQL this should work:
```
BEGIN;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO questions (questionid, answerid, question)
VALUES (1, 100, 'How long are Abraham Lincoln\'s legs?');
INSERT INTO answers (answerid, questionid, an... | I'd do it in the following way:
1. Define Questions.correct\_answer as a
nullable column.
2. Insert row into Questions, with correct\_answer set to NULL.
3. Insert row(s) into Answers, referencing the row in Questions.
4. UPDATE Questions SET correct\_answer
= ? | Can/how do you add a circle of references without breaking RI? | [
"",
"sql",
"postgresql",
"foreign-keys",
""
] |
I have a questionable coding practice.
When I need to iterate through a small list of items whose count limit is under `32000`, I use `Int16` for my *i* variable type instead of `Integer`. I do this because I assume using the `Int16` is more efficient than a full blown `Integer`.
Am I wrong? Is there no effective per... | According to the below reference, the *runtime* optimizes performance of **Int32** and recommends them for counters and other frequently accessed operations.
From the book: **MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0—Application Development Foundation**
Chapter 1: "Framework Fundamenta... | You should **almost always** use `Int32` or `Int64` (and, no, you do not get credit by using `UInt32` or `UInt64`) when looping over an array or collection by index.
The most obvious reason that it's less efficient is that all array and collection indexes found in the BCL take `Int32`s, so an implicit cast is *always*... | .NET Integer vs Int16? | [
"",
"c#",
".net",
"vb.net",
"variables",
"types",
""
] |
I'm not committed to any particular GUI tookit or anything - just needs to be Java based. I want to do simple syntax highlighting ( XML and XQuery ) inside editable text areas.
My only candidate so far is Swing's JTextPane, as it supports seems to support the styling of text, but I have no idea how to implement it in ... | JSyntaxPane handles XML and can be extended
<http://code.google.com/p/jsyntaxpane/wiki/Using>
Or, it should be possible to extract the NetBeans editor, but that would probably be more work...
[edit] btw, I got the XML info from [here](http://saveabend.blogspot.com/2008/06/jsyntaxpane-is-born.html)... it doesn't seem... | Jide software has a [Syntax Highligher](http://www.jidesoft.com/products/editor.htm) component. It is still in beta, but I think it supposed XML. I haven't used it myself, so I don't know how well it will do what you want. | looking for Java GUI components / ideas for syntax highlighting | [
"",
"java",
"xml",
"user-interface",
"syntax-highlighting",
"xquery",
""
] |
I'm a kinda newbie developer with a few years under my belt. Recently I interviewed at a game company and was asked "have you done any multi-threading?" I told them about having a C# app with a few Threads... and then I said a bit about transactions and locking etc in Sql. The interviewer politely told me that this was... | The canonical implementation of "low level threads" is [pthreads](http://en.wikipedia.org/wiki/POSIX_Threads). The most basic examples of threading problems that are usually taught along with pthreads are some form of [readers and writers problem](http://en.wikipedia.org/wiki/Readers-writers_problem). That page also li... | He was probably referring to your use of C#, not your threading experience. | What is a basic example of "low-level" multi-threading in C++? | [
"",
"c++",
"multithreading",
""
] |
For example:
```
javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
``` | This comes up in Java 5 and later if you're using collections without type specifiers (e.g., `Arraylist()` instead of `ArrayList<String>()`). It means that the compiler can't check that you're using the collection in a type-safe way, using [generics](http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html).
T... | If you do what it suggests and recompile with the "-Xlint:unchecked" switch, it will give you more detailed information.
As well as the use of raw types (as described by the other answers), an unchecked cast can also cause the warning.
Once you've compiled with -Xlint, you should be able to rework your code to avoid ... | What causes javac to issue the "uses unchecked or unsafe operations" warning | [
"",
"java",
"generics",
"warnings",
""
] |
I have a main frame with a splitter. On the left I have my (imaginatively named) CAppView\_Leftand on the right I have CAppView\_Right\_1and CAppView\_Right\_2. Through the following code I initialise the two primary views correctly:
```
if (!m_wndSplitter.CreateStatic(this, 1, 2))
{
TRACE0("Failed to CreateStatic... | There is a CodeProject article that should help you achieve what you want:
<http://www.codeproject.com/KB/splitter/usefulsplitter.aspx>
I have replaced views in a splitter before, so if the above doesn't help I'll post some of my own code. | You can't create a second right hand view because your
```
m_wndSplitter.CreateStatic(this, 1, 2)
```
has only created two columns. You could change this to
```
m_wndSplitter.CreateStatic(this, 1, 3)
```
and change your second right view to
```
if (!m_wndSplitter.CreateView(0, 2, RUNTIME_CLASS(CAppView_Right_2), C... | Multiple Interchangeable Views (MFC/C++) | [
"",
"c++",
"view",
"mfc",
"document",
"csplitterwnd",
""
] |
I'm getting ready to start a new project and I've been researching the entity framework. My question is what is the best strategy for validating the entities? Other projects I've worked on have used attributes for most of the validation, but obviously this is not possible in the entity framework. Is the only way to do ... | I have not actually used the Entity framework before but a quick search indicates that you have several options.
1) Validate at another layer in your application
Always an option, I just thought I would throw it out there explicitly.
2) Hook into the OnChanged events of the Entity then perform validation
Likely bri... | In .NET 4, there is going to be out-the-box validation support in Entity-Framework.
Check out: <http://blogs.msdn.com/adonet/archive/2010/01/13/introducing-the-portable-extensible-metadata.aspx>
So don't work to hard on implementing too complex validation logic... | Entity Framework Validation | [
"",
"c#",
".net",
"entity-framework",
"validation",
""
] |
I can run the server on my local machine and connect to it on the same machine, but when I try to connect to it from a different computer over the internet, there is not sign of activity on my server, nor a response from the server on the computer I'm testing it on. I've tried both XP and Vista, turn off firewalls, ope... | I think that the problem is in your router, not your computer. When packets come from the Internet, it should be routed to an specific server. You have to configure your router to redirect the traffic on port `3326` to your server. | You've probably got something blocking the connection higher up. Try connecting from another host on the LAN. If you can do that, then the OS itself isn't firewalling the connection.
If either you or your ISP run a NAT router, then your machine probably doesn't have a publicly accessible address, in which case it's im... | I can't connect to my server over the internet | [
"",
"c#",
"networking",
"sockets",
""
] |
I have seen this link: [Implementing Mutual Exclusion in JavaScript](http://www.developer.com/lang/jscript/article.php/3592016).
On the other hand, I have read that there are no threads in javascript, but what exactly does that mean?
When events occur, where in the code can they interrupt?
And if there are no threads... | Javascript is defined as a *reentrant* language which means there is no threading exposed to the user, there may be threads in the implementation. Functions like `setTimeout()` and asynchronous callbacks need to wait for the script engine to sleep before they're able to run.
That means that everything that happens in ... | The answers to this question are a bit outdated though correct at the time they were given. And still correct if looking at a client-side javascript application that does NOT use webworkers.
Articles on web-workers:
[multithreading in javascript using webworkers](http://xebee.xebia.in/2010/11/02/multithreading-in-ja... | Are Mutexes needed in javascript? | [
"",
"javascript",
"multithreading",
"mutex",
""
] |
Here's the XML file i'm working on:
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<activity>soccer</activity>
</list>
```
The index.php, page that shows the list of activities with checkboxes, a button to delete the checked activities, and a field to add new activities:
```
<html>... | the DOMNodeList items are indexed starting with 0;
You need to move the $count++ to the end of the while loop in the output step. | The tricky thing about DOMNodeLists is that they are NOT arrays. If you delete a node, the list will re-index. This will cause your code to break if a user selects more than one item for deletion. If you selected swimming and running, swimming and soccer would be deleted.
You might want to start by giving each activit... | Problems with deleting XML elements using PHP DOM | [
"",
"php",
"xml",
"dom",
""
] |
What are your usage of delegates in C#? | Now that we have lambda expressions and anonymous methods in C#, I use delegates much more. In C# 1, where you always had to have a separate method to implement the logic, using a delegate often didn't make sense. These days I use delegates for:
* Event handlers (for GUI and more)
* Starting threads
* Callbacks (e.g. ... | Delegates are very useful for many purposes.
One such purpose is to use them for filtering sequences of data. In this instance you would use a predicate delegate which accepts one argument and returns true or false depending on the implementation of the delegate itself.
Here is a silly example - I am sure you can ext... | When would you use delegates in C#? | [
"",
"c#",
".net",
"delegates",
""
] |
What exactly is the difference between the `window.onload` event and the `onload` event of the `body` tag? when do I use which and how should it be done correctly? | `window.onload = myOnloadFunc` and `<body onload="myOnloadFunc();">` are different ways of using **the same event**. Using `window.onload` is less obtrusive though - it takes your JavaScript out of the HTML.
All of the common JavaScript libraries, Prototype, ExtJS, Dojo, JQuery, YUI, etc. provide nice wrappers around ... | There is no difference, but you should not use either.
In many browsers, the `window.onload` event is not triggered until all images have loaded, which is not what you want. Standards based browsers have an event called `DOMContentLoaded` which fires earlier, but it is not supported by IE (at the time of writing this ... | window.onload vs <body onload=""/> | [
"",
"javascript",
""
] |
I'm in search of a JavaScript month selection tool. I'm already using jQuery on the website, so if it were a jQuery plugin, that would fit nicely. I'm open to other options, as well.
Basically, I'm after a simplified version of the [jQuery UI Date Picker](http://docs.jquery.com/UI/Datepicker). I don't care about the d... | To anyone *still* looking forward into this (as I was), here is an beautiful, easy to use, jQuery UI compatible, well documented, tested alternative:

Its default usage is simple as doing the following:
```
$("input[type='month']").MonthPicker();
```
* [Gi... | [Ben Koehler](https://stackoverflow.com/users/11996/ben-koehler) from [this equivalent question](https://stackoverflow.com/questions/2208480/jquery-date-picker-to-show-month-year-only) offers a jquery ui hack that works decently. Quoted here for convenience, all credit is his.
[JSFiddle of this solution](http://jsfidd... | In search of JavaScript Month Picker | [
"",
"javascript",
"jquery",
""
] |
Does the compiler optimize out any multiplications by 1? That is, consider:
```
int a = 1;
int b = 5 * a;
```
Will the expression 5 \* a be optimized into just 5? If not, will it if a is defined as:
```
const int a = 1;
``` | It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the **`const`** it will be left alone.
Your first example compiles to this IL:
```
.maxstack 2
.locals init ([0] int32, [1] int32)
ldc.i4.1 //load 1
stloc.0 //store in 1st local variable
ldc.i4.5 //load 5
... | Constant propagation is one of the most common and easiest optimisations. | .NET multiplication optimization | [
"",
"c#",
".net",
"optimization",
"compiler-construction",
"multiplication",
""
] |
I have a class library with some extension methods written in C# and an old website written in VB.
I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.
I have got all the required *Import*s because other classes contained in the same... | It works for me, although there are a couple of quirks. First, I created a C# class library targeting .NET 3.5. Here's the only code in the project:
```
using System;
namespace ExtensionLibrary
{
public static class Extensions
{
public static string CustomExtension(this string text)
{
char[] chars =... | Extension methods are just syntactic sugar for static methods. So
```
public static string MyExtMethod(this string s)
```
can be called in both VB.NET and C# with
```
MyExtMethod("myArgument")
``` | How can I call C# extension methods in VB code | [
"",
"c#",
"vb.net",
"extension-methods",
"class-library",
""
] |
How would I disable and later enable all indexes in a given schema/database in Oracle?
Note: This is to make sqlldr run faster. | Here's making the indexes unusable without the file:
```
DECLARE
CURSOR usr_idxs IS select * from user_indexes;
cur_idx usr_idxs% ROWTYPE;
v_sql VARCHAR2(1024);
BEGIN
OPEN usr_idxs;
LOOP
FETCH usr_idxs INTO cur_idx;
EXIT WHEN NOT usr_idxs%FOUND;
v_sql:= 'ALTER INDEX ' || cur_idx.index_name |... | combining 3 answers together:
(because a select statement does not execute the DDL)
```
set pagesize 0
alter session set skip_unusable_indexes = true;
spool c:\temp\disable_indexes.sql
select 'alter index ' || u.index_name || ' unusable;' from user_indexes u;
spool off
@c:\temp\disable_indexes.sql
```
Do import...
... | Disable and later enable all table indexes in Oracle | [
"",
"sql",
"oracle",
"sql-loader",
""
] |
I'm developing a shareware desktop application. I'm to the point where I need to implement the trial-use/activation code. How do you approach something like this? I have my own ideas, but I want to see what the stackoverflow community thinks.
I'm developing with C++/Qt. The intended platform is Windows/Mac/Linux.
Tha... | **What to protect against and what not to protect against:**
Keep in mind that people will always find a way to get around your trial period. So you want to make it annoying for the person to have to get around your trial period, but it doesn't matter if it's impossible to get around you trial period.
Most people wil... | Whatever you do, keep a keen eye on the system date. The oldest trick in the book is to install an application at some point in the future and then return to the real date once the application stored the silly date on first run. Maybe synchronise the key with a online repository ? | Need Advice on Implementing a Time-limited Trial | [
"",
"c++",
"desktop",
"shareware",
"trialware",
"time-trial",
""
] |
I want to put "random" output from my result set (about 1.5 mil rows) in a file in a sorted manner. I know i can use sort by command in my query but that command is "expensive".
Can you tell me is there any algorithm for writing result set rows in a file so the content would be sorted in the end and can i gain in perfo... | Define an index for the sort criteria in your table, then you can use the order by clause without problems and write the file as it comes from the resultset.
If your query has multiple joins, create the proper indexes for the joins and for the sort criteria. You can sort the data on your program but you'd be wasting t... | In my experience sorting at the database side is usually as fast or faster...certainly if the column you sort on is indexed | Writing resultset to file with sorted output | [
"",
"java",
"file",
"sorting",
"resultset",
""
] |
I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you. | First, a general definition:
> When a program or function statement
> is executed, the current values of
> formal parameters are saved (on the
> stack) and within the scope of the
> statement, they are bound to the
> values of the actual arguments made in
> the call. When the statement is
> exited, the original values... | I've never heard that term, but one explanation could be the "default parameter" hack used to assign a value directly to a lambda's parameter. Using Swati's example:
```
def foo(x):
a = lambda x=x: x
x = 7
b = lambda: x
return a,b
aa, bb = foo(4)
aa() # Prints 4
bb() # Prints 7
``` | What is "lambda binding" in Python? | [
"",
"python",
"binding",
"lambda",
""
] |
If I do not specify the following in my web.xml file:
```
<session-config>
<session-timeout>10</session-timeout>
</session-config>
```
What will be my default session timeout? (I am running Tomcat 6.0) | If you're using Tomcat, it's 30 minutes. You can read more about it [here](http://forums.sun.com/thread.jspa?threadID=565341&messageID=2788327). | You can also set this in code, for a specific session using the `HttpSession` [setMaxInactiveInterval](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpSession.html#setMaxInactiveInterval(int)) API:
> Specifies the time, in seconds,
> between client requests before the
> servlet container will invalidate t... | What is the default session timeout for a Java EE website? | [
"",
"java",
"jsp",
"tomcat",
"jakarta-ee",
""
] |
Essentially the only thing I can deploy to my deployment machine is a JAR file. I can't install JRuby, nor can I install Glassfish or Tomcat.
Is it possible to package up a Rails application (including Rails, vendored, of course) to a JAR file such that I can do
```
c:\my_server> java rails_app.jar
```
and have it r... | I'd recommend that you checkout Jetty. The process for [Embedding Jetty](http://docs.codehaus.org/display/JETTY/Embedding+Jetty) is surprisingly easy, and it should be possible to give it your servlets from your current jar file. I haven't used Ruby/Rails, though, so I'm not sure if there are any complications there.
... | I wrote an article a year ago about how to embed your ruby sources with jruby and everything else you want into one jar file, and then run it with "java -jar myapp.jar".
It will need some work to make it boot rails I guess, but it should not be too hard. And with the complimentary jruby documentation on their wiki, i ... | Is it possible to compile a Rails app to a Java VM JAR file? | [
"",
"java",
"ruby-on-rails",
"ruby",
"jruby",
""
] |
I need a way to do key-value lookups across (potentially) hundreds of GB of data. Ideally something based on a distributed hashtable, that works nicely with Java. It should be fault-tolerant, and open source.
The store should be persistent, but would ideally cache data in memory to speed things up.
It should be able ... | You might want to check out [Hazelcast](http://www.hazelcast.com). It is distributed/partitioned, super lite, easy and free.
```
java.util.Map map = Hazelcast.getMap ("mymap");
map.put ("key1", "value1");
```
Regards,
-talip | [Open Chord](http://open-chord.sourceforge.net/) is an implementation of the [CHORD](http://en.wikipedia.org/wiki/Chord_(DHT)) protocol in Java. It is a distributed hash table protocol that should fit your needs perfectly. | Need a distributed key-value lookup system | [
"",
"java",
"database",
"bigtable",
"key-value-store",
"distributed-database",
""
] |
I'm using the PHP function imagettftext() to convert text into a GIF image. The text I am converting has Unicode characters including Japanese. Everything works fine on my local machine (Ubuntu 7.10), but on my webhost server, the Japanese characters are mangled. What could be causing the difference? Everything should ... | Here's the solution that finally worked for me:
```
$text = "你好";
// Convert UTF-8 string to HTML entities
$text = mb_convert_encoding($text, 'HTML-ENTITIES',"UTF-8");
// Convert HTML entities into ISO-8859-1
$text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
// Convert characters > 127 into their hexidecim... | I have been having the same problem with a script that will render text in an image and output it. Problem was, that due to different browsers (or code hardiness/paranoia, whichever way you want to think of it), I had no way of knowing what encoding was being put inside the `$_GET` array.
Here is how I solved the prob... | PHP function imagettftext() and unicode | [
"",
"php",
"unicode",
"gd",
""
] |
Given an aggregation of class instances which refer to each other in a complex, circular, fashion: is it possible that the garbage collector may not be able to free these objects?
I vaguely recall this being an issue in the JVM in the past, but I *thought* this was resolved years ago. yet, some investigation in jhat h... | Only a very naive implementation would have a problem with circular references. Wikipedia has a good [article](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) on the different GC algorithms. If you really want to learn more, try (Amazon) [Garbage Collection: Algorithms for Automatic Dynamic Memory M... | The garbage collector knows where the root objects are: statics, locals on the stack, etc and if the objects aren't reachable from a root then they will be reclaimed. If they are reachable, then they need to stick around. | Circular References in Java | [
"",
"java",
"memory",
"memory-management",
"memory-leaks",
"garbage-collection",
""
] |
My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values ar... | Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes. | I know that on PC, floating point registers are 80 bits wide. So if a calculation is done entirely within the FPU, you get the benefit of 80 bits of precision. On the other hand, if an intermediate result is moved out into a normal register and back, it gets truncated to 32 bits, which gives different results.
Now con... | Float values behaving differently across the release and debug builds | [
"",
"c++",
"c",
"debugging",
"compiler-construction",
"floating-point",
""
] |
One of our programs is sometimes getting an `OutOfMemory` error on one user's machine, but of course not when I'm testing it. I just ran it with JProfiler (on a 10 day evaluation license because I've never used it before), and filtering on our code prefix, the biggest chunk both in total size and number of instances is... | Dump the heap and inspect it.
I'm sure there's more than one way to do this, but here is a simple one. This description is for MS Windows, but similar steps can be taken on other operating systems.
1. Install the JDK if you don't already have it. [It comes with a bunch of neat tools.](http://java.sun.com/javase/6/doc... | Try Eclipse Memory Analyzer. It will show you for each object how it is connected to a GC root - an object that is not garbage collected because it is held by the JVM.
See <http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/> for more information on ... | How can I figure out what is holding on to unfreed objects? | [
"",
"java",
"garbage-collection",
"jprofiler",
""
] |
I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :
```
public interface Translator {
public void loadTranslations();
public String getTranslation(String key);
}
```
loadTranslat... | Use some form of locking mechanism to only perform the task if it is not already in progress. Acquiring the locking token must be a one-step process. See:
```
/**
* @author McDowell
*/
public abstract class NonconcurrentTask implements Runnable {
private boolean token = true;
private synchronized boolean a... | I am from a .net background(no java experience at all), but you could try a simple static flag of some sort that checks at the beginning of the method if its alrady running. Then all you need to do is make sure any read/write of that flag is synchronized. So at beginning check the flag, if its not set, set it, if it is... | Java 1.4 synchronization: only allow one instance of method to run (non blocking)? | [
"",
"java",
"concurrency",
"synchronization",
""
] |
> **Possible Duplicate:**
> [What is the difference between "typename" and "class" template parameters?](https://stackoverflow.com/questions/2023977/c-difference-of-keywords-typename-and-class-in-templates)
When defining a function template or class template in C++, one can write this:
```
template <class T> ...
``... | Stan Lippman talked about this [here](https://learn.microsoft.com/archive/blogs/slippman/why-c-supports-both-class-and-typename-for-type-parameters). I thought it was interesting.
*Summary*: Stroustrup originally used `class` to specify types in templates to avoid introducing a new keyword. Some in the committee worri... | According to Scott Myers, Effective C++ (3rd ed.) item 42 (which must, of course, be the ultimate answer) - the difference is "nothing".
Advice is to use "class" if it is expected T will always be a class, with "typename" if other types (int, char\* whatever) may be expected. Consider it a usage hint. | Use 'class' or 'typename' for template parameters? | [
"",
"c++",
"templates",
""
] |
[edit]
So I used one of the javascript tooltips suggested below. I got the tips to show when you stop and hide if you move. The only problem is it works when I do this:
```
document.onmousemove = (function() {
var onmousestop = function() {
Tip('Click to search here');
document.getElementById('MyDi... | A bit late to be answering this, but this will be helpful for those in need.
I needed this function to be able to detect when the mouse stopped moving for a certain time to hide an HTML/JS player controller when hovering over a video. This is the revised code for the tooltip:
```
document.getElementById('MyDiv').onmo... | The jQuery plugin [hoverIntent](http://cherne.net/brian/resources/jquery.hoverIntent.html) provides a similar behaviour. It determines if the user 'meant' to hover over a particular element by checking if they slow the mouse down moving into the elements and spend a certain amount of time hovering over the element.
It... | How to Show Ballon tooltip when mouse stops | [
"",
"javascript",
"onmousemove",
"balloon",
""
] |
I've found a couple of references ([for example](http://www.javapractices.com/topic/TopicAction.do?Id=23)) that suggest using `final` as much as possible and I'm wondering how important that is. This is mainly in the the context of method parameters and local variables, not final methods or classes. For constants, it m... | Obsess over:
* Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things... | > Is it something I should make an effort to remember to do?
No, if you are using Eclipse, because you can configure a Save Action to automatically add these *final* modifiers for you. Then you get the benefits for less effort. | When should one use final for method parameters and local variables? | [
"",
"java",
"final",
""
] |
I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey.
I will try to explain this with an example:
```
class Project(models.Model):
name = models.CharFiel... | Use threadlocals if you want to get **current** user that edits this model. Threadlocals middleware puts current user into process-wide variable. Take this middleware
```
from threading import local
_thread_locals = local()
def get_current_user():
return getattr(getattr(_thread_locals, 'user', None),'id',None)
c... | This limiting of choices to current user is a kind of validation that needs to happen dynamically in the request cycle, not in the static Model definition.
In other words: at the point where you are creating an *instance* of this model you will be in a View and at that point you will have access to the current user an... | Model limit_choices_to={'user': user} | [
"",
"python",
"django",
"model",
""
] |
This issue came up when I got different records counts for what I thought were identical queries one using a `not in` `where` constraint and the other a `left join`. The table in the `not in` constraint had one null value (bad data) which caused that query to return a count of 0 records. I sort of understand why but I ... | Query A is the same as:
```
select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null
```
Since `3 = 3` is true, you get a result.
Query B is the same as:
```
select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null
```
When `ansi_nulls` is on, `3 <> null` is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't ... | ## `NOT IN` returns 0 records when compared against an unknown value
Since `NULL` is an unknown, a `NOT IN` query containing a `NULL` or `NULL`s in the list of possible values will always return `0` records since there is no way to be sure that the `NULL` value is not the value being tested. | NULL values inside NOT IN clause | [
"",
"sql",
"sql-server",
"t-sql",
"null",
"notin",
""
] |
What's the easiest way to centre a `java.awt.Window`, such as a `JFrame` or a `JDialog`? | From [this link](https://web.archive.org/web/20080921040824/http://blog.codebeach.com/2008/02/center-dialog-box-frame-or-window-in.html)
> If you are using Java 1.4 or newer,
> you can use the simple method
> setLocationRelativeTo(null) on the
> dialog box, frame, or window to center
> it. | This should work in all versions of Java
```
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocati... | How to center a Window in Java? | [
"",
"java",
"swing",
"user-interface",
"awt",
""
] |
How would I be able to get N results for several groups in
an oracle query.
For example, given the following table:
```
|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Ja... | This produces what you want, and it uses no vendor-specific SQL features like TOP N or RANK().
```
SELECT MAX(e.name) AS name, MAX(e.occupation) AS occupation
FROM emp e
LEFT OUTER JOIN emp e2
ON (e.occupation = e2.occupation AND e.emp_id <= e2.emp_id)
GROUP BY e.emp_id
HAVING COUNT(*) <= 3
ORDER BY occupa... | I don't have an oracle instance handy right now so I have not tested this:
```
select *
from (select emp_id, name, occupation,
rank() over ( partition by occupation order by emp_id) rank
from employee)
where rank <= 3
```
Here is a link on how rank works: <http://www.psoug.org/reference/rank.html> | Get top results for each group (in Oracle) | [
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
I have heard that WPF primitives will not be supported by remote desktop on windows XP. The implication of this is that if you run a WPF application on a vista machine and display it on an XP machine (via remote desktop) the display will be sent as a compressed bitmap.
This issue is resolved in Vista-Vista comunicatio... | As of .NET 3.5 SP1, all WPF graphics are remoted as bitmaps, even on Vista-to-Vista communication. From <http://blogs.msdn.com/jgoldb/archive/2008/05/15/what-s-new-for-performance-in-wpf-in-net-3-5-sp1.aspx>:
> We now remote as bitmaps in ALL cases.
>
> The reason is that WPF 3.5 SP1 now
> uses a new graphics DLL (wpf... | We have had no problems using both Remote Admin and Bomgar for remoting once those apps were updated to work with WPF. We've tested XP to XP, XP to Vista, Vista to XP, and Vista to Vista. We'd initially only had problems with tooltips and combo-box drop downs/popups. For the last six months or so, things have been fine... | Are there problems with rendering WPF over Remote Desktop under Windows XP? | [
"",
"c#",
".net",
"wpf",
"windows-xp",
"remote-desktop",
""
] |
In my ideal world, what I'm looking for would exist as something along the lines of this:
```
public string UserDefinedField
{
get { return _userDefinedField; }
internal set { _userDefinedField = value; }
set { _userDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }
}
```
Where on... | ```
public string UserDefinedField
{
get { return _userDefinedField; }
set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }
}
// Call this from internal methods and use the public property for other cases
internal string SetField(string userValue)
{
_userDefinedField = userValue;
}
```
You... | Redefining Isak's Answer
```
public string UserDefinedField
{
get { return InternalUserDefinedField; }
set { InternalUserDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }
}
internal string InternalUserDefinedField
{
get { return _userDefinedField; }
set { _userDefinedField= value; ... | Is there any elegant way to execute specific code depending on the caller, using reflection or otherwise? | [
"",
"c#",
""
] |
I want to know how the glBlendFunc works. For example, i have 2 gl textures, where the alpha is on tex1, i want to have alpha in my final image. Where the color is on tex1, i want the color from tex2 to be. | Sadly, this is for openGL ES on the iPhone, so no shaders, but point taken. My problem was a very simplified version of the questions, i needed to apply a simple color ( incl alpha ), to a part of a defined texture. As Lee pointed out, texture blending is to allow alpha to show up on the framebuffer. The solution was t... | glBlendFunc applies only to how the final color fragment gets blended with the frame buffer. I think what you want is multitexturing, to combine the two textures by blending the texture stages using glTexEnv, or using a fragment shader to combine the the two textures. | glBlendFunc and alpha blending | [
"",
"c++",
"opengl",
""
] |
I have a page with a tab control and each control has almost 15 controls. In total there are 10 tabs and about 150 controls in a page (controls like drop down list, textbox, radiobutton, listbox only).
My requirement is that there is a button (submit) at the bottom of the page. I need to check using JavaScript that at... | Assuming there's only one form on the page (if more then loop through forms and nest the below loop within).
```
var selectedCount = 0;
var element;
for (var i = 0; i < document.forms[0].elements.length; i++)
{
element = document.forms[0].elements[i];
switch (element.type)
{
case 'text':
... | I would look at something based on the prototype [serialize](http://www.prototypejs.org/api/form#method-serializeelements) method - it can give you a hash of all form controls - it might give you a headstart on what you want.
Something like firebug will help you see what you get and assess if it meets your needs. | How to get all the controls in page using javascript in ASP.net page | [
"",
"asp.net",
"javascript",
""
] |
We are using Hibernate 3.1 with Spring MVC 2.0. Our problem occurs when data is updated on the database directly (not in the application). We use a Filter to filter a collection of results by whether the orders are opened or closed. If we change an order on the DB to be closed, the filter returns the correct list, howe... | The Session always has a "first-level" cache, so if you're using one Session everything you read through it is going to be cached. Hibernate will execute the query against the database, but then as it's building the objects it checks the Session cache to avoid building a new object, so any columns changed in the databa... | You can't really expect Hibernate to properly manage the "dirty" state of its cached objects when you have processes "going behind its back". If you're using annotations, I'd suggest marking the status (if that's the field's name) as @Transient, so that Hibernate knows it has to get this value from the database every t... | Strange Hibernate Cache Issue | [
"",
"java",
"hibernate",
"spring",
""
] |
Here's the code I want to speed up. It's getting a value from an ADO recordset and converting it to a char\*. But this is slow. Can I skip the creation of the \_bstr\_t?
```
_variant_t var = pRs->Fields->GetItem(i)->GetValue();
if (V_VT(&var) == VT_BSTR)
{
... | The first 4 bytes of the BSTR contain the length. You can loop through and get every other character if unicode or every character if multibyte. Some sort of memcpy or other method would work too. IIRC, this can be faster than `W2A` or casting `(LPCSTR)(_bstr_t)` | Your problem (other than the possibility of a memory copy inside \_bstr\_t) is that you're converting the UNICODE BSTR into an ANSI char\*.
You can use the USES\_CONVERSION macros which perform the conversion on the stack, so they might be faster. Alternatively, keep the BSTR value as unicode if possible.
to convert:... | Getting a char* from a _variant_t in optimal time | [
"",
"c++",
"visual-c++",
"com",
"ole",
"bstr",
""
] |
In SQL Server 2017, you can use this syntax, but not in earlier versions:
```
SELECT Name = TRIM(Name) FROM dbo.Customer;
``` | ```
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
``` | To Trim on the right, use:
```
SELECT RTRIM(Names) FROM Customer
```
To Trim on the left, use:
```
SELECT LTRIM(Names) FROM Customer
```
To Trim on the both sides, use:
```
SELECT LTRIM(RTRIM(Names)) FROM Customer
``` | How to trim a string in SQL Server before 2017? | [
"",
"sql",
"sql-server",
""
] |
I getting the following error when I try to connect to my server app using remoting:
> *A problem seems to have occured whilst connecting to the remote server:
> Server encountered an internal error. For more information, turn off customErrors in the server's .config file.*
This is the code on my server app:
```
T... | For .Net 1.0/1.1 , you need a config file for remoting server
If you don't have a `<ServerEXE>.config` file, create one and have this in it:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.runtime.remoting>
<customErrors mode="off" />
</system.runtime.remoting>
</configuration>
```... | In the server file, use:
```
RemotingConfiguration.CustomErrorsEnabled(bool);
``` | C# Remoting - How to turn off CustomErrors | [
"",
"c#",
".net",
"remoting",
"custom-errors",
""
] |
I have a bit of code that passes around a ton of objects and I want to determine if there are any references still lingering around that I am unaware of and where it is those references are located. Any idea of how I can do this?
My understanding is that the watch window only allows me to see items available to the cu... | A profiler will allow you to do this. CLR Profiler or ANTS Profiler are two examples. | if you are talking in the code, just right click on the object name, in the drop down menu pick "Find all references", the list of references will appear below in the output window
EDIT: Since there was only a .NET tag, Visual Studio assumed | How do I find the number of references that exist for a particular object? | [
"",
"c#",
".net",
"vb.net",
"visual-studio-2008",
""
] |
I am wondering - What's the most effective way of parsing something like:
```
{{HEADER}}
Hello my name is {{NAME}}
{{#CONTENT}}
This is the content ...
{{#PERSONS}}
<p>My name is {{NAME}}.</p>
{{/PERSONS}}
{{/CONTENT}}
{{FOOTER}}
```
Of course this is intended to be somewhat of a templating... | Is the expected output of this something like:
This is a header
Hello my name is David
```
This is the content ...
My name is Heino.
My name is Sebastian.
```
This is the footer
---
How are you managing the relationship of nested arrays in the hash map to repeatable sections in the template? What is the actual ... | The most efficient way to is to **compile** the template to php code. And just **include** the compiled version.
The [Smarty Template Engine](http://www.smarty.net) does something similar. You can also look at the smarty source and check how they parse tags. | Parsing of nested tags in a file | [
"",
"php",
"parsing",
"recursion",
"templates",
"nested",
""
] |
I am trying to use a third party DLL that wants an int\*\* as one of the parameters to the method. It describes the parameter as the address of the pointer that will point to the memory allocation.
Sorry for any confusion. The parameter is two-way I think. The DLL is for talking to an FPGA board and the method is sett... | Use a by-ref [`System.IntPtr`](http://msdn.microsoft.com/en-us/library/system.intptr.aspx).
```
[DllImport("thirdparty.dll")]
static extern long ThirdPartyFunction(ref IntPtr arg);
long f(int[] array)
{ long retval = 0;
int size = Marshal.SizeOf(typeof(int));
var ptr = IntPtr.Zero;
try
... | You will have to make use of the Marshal class or go unsafe in this case.
It could also just be a pointer to an array, so a `ref int[] list` might work. | DLLImport Int** - How to do this if it can be done | [
"",
"c#",
"interop",
"pinvoke",
"dllimport",
""
] |
I have created a timeclock application in C# that connects to a web service on our server in order to clock employees in/out. The application resides in the system tray and clocks users out if they shut down/suspend their machines or if they are idle for more than three hours to which it clocks them out at the time of ... | The best way is going to be to actually try to make the connection and catch the errors. You can ping the machine, but that will only tell you if the machine is running and on the network, which doesn't necessarily reflect on whether the webservice is running and available. | Implement a queue where you post messages and have a thread periodically try to flush the in-memory queue to the web service. | Best way to check if server is reachable in .NET? | [
"",
"c#",
".net",
"web-services",
""
] |
Recently I had to do some very processing heavy stuff with data stored in a DataSet. It was heavy enough that I ended up using a tool to help identify some bottlenecks in my code. When I was analyzing the bottlenecks, I noticed that although DataSet lookups were not terribly slow (they weren't the bottleneck), it was s... | Via [Reflector](http://www.red-gate.com/products/reflector/) the steps for DataRow["ColumnName"] are:
1. Get the DataColumn from ColumnName. Uses the row's DataColumnCollection["ColumnName"]. Internally, DataColumnCollection stores its DataColumns in a Hastable. O(1)
2. Get the DataRow's row index. The index is stored... | Actually it's advisable to use integer when referencing column, which can improve a lot in terms of performance. To keep things manageable, you could declare constant integer. So instead of what you did, you could do
```
const int SomeTable_SomeColumn = 0;
DataTable dt = new DataTable();
if(dt.Columns.Contains(SomeTa... | Speed of DataSet row/column lookups? | [
"",
"c#",
".net",
"optimization",
"datatable",
""
] |
Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?
One example:
I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expres... | If you're specifically after parsing links out of web-pages, then Perl's [WWW::Mechanize](http://search.cpan.org/perldoc?WWW::Mechanize) module will figure things out for you in a very elegant fashion. Here's a sample program that grabs the first page of Stack Overflow and parses out all the links, printing their text ... | Look at documentation for following modules on [CPAN](http://www.cpan.org/)
[HTML::TreeBuilder](http://search.cpan.org/search?query=HTML%3A%3ATreeBuilder&mode=all)
[HTML::TableExtract](http://search.cpan.org/author/MSISK/HTML-TableExtract-2.10/lib/HTML/TableExtract.pm)
and
[Parse::RecDescent](http://search.cpan.org... | Emulation of lex like functionality in Perl or Python | [
"",
"python",
"perl",
"parsing",
"lex",
""
] |
I'm an expert C# 3 / .NET 3.5 programmer looking to start doing some runtime codegen using System.Reflection.Emit.DynamicMethod. I'd love to move up to the next level by becoming intimately familiar with IL.
Any pointers (pun intended)? | The best way to learn it, is to write something you understand, then look at the IL it created. Also, depending on what you are doing, you can use expression trees instead of emitting IL, and then when you compile the expression trees, those smart guys at microsoft create the IL for ya. | In addition to Darren's answer, I'd suggest picking or inventing a toy language, and writing a simple compiler for it. Pick something that requires little parsing, like BF or a stack-based language, and you'll find that writing a compiler is actually simpler than it seems. | What are the best resources for learning CIL (MSIL) | [
"",
"c#",
".net",
"code-generation",
"cil",
""
] |
How do I stop a Java process gracefully in Linux and Windows?
When does `Runtime.getRuntime().addShutdownHook` get called, and when does it not?
What about finalizers, do they help here?
Can I send some sort of signal to a Java process from a shell?
I am looking for preferably portable solutions. | Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (`SIGTERM` from a kill command) then they will execute. Similarly, they will execute after calling `System.exit(int)`.
However a hard kill (`kill -9` or `kill -SIGKILL`) then they won't execute. Similarl... | Ok, after all the possibilities I have chosen to work with "Java Monitoring and Management"
[Overview is here](http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html)
That allows you to control one application from another one in relatively easy way. You can call the controlling application from a scrip... | How to stop java process gracefully? | [
"",
"java",
"linux",
"windows",
"shell",
"process",
""
] |
When generating XML from XmlDocument in .NET, a blank `xmlns` attribute appears the first time an element *without* an associated namespace is inserted; how can this be prevented?
Example:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentE... | Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank `xmlns` attributes: pass in the root node's namespace when creating any child node you want *not* to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child ele... | This is a variant of JeniT's answer (Thank you very very much btw!)
```
XmlElement new_element = doc.CreateElement("Foo", doc.DocumentElement.NamespaceURI);
```
This eliminates having to copy or repeat the namespace everywhere. | How to prevent blank xmlns attributes in output from .NET's XmlDocument? | [
"",
"c#",
".net",
"xml",
"xml-namespaces",
"xmldocument",
""
] |
Rep steps:
1. create example .NET form application
2. put a TextBox on the form
3. wire a function up to the TextBox's Enter event
When you run this application, the **Control.Enter** event fires when focus first goes to the TextBox. However, if you click away into another application and then click back into the tes... | If I try your example and click outside the control on another window, desktop, etc, I can get the Got and Lost Focus events to fire, but if you're only trying to click within a form or a control with only 1 control, these event will *never* be fired because it is the only thing to focus on. Neither will Entered or lef... | What are you trying to do in the Enter event?
I can't find another control-level event that fires in your example program but when my test app does regain focus, the control that last had focus still has it.
Interesting question but it needs a little more context. | Control.Enter event doesn't fire when switching tasks. Is there an alternative that does? | [
"",
"c#",
"events",
"user-interface",
""
] |
I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back.
I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has t... | You can construct the 'multipart/form-data' request yourself (read more about it at <http://www.faqs.org/rfcs/rfc2388.html>) and then use the `send` method (ie. xhr.send(your-multipart-form-data)). Similarly, but easier, in Firefox 4+ (also in Chrome 5+ and Safari 5+) you can use the [FormData](http://hacks.mozilla.org... | There isn't any way to access a file input field inside javascript so there isn't a javascript only solution for ajax file uploads.
There are workaround like [using an iframe](http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html).
The other option would be to use something like [SWFUpload](http://www.swfuplo... | XMLHttpRequest POST multipart/form-data | [
"",
"javascript",
"ajax",
"xmlhttprequest",
""
] |
I'm working with a datagrid and adapter that correspond with an MSAccess table through a stored query (named "UpdatePaid", 3 paramaters as shown below) like so:
```
OleDbCommand odc = new OleDbCommand("UpdatePaid", connection);
OleDbParameter param;
odc.CommandType = CommandType.StoredProcedure;
par... | This is called, oddly enough, a prepared statement, and they're actually really nice. Basically what happens is you either create or get a sql statement (insert, delete, update) and instead of passing actual values, you pass "?" as a place holder. This is all well and good, except what we want is our values to get pass... | I don't use it with SqlDbCommand. It seems as a bug to me that it's *required*. It should only be *nice to have* if you're going to call a procedure multiple times in a row. Maybe I'm wrong and there's a note in documentation about providers that love this call too much. | Why do I need OleDbCommand.Prepare()? | [
"",
"c#",
".net",
"stored-procedures",
"ole",
""
] |
I have a `double` value `f` and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original.
It doesn't have to be close down to the last bit—it's more important that whatever change I ma... | Check your math.h file. If you're lucky you have the [`nextafter`](http://en.cppreference.com/w/c/numeric/math/nextafter) and [`nextafterf`](http://en.cppreference.com/w/c/numeric/math/nextafter) functions defined. They do exactly what you want in a portable and platform independent way and are part of the C99 standard... | ```
u64 &x = *(u64*)(&f);
x++;
```
Yes, seriously.
**Edit:** As someone pointed out, this does not deal with -ve numbers, Inf, Nan or overflow properly. A safer version of the above is
```
u64 &x = *(u64*)(&f);
if( ((x>>52) & 2047) != 2047 ) //if exponent is all 1's then f is a nan or inf.
{
x += f>0 ? 1 : -1... | How to alter a float by its smallest increment (or close to it)? | [
"",
"c++",
"c",
"floating-point",
""
] |
Is there any one website which contains many good C# screencasts? | I like the [channel 9 screencasts](http://channel9.msdn.com/tags/CSharp/) tagged C#.. | [Dimecasts.net](http://dimecasts.net/) is coming out with lots of good, short screencasts on various .NET topics. Some in the ALT.NET space. Most of the example code they write is in C#. | Is there any one website which contains many good C# screencasts? | [
"",
"c#",
""
] |
I have an .net C# console application (not a service). it basically connects to a webservice, gets some xml files, copies those files to a few location on a drives, validates the xml, processes it and sends these objects to another web service.
However, when the main method exists (and the console window closes) I can... | Look at Thread usage and async calls. | If the console window has closed, it seems very odd indeed that the process is still running. Can you attach to it in the Visual Studio debugger? (Obviously a debug build.)
Are you sure it's not a previous run which is still executing? | C# Console Application still resident in memory after exit | [
"",
"c#",
".net",
"console-application",
""
] |
I've used [WWW SQL Designer](http://ondras.zarovi.cz/sql/) several times to design databases for applications. I'm now in charge of working on an application with a lot of tables (100+ mysql tables) and I would love to be able to look at the relations between tables in a manner similar to what WWW SQL Designer provides... | <http://code.google.com/p/database-diagram/>
This takes a SQL structure (SQL dump) and shows a diagram :) | I know this is really old stuff, but I found the solution (if people are looking for it) : you have to edit the file *backend/php-mysql/index.php* and fill the connection settings. All you need is then to click on **Import From DB**, and then **Load** with the name of your database.
```
function setup_import() {
d... | Loading an existing database into WWW SQL Designer? | [
"",
"sql",
"mysql",
"diagram",
""
] |
I tried to set innerHTML on an element in firefox and it worked fine, tried it in IE and got unexpected errors with no obvious reason why.
For example if you try and set the innerHTML of a table to " hi from stu " it will fail, because the table must be followed by a sequence. | "Apparently firefox isn't this picky" ==> Apparently FireFox is so buggy, that it doesn't register this obvious violation of basic html-nesting rules ...
As someone pointed out in another forum, FireFox will accept, that you append an entire html-document as a child of a form-field or even an image ,-( | You're seeing that behaviour because innerHTML is read-only for table elements in IE. From MSDN's [innerHTML Property](http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx) documentation:
> The property is read/write for all objects except the following, for which it is read-only: COL, COLGROUP, FRAMESET, HEAD... | Why does IE give unexpected errors when setting innerHTML | [
"",
"javascript",
"internet-explorer",
"innerhtml",
""
] |
I have a form element that I want to address via javascript, but it doesn't like the syntax.
```
<form name="mycache">
<input type="hidden" name="cache[m][2]">
<!-- ... -->
</form>
```
I want to be able to say:
```
document.mycache.cache[m][2]
```
but obviously I need to indicate that `cache[m][2]` is the whole... | UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.
Here's some code that proves it:
```
<html>
<body>
<form id="form1">
<input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>
<input type='button' value='Test' onclick='showtest();'/>
<s... | Use `document.getElementsByName("input_name")` instead. Cross platform too. Win. | How can I escape a DOM name in javascript? | [
"",
"javascript",
""
] |
I have an activex object I loaded into an html page. I then use that activex object to create another object, but I need to register an event with the new object created. The object is expecting an event listener of a certain type.
I can load this same dll in c# and it will work fine. Code looks like this for c#.
```... | Found out from the company that these properties are not accessible through javascript. They will need to externalize them for use within javascript. | Your javascript should look something like this:
```
function uploadAction::stateChanged( parms )
{
// ...
// implementation
// ...
}
```
Note, that this is a static function declaration, assuming that you have an Active X object named 'uploadAction'. I know that this does work - we use it at my company. | Javascript registering event to object | [
"",
"javascript",
"events",
"activex",
""
] |
The situation is like this : Main project A. and a class library B. **A references B**
Project B has the classes that will be serialized. The classes are used in A. Now, the problem appears when from Project A I try to serialize the objects from B. An exception is thrown that says a class from A cannot be serialized. ... | I have written a tool called [sertool](http://kent-boogaart.com/blog/sertool) that will tell you what in your object graph cannot be serialized and how it is being referenced. | You will first need to isolate the problem to a specific class. Then you can implement custom serialization and debug it to find the real problem.
Just a simple implementation to let you step through the process:
```
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
[Serializable]
... | Serialization problem | [
"",
"c#",
"serialization",
""
] |
I have an idea for a website which involves a canvas area which has no limit to its size. Basically you would be able to add items to the canvas (notes, photos whatever really). You would then be able to drag the canvas which would move those items along with the canvas until they disappear of screen. If you dragged th... | I don't think this is a question that will get you an objective answer - Flash developers will tell you Flash is better, web developers will say JavaScript. Trying to remain objective, I'd say that both technologies are suitable for what you describe, but have different advantages.
Flash will definitely render faster,... | My initial thought would be to go with Javascript - if it's good enough for Google Maps, it's probably good enough for your app too. | What would be quicker Flash or Javascript? | [
"",
"javascript",
"flash",
""
] |
i am writing a game in C++ and have a level consisting of many seperate meshes, each with their own vertex buffer. i am using vmmlib ( brilliant free gl compat. vector/matrix library ) to create my frustum culler and testing it against the bounding sphere of every mesh in the level. sadly my level can consist of up to ... | Yes bounding object is the way to go, you should take care in choosing an adequate bounding volume, for example for meshes that move about the scene like bots and dont lie down a cylinder is the best volume, other are better represented by cubes (axis aligned or not).
Then you create a quadtree or octree to hierarchic... | [Binary space partitioning](http://en.wikipedia.org/wiki/Binary_space_partitioning) or its cousin [Quadtree](http://en.wikipedia.org/wiki/Quadtree). | Optimize Frustum Culling | [
"",
"c++",
"3d",
"frustum",
"space-partitioning",
""
] |
I have 2 tables. Table1 has fields A, B, C, D and Table2 has fields A, B. Field A and B of both tables have same record type. I would like to grab the records from both tables of fields A and B as single result.
Is there any Query or Function in PHP+MySql?
Thanks... | I assume MySql does this:
select a,b from table1 where your\_criteria=test\_value
union
select a,b from table2 where your\_criteria=test\_value | There's a union clause in SQL that does what you want:
```
select a,b from table1
where <where-clause>
union all select a,b from table2
where <where-clause>
```
or, if you want all fields (spaces for table2):
```
select a,b,c,d from table1
where <where-clause>
union all select a,b,' ' as c,' ' as d from ... | Grabbing rows from multiple tables as single result? | [
"",
"php",
"mysql",
""
] |
Currently I am [borrowing `java.math.BigInteger` from the J# libraries as described here](http://msdn.microsoft.com/en-us/magazine/cc163696.aspx). Having never used a library for working with large integers before, this seems slow, on the order of 10 times slower, even for `ulong` length numbers. Does anyone have any b... | As of .NET 4.0 you can use the System.Numerics.BigInteger class. See documentation here: <http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx>
Another alternative is the [IntX](https://github.com/devoyster/IntXLib) class.
> IntX is an arbitrary precision
> integers library written in pur... | `F#` also ships with one. You can get it at `Microsoft.FSharp.Math`. | Big integers in C# | [
"",
"c#",
"biginteger",
"largenumber",
"j#",
""
] |
I'm getting XML like this:
`<Items>
<Row attr1="val"></Row>
<Row attr1="val2"></Row>
</Items>`
This is valid XML, as you know, but another library I'm using is busted and it will only accept XML in this format:
`<Items>
<Row attr1="val"/>
<Row attr1="val2"/>
</Items>`
I'm already reading the XML into XmlDocuments, ... | Set the [IsEmpty](http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.isempty.aspx) property of each XmlElement you want to collapse to true. | If you use System.XML's DOM manipulation objects (XmlElement etc) instead of XmlWriter, you get this for free.
```
XmlElement items = xmlDoc.SelectNodes("items");
XmlElement row = xmlDoc.CreateElement("row");
items[0].appendChild(row);
```
You'll get a "<row/>" | How do I collapse empty xml tags? | [
"",
"c#",
"xml",
""
] |
I'm using StringBuffer in Java to concat strings together, like so:
```
StringBuffer str = new StringBuffer();
str.append("string value");
```
I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding".
Let me explain; every... | I think this is handled easier either with a helper method (untested code):
```
public String myMethod() {
StringBuilder sb = new StringBuilder();
addToBuffer(sb, "Hello").addToBuffer("there,");
addToBuffer(sb, "it").addToBuffer(sb, "works");
}
private StringBuilder addToBuffer(StringBuilder sb, String wh... | You should be using [StringBuilder](http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html).
> Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. | Java: StringBuffer & Concatenation | [
"",
"java",
"concatenation",
"stringbuffer",
""
] |
I was wondering if there was a way to get at the raw HTTP request data in PHP running on apache that doesn't involve using any additional extensions. I've seen the [HTTP](https://www.php.net/http) functions in the manual, but I don't have the option of installing an extension in my environment.
While I can access the ... | Do you mean the information contained in `$_SERVER`?
```
print_r($_SERVER);
```
Edit:
Would this do then?
```
foreach(getallheaders() as $key=>$value) {
print $key.': '.$value."<br />";
}
``` | Use the following php wrapper:
```
$raw_post = file_get_contents("php://input");
``` | How can I access the raw HTTP request data with PHP/apache? | [
"",
"php",
"apache",
""
] |
How do I go about positioning a JDialog at the center of the screen? | In Java 1.4+ you can do:
```
final JDialog d = new JDialog();
d.setSize(200,200);
d.setLocationRelativeTo(null);
d.setVisible(true);
```
Or perhaps (pre 1.4):
```
final JDialog d = new JDialog();
d.setSize(200, 200);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenS... | Use this line after the `pack()` method:
```
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width)/2 - getWidth()/2, (Toolkit.getDefaultToolkit().getScreenSize().height)/2 - getHeight()/2);
``` | How do I center a JDialog on screen? | [
"",
"java",
"swing",
""
] |
I am a big fan of the Lightbox2 library, and have used it in the past just not on an MVC project. In the past I remember that Lightbox2 was picky about the paths it scripts, css, and images resided in. I remember specifically have to put everything in subdirectories of the page's path, else it wouldn't work.
In a non-... | I believe Lightbox assumes you have a structure as follows:
```
/images
prevlabel.gif
nextlabel.gif
loading.gif
closelabel.gif
/css
lightbox.css
lightbox.js
```
You can just open lightbox.js and find:
```
fileLoadingImage: 'images/loading.gif',
fileBottomNavCloseImage: 'images/closela... | ```
<script src="~/LightBox/js/jquery.js"></script>
<script src="~/LightBox/js/jquery.lightbox-0.5.min.js"></script>
<a title="Title here" class="lightbox" href="~/LightBox/images/lightbox-btn-close.gif">click</a>
<script type="text/javascript">
$(function () {
$('a.lightbox').lightBox();//.lightBox();... | How to use Lightbox under MVC | [
"",
"javascript",
"model-view-controller",
"lightbox2",
""
] |
I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.
I have the e-mailing of the link, MySQL query, etc. covered.
How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?
I have all the information to get the record already. I just ... | Try:
```
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
die;
```
etc
Edit: Here's a snippet of code I use to optionally encode CSV fields:
```
function maybeEncodeCSVField($string) {... | ```
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
function outputCSV($data) {
$output = fopen("php://output", "wb");
foreach ($data as $row)
fputcsv($output, $row); // here you can change delimiter/enclosure
fclose($output);
}
outputCSV(array(
array("name ... | Create a CSV File for a user in PHP | [
"",
"php",
"csv",
"download",
"http-headers",
""
] |
I've looked at [Microsoft GLEE](http://blogs.msdn.com/powershell/archive/2007/11/27/graphing-with-glee.aspx) (non-commerical use) and other libraries for drawing graphs, but I need a good commercial use graph API to show complex routes through the Internet.
I need to be able to show a large number of nodes and vertexe... | The [Graphviz resources page](http://www.graphviz.org/Resources.php) lists a project, [QuickGraph](http://www.codeplex.com/quickgraph), which may solve your problem. | You should check out Microsoft Research's NetMap
<http://www.codeplex.com/NetMap>
".NetMap is a pair of applications for viewing network graphs, along with a set of .NET Framework 2.0 class libraries that can be used to add network graphs to custom applications.
A network graph is a series of vertices (sometimes cal... | Is there a good graph (not charting) visualization API for .Net? | [
"",
"c#",
".net",
"graph-theory",
""
] |
i want to know how to edit a single row (which i select) from a data grid
for example i have a datagrid with columns A, B and C
and i have a couple rows of data, approx 10 rows.
lets say i want to change the value of data within row 4.
how would i do this?
i am using visual studio 2003, but i guess if visual studio... | All grid-like components of asp.net have the same machanism as it comes to starting to edit a single row. Actually it's default for asp.net only to edit a single row in a grid.
Needed to start editing is to include asp:button or asp:linkbutton in the ItemTemplate with the CommandName set to "Edit". This one of reserve... | Take a look at the documentation for adding an EditItemTemplate to your datagrid. You use the ItemTemplate for view-only, display elements and you use the EditItemTemplate for controls used to bind against a single row that you select.
Here's a link that might help:
<http://www.gridviewguy.com/> | edit datagrid row | [
"",
"c#",
"visual-studio",
"datagrid",
""
] |
I want to take the value stored in a 32 bit unsigned int, put it into four chars and then store the integer value of each of these chars in a string.
I think the first part goes like this:
```
char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;
``` | If you really want to extract the individual bytes first:
```
unsigned char a = orig & 0xff;
unsigned char b = (orig >> 8) & 0xff;
unsigned char c = (orig >> 16) & 0xff;
unsigned char d = (orig >> 24) & 0xff;
```
Or:
```
unsigned char *chars = (unsigned char *)(&orig);
unsigned char a = chars[0];
unsigned char b = c... | Let's say "orig" is a 32bit variable containing your value.
I imagine you want to do something like this:
```
unsigned char byte1=orig&0xff;
unsigned char byte2=(orig>>8)&0xff;
unsigned char byte3=(orig>>16)&0xff;
unsigned char byte4=(orig>>24)&0xff;
char myString[256];
sprintf(myString,"%x %x %x %x",byte1,byte2,byt... | How do I get the integer value of a char in C++? | [
"",
"c++",
"bit-manipulation",
"endianness",
""
] |
I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things?
EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS... | Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:
...in VB.NET:
```
String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))
```
...in C#
```
string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")... | The solutions so far are all quite complicated. The idiomatic solution should doubtless be:
```
String.Join(",", x.Cast(Of String)().ToArray())
```
There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:
```
Console.WriteLine(String.Join(",",... | How do I create a comma delimited string from an ArrayList? | [
"",
"c#",
"vb.net",
"parsing",
""
] |
For our Django App, we'd like to get an `AutoField` to start at a number other than 1. There doesn't seem to be an obvious way to do this. Any ideas? | Like the others have said, this would be much easier to do on the database side than the Django side.
For Postgres, it'd be [like so](http://www.postgresql.org/docs/9.1/static/sql-altersequence.html): `ALTER SEQUENCE sequence_name RESTART WITH 12345;` Look at your own DB engine's docs for how you'd do it there. | For MySQL i created a signal that does this after syncdb:
```
from django.db.models.signals import post_syncdb
from project.app import models as app_models
def auto_increment_start(sender, **kwargs):
from django.db import connection, transaction
cursor = connection.cursor()
cursor = cursor.execute("""
... | How to get Django AutoFields to start at a higher number | [
"",
"python",
"django",
"autofield",
""
] |
I am working on C++ and COM/ATL in Windows from last few years. Now I want to shift to Linux Programming. I know basic architecture of Linux. I did some of the projects which are using ncurses, sockets and audio libraries(Terminal Applications). On which tool I should be familiar to start with projects. In windows I ha... | Start reading the book [Advanced Linux Programming](http://www.advancedlinuxprogramming.com/) which is also available as a free PDF.
Do not fear the *advanced* keyword. From the details of your post (ncurses, sockets) you are already "advanced".
You can also look later at the [glib](http://www.gtk.org/overview.html) ... | * gcc/g++
* understand shell basics: probably bash (typically the default)
* make (you don't have to be an expert, or even use it in your own work, but you should understand it)
* a scripting language (bash, ruby, python, tcl, perl; you choose)
* basic unix command line utilities (ls, cd, etc....)
* an editor: vi or em... | How to start Linux Programming | [
"",
"c++",
"c",
"linux",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.