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 implementing this in java as well and they have this nice addShutdownHook that catches terminating the app. I need to spend a little more time sorting out the dependencies for mono service, or find a way to catch app termination.
There is the SessionEnd event, but thats only available for services and not console apps
**Answer:**
[using mono-service to wrap a windows service on linux](https://stackoverflow.com/questions/351971/using-mono-service-to-wrap-a-windows-service-on-linux)
|
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 this on a separate thread.
|
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 "\_".
Length comparison were used to escape == operator working with STL strings, which obviously takes more time then simple integer comparison. But in the same time first letter distribution in the given dictionary is simply wider than a distribution of words size, so two first letters of comparing strings will be generally more often different, than the sizes of that strings. That makes length comparison unnecessary.
I've ran some tests and that is what I've found out: While testing two random strings comparison million times, second way is much faster, so length comparison seems to be helpful. But in a working project it works even slower in a debug mode and insufficiantly faster in a release mode.
So, my question is: why length comparison can fasten the comparison and why can it slow it down?
UPD: I don't like that second way either, but it had been done for a reason, I suppose, and I wonder, what is this reason.
UPD2: Seriously, the question is not how to do best. I'm not even using STL strings in this case anymore. There's no wonder that length comparison is unnecessary and wrong etc. The wonder is - it really tends to work slightly better in one certain test. How is this possible?
|
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 filename, float position)
{
}
```
Does anyone know how to do this in .Net 3.0?
The correct solution will be the "best" implementation of this function.
Bonus points for avoiding selection of blank frames.
|
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.net](http://sourceforge.net/projects/directshownet/) project so you will have to clear that portion of the code with them.
This class will not work for DVR-MS files, you need to inject a direct show filter for those.
|
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 world?
|
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 destination. Understand that the sample code you are looking took many forms before it became what you see now. You did not see the awkward models that were used initially and you're missing the steps taken to refactor the model based on insight gained along the way. While the building blocks are important in DDD, Eric belives they are over-emphasized, so take all samples with a grain of salt.
|
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 know of any good libraries? Post links to tutorials and any other interesting information...
|
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.openframeworks.cc/index.php?title=OfAmsterdam>
and some processing animation code here:
<http://thesystemis.com/makingthingsmove>
that might be a helpful starting point.
have fun !
zach
|
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 together with regular cindent.
edit: The filetype plugin was already turned on I just got a bit confused about indenting plugins. The accepted answer may be a bit hackish but works for me as well.
|
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 indent on`.
That said, the indentation file coming with the Vim 7.1 from my linux distribution (looking at the current vim svn this is still true for 7.2) doesn't account for annotations yet. I therefore copied `/usr/share/vim/vim71/indent/java.vim` (see <https://vim.svn.sourceforge.net/svnroot/vim/branches/vim7.1/runtime/indent/java.vim>) to `~/.vim/indent/java.vim` and added the following lines right before the end:
```
let lnum = prevnonblank(v:lnum - 1)
let line = getline(lnum)
if line =~ '^\s*@.*$'
let theIndent = indent(lnum)
endif
```
I'm not sure if this breaks any of the other indentations, but it works for me.
|
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 = GetJavaIndent()
let lnum = prevnonblank(v:lnum - 1)
let line = getline(lnum)
if line =~ '^\s*@.*$'
let theIndent = indent(lnum)
endif
return theIndent
endfunction
setlocal indentexpr=GetJavaIndent_improved()
```
That way it loads the stock java indent and only modifies the indent to remove the annotation indents.
|
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 as a conventional Form Post.
The W3C docs mention the data param of the send method is a DOMString but I am not sure how the major browsers implement that.
Here is a simplified version of my JavaScript, if bigText is over about 3k it fails, otherwise it works...
```
var xhReq = createXMLHttpRequest();
function createXMLHttpRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
alert("XMLHttpRequest not supported");
return null;
}
function mySubmit(id, bigText) {
var url = "SubmitPost.cfm";
var params = "id=" + id + "&bigtext=" + encodeURI(bigText);
xhReq.open("POST", url, true);
//Send the header information along with the request
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("Content-length", params.length);
xhReq.setRequestHeader("Connection", "close");
xhReq.onreadystatechange = onPostSubmit;
xhReq.send(params);
}
function onPostSubmit() {
if (xhReq.readyState==4 || xhReq.readyState=="complete")
{
if (xhReq.status != 200)
{
alert('BadStatus');
return;
}
}
}
```
|
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. IIS 6 and 7 for example have a 200KB default limit.
|
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 like that? Googling revealed only some hacks with listing files.
|
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 interface? Normally I'd put this kind of logic in my views. Is this the right place or should I be moving some more logic down into the model? Alternatively is there a better library out there or do I need to roll my own?
|
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.com/p/django-rest-interface/issues/detail?id=32).
However, it's relatively easy to extend it to add some features. I use a lot of subclasses to add features.
Updating the request with login information, however, is tricky in Django. Rather than do that, I leave the information in the Collection.
Right now, I'd estimate that between patches and subclasses, what I've written is about as big as rolling my own RESTful view functions.
Django-REST, however, gracefully and neatly handles HTTP Digest Authentication. I don't look forward to replacing theirs with some kind of decorator for my Django view functions.
[Maybe we should open a source forge project and work out a clean replacement?]
|
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 describing roles and a many-to-many association table linking artefact ID to Role ID.
Domain wise, we have two classes - one for a role and one for an artefact. the artefact class has an IList property that returns a list of roles that can access it. (Roles however do not offer a property to get artefacts that can be accessed).
As such, the nhibernate mapping for artefact contains the following;
```
<bag name="AccessRoles" table="ArtefactAccess" order-by="RoleID"
lazy="true" access="field.camelcase-underscore" optimistic-lock="false">
<key column="ArtefactID"/>
<many-to-many class="Role" column="RoleID"/>
</bag>
```
This all works fine and if I delete an artefact, the association table is cleaned up appropriately and all references between the removed artefact and roles are removed (the role isn't deleted though, correctly - as we don't want orphans deleted).
The problem is - how to delete a role and have it clear up the association table automatically. If I presently try to delete a role, I get a reference constraint as there are still entries in the association table for the role. 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 with any number of other tables/objects.
I need to be able to hint to NHibernate that I want this association table cleared whenever I delete a role - is this possible, and if so - how do I do it?
Thanks for any help.
|
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="AccessId" />
<many-to-many column="AccessId" class="Domain.Compound,Domain" />
</bag>
<bag name="RolesToAccess" cascade="save-update" inverse="true" lazy="false">
<key column="AccessId" on-delete="cascade" />
<one-to-many class="Domain.RolesToAccess,Domain" />
</bag>
```
Roles:
```
<bag name="Accesses" table="RolesToAccess" cascade="none" lazy="false">
<key column="RoleId" />
<many-to-many column="RoleId" class="Domain.Compound,Domain" />
</bag>
<bag name="RolesToAccess" cascade="save-update" inverse="true" lazy="false">
<key column="RoleId" on-delete="cascade" />
<one-to-many class="Domain.RolesToAccess,Domain" />
</bag>
```
As mentioned above you can make the RolesToAccess properties protected so they don't pollute your model.
|
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 with any number of other tables/objects.
Is not necessary. Suppose you don't want to map the association table (make it a domain object), you can still perform deletes on both ends with minimal code.
Let's say there are 3 tables: Role, Artifact, and ArtifactAccess (the link table).
In your mapping, you only have domain objects for Role and Artifact. Both have a bag for the many-many association.
Role:
```
<bag name="Artifacts" table="[ArtifactAccess]" schema="[Dbo]" lazy="true"
inverse="false" cascade="none" generic="true">
<key column="[ArtifactID]"/>
<many-to-many column="[RoleID]" class="Role" />
</bag>
```
Artifact:
```
<bag name="Roles" table="[ArtifactAccess]" schema="[Dbo]" lazy="true"
inverse="false" cascade="none" generic="true">
<key column="[RoleID]"/>
<many-to-many column="[ArtifactID]" class="Role" />
</bag>
```
As you can see, both ends have inverse=false specified. The NHibernate documentation recommends you to choose one end of your association as the 'inverse' end, but nothing stops you from using both as 'controlling end'. When performing updates or inserts, this works from both directions without a hitch. When performing deletes of either one of the ends, you get a FK violation error because the association table is not updated, true. But you can solve this by just clearing the collection to the other end, before performing the delete, which is a lot less complex than what you do, which is looking in the 'other' end of the association if there are uses of 'this' end. If this is a bit confusing, here is a code example. If you only have one end in control, for your complex delete you need to do:
```
foreach(var artifact in role.Artifacts)
foreach(var role in artifact.Roles)
if(role == roleToDelete)
artifact.Roles.Remove(role)
artifact.Save();
roleToDelete.Delete();
```
What I do when deleting a role is something like
```
roleToDelete.Artifacts.Clear(); //removes the association record
roleToDelete.Delete(); // removes the artifact record
```
It's one extra line of code, but this way you don't need to make a decision on which end of the association is the inverse end. You also don't need to map the association table for full control.
|
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\_globals is enabled. You can
> disable this functionality and this
> warning by setting
> session.bug\_compat\_42 or
> session.bug\_compat\_warn to off,
> respectively. in **Unknown** on line **0**
What does this mean? How might I track down the source of this problem within the code?
|
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', 0);
ini_set('session.bug_compat_42', 0);
```
these values can be set in php.ini or .htaccess as well
|
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']=$_REQUEST['firstname'];
```
will trigger the warning.
Additionally, I interpret this php bug content: <http://bugs.php.net/bug.php?id=41540> to mean that this error may also occur when you assign a variable to the session superglobal that is not yet initialized, e.g.
```
//Start of script
$_SESSION['bob'] = $bob;
```
|
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 guaranteed to work on any platform, unless the platform states to support this standard.
Every solution people have suggested here is a solution that uses an external library and thus can only work on platforms supported by that library; and no library is available for every existing platform.
Probably the one that will get you farthest is POSIX, after all every UNIX like system tries to support at least some POSIX (the more the better), very little can call themselves really being 100% POSIX-compliant platforms (e.g. A/UX, AIX, HP-UX, IRIX, Mac OS X 10.5, MINIX, QNX, Solaris, UnixWare, VxWorks, ... to name a few, there are more of course). However, there are quite a couple of platforms that offer at least some POSIX support, some more, some less and some are almost POSIX-compliant (e.g. FreeBSD, Linux, NetBSD, BeOS, OpenBSD, ... and others).
Windows is unfortunately far away from being one. NT used to be partly POSIX conform, but now it has more or less vanished (Win2000/20003, WinXP, and Vista can still be set into a POSIX emulating mode, translating some POSIX call to internal API calls by installing Microsoft Windows Services for UNIX - SFU 3.5 or higher), however there are ways to get some POSIX functionality on Windows through external libraries as well (Cygwin offers LGPL libraries you can link with your app to enable a fair amount of POSIX functions on Windows).
The advantage of POSIX is not only that it is relatively widespread, but also that it is standardized and you can easily look up the standard on the Internet. Using POSIX calls you can get a thread id and a process id.
|
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](http://www.trolltech.com) library. This is less portable and imply to work with Qt, a big library.
If you already use any on these two libraries, I would recommend sticking with it. Otherwise, look at what other tools they provide and make a choice.
|
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 rcClient;
GetClientRect(rcClient);
Bitmap bmp(rcClient.Width(), rcClient.Height());
Graphics graphics(&bmp);
graphics.DrawImage(m_image, rcClient.left, rcClient.top);
Graphics grph(pDC->m_hDC);
grph.DrawImage(&bmp, 0, 0);
}
```
Am I doing something wrong? Or is there another way to achieve this?
|
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 relied on even on systems running Vista). Therefore, the best you can do to minimize flicker is to draw everything as quickly as possible (*reduce* tearing by increasing your chances of completing all drawing within a refresh cycle), and avoid overdraw (drawing part of the screen and then drawing something else over the top: risks presenting user with a partially-drawn screen).
Let's discuss the techniques presented here so far:
* **Do-nothing *OnEraseBkgnd()***: helps to avoid over-draw by preventing the invalidated area of the window from being filled with the window's background color. Useful when you will be drawing the entire area again during *WM\_PAINT* handling *anyway*, as in the case of double-buffered drawing... but see *Notes on avoiding overdraw by preventing drawing after your* WM\_PAINT *method*.
* **Returning NULL for *OnCtlColor()***: this shouldn't actually do *anything*... unless you have child controls on your form. In that case, see *Notes on avoiding overdraw by preventing drawing after your* WM\_PAINT *method* instead.
* **Double buffered drawing**: helps to avoid tearing (and potentially overdraw as well), by reducing the actual on-screen drawing to a single [BitBLT](https://en.wikipedia.org/wiki/Bit_blit). May hurt the time needed for drawing though: hardware acceleration cannot be used (although with GDI+, the chances of any hardware-assisted drawing being used are quite slim), an off-screen bitmap must be created and filled for each redraw, and the entire window must be repainted for each redraw. See *Notes on efficient double-buffering*.
* **Using GDI calls rather than GDI+ for the BitBlt**: This is often a good idea - `Graphics::DrawImage()` can be very slow. I've even found the normal GDI [`BitBlt()`](https://msdn.microsoft.com/en-us/library/dd183370.aspx) call to be faster on some systems. Play around with this, but only after trying a few other suggestions first.
* **Avoiding window class styles that force a full redraw on each resize (*CS\_VREDRAW*, *CS\_HREDRAW*)**: This will help, but only if you don't *need* to redraw the entire window when size changes.
### Notes on avoiding overdraw by preventing drawing prior to your *WM\_PAINT* method
When all or a portion of a window is invalidated, it will be erased and repainted. As already noted, you can skip erasing if you plan to repaint the entire invalid area. **However**, if you are working with a child window, then you must ensure that parent window(s) are not also erasing your area of the screen. The *WS\_CLIPCHILDREN* style should be set on all parent windows - this will prevent the areas occupied by child windows (including your view) from being drawn on.
### Notes on avoiding overdraw by preventing drawing after your *WM\_PAINT* method
If you have *any* child controls hosted on your form, you will want to use the *WS\_CLIPCHILDREN* style to avoid drawing over them (and subsequently being over drawn by them. Be aware, this will impact the speed of the BitBlt routine somewhat.
### Notes on efficient double-buffering
Right now, you're creating a new back-buffer image each time the view draws itself. For larger windows, this can represent a significant amount of memory being allocated and released, and *will* result in significant performance problems. I recommend keeping a dynamically-allocated bitmap in your view object, re-allocating it as needed to match the size of your view.
Note that while the window is being resized, this will result in just as many allocations as the present system, since each new size will require a new back buffer bitmap to be allocated to match it - you can ease the pain somewhat by rounding dimensions up to the next largest multiple of 4, 8, 16, etc., allowing you to avoid re-allocated on each tiny change in size.
Note that, if the size of the window hasn't changed since the last time you rendered into the back buffer, you don't need to re-render it when the window is invalidated - just Blt out the already-rendered image onto the screen.
Also, allocate a bitmap that matches the bit depth of the screen. The constructor for `Bitmap` you're currently using will default to 32bpp, ARGB-layout; if this doesn't match the screen, then it will have to be converted. Consider using the GDI method [`CreateCompatibleBitmap()`](https://msdn.microsoft.com/en-us/library/dd183488.aspx) to get a matching bitmap.
Finally... I assume your example code is just that, an illustrative snippet. But, if you are actually doing nothing beyond rendering an existing image onto the screen, then you don't really need to maintain a back buffer at all - just Blt directly from the image (and convert the format of the image ahead of time to match the screen).
|
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 (GUIDs) in a hiddenfield. On postback I simply read the GUIDs from the field. Everything works great but on postback, I get the following exception:
> Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I've prepared a test application. All you have to do is download the archive and run the project. On the web page select the 3 items, press Add all, then move the third element up one level and then hit "Button". The error will show up. Turning event validation off is by no means acceptable. Can anyone help me, I've spent two already days without finding a solution.
[TEST APPLICATION](http://cid-c9672af9b84b07ef.skydrive.live.com/self.aspx/TestApp/TestProject.zip)
|
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.NameValueCollection postCollection)
{
return true;
}
}
```
Using this instead of the regular listbox in my user control solved the problem, however are there any risks associated with my approach?
|
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 problems with this approach, even if you succeed to avoid the event validation issue. You have several alternatives:
1) The simplest is to do the swapping logic on server instead of using javascript. This way the view state will be preserved between postbacks and the added overhead of multiple round trips to the server might not be an issue.
2) If the multiple round trips to server is an issue, write a server control that handles it's own view state. This is of course a much engaging approach.
3) A middle ground approach could be to use two simple html lists (just write the html tags without using the asp.net controls) and maintain on the client side from javascript a list of id's in a hidden field. On post back just parse the hidden field and extract the id's ignoring the html lists.
I would go with 1 if there aren't SERIOUS arguments against it.
|
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 the thing.
It will also generate code, but I was mainly in "make pretty diagrams" mode, rather than a full round-trip back and forth attempt to use UML like architecture astronauts say it should be use.
|
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 that I need to now create a private variable for BarName , e.g. \_BarName, and change the current BarName variable used throughout my class to \_BarName?
```
Public Class foo
{
public foo() {}
private string _BarName = "";
public string BarName
{
get {return _BarName;}
set {_BarName = Value.ToString().ToUpper();}
}
}
```
I am trying to make sure I understand the implications of using auto-implemented properties, and what it will entail down the road when/if I need to change something. I am assuming that the refactoring, as shown above, is not a [breaking](http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx) change because the property is basically staying the same; it just took a little work inside the class to keep it that way and add the needed logic.
Another example, which may be more meaningful is that I need to call some method when a setter or getter is used; more then changing the value.
This seems a fair trade off the the lines and lines of code to setup properties.
|
> 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 other things), for the purpose of avoiding the sweeping changes you contemplate to the rest of your code.
> I am assuming that the refactoring, as
> shown above, is not a breaking change
> because the property is basically
> staying the same; it just took a
> little work to keep it that way and
> add the needed logic.
Correct.
|
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 that property are concerned, nothing has changed; any code referencing your property will continue to work.
|
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-parse format I can access from my PHP script ?
|
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 the exchange rate, but no one gets the spot because you can only sell at the bid or buy at the ask. You're usually looking at least a 1% spread between them, so the spot rate is 0.5% off for your customers.
But it doesn't stop there, your customers almost certainly are using a credit card and Visa/Mastercard/Amex all charge foreign exchange fees. These are non-trivial in my experience, at LEAST 2.5%. For example, Citibank Australia charges 3.3%. These vary from card to card so there's no way for you to predict the final price that your customers will be billed.
If you want to quote an "accurate" price to your customers based on an exchange rate, you need to factor in the above and provide a buffer so that you don't end up charging more than what you quoted.
FWIW, I've been adding 4% to what the F/X conversion would otherwise indicate.
|
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 while it's being accessed, so I don't know how I should proceed when the user wants to insert new data in the file (which would exceed the file's original size, when it was mapped.)
Should I remap the whole thing every time? That's bound to be slow. However, I'd want to keep the editor real-time with exclusive file access, since that simplifies the programming a lot, and won't let the file get screwed by other applications while being modified. I wouldn't want to spend an eternity working on the editor; It's just a simple dev-tool for the actual project I'm working on.
So I'd like to hear how you've handled similar cases, and what other archiving software and especially other games do to solve this?
To clarify:
* This is not a text file, I'm writing a specific binary *archive file format*. By which I mean a big file that contains many others, in directories. Custom archive files are very common in game usage for a number of reasons. With my format, I'm aiming to a similar (but somewhat simpler) structure as with [Valve Software's GCF format](http://www.wunderboy.org/docs/gcfformat.php) - I would have used the GCF format as it is, but unfortunately no editor exists for the format, although there are many great implementations for reading them, like [HLLib](http://nemesis.thewavelength.net/index.php?p=35).
* Accessing the file must be fast, as it is intended for storing game resources. So it's not a database. Database files would be contained inside it, along with GFX, SFX etc. files.
* "File mapping" as talked here is a specific technique on the Windows platform, which allows direct access to a large file through creating "views" to parts of it, see here: <http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx> - This technique allows minimal latency and memory usage and is a no-brainer for accessing any large files.
So this does *not* mean reading the whole 4GB file into memory, it's exactly the contrary.
|
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 MappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);
void* ViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);
...
// increase size of file
UnmapViewOfFile(ViewHandle);
CloseHandle(MappingHandle);
Size += 1024;
LARGE_INTEGER offset;
offset.QuadPart = Size;
LARGE_INTEGER newpos;
SetFilePointerEx(FileHandle, offset, &newpos, FILE_BEGIN);
SetEndOfFile(FileHandle);
MappingHandle = ::CreateFileMapping(FileHandle, NULL, PAGE_READWRITE, 0, Size, NULL);
ViewHandle = ::MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);
```
The above code has no error checking and does not handle 64bit sizes, but that's not hard to fix.
|
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 not sure that mmapping is the way to go. Mmapping a huge file will put a lot of pressure on your machine's VM system, and unless there are many editing operations all over the file its efficiency may lag behind a simple read/write scheme. Worse, as you say, you have problems when you want to extend the file.
Instead, maintain buffer windows to the file's data, which the user can modify. When the user decides to save the file, traverse sequentially the file and the edited buffers to create the new file image. If you have disk space it's easier to write a new file (especially if a buffer's size has changed), otherwise you need to be clever on how you read-ahead existing data, before you overwrite it with the new contents.
Alternatively, you can keep a journal of editing operations. When the user decides to save the file, perform a topological sort on the journal and play it on the existing file to create the new one.
For exclusive file access use the file locking of your operating system or implement application-level locking (if only your editor will touch these files). Depending on mmap for exclusive access constrains your implementation choices.
|
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) blog entry that showed me the offset, as another response noted.
```
public enum MachineType {
Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664
}
public static MachineType GetMachineType(string fileName)
{
const int PE_POINTER_OFFSET = 60;
const int MACHINE_OFFSET = 4;
byte[] data = new byte[4096];
using (Stream s = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
s.Read(data, 0, 4096);
}
// dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header
int PE_HEADER_ADDR = BitConverter.ToInt32(data, PE_POINTER_OFFSET);
int machineUint = BitConverter.ToUInt16(data, PE_HEADER_ADDR + MACHINE_OFFSET);
return (MachineType)machineUint;
}
```
|
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 either `PE32` or `PE32+`
|
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 imposes no limit on the length of names stored in metadata and subsequently processed by the CLI
If I've read this correctly and the context is correct then there's no actual limit to the length of an identifier in the CLR.
|
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 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 5;
}
}
```
The length of the variable name there is 511 characters. This code compiles, but if one character is added to the name, the compiler outputs `error CS0645: Identifier too long`.
|
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 is a list implemented like this:
public class MyList : List< SomeCustomType> { }
This is a legacy site so not so many modifications are allowed to it.
How should I refactor this in order to safely lock when iterating over it ?
any idea!
|
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 it and other compound operations. Just locking on each specific access isn't good enough.
|
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.python.org/3/library/stdtypes.html#str.format):
```
number = 1
print("{:02d}".format(number))
```
---
For Python 3.6+ the same behavior can be achieved with [f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings):
```
number = 1
print(f"{number:02d}")
```
|
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.)
For a practical example, if you had a multiple-choice quiz system, with tables "question" and "answer", where question.correct\_answer refers to answer.id, and answer.question refers to question.id, is it possible to add a question and its answers simultaneously?
(For the record, I'm aware that you can do the disabling and re-enabling in a transaction block, and that another solution is to not have a correct\_answer column but instead have answer.correct as a boolean and have a check constraint making sure there's exactly one correct answer per question. But I'm not curious about alternative solutions here.)
|
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, answer)
VALUES (100, 1, 'Long enough to reach the ground.');
COMMIT;
```
It has to be in a transaction block because if either INSERT statement failed the database would be in an invalid state (table constraints not met).
|
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 performance difference between using an `Int16` vs an `Integer`? Should I stop using `Int16` and just stick with `Integer` for all my counting/iteration needs?
|
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 Fundamentals"
Lesson 1: "Using Value Types"
> Best Practices: Optimizing performance
> with built-in types
>
> **The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counters and other frequently accessed integral variables.**
>
> For floating-point operations, Double is the most efficient type because those operations are optimized by hardware.
Also, Table 1-1 in the same section lists recommended uses for each type.
Relevant to this discussion:
* Int16 - Interoperation and other specialized uses
* Int32 - Whole numbers and counters
* Int64 - Large whole numbers
|
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* going to happen in code that tries to use `Int16`s as an index.
The less-obvious reason (and the reason that arrays take `Int32` as an index) is that the CIL specification says that all operation-stack values are **either** `Int32` or `Int64`. Every time you either load or store a value to any other integer type (`Byte`, `SByte`, `UInt16`, `Int16`, `UInt32`, or `UInt64`), there is an implicit conversion operation involved. Unsigned types have no penalty for loading, but for storing the value, this amounts to a truncation and a possible overflow check. For the signed types *every* load sign-extends, and every store sign-collapses (and has a possible overflow check).
The place that this is going to hurt you most is the loop itself, not the array accesses. For example take this innocent-looking loop:
```
for (short i = 0; i < 32000; i++) {
...
}
```
Looks good, right? Nope! You can basically ignore the initialization (`short i = 0`) since it only happens once, but the comparison (`i<32000`) and incrementing (`i++`) parts happen 32000 times. Here's some pesudo-code for what this thing looks like at the machine level:
```
Int16 i = 0;
LOOP:
Int32 temp0 = Convert_I16_To_I32(i); // !!!
if (temp0 >= 32000) goto END;
...
Int32 temp1 = Convert_I16_To_I32(i); // !!!
Int32 temp2 = temp1 + 1;
i = Convert_I32_To_I16(temp2); // !!!
goto LOOP;
END:
```
There are **3** conversions in there that are run **32000** times. And they could have been completely avoided by just using an `Int32` or `Int64`.
*Update: As I said in the comment, I have now, in fact written a blog post on this topic, [.NET Integral Data Types And You](http://alexjlyman.blogspot.com/2009/03/net-integral-data-types-and-you.html)*
|
.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 this context.
If a particular toolkit has something like this out of the box, that would be awesome, but I'm open to doing this by hand if need be.
|
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 to mention it on the google code pages...
|
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 too high-level and they are looking for someone with experience doing multi-threading in C++.
So what is a basic example of "low-level" multi-threading in C++ ?
|
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 links to more classical threading problems like producers/consumers and dining philosophers.
|
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).
To get rid of the warning, you need to be specific about what type of objects you're storing in the collection. So, instead of
```
List myList = new ArrayList();
```
use
```
List<String> myList = new ArrayList<String>();
```
---
In Java 7 you can shorten generic instantiation by using [Type Inference](http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html).
```
List<String> myList = new ArrayList<>();
```
|
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 the warning. This is not always possible, particularly if you are integrating with legacy code that cannot be changed. In this situation, you may decide to suppress the warning in places where you know that the code is correct:
```
@SuppressWarnings("unchecked")
public void myMethod()
{
//...
}
```
|
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 CreateStaticSplitter\n");
return FALSE;
}
else
if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CAppView_Left), CSize(300, 200), pContext))
{
TRACE0("Failed to create left pane\n");
return FALSE;
}
else
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CAppView_Right_1), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
```
...
What I would like to do is create a second view inside the right frame, however when I try to add this:
```
if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CAppView_Right_2), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
```
VS compiles but fails to run the application, raising an exception telling me I have already defined the view.
Can someone suggest how I do this? Also, how to change between the views from either a view or the document class?
|
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), CSize(375, 200), pContext))
{
TRACE0("Failed to create first right pane\n");
return FALSE;
}
```
This results in three columns each with a seperate view. You could also create an additional splitter window to split one of the existing views, e.g. something like
```
m_wndSplitter2.CreateStatic(m_View2, 2, 1)
```
where m\_view2 was your second view
|
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 this by handling the partial methods in the property setters? All advice is much appreciated.
|
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 brittle and would become confusing/slow after if you have many different properties things that can change for each entity.
3) Implement partial methods to validate property changes
According to [this](http://www.simple-talk.com/dotnet/.net-framework/entity-framework-the-cribsheet/) post and [this](http://msdn.microsoft.com/en-us/library/bb629301.aspx) walkthrough there are partial methods available for validation. This seems like your best option as it is not very intrusive and you can selectively implement the validation you want.
I hope that helps. Good luck.
|
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, opened ports, ran as admin; nothing is working. :(
**Here is my code that I'm using to accept an incoming connection:**
```
int port = 3326;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
listener.Start();
Console.WriteLine("Server established\nListening on Port: {0}\n", port);
while (true)
{
socket = listener.AcceptSocket();
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, outime);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.DontFragment = true;
NewConnection pxy = new NewConnection(socket);
Thread client = new Thread(new ThreadStart(pxy.Start));
client.IsBackground = true;
client.Start();
}
}
```
|
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 impossible to connect directly to it.
If there is no NAT router, something may still be blocking the connection upstream.
|
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 in JS, do I need to use mutexes in JS or not?
Specifically, I am wondering about the effects of using functions called by `setTimeout()` and `XmlHttpRequest`'s `onreadystatechange` on globally accessible variables.
|
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 an event must be finished before the next event will be processed.
That being said, you may need a mutex if your code does something where it expects a value not to change between when the asynchronous event was fired and when the callback was called.
For example if you have a data structure where you click one button and it sends an XmlHttpRequest which calls a callback the changes the data structure in a destructive way, and you have another button that changes the same data structure directly, between when the event was fired and when the call back was executed the user could have clicked and updated the data structure before the callback which could then lose the value.
While you could create a race condition like that it's very easy to prevent that in your code since each function will be atomic. It would be a lot of work and take some odd coding patterns to create the race condition in fact.
|
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-javascript-with-web-workers/)
[Mozilla on webworkers](https://developer.mozilla.org/En/Using_web_workers)
This clearly shows that javascript via web-workers has multithreading capabilities. As concerning to the question are mutexes needed in javascript? I am unsure of this. But this stackoverflow post seems relevant:
[Mutual Exclusion for N Asynchronous Threads](https://stackoverflow.com/questions/3693550/mutual-exclusion-for-n-asynchronous-threads)
|
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>
<head></head>
<body>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$count = 0;
$activities = $xmldoc->firstChild->firstChild;
//prints the list of activities, with checkboxes on the left for each item
//the $count variable is the id to each entry
if($activities!=null){
echo '<form name=\'erase\' action=\'delete.php\' method=\'post\'>' . "\n";
while($activities!=null){
$count++;
echo " <input type=\"checkbox\" name=\"activity[]\" value=\"$count\"/>";
echo ' '.$activities->textContent.'<br/>'."\n";
$activities = $activities->nextSibling;
}
echo ' <input type=\'submit\' value=\'erase selected\'>';
echo '</form>';
}
?>
//section used for inserting new entries. this feature is working as expected.
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text name='activity'/>
<input type='submit' value='send'/>
<br/>
</form>
</body>
</html>
```
the delete.php, which is not working as expected:
```
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$atvID = $_POST['activity'];
foreach($atvID as $id){
$delnode = $xmldoc->getElementsByTagName('activity');
$xmldoc->firstChild->removeChild($delnode->item($id));
}
$xmldoc->save('sample.xml');
?>
```
I've tested the deletion routine without the loop, using an hard-coded arbitrary id, and it worked. I also tested the $atvID array, and it printed the selected id numbers correctly. When it is inside the loop, here's the error it outputs:
> Catchable fatal error: Argument 1
> passed to DOMNode::removeChild() must
> be an instance of DOMNode, null given
> in
> /directorypath/delete.php
> on line 9
What is wrong with my code?
|
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 activity a unique identifier you can search for, say an attribute called 'id' (this likely wouldn't be a real ID. The DOM's getElementByID() only works for XML that has a DTD, like an HTML page. I'm guessing you don't want to go there.)
You might update you're XML to look like this.
```
<list>
<activity name="swimming">swimming</activity>
<activity name="running">running</activity>
<activity name="soccer">soccer</activity>
</list>
```
You'd use these name attributes instead of $count as the value inside your checkboxes.
You can then use xPath to find items to remove inside your foreach.
```
$xpath = new DOMXPath($xmldoc);
$xmldoc->firstChild->removeChild($xpath->query("/list/activity[@name='$id']")->item(0));
```
Hope this helps get you started.
|
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. for async APIs)
* LINQ and similar (List.Find etc)
* Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)
|
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 extrapolate something more useful out of this:
```
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>
{
"Nicole Hare",
"Michael Hare",
"Joe Hare",
"Sammy Hare",
"George Washington",
};
// Here I am passing "inMyFamily" to the "Where" extension method
// on my List<String>. The C# compiler automatically creates
// a delegate instance for me.
IEnumerable<String> myFamily = names.Where(inMyFamily);
foreach (String name in myFamily)
Console.WriteLine(name);
}
static Boolean inMyFamily(String name)
{
return name.EndsWith("Hare");
}
}
```
|
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 events that occur as the document is loaded. You can listen for the window onLoad event, and react to that, but onLoad is not fired until all resources have been downloaded, so your event handler won't be executed until that last huge image has been fetched. In some cases that's exactly what you want, in others you might find that listening for when the DOM is ready is more appropriate - this event is similar to onLoad but fires without waiting for images, etc. to download.
|
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 answer). I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use. jQuery's `$(document).ready()`, is a good example.
|
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 day of the month, just the month and year. Using the Date Picker control feels like overkill and a kludge. I know I could just use a pair of select boxes, but that feels cluttered, and then I also need a confirmation button.
I'm envisioning a grid of either two rows of six columns, or three rows of four columns, for month selection, and current and future years across the top. (Maybe the ability to list a few years? I can't see anyone ever needing to go more than a year or two ahead, so if I could list the current and next two years, that would be swell.)
It's really just a dumbed down version of the DatePicker. Does something like this exist?
|
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();
```
* [GitHub](https://github.com/KidSysco/jquery-ui-month-picker)
* [Fiddle with Examples and tests](http://jsfiddle.net/kidsysco/JeZap/)
|
[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://jsfiddle.net/yLjDH/)
--
Here's a hack (updated with entire .html file):
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
</head>
<body>
<label for="startDate">Date :</label>
<input name="startDate" id="startDate" class="date-picker" />
</body>
</html>
```
|
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
ldloc.0 //load 1st variable
mul // 1 * 5
stloc.1 // store in 2nd local variable
```
The second example compiles to this:
```
.maxstack 1
.locals init ( [0] int32 )
ldc.i4.5 //load 5
stloc.0 //store in local variable
```
|
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 namespaces are appearing fine in Intelisense.
Any suggestions
**EDIT:** More info to help with some comments.
my implementation looks like this
```
//C# code compiled as DLL
namespace x.y {
public static class z {
public static string q (this string s){
return s + " " + s;
}
}
}
```
and my usage like this
```
Imports x.y
'...'
Dim r as string = "greg"
Dim s as string = r.q() ' does not show in intelisense
' and throws error : Compiler Error Message: BC30203: Identifier expected.
```
|
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 = text.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
}
}
```
Then I created a VB console app targeting .NET 3.5, and added a reference to my C# project. I renamed Module1.vb to Test.vb, and here's the code:
```
Imports ExtensionLibrary
Module Test
Sub Main()
Console.WriteLine("Hello".CustomExtension())
End Sub
End Module
```
This compiles and runs. (I would have called the method Reverse() but I wasn't sure whether VB might magically have reverse abilities already somewhere - I'm not a VB expert by a long chalk.)
Initially, I wasn't offered ExtensionLibrary as an import from Intellisense. Even after building, the "Imports ExtensionLibrary" is greyed out, and a lightbulb offers the opportunity to remove the supposedly redundant import. (Doing so breaks the project.) It's possible that this is ReSharper rather than Visual Studio, mind you.
So to cut a long story short, it can be done, and it should work just fine. I don't suppose the problem is that you're either using an old version of VB or your project isn't targeting .NET 3.5?
As noted in comments: there's one additional quirk, which is that [extension methods won't be found when the compile-time type of the target is `Object`](https://stackoverflow.com/questions/3227888).
|
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 || ' UNUSABLE';
EXECUTE IMMEDIATE v_sql;
END LOOP;
CLOSE usr_idxs;
END;
```
The rebuild would be similiar.
|
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...
```
select 'alter index ' || u.index_name ||
' rebuild online;' from user_indexes u;
```
Note this assumes that the import is going to happen in the same (sqlplus) session.
If you are calling "imp" it will run in a separate session so you would need to use "ALTER SYSTEM" instead of "ALTER SESSION" (and remember to put the parameter back the way you found it.
|
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.
Thanks for your advice!
|
**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 will think it's too much work to try and get around your trial period if there is even a simple mechanism. For example people can always use filemon/regmon to see which files and registry entries change upon installing your software.
That being said, a simple mechanism is best, because it wastes less of your time.
**Here are some ideas:**
* You can do a tick count somewhere in registry for every unique day that is run. If tick count > 30 then show them an expired message.
* You can store the install date, but take head to check if they have more days available than your trial is supposed to be, then do tell them they are expired. This will protect against people changing their date before installing to a future day.
* I would recommend to make your uninstall, remove your "days running" count. This is because people may re-evaluate your product months later and eventually buy. But if they can't evaluate it, they won't buy. No serious user would have time to uninstall/re-install just to gain extra use of your product.
**Extending trials:**
For us, when a customer requests a trial extension, we send them an automated email that contains a program "TrialExtend.exe" and a trial extend code. This program contacts our server with the trial extend code to validate it. If the code is validated, their trial period is reset.
|
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 performance with this?
I'm using java 1.6, and query has multiple joins.
|
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 time. That time will be a lot more valuable when employed learning how to properly tune/use your database rather than reinventing sorting algorithms already present in the database engine.
Grab your database's profiler and check the query's execution plan.
|
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 of those
> formal arguments are restored. This
> protocol is fully recursive. If within
> the body of a statement, something is
> done that causes the formal parameters
> to be bound again, to new values, the
> lambda-binding scheme guarantees that
> this will all happen in an orderly
> manner.
Now, there is an excellent [python example in a discussion here](http://markmail.org/message/fypalne4rp5curta "Theoretical question about Lambda"):
"...there is only one binding for `x`: doing `x = 7` just changes the value in the pre-existing binding. That's why
```
def foo(x):
a = lambda: x
x = 7
b = lambda: x
return a,b
```
returns two functions that both return 7; if there was a new binding after the `x = 7`, the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested\_scopes]...."
|
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 this
> session. A negative time indicates the
> session should never timeout.
I mention this in case you see timeouts that are not 30 minutes, but you didn't specify another value (e.g. another developer on the project used this API).
Another item to note is this timeout may not trigger on the exact second the session is eligible to expire. The Java EE server may have a polling thread that checks for expired sessions every minute. I don't have a reference for this, but have seen this behavior in the WebSphere 5.1 era.
|
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 run WEBRick or Mongrel within the JVM?
|
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.
Is it normally possible to embed all of your rails templates/models into a jar inside of a war file for deployment on Tomcat? If so, then you should be able to get embedded Jetty to pull it from your single jar as well.
|
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 guess you can run a jetty+war thing fairly easily with this technique.
The article is here:
<http://blog.kesor.net/2007/08/14/jruby-in-a-jar/>
|
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 to support concurrent reads and writes from multiple machines (reads will be 100X more common though). Basically the purpose is to do a quick initial lookup of user metadata for a web-service.
Can anyone recommend anything?
|
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 be encoded as UTF-8.
Broken Image on webhost server:
<http://www.ibeni.net/flashcards/imagetest.php>
Copy of correct image from my local machine:
<http://www.ibeni.net/flashcards/imagetest.php.gif>
Copy of phpinfo() from my local machine:
<http://www.ibeni.net/flashcards/phpinfo.php.html>
Copy of phpinfo() from my webhost server:
<http://example5.nfshost.com/phpinfo>
Code:
```
mb_language('uni');
mb_internal_encoding('UTF-8');
header('Content-type: image/gif');
$text = '日本語';
$font = './Cyberbit.ttf';
// Create the image
$im = imagecreatetruecolor(160, 160);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Create some colors
imagefilledrectangle($im, 0, 0, 159, 159, $white);
// Add the text
imagettftext($im, 12, 0, 20, 20, $black, $font, $text);
imagegif($im);
imagedestroy($im);
```
|
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 hexidecimal equivalents
$out = "";
for($i = 0; $i < strlen($text); $i++) {
$letter = $text[$i];
$num = ord($letter);
if($num>127) {
$out .= "&#$num;";
} else {
$out .= $letter;
}
}
```
Converting the string to HTML entities works except that the function imagettftext() doesn't accept named entities. For example,
```
日本語
```
is OK, but
```
ç
```
is not. Converting back to ISO-8859-1, converts the named entities back to characters, but there is a second problem. imagettftext() doesn't support characters with a value greater than >127. The final for-loop encodes these characters in hexadecimal. This solution is working for me with the text that I am using (includes Japanese, Chinese and accented latin characters for Portuguese), but I'm not 100% sure it will work in all cases.
All of these gymnastics are needed because imagettftext() doesn't really accept UTF-8 strings on my server.
|
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 problem.
```
$item_text = $_GET['text'];
// Detect if the string was passed in as unicode
$text_encoding = mb_detect_encoding($item_text, 'UTF-8, ISO-8859-1');
// Make sure it's in unicode
if ($text_encoding !== 'UTF-8') {
$item_text = mb_convert_encoding($item_text, 'UTF-8', $text_encoding);
}
// HTML numerically-escape everything (&#[dec];)
$item_text = mb_encode_numericentity($item_text,
[0x0, 0xffff, 0, 0xffff], 'UTF-8');
```
This solves any problem with `imagettftext` not being able to handle characters above #127 by simply changing ALL the characters (including multibyte Unicode characters) into their HTML numeric character entity—"A" for "A", "B" for "B", etc.—which the [manual page](http://www.php.net/imagettftext) claims support for.
|
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 has revealed a circular reference being the reason for a memory leak that I am now faced with.
*Note: I have always been under the impression that the JVM was capable of resolving circular references and freeing such "islands of garbage" from memory. However, I am posing this question just to see if anyone has found any exceptions.*
|
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 Management](https://rads.stackoverflow.com/amzn/click/com/0471941484) . Java has had a good garbage collector since 1.2 and an exceptionally good one in 1.5 and Java 6.
The hard part for improving GC is reducing pauses and overhead, not basic things like circular reference.
|
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 are different about 1/2 of the cases.
Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug.
For example:
```
LEFTPOS and SPACING are defined floating point values.
float def_x;
int xpos;
def_x = LEFTPOS + (xpos * (SPACING / 2));
```
The issue is in regards to the X360 compiler.
|
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 consider that a release build will have optimisations which keep intermediate results in FPU registers, whereas a debug build will probably naively copy intermediate results back and forward between memory and registers - and there you have your difference in behaviour.
I don't know whether this happens on X360 too or not.
|
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 8000+ instances of a particular simple class.
I clicked the "Garbage Collect" button on JProfiler, and most instances of other classes of ours went away, but not these particular ones. I ran the test again, still in the same instance, and it created 4000+ more instances of the class, but when I clicked "Garbage Collect", those went away leaving the 8000+ original ones.
These instances do get stuck into various Collections at various stages. I assume that the fact that they're not garbage collected must mean that something is holding onto a reference to one of the collections so that's holding onto a reference to the objects.
Any suggestions how I can figure out what is holding onto the reference? I'm looking for suggestions of what to look for in the code, as well as ways to find this out in JProfiler if there are.
|
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/docs/technotes/tools/index.html)
2. Start the application.
3. Open task manager and find the process id (PID) for java.exe (or whatever executable you are using). If the PID's aren't shown by default, use View > Select Columns... to add them.
4. Dump the heap using *jmap*.
5. Start the *jhat* server on the file you generated and open your browser to *<http://localhost:7000>* (the default port is 7000). Now you can browse the type you're interested in and information like the number of instances, what has references to them, etcetera.
Here is an example:
```
C:\dump>jmap -dump:format=b,file=heap.bin 3552
C:\dump>jhat heap.bin
Reading from heap.bin...
Dump file created Tue Sep 30 19:46:23 BST 2008
Snapshot read, resolving...
Resolving 35484 objects...
Chasing references, expect 7 dots.......
Eliminating duplicate references.......
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.
```
To interpret this, it is useful to understand some of the [array type nomenclature](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()) Java uses - like knowing that **class [Ljava.lang.Object;** really means an object of type **Object[]**.
|
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 Eclipse MAT works.
|
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);
}
```
loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.
My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.
A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.
Thanks for your help !
|
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 acquire() {
boolean ret = token;
token = false;
return ret;
}
private synchronized void release() {
token = true;
}
public final void run() {
if (acquire()) {
try {
doTask();
} finally {
release();
}
}
}
protected abstract void doTask();
}
```
Test code that will throw an exception if the task runs concurrently:
```
public class Test {
public static void main(String[] args) {
final NonconcurrentTask shared = new NonconcurrentTask() {
private boolean working = false;
protected void doTask() {
System.out.println("Working: "
+ Thread.currentThread().getName());
if (working) {
throw new IllegalStateException();
}
working = true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (!working) {
throw new IllegalStateException();
}
working = false;
}
};
Runnable taskWrapper = new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
shared.run();
}
}
};
for (int i = 0; i < 100; i++) {
new Thread(taskWrapper).start();
}
}
}
```
|
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 set, return. If its not set, run the rest of the method, and after its complete, unset it. Just make sure to put the code in a try/finally and the flag iunsetting in the finally so it always gets unset in case of error. Very simplified but may be all you need.
Edit: This actually probably works better than synchronizing the method. Because do you really need a new translation *immediately* after the one before it finishes? And you may not want to lock up a thread for too long if it has to wait a while.
|
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> ...
```
or one can write this:
```
template <typename T> ...
```
Is there a good reason to prefer one over the other?
---
I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other."
* They are equivalent (except as noted below).
* Some people have reasons to always use `typename`.
* Some people have reasons to always use `class`.
* Some people have reasons to use both.
* Some people don't care which one they use.
Note, however, that before C++17 in the case of *template template* parameters, use of `class` instead of `typename` was required. See [user1428839's answer](https://stackoverflow.com/a/11311432/3964522) below. (But this particular case is not a matter of preference, it was a requirement of the language.)
|
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 worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword `typename` to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, `class` kept its overloaded meaning.
|
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('MyDiv').onmousemove = function() {
UnTip();
};
}, thread;
return function() {
clearTimeout(thread);
thread = setTimeout(onmousestop, 1500);
};
})();
```
But I want the function to only apply to a specific div and if I change the first line to "document.getElementById('MyDiv').onmousemove = (function() {" I get a javascript error document.getElementById('MyDiv') is null What am I missing....??
[/edit]
I want to display a balloon style message when the users mouse stops on an element from more than say 1.5 seconds. And then if they move the mouse I would like to hide the balloon. I am trying to use some JavaScript code I found posted out in the wild. Here is the code I am using to detect when the mouse has stopped:
```
document.onmousemove = (function() {
var onmousestop = function() {
//code to show the ballon
};
}, thread;
return function() {
clearTimeout(thread);
thread = setTimeout(onmousestop, 1500);
};
})();
```
So I have two questions. One, does anyone have a recommended lightweight javascript balloon that will display at the cursor location. And two, the detect mouse stopped code works ok but I am stumped on how to detect that the mouse has started moving again and hide the balloon. Thanks...
|
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').onmousemove = (function() {
var onmousestop = function() {
Tip('Click to search here');
}, thread;
return function() {
UnTip();
clearTimeout(thread);
thread = setTimeout(onmousestop, 1500);
};
})();
```
In my case, I used a bit of jQuery for selecting the elements for my player controller:
```
$('div.video')[0].onmousemove = (function() {
var onmousestop = function() {
$('div.controls').fadeOut('fast');
}, thread;
return function() {
$('div.controls').fadeIn('fast');
clearTimeout(thread);
thread = setTimeout(onmousestop, 1500);
};
})();
```
|
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 only fires the "out" event when the user leaves the element, which doesn't sound like exactly what you're looking for, but the code is pretty simple.
Also watch out for binding things to mousemove when you don't need to be collecting the events, mousemove fires a lot of events quickly and can have serious effects on your site performance. hoverIntent only binds mousemove when the cursor enters the active element, and unbinds it afterwards.
If you do try hoverIntent I have had some trouble with the minified version not firing "out" events, so I would recommend using the full, unminified source.
|
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 makes obvious sense.
On one hand, the compiler can make some optimizations and it makes the programmer's intent clearer. On the other hand, it adds verbosity and the optimizations may be trivial.
Is it something I should make an effort to remember?
|
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 that object reference refers to can still change and that affects the immutability.)
* Final static fields - Although I use enums now for many of the cases where I used to use static final fields.
Consider but use judiciously:
* Final classes - Framework/API design is the only case where I consider it.
* Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation.
Ignore unless feeling anal:
* Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.
* Edit: note that one use case where final local variables are actually very useful as mentioned by [@adam-gent](https://stackoverflow.com/a/18856192/2750743) is when value gets assigned to the var in the `if`/`else` branches.
|
> 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.CharField(max_length=100)
employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'})
class TimeWorked(models.Model):
project = models.ForeignKey(Project, limit_choices_to={'user': user})
hours = models.PositiveIntegerField()
```
Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.
Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(
**UPDATE**: The solution is here: <http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/> sending `request.user` to a model.
|
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)
class ThreadLocals(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
_thread_locals.user = getattr(request, 'user', None)
```
Check the documentation on how to use middleware classes. Then anywhere in code you can call
```
user = threadlocals.get_current_user
```
|
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 and can limit the choices.
Then you just need a custom ModelForm to pass in the request.user to, see the example here:
<http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/>
```
from datetime import datetime, timedelta
from django import forms
from mysite.models import Project, TimeWorked
class TimeWorkedForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProjectForm, self).__init__(*args, **kwargs)
self.fields['project'].queryset = Project.objects.filter(user=user)
class Meta:
model = TimeWorked
```
then in your view:
```
def time_worked(request):
form = TimeWorkedForm(request.user, request.POST or None)
if form.is_valid():
obj = form.save()
# redirect somewhere
return render_to_response('time_worked.html', {'form': form})
```
|
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 could use some help fully grasping the concept.
To state it simply, why does query A return a result but B doesn't?
```
A: select 'true' where 3 in (1, 2, 3, null)
B: select 'true' where 3 not in (1, 2, null)
```
This was on SQL Server 2005. I also found that calling `set ansi_nulls off` causes B to return a result.
|
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 get any rows.
When `ansi_nulls` is off, `3 <> null` is true, so the predicate evaluates to true, and you get a row.
|
## `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.setLocation(x, y);
}
```
|
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 | Jack Black | Funnyman |
|--------+------------+------------|
```
There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.
Is there a way to do this without using a subquery?
|
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 occupation;
```
In this example it gives the three employees with the lowest emp\_id values per occupation. You can change the attribute used in the inequality comparison, to make it give the top employees by name, or whatever.
|
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 comunication via DirectX 11 (?) but this will not be made available on XP. There is obviously a performance hit here, I would like to understand it before making any inroads into developing applications to WPF.
Some information on this topic can be found here:
<http://blogs.msdn.com/tims/archive/2007/01/05/comparing-wpf-on-windows-vista-v-windows-xp.aspx>
See comment from the above link (quote):
---
To SpongeJim's question, this is done by the MIL (media integration layer), which is the underlying core of WPF that handles composition. On a Vista/Vista remote desktop connection, the MIL primitives are remoted and then reconstituted. On other combinations (e.g. 2003/XP), what gets remoted is bitmaps, which is obviously far more bandwidth-intensive. More depth on this topic can be found on Greg Schechter's blog, and in this entry in particular: <http://blogs.msdn.com/greg_schechter/archive/2006/06/09/623566.aspx>
---
Does anyone have any experience or more up to date information on this issue?
|
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 (wpfgfx.dll)
> and certain changes could not be made
> to Vista’s existing graphics DLL
> (milcore.dll) that is also used by
> DWM.
As other commenters have noted, the performance will greatly depend on the design of your application’s UI. The potential upshot is that you only have to test in one scenario; remoting performance should now be the same regardless of the client or server.
|
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.
I just tested remoting into a Vista VM from my XP desktop and our app looked great (if running a bit slow, but it is a VM...) I switched to low quality 8-bit color and the performance problems almost completely went away. The gradiation, etc, was lost on our window background, etc, but it was definitely still usable.
I don't think you should have any functional problems, and only minor performance issues.
|
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 one statement is executed regardless of the access modifier, and another statement is executed if it's called from an external assembly or class.
I'm sure I could code something by using reflection and checking up the current call stack to see if the caller is in the same assembly, but I'm looking to see if there's a more elegant approach than that.
|
```
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 **could** get the caller information by [examining the calling stack](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) but that is extremely slow (compared to the above) and I wouldn't recommend it.
|
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 to insist that the artist makes the "action bit" of the texture white, and then assigning a color to the vertices that i render. Something like this.
```
glTexCoordPointer( 2, GL_FLOAT, 0, sprite->GetTexBuffer() );
glVertexPointer( 3, GL_FLOAT, 0, sprite->GetVertexBuffer() );
glColorPointer( 4, GL_FLOAT, 0, sprite->GetColorBuffer() );
glDrawArrays( GL_TRIANGLES, 0, 6 ); // Draw 2 triangles
```
Where even tho it has a texture, having the color means it adds to the texture's color, so where it's an alpha, it remains alpha, and where it is white ( as i had to make it ), it becomes the color of the color pointer at the point.
|
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 least 3 options are selected out of 150 controls in that page irrespective of the tabs which they choose.
Please suggest the simplest and easiest way which this could be done in JavaScript on my aspx page.
|
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':
if (element.value.length > 0)
{
selectedCount++;
}
break;
case 'select-one':
if (element.selectedIndex > 0)
{
selectedCount++;
}
break;
//etc - add cases for checkbox, radio, etc.
}
}
```
|
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, however, the object's status does not change.
* We do not have second-level or query caching enabled.
* The retrieval of the collection from the DB is via Hibernate's Session.createQuery.
* Also, we have one SessionFactory wired, and using one Session throughout the application.
The only time the object displays the correct status result is when the server is restarted--which we'd prefer not to have to do on a regular basis.
|
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 database will not be refreshed. If you close it and get a new Session, it will read the full object from the database on the next query.
|
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 time.
|
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)
{
char* p = (const char*) (_bstr_t) var;
```
|
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:
```
USES_CONVERSION;
char* p = strdup(OLE2A(var.bstrVal));
// ...
free(p);
```
remember - the string returned from OLE2A (and its sister macros) return a string that is allocated on the stack - return from the enclosing scope and you have garbage string unless you copy it (and free it eventually, obviously)
|
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:
```
TcpChannel tcpChannel = new TcpChannel(999);
MyRemoteObject remObj = new MyRemoteObject (this);
RemotingServices.Marshal(remObj, "MyUri");
ChannelServices.RegisterChannel(tcpChannel);
```
It seems to work the first time, but unless the server app is restarted the error occurs.
I would guess something isn't being cleaned up properly but I'm not sure what as the customError is still on.
Any ideas where I start. Thanks.
[EDIT] - Thanks to Gulzar, I modified my code above to the following and now the errors are shown:
```
RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
TcpChannel tcpChannel = new TcpChannel(999);
MyRemoteObject remObj = new MyRemoteObject (this);
RemotingServices.Marshal(remObj, "MyUri");
ChannelServices.RegisterChannel(tcpChannel);
```
|
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>
```
For .Net 2.0, you can use [RemotingConfiguration.CustomErrorsMode](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.remotingconfiguration.customerrorsmode.aspx) property
|
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 currently executing code block, and the "Find All References" only helps if I add references to objects at compile time. Unless there is more to the watch window than I am aware of.
|
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 system in the end, so my plan is to create a hashmap to "lay over" the template, as something like this
```
$hash = array(
'HEADER' => 'This is a header',
'NAME' => 'David',
'CONTENT' => array('PERSONS' => array(array('NAME' => 'Heino'), array('NAME' => 'Sebastian')),
'FOOTER' => 'This is the footer'
);
```
It's worth noticing that the "sections" (the tags that start with #), can be repeated more than once, and i think this is what trips me up ...
Also, any section can contain any number of other sections, and regular tags...
So.. how'd you do it?
|
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 behaviour of the template supposed to be? If an array is provided for a non-section element, what will it do? If a section element is provided a single value, will it be treated the same as an array with only a single element (I assume so)?
Anyhow, with regards to the parser for the template (regardless of what you end up doing with the mapping of data)... What I would do is create a class for each type of token, including a generic one for non-token content. These would inherit from a common token base class with overridable Parse, Render and Map methods.
Chart out your state diagram and figure out what your entry and exit points are for each state, then encode that into the call structure between the tokens. In the end you want to yield an enumerable collection of tokens that describes your template.
Once you have that in an abstract form, you can iteate over the collection calling Map on the tokens to assign the data from the hashmap to the tokens, and then call Render to render the template into it's final form.
Hope that helps.
|
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 setting up DMA transfer between the host PC and the PCI board.
|
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
{ ptr = Marshal.AllocHGlobal(size * array.Length);
for (int i= 0; i < array.Length; ++i)
{ IntPtr tmpPtr = new IntPtr(ptr.ToInt64() + (i * size));
Marshal.StructureToPtr(array, tmpPtr, false);
}
retval = ThirdPartyFunction(ref ptr);
}
finally
{ if (ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr);
}
return retval;
}
```
|
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 last activity.
My issue arises that when a user brings his machine back up from a sleep state (which fires the SystemEvents.PowerModeChanged event), the application attempts to clock the employee back in but the network connection isn't fully initialized at that time and the web-service call times out.
An obvious solution, albeit it a hack, would be to put a delay on the clock in but this wouldn't necessarily fix the problem across the board. What I am looking to do is a sort of "relentless" clock in where it will wait until it can see the server until it actually attempts to clock in.
What is the best method to determine if a connection to a web service can be made?
|
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 slower than I expected. I always assumed that DataSets used some sort of HashTable style implementation which would make lookups O(1) (or at least thats what I think HashTables are). The speed of my lookups seemed to be significantly slower than this.
I was wondering if anyone who knows anything about the implementation of .NET's DataSet class would care to share what they know.
If I do something like this :
```
DataTable dt = new DataTable();
if(dt.Columns.Contains("SomeColumn"))
{
object o = dt.Rows[0]["SomeColumn"];
}
```
How fast would the lookup time be for the `Contains(...)` method, and for retrieving the value to store in `Object o`? I would have thought it be very fast like a HashTable (assuming what I understand about HashTables is correct) but it doesn't seem like it...
I wrote that code from memory so some things may not be "syntactically correct".
|
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 in an internal member. O(1)
3. Get the DataColumn's value at the index using DataColumn[index]. DataColumn stores its data in a System.Data.Common.DataStorage (internal, abstract) member:
return dataColumnInstance.\_storage.Get(recordIndex);
A sample concrete implementation is System.Data.Common.StringStorage (internal, sealed). StringStorage (and the other concrete DataStorages I checked) store their values in an array. Get(recordIndex) simply grabs the object in the value array at the recordIndex. O(1)
So overall you're O(1) but that doesn't mean the hashing and function calling during the operation is without cost. It just means it doesn't cost more as the number of DataRows or DataColumns increases.
Interesting that DataStorage uses an array for values. Can't imagine that's easy to rebuild when you add or remove rows.
|
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(SomeTable_SomeColumn))
{
object o = dt.Rows[0][SomeTable_SomeColumn];
}
```
|
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 expression.
I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).
The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.
Tokenizing is just one of the things that I want to do as part of my application.
Apart from perl or python can any language (functional also) do this?
I did read about PLY and ANTLR here ([Parsing, where can I learn about it](https://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085)).
But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?
Thank you.
|
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 and corresponding URLs:
```
#!/usr/bin/perl
use strict;
use warnings;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new;
$mech->get("http://stackoverflow.com/");
$mech->success or die "Oh no! Couldn't fetch stackoverflow.com";
foreach my $link ($mech->links) {
print "* [",$link->text, "] points to ", $link->url, "\n";
}
```
In the main loop, each `$link` is a [WWW::Mechanize::Link](http://search.cpan.org/perldoc?WWW::Mechanize::Link) object, so you're not just constrained to getting the text and URL.
All the best,
Paul
|
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/search?query=parse+recdescent&mode=all)
I've used these modules to process quite large and complex web-pages.
|
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. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.
Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!
|
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 script to stop controlled application gracefully before killing it.
Here is the simplified code:
**Controlled application:**
run it with the folowing VM parameters:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
```
//ThreadMonitorMBean.java
public interface ThreadMonitorMBean
{
String getName();
void start();
void stop();
boolean isRunning();
}
// ThreadMonitor.java
public class ThreadMonitor implements ThreadMonitorMBean
{
private Thread m_thrd = null;
public ThreadMonitor(Thread thrd)
{
m_thrd = thrd;
}
@Override
public String getName()
{
return "JMX Controlled App";
}
@Override
public void start()
{
// TODO: start application here
System.out.println("remote start called");
}
@Override
public void stop()
{
// TODO: stop application here
System.out.println("remote stop called");
m_thrd.interrupt();
}
public boolean isRunning()
{
return Thread.currentThread().isAlive();
}
public static void main(String[] args)
{
try
{
System.out.println("JMX started");
ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread());
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=ThreadMonitor");
server.registerMBean(monitor, name);
while(!Thread.interrupted())
{
// loop until interrupted
System.out.println(".");
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
// TODO: some final clean up could be here also
System.out.println("JMX stopped");
}
}
}
```
**Controlling application:**
run it with the *stop* or *start* as the command line argument
```
public class ThreadMonitorConsole
{
public static void main(String[] args)
{
try
{
// connecting to JMX
System.out.println("Connect to JMX service.");
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
// Construct proxy for the the MBean object
ObjectName mbeanName = new ObjectName("com.example:type=ThreadMonitor");
ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true);
System.out.println("Connected to: "+mbeanProxy.getName()+", the app is "+(mbeanProxy.isRunning() ? "" : "not ")+"running");
// parse command line arguments
if(args[0].equalsIgnoreCase("start"))
{
System.out.println("Invoke \"start\" method");
mbeanProxy.start();
}
else if(args[0].equalsIgnoreCase("stop"))
{
System.out.println("Invoke \"stop\" method");
mbeanProxy.stop();
}
// clean up and exit
jmxc.close();
System.out.println("Done.");
}
catch(Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
```
That's it. :-)
|
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.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
```
Output:
```
<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
```
*Desired* Output:
```
<root xmlns="whatever:name-space-1.0"><loner /></root>
```
Is there a solution applicable to the `XmlDocument` code, not something that occurs *after* converting the document to a string with `OuterXml`?
My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank `xmlns` attribute *may* not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.
|
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 elements for them to *also* not have prefixes.
Fixed Code:
```
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0"));
Console.WriteLine(xml.OuterXml);
```
Thanks everyone to all your answers which led me in the right direction!
|
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 test application, the event will not fire again.
So **moving between applications does not trigger Enter/Leave**.
Is there another alternative *Control-level* event that I can use, which will fire in this scenario?
Ordinarily, I would use **Form.Activated**. Unfortunately, that is troublesome here because my component is hosted by a docking system that can undock my component into a new Form without notifying me.
|
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 left, unless you change the dynamics or overload the controls, you cannot get this to happen
|
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 two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe.
Submitting the form results in HTTP that looks like:
```
Content-Type: multipart/form-data;boundary=<boundary string>
Content-Length: <length>
--<boundary string>
Content-Disposition: form-data, name="<input element name>"
<input element value>
--<boundary string>
Content-Disposition: form-data, name=<input element name>"; filename="<input element value>"
Content-Type: application/octet-stream
<element body>
```
How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream?
|
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/2010/07/firefox-4-formdata-and-the-new-file-url-object/) interface that helps to construct such requests. The `send` method is good for text content but if you want to send binary data such as images, you can do it with the help of the `sendAsBinary` method that has been around starting with Firefox 3.0. For details on how to send files via `XMLHttpRequest`, please refer to <http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html>.
|
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.swfupload.org/) or [Google Gears](http://ajaxian.com/archives/youtube-uploader-now-using-gears-and-what-people-missed-in-gears-04)
|
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;
param = odc.Parameters.Add("v_iid", OleDbType.Double);
param.SourceColumn = "I";
param.SourceVersion = DataRowVersion.Original;
param = odc.Parameters.Add("v_pd", OleDbType.Boolean);
param.SourceColumn = "Paid";
param.SourceVersion = DataRowVersion.Current;
param = odc.Parameters.Add("v_Projected", OleDbType.Currency);
param.SourceColumn = "ProjectedCost";
param.SourceVersion = DataRowVersion.Current;
odc.Prepare();
myAdapter.UpdateCommand = odc;
...
myAdapter.Update();
```
It works fine...but the really weird thing is that it *didn't* until I put in the **odc.Prepare()** call.
My question is thus: Do I need to do that all the time when working with OleDb stored procs/queries? Why? I also have another project coming up where I'll have to do the same thing with a SqlDbCommand... do I have to do it with those, too?
|
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 passed in instead of the "?".
So we prepare the statement so instead of "?", we pass in parameters as you have above that are going to be the values that go in in place of the place holders.
Preparing parses the string to find where parameters can replace the question marks so all you have to do is enter the parameter data and execute the command.
Within oleDB, stored queries are prepared statements, so a prepare is required. I've not used stored queries with SqlDB, so I'd have to defer to the 2 answers previous.
|
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 make is guaranteed to produce a different value and not round back to the original.
|
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.
Another way to do it (could be a fallback solution) is to decompose your float into the mantissa and exponent part. Incrementing is easy: Just add one to the mantissa. If you get an overflow you have to handle this by incrementing your exponent. Decrementing works the same way.
**EDIT**: As pointed out in the comments it is sufficient to just increment the float in it's binary representation. The mantissa-overflow will increment the exponent, and that's exactly what we want.
That's in a nutshell the same thing that nextafter does.
This won't be completely portable though. You would have to deal with endianess and the fact that not all machines do have IEEE floats (ok - the last reason is more academic).
Also handling NAN's and infinites can be a bit tricky. You cannot simply increment them as they are by definition not numbers.
|
```
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 still see the process in task manager.
I tried surrounding everything in the main method with a try, to catch an ApplicationException, and I still got nothing as to why the app crashes even though everything works smoothly otherwise...
Anybody has a clue as to where to begin to check for the faulty part?
|
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. It seems that it comes with the provisions to hook up to a database and provide a diagram of its structure, but I've not yet been able to figure out exactly how one would do that.
|
<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() {
define("SERVER","localhost");
define("USER","");
define("PASSWORD","");
define("DB","information_schema");
}
```
|
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, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.
|
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 name, and not an array reference to `cache`. Can it be done?
|
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();'/>
<script type="text/javascript">
function showtest() {
var value = document.getElementById("field[m][2]").value;
alert(value);
}
</script>
</form>
</body>
</html>
```
Update: You can also use the following to get the value from the form element:
```
var value = document.forms.form1["field[m][2]"].value;
```
|
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#.
```
upload = obj.constructUploadObj(uploadConfig);
upload.stateChanged += new UploadActionEvents_stateChangedEventHandler(upload_stateChanged);
```
In javascript I have similar code however I cannot get the event registered with the object.
```
uploadAction = obj.constructUploadObj(uploadConfig);
uploadAction.stateChanged = upload_stateChanged;
function upload_stateChanged(sender){
writeLine("uploadState changed " + sender.getState());
}
```
I have enumerated some of the properties of the uploadAction object in javascript to ensure that it is actually created. When I try and register the event with uploadAction it throws an error saying "Object doesn't support this property or method."
To me it seems like its expecting a strongly typed event. Is there anyway to register the event similar to that of C# in javascript?
Thanks In Advance.
|
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. This is the strange part since in the classes in B I cant have a reference to those in A. (a circular dependency would be created).
How can I track down the problem ? because the exception method doesn't say where the Problem appeared ?
**Edit :**
Ok, I found the problem with the help of **Kent Boogaart's** small app :D . I have a PropertyChanged listener in a class in project A that is not marked Serializable - and I don't want to mark it so. ( it would serialize that class to right ?)
I've solved the problem with the event by following this link : [.NET 2.0 solution to serialization of objects that raise events](http://www.lhotka.net/weblog/CommentView,guid,776f44e8-aaec-4845-b649-e0d840e6de2c.aspx#commentstart).
There still is a problem , but it's probably something similar.
**PS:** Great tool from **Kent Boogaart**
|
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]
public class Test : ISerializable
{
private Test(SerializationInfo info, StreamingContext context)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Test));
foreach (SerializationEntry entry in info)
{
PropertyDescriptor property = properties.Find(entry.Name, false);
property.SetValue(this, entry.Value);
}
}
[SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Test));
foreach (PropertyDescriptor property in properties)
{
info.AddValue(property.Name, property.GetValue(this));
}
}
}
```
Kent's tool also looks very nice and will, without doubt, help you.
|
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 the canvas back the other way they would appear again.
Question:
Which would be the best suited to this type of thing, Flash or Javacsript?
My main worries are the speed at which javascript/ flash could handle moving multiple items around on screen in the way discribed. Which language would handle better for a user on a slow machine.
**UPDATE:**
Thanks for your opnions guys, but to clarify what are the benefits of canvas over straight jQuery DOM manipulation? or visa versa. I've never used canvas before.
|
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, even on slow machines, and is much richer graphically.
JavaScript is more accessible and works on a greater number of devices. Use a good JS framework though.
|
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 800 meshes and iterating through all of them each frame is slow. what is the best way of optimizing the code so that i don't have to look at all of the meshes on every iteration? Bounding volumes inside the frustum?
|
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 hierarchically divide the mesh data.
This works very well for outdoor frustrum culling.
For indoors a BSP is the best way to go since you have lots of walls to partition your space. You should still volume bound your meshes that have more than 10 polygons.
|
[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 table2
where <where-clause>
```
The spaces in the second query may need to be expanded to fit the field sizes for c and d.
|
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 better (preferably free) libraries, or is this level of performance normal?
|
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 pure C#
> 2.0 with fast - O(N \* log N) - multiplication/division algorithms
> implementation. It provides all the
> basic operations on integers like
> addition, multiplication, comparing,
> bitwise shifting etc.
|
`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, manipulating them, and rewriting them using an XmlWriter(), what's the easiest (and most efficient) way for me to "collapse" these empty tags?
|
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 time I append something to the string, I want to add a space in the end, like so:
```
String foo = "string value";
str.append(foo + " ");
```
and I have several calls to append.. and every time, I want to add a space. Is there a way to set the object so that it will add a space automatically after each append?
EDIT --
```
String input
StringBuffer query = new StringBuffer();
Scanner scanner = new Scanner(System.in);
scanner.UseDelimiter("\n");
do {
System.out.println("sql> ");
input = scanner.next();
if (!empty(input)) query.append(input);
if (query.toString().trim().endsWith(";")) {
//run query
}
}
while (!input.equalsIgnoreCase("exit");
```
I'll use StringBuilder though as grom suggested, but that's how the code looks right now
|
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 what) {
return sb.append(what).append(' '); // char is even faster here! ;)
}
```
Or even using a Builder pattern with a fluent interface (also untested code):
```
public String myMethod() {
SBBuilder builder = new SBBuilder()
.add("Hello").add("there")
.add("it", "works", "just", "fine!");
for (int i = 0; i < 10; i++) {
builder.add("adding").add(String.valueOf(i));
}
System.out.println(builder.build());
}
public static class SBBuilder {
private StringBuilder sb = new StringBuilder();
public SBBuilder add(String... parts) {
for (String p : parts) {
sb.append(p).append(' '); // char is even faster here! ;)
}
return this;
}
public String build() {
return sb.toString();
}
}
```
Here's an [article](http://java.dzone.com/news/factories-builders-and-fluent-) on the subject.
Hope it helps! :)
|
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 information from $\_SERVER, I would like to see the raw request exactly as it was sent to the server. PHP munges the header names to suit its own array key style, for eg. Some-Test-Header becomes HTTP\_X\_SOME\_TEST\_HEADER. This is not what I need.
|
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.getScreenSize();
final int x = (screenSize.width - d.getWidth()) / 2;
final int y = (screenSize.height - d.getHeight()) / 2;
d.setLocation(x, y);
d.setVisible(true);
```
|
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-MVC application that approach was fine, but now I find myself working on an MVC application and a page's URL may have nothing to do with the directory structure. So linking to Lightbox2 per the instructions of:
```
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script>
<script type="text/javascript" src="js/lightbox.js"></script>
```
obviously does not work.
I tried putting the absolute path to the JavaScript which gave me the effects, just without the images. I am suspecting that the JavaScript "knows" where its images are, and cannot find them.
Has anyone had success with Lightbox2 in an MVC environment? Perhaps just success deploying Lightbox2 to a non-subdirectory?
Thanks!
|
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/closelabel.gif',
```
And in lightbox.css find:
```
#prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; }
#nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; }
```
And do as you please with it.
|
```
<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(); // Select all links with lightbox class
});
</script>
```
|
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 don't see how to have PHP create the CSV file and let them download a file with a .csv extension.
|
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) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $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 1", "age 1", "city 1"),
array("name 2", "age 2", "city 2"),
array("name 3", "age 3", "city 3")
));
```
[php://output](http://php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq)
[fputcsv](http://php.net/manual/en/function.fputcsv.php)
|
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 vertexes. Any Ideas?
|
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 called nodes) connected by edges. See this Wikipedia article for an overview of network graphs.
.NetMap was created by Marc Smith's team at Microsoft Research."
|
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 2005 would be okay too. for the coding I'm using c#
thanks..
|
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 reserved commandnames all grid-like components knows how to respond to. Clicking this button in DataGrid will raise the EditCommand Event. In this event you have to set the EditItemIndex of the grid equal to Item.Itemindex of the eventargs. This will render the row vaccordeing to the EditItemTemplate.
In this template you put 2 buttons or linkbuttons. One should have the CommandName set to "Update" and one should have the CommandName set to "Cancel".
The "Update" button raises the UpdateCommand event. In which you execute code that store the data in the row to its storage (eg.: database) and sets the EditItemIndex to -1 --> all rows are rendered read-only(ItemTemplate or AlternateItemTemplate).
The "Cancel" button raises the CancelCommand event. In the event handler you have to do si set the EditItemIndex to -1.
This description is only true for DataGrid en not for the in asp.net introduced GridView which handles most of this "Boilerplate"code it self working together with the datasource controls. Google the web for more info on this. it's to much to explain here right now.
Hope it helps?
|
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 = chars[1];
unsigned char c = chars[2];
unsigned char d = chars[3];
```
Or use a union of an unsigned long and four chars:
```
union charSplitter {
struct {
unsigned char a, b, c, d;
} charValues;
unsigned int intValue;
};
charSplitter splitter;
splitter.intValue = orig;
// splitter.charValues.a will give you first byte etc.
```
Update: as friol pointed out, solutions 2 and 3 are not endianness-agnostic; which bytes `a`, `b`, `c` and `d` represent depend on the CPU architecture.
|
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,byte3,byte4);
```
I'm not sure this is always endian correct, by the way. (*Edit*: indeed, it is endian correct, since bitshift operations shouldn't be affected by endianness)
Hope this helps.
|
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 easier if you have it available.
|
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 only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.
EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!
```
String.Join(",", TargetList.ToArray())
```
|
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(",", CType(x.ToArray(GetType(String)), String())))
```
mspmsp's second solution is a nice approach as well but it's not working because it misses the `AddressOf` keyword. Also, `Convert.ToString` is rather inefficient (lots of unnecessary internal evaluations) and the `Convert` class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.
|
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("""
ALTER table app_table AUTO_INCREMENT=2000
""")
transaction.commit_unless_managed()
post_syncdb.connect(auto_increment_start, sender=app_models)
```
After a syncdb the alter table statement is executed. This will exempt you from having to login into mysql and issuing it manually.
EDIT: I know this is an old thread, but I thought it might help someone.
|
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 have started with Win32 Programming then moved to COM and ATL. Win32 Programming gave me the insights of Windows.
Can you give me the steps to start with Linux Programming?
|
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) library (Standard component of GTK+/GNOME but
also used in command line applications.)
If you absolutely have to program in C++, read the whole documenation of [QT](http://www.qtsoftware.com/developer)
and you are good to go.
|
* 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 emacs are the most popular choices.
* linux. your distribution in particular (ubuntu is popular; you may want to start there). know how to tweek your environment and how to fix things when they break.
The rest depends on what you want to do.
You do not need to be an expert at any of this; you will learn over time.
|
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.