Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Given the email address: "Jim" <jim@example.com>
If I try to pass this to MailAddress I get the exception:
> The specified string is not in the form required for an e-mail address.
How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?
EDIT: I'm looking for C# code to parse... | If you are looking to parse the email address manually, you want to read RFC2822 (<https://www.rfc-editor.org/rfc/rfc822.html#section-3.4>). Section 3.4 talks about the address format.
But parsing email addresses correctly is not easy and `MailAddress` should be able to handle most scenarios.
According to the MSDN do... | Works for me:
```
string s = "\"Jim\" <jim@example.com>";
System.Net.Mail.MailAddress a = new System.Net.Mail.MailAddress(s);
Debug.WriteLine("DisplayName: " + a.DisplayName);
Debug.WriteLine("Address: " + a.Address);
```
The MailAddress class has a private method that parses an email address. Don't know how good ... | How to parse formatted email address into display name and email address? | [
"",
"c#",
"parsing",
"mailaddress",
""
] |
A few years ago, I read a book that described how you could override the default event 'dispatcher' implementation in .NET with your own processor.
```
class foo {
public event EventHandler myEvent;
...
}
...
myFoo.myEvent += myBar1.EventHandler;
myFoo.myEvent += myBar2.EventHand... | It could have been one of many books or web articles.
There are various reasons why you might want to change how events are subscribed/unsubscribed:
* If you have many events, many of which may well not be subscribed to, you may want to use [EventHandlerList](http://msdn.microsoft.com/en-us/library/system.componentmo... | I seem to remember something similar in Jeffrey Richter's CLR via C#. **Edit:** I definitely do remember that he goes into detail about it.
There are a few different reasons for taking control of event registration. One of them is to reduce code bloat when you've got TONS of events. I think Jeffrey went into this in d... | Doing your own custom .NET event processing loop | [
"",
"c#",
".net",
"dispatchertimer",
""
] |
I have a ASP.NET application running on a remote web server and I just started getting this error:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that imp... | Ahh, ILMerge - that extra info in your question really helps with your problem. While I wouldn't ever expect the .net compiler to fail in this way I would expect to occasionally see this sort of thing with ILMerge (given what it's doing).
My guess is that two of your assemblies are using the same optimisation 'trick',... | Are you sure that the assembly you're looking at was actually generated from the source code in question? Are you able to reproduce this problem with a small test case?
**Edit:** if you're using Reflector, it's possible that the MSIL to C# conversion isn't correct -- Reflector isn't always 100% accurate at decompiling... | C# Compiler Incorrectly Optimizes Code | [
"",
"c#",
"asp.net",
"optimization",
"compiler-construction",
"ilmerge",
""
] |
Boost is a very large library with many inter-dependencies -- which also takes a long time to compile (which for me slows down our [**CruiseControl**](http://cruisecontrol.sourceforge.net/) response time).
The only parts of boost I use are boost::regex and boost::format.
Is there an easy way to extract only the parts... | First, you can use the bcp tool (can be found in the tools subfolder) to extract the headers and files you are using. This won't help with compile times, though. Second, you don't have to rebuild Boost every time. Just pre-build the lib files once and at every version change, and copy the "stage" folder at build time. | Unless you are patching the boost libraries themselves, there is no reason to recompile it every time you do a build. | How do you deal with large dependencies in Boost? | [
"",
"c++",
"boost",
"dependencies",
""
] |
What is the best way to parse a float in CSharp?
I know about TryParse, but what I'm particularly wondering about is dots, commas etc.
I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round.
How can I best capture this... | Depends where the input is coming from.
If your input comes from the user, you should use the CultureInfo the user/page is using ([Thread.CurrentThread.CurrentUICulture](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx)).
You can get and indication of the culture of the user, by l... | I agree with leppie's reply; to put that in terms of code:
```
string s = "123,456.789";
float f = float.Parse(s, CultureInfo.InvariantCulture);
``` | Best way to parse float? | [
"",
"c#",
"parsing",
"floating-point",
"currentculture",
""
] |
I made a Java Applet with some Standard GUI Components on it. I used the [MigLayout](http://www.miglayout.com/) Manager.
If I move the mouse slowly over the various GUI Components everything appears to be fine, but if I move the mouse fast, it flickers.
What could make that nasty ugly redraw?
(Core 2 Duo 6300, 2GB Ra... | One thought would be to check your code (and/or the MigLayout code) for unnecessary `repaint()` operations.
Custom UIs and layouts can cause weird problems sometimes... | you could use double buffering in java applet to improve screen refreshing speed. ask more if details needed.. | Why does Swing in my Java Applet flicker on fast mouse over? | [
"",
"java",
"swing",
"applet",
""
] |
I'm working on a little test application at the minute and I have multiple window objects floating around and they each call RegisterWindowEx with the same WNDCLASSEX structure (mainly because they are all an instance of the same class).
The first one registers ok, then multiple ones fail, saying class already registe... | You can test if the window class was previously registered calling **GetClassInfoEx**.
> If the function finds a matching class
> and successfully copies the data, the
> return value is nonzero.
<http://msdn.microsoft.com/en-us/library/ms633579(VS.85).aspx>
This way you can conditionally register the window class ba... | ## If your window class is defined in a DLL
Perhaps you should call your `RegisterClass()` in the PROCESS\_ATTACH part of the DllMain, and call your `UnregisterClass()` in the PROCESS\_DETACH part of the DllMain
## If your window class is defined in the executable
Perhaps you should call your `RegisterClass()` in th... | Side effects of calling RegisterWindow multiple times with same window class? | [
"",
"c++",
"windows",
"winapi",
""
] |
What is the best way to track down a memory leak that is only found on one customer's test/release box, and no where else? | [dotTrace3.1](http://www.jetbrains.com/profiler/index.html)
(This question is kinda funny, cause I am tracking a mem leak that isn't present on my machine ...) | Try a memory profiler like [ANTS Profiler](http://www.red-gate.com/products/ants_memory_profiler/index.htm). | Best way to track down a memory leak (C#) only visible on one customer's box | [
"",
"c#",
".net",
"memory",
"memory-leaks",
"garbage-collection",
""
] |
Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.
Here is an example:
```
def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int... | 1. Install [decorator](http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution) module:
```
$ pip install decorator
```
2. Adapt definition of `args_as_ints()`:
```
import decorator
@decorator.decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args... | This is solved with Python's standard library `functools` and specifically [`functools.wraps`](https://docs.python.org/3.5/library/functools.html#functools.wraps) function, which is designed to "*update a wrapper function to look like the wrapped function*". It's behaviour depends on Python version, however, as shown b... | Preserving signatures of decorated functions | [
"",
"python",
"decorator",
""
] |
This is somewhat of a follow-up to an answer [here](https://stackoverflow.com/questions/26536/active-x-control-javascript).
I have a custom ActiveX control that is raising an event ("ReceiveMessage" with a "msg" parameter) that needs to be handled by Javascript in the web browser. Historically we've been able to use t... | I was able to get this working using the following script block format, but I'm still curious if this is the best way:
```
<script for="MyControl" event="ReceiveMessage(msg)">
alert(msg);
</script>
``` | I have used activex in my applications before. i place the object tags in the ASP.NET form and the following JavaScript works for me.
```
function onEventHandler(arg1, arg2){
// do something
}
window.onload = function(){
var yourActiveXObject = document.getElementById('YourObjectTagID');
if(typeof(yourAct... | How to handle an ActiveX event in Javascript | [
"",
"javascript",
"events",
"activex",
""
] |
I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 ste... | Oh ye of little faith:
```
SELECT *, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable
```
<http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx> | You commented: not working if oldtable has an identity column.
I think that's your answer. The #newtable gets an identity column from the oldtable automatically. Run the next statements:
```
create table oldtable (id int not null identity(1,1), v varchar(10) )
select * into #newtable from oldtable
use tempdb
GO
sp_... | INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table? | [
"",
"sql",
"sql-server",
""
] |
I have a scenario. (Windows Forms, C#, .NET)
1. There is a main form which hosts some user control.
2. The user control does some heavy data operation, such that if I directly call the `UserControl_Load` method the UI become nonresponsive for the duration for load method execution.
3. To overcome this I load data on d... | As per [Prerak K's update comment](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the#142108) (since deleted):
> I guess I have not presented the question properly.
>
> Situation is this: I want to load data into a global variable based on the valu... | # Threading Model in UI
Please read the *[Threading Model](https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/threading-model)* in UI applications ([old VB link is here](https://msdn.microsoft.com/library/ms741870(v=vs.100).aspx)) in order to understand basic concepts. The link navigates to page that desc... | Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on | [
"",
"c#",
"multithreading",
"winforms",
"invoke",
""
] |
does any one know how to get the current motherboard, processor or HD temperature statistics?
In GNU/Linux, I know I could use something like hddtemp or sensord to get the info, and then parse it... but in Windows: How can I do this? And, Can it be done with with C# or Java or any other hight level programming langua... | The problem with temperature and other monitoring sensors is that there is no common protocol on the hardware level, nor drivers allowing to retrieve that information with common API.
Software like already mentioned SpeedFan and [HWMonitor](http://www.cpuid.com/hwmonitor.php) (from the makers of CPU-Z utility) work by... | I would argue that when the right configurations are in place, it can be superior to windows's one.
<http://www.lm-sensors.org/> is what does all the work. I had that plugged into RRDgraph & Munin and I was monitoring the temperature of my room over a period of almost a year and had nice pretty graphs. Also showed me ... | How to get the temperature of motherboard of a PC (and other hardware statistics)? | [
"",
"java",
"statistics",
"hardware",
"temperature",
""
] |
I have an Enum called Status defined as such:
```
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
}
```
I would like to access the value of `VALID` from a JSTL tag.... | A simple comparison against string works:
```
<c:when test="${someModel.status == 'OLD'}">
``` | If using Spring MVC, the Spring Expression Language (SpEL) can be helpful:
```
<spring:eval expression="dp.status == T(com.example.Status).VALID" var="isValid" />
<c:if test="${isValid}">
isValid
</c:if>
``` | Access Enum value using EL with JSTL | [
"",
"java",
"jsp",
"jakarta-ee",
"jstl",
""
] |
To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it wo... | JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode.
But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position:
```
function isDoubleByte(str) {
for (var i = 0, n = str.length; i < ... | I used mikesamuel answer on this one. However I noticed perhaps because of this form that there should only be one escape slash before the `u`, e.g. `\u` and not `\\u` to make this work correctly.
```
function containsNonLatinCodepoints(s) {
return /[^\u0000-\u00ff]/.test(s);
}
```
Works for me :) | How to find whether a particular string has unicode characters (esp. Double Byte characters) | [
"",
"javascript",
"unicode",
"double-byte",
""
] |
I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 ([adLDAP](http://adldap.sourceforge.net/) does it on Apache). Anyone had done anything similar, with success?
* Edit: I'd prefer a library/class with code that's read... | Importing a whole library seems inefficient when all you need is essentially two lines of code...
```
$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
// log them in!
} else {
// error message
}
``` | You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
* You must validate input. An empty username/password would pass otherwise.
* You should ensure the ... | Authenticating in PHP using LDAP through Active Directory | [
"",
"php",
"authentication",
"active-directory",
"ldap",
""
] |
I want my Python script to copy files on Vista. When I run it from a normal `cmd.exe` window, no errors are generated, yet the files are NOT copied. If I run `cmd.exe` "as administator" and then run my script, it works fine.
This makes sense since User Account Control (UAC) normally prevents many file system actions.
... | As of 2017, an easy method to achieve this is the following:
```
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.... | It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:
```
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.joi... | Request UAC elevation from within a Python script? | [
"",
"python",
"windows",
"windows-vista",
"uac",
""
] |
Depends on your experience could you recommend something?
I've use [izpack](http://izpack.org/), and it's very nice tool, is there any other, better tool? | In MS Windows [NSIS](http://nsis.sourceforge.net/Main_Page) is great and it's free & OSS
Ref: [Java Launcher with automatic JRE installation](http://nsis.sourceforge.net/Java_Launcher_with_automatic_JRE_installation) | for Windows there's [AdvancedInstaller](http://www.advancedinstaller.com/java.html), it was very easy to use and created standard .msi files. It has some extra features for Java installs. | What is the best installation tool for java? | [
"",
"java",
"installation",
""
] |
PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array *"is a list"* (contains only numeric keys starting from 0)?
Basically, I want to be able to differentiate between this:
```
$sequentialArray = [
'apple', 'orange', 'tomato... | Since 8.1 PHP has a simple answer, [array\_is\_list()](https://www.php.net/manual/en/function.array-is-list.php).
For the legacy code you can use the following function (wrapping it in `function_exists()` to make it portable):
```
if (!function_exists('array_is_list')) {
function array_is_list(array $arr)
{
... | To merely check whether the array has non-integer keys (not whether the array is sequentially-indexed or zero-indexed):
```
function has_string_keys(array $array) {
return count(array_filter(array_keys($array), 'is_string')) > 0;
}
```
If there is at least one string key, `$array` will be regarded as an associative... | How to check if PHP array is associative or sequential? | [
"",
"php",
"arrays",
""
] |
For example, if I have an echo statement, there's no guarantee that the browser might display it right away, might display a few dozen echo statements at once, and might wait until the entire page is done before displaying anything.
Is there a way to have each echo appear in a browser as it is executed? | You can use [`flush()`](http://php.net/flush) to force sending the buffer contents to the browser.
You can enable implicit flushing with "[`ob_implicit_flush(true)`](http://php.net/ob_implicit_flush)". | ```
function printnow($str, $bbreak=true){
print "$str";
if($bbreak){
print "<br />";
}
ob_flush(); flush();
}
```
Obviously this isn't going to behave if you pass it complicated objects (or at least those that don't implement \_\_toString) but, you get the idea. | Is there a way to have PHP print the data to a web browser in real time? | [
"",
"php",
""
] |
I have a table in a MSSQL database that looks like this:
```
Timestamp (datetime)
Message (varchar(20))
```
Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.
What is a good query or set of st... | ```
Select Count(Message) As Status
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
```
You could modify this slightly to detect invalid conditions, like multiple starts, finishes, starts without a finish, etc...
```
Sele... | ```
DECLARE @TargetDate datetime
SET @TargetDate = '2008-01-01'
DECLARE @Messages varchar(max)
SET @Messages = ''
SELECT @Messages = @Messages + '|' + Message
FROM process_monitor
WHERE @TargetDate <= Timestamp and Timestamp < DateAdd(dd, 1, @TargetDate)
and Message in ('Finished', 'Started')
ORDER BY Timestamp d... | Sql query to determine status? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using
```
document.body.clientHeight
```
but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big.
Now, I really don't want to use... | have you considered using [jQuery](http://jquery.com)? it abstracts most of the browser specific functionality away into a common interface.
```
var width = $(document).width();
var height = $(document.height();
$('#mySpecialElement').width(width).height(height);
``` | This *may* help the cause ...
> From <http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/> :
```
<script type="text/javascript">
<!--
var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
... | Proper IE6 HTML element dimensions | [
"",
"javascript",
"internet-explorer",
""
] |
In a [Pygame](http://www.pygame.org/) application, I would like to render resolution-free GUI widgets described in SVG.
How can I achieve this?
(I like the [OCEMP GUI](http://ocemp.sourceforge.net/gui.html) toolkit, but it seems to be bitmap-dependent for its rendering.) | This is a complete example which combines hints by other people here.
It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.
```
#!/usr/bin/python
import array
import math
import cairo
import pygame
import rsvg
... | **SVG files are supported with Pygame Version 2.0**. Since Version 2.0.2, SDL Image supports SVG ([Scalable Vector Graphics](https://en.wikipedia.org/wiki/Scalable_Vector_Graphics)) files (see [SDL\_image 2.0](https://www.libsdl.org/projects/SDL_image)). Therefore, with pygame version 2.0.1, SVG files can be loaded int... | SVG rendering in a Pygame application. Prior to Pygame 2.0, Pygame did not support SVG. Then how did you load it? | [
"",
"python",
"svg",
"pygame",
"widget",
"pygame-surface",
""
] |
I have always been for documenting code, but when it comes to AJAX + PHP, it's not always easy: the code is really spread out! Logic, data, presentation - you name it - are split and mixed between server-side and client-side code. Sometimes there's also database-side code (stored procedures, views, etc) doing part of t... | I think it's best to take a hierarchical approach.
For api-level documentation like on the function and class level, write inline documentation in the code and generate html documentation out of them using the many documentation tools out there ([JSDoc](http://jsdoc.sourceforge.net/), [phpDocumentor](http://www.phpdoc... | I think your method is pretty good. The only thing is that everything inside the js file is readable by others and therefore documenting what PHP files are used could lead to a security hole, in the off chance they can get to a file that returns something it shouldn't. Also, although not a big deal, on higher traffic s... | Best way to document AJAX + PHP code? | [
"",
"php",
"ajax",
"documentation",
""
] |
Is there a tool/plugin/function for Firefox that'll dump out a memory usage of Javascript objects that you create in a page/script? I know about Firebug's profiler but I'd like something more than just times. Something akin to what Yourkit has for Java profiling of memory usage.
Reason is that a co-worker is using id'... | I haven't tried the Sofware verify tools, but Mozilla has tools that track overall memory consumed by firefox for the purpose of stemming leaks:
<http://www.mozilla.org/performance/tools.html>
and:
<https://wiki.mozilla.org/Performance:Leak_Tools>
There's also this guy saying to avoid large arrays in the context of... | I think [JavaScript Memory Validator](http://www.softwareverify.com/javascript/memory/feature.html) from Software Verification Limited can help you, it has allocations view, objects view, generations view, etc. It's not free but you can use the evaluation version to check your coworker's code. They also have a Performa... | Javascript memory profiler for Firefox | [
"",
"javascript",
"firefox",
"memory",
"profiling",
""
] |
Let's say we have `index.php` and it is stored in `/home/user/public/www` and `index.php` calls the class `Foo->bar()` from the file `inc/app/Foo.class.php`.
I'd like the bar function in the `Foo` class to get a hold of the path `/home/user/public/www` in this instance — I don't want to use a global variable, pass a v... | Wouldn't this get you the directory of the running script more easily?
```
$dir=dirname($_SERVER["SCRIPT_FILENAME"])
``` | You can use [debug\_backtrace](https://www.php.net/debug_backtrace) to look at the calling path and get the file calling this function.
A short example:
```
class Foo {
function bar() {
$trace = debug_backtrace();
echo "calling file was ".$trace[0]['file']."\n";
}
}
``` | Can I get the path of the PHP file originally called within an included file? | [
"",
"php",
"path",
""
] |
I would like to be able to monitor my major system health indicators from inside our Java-based system. Major points of interest include CPU temperature, motherboard temperature, fan speed, etc.
Is there a package available that:
1. Makes this sort of data available to Java?
2. Works on Windows or Linux or both?
3. I... | There are MIBs supported by both Windows and Linux that expose the parameters you are looking for via SNMP. Also, most major vendors have special MIBs published for their server hardware.
I have implemented SNMP MIBs and monitoring for Java applications using the commercial [iReasoning SNMP API](http://www.ireasoning.... | The closest thing you'll find is the Hyperic Sigar library:
<http://www.hyperic.com/products/sigar.html>
It doesn't get down to temperatures AFAIK but does show you a number of native stats like CPU, memory, disk I/O, network I/O, etc. It's ported to most of the architectures people are deploying Java on today. Licen... | What is the best way for a Java program to monitor system health? | [
"",
"java",
"system-monitoring",
""
] |
I have used IPC in Win32 code a while ago - critical sections, events, and semaphores.
How is the scene in the .NET environment?
Are there any tutorial explaining all available options and when to use and why? | Most recent Microsoft's stuff in IPC is [Windows Communication Foundation](http://en.wikipedia.org/wiki/Windows_Communication_Foundation). Actually there is nothing new in the lower level (tcp, upd, named pipes etc) But WCF simplifies IPC development greatly.
Useful resource:
* [Interprocess Communication with WCF](h... | Apart from the obvious (WCF), there is a ZeroMQ binding for C#/CLR which is pretty good:
<http://www.zeromq.org/bindings:clr>
Does message-oriented IPC, pub/sub and various other strategies with much less code and config than WCF.
It's also at least an order of magnitude faster than anything else and has less latenc... | IPC Mechanisms in C# - Usage and Best Practices | [
"",
"c#",
".net",
"ipc",
""
] |
I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.
IE: given
```
struct mstct {
int myfield;
int myfield2;
};
```
I could write:
```
mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
```
An... | How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
```
#define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))
``` | Right, use the `offsetof` macro, which (at least with GNU CC) is available to both C and C++ code:
```
offsetof(struct mstct, myfield2)
``` | C/C++ Structure offset | [
"",
"c++",
"c",
"oop",
""
] |
I definitifely like the one at stackoverflow, because it's clean and simple. Also the live preview with code/syntax hilighting is really helpful (and motivating).
What is your favourite Javascript Editor Framework and why? | I like [widgEditor](http://themaninblue.com/experiment/widgEditor/) because it's very simple and it only do the minimum. TinyMCE or FCKeditor are goods, but they are too big for what I need. | [TinyMCE](http://tinymce.moxiecode.com/index.php) looks good with lots of useful features. | What is your favourite Java Script WYSIWYG Editor component? | [
"",
"javascript",
"html",
"editor",
"textarea",
"wysiwyg",
""
] |
**Has anyone had success automating testing directly on embedded hardware?**
Specifically, I am thinking of automating a battery of unit tests for hardware layer modules. We need to have greater confidence in our hardware layer code. A lot of our projects use interrupt driven timers, ADCs, serial io, serial SPI device... | Sure. In the automotive industry we use $100,000 custom built testers for each new product to verify the hardware and software are operating correctly.
The developers, however, also build a cheaper (sub $1,000) tester that includes a bunch of USB I/O, A/D, PWM in/out, etc and either use scripting on the workstation, o... | Yes. I have had success, but it is not a stragiht-forward problem to solve. In a nutshell here is what my team did:
1. Defined a variety of unit tests using a home-built C unit-testing framework. Basically, just a lot of macros, most of which were named `TEST_EQUAL`, `TEST_BITSET`, `TEST_BITVLR`, etc.
2. Wrote a boot ... | Test Automation with Embedded Hardware | [
"",
"c++",
"c",
"unit-testing",
"embedded",
"testing-strategies",
""
] |
I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.
Please don't tell me that I should be develo... | ## PyS60 -- its cool :)
I worked quite a lot on PyS60 ver 1.3 FP2. It is a great language to port your apps on
Symbian Mobiles and Powerful too. I did my Major project in PyS60, which was a [GSM locator](http://sourceforge.net/projects/gsmlocator)(its not the latest version) app for Symbian phones.
There is also a ve... | Have you checked out the [Mobile Python Book](http://www.mobilepythonbook.com/)?
> This practical hands-on book effectively teaches how to program your own powerful and fun applications easily on Nokia smartphones based on Symbian OS and the S60 platform.
[. I'm looking
forward to any solutions. Thank you!
## Used en... | OK, what you have to do is File->New->Other->Server, and set up your JBoss server there. It will then appear in Preferences->JBossTools->Servers.
Convoluted. | Here is a detailed fix for this problem:
The Eclipse WTP server connector won't shut down JBoss when the jndi port is remapped.
This is because the default server connector profiles don't use their own alias for the jndiPort. This problem is also discussed at eclipse.org:
<http://www.eclipse.org/forums/index.php?t=msg... | Problems with shutting down JBoss in Eclipse if I change JNDI port | [
"",
"java",
"eclipse",
"jboss",
"jboss-tools",
""
] |
I'm calling some code that uses the BitmapData class from .NET. I've hit something where I can't find a definitive answer on Googlespace.
Because it seems that LockBits and UnlockBits must always be called in a pair, I'm using this:
```
System.Drawing.Imaging.BitmapData tempImageData = tempImage.LockBits(
... | The try-finally pattern is correct. Since this is external code, you have no control over what exceptions are thrown, and the UnlockBits cleanup code needs to be executed regardless of what error has occurred. | Even if you do catch the exception, using finally means you don't duplicate the UnlockBits call, which is a plus in my option. | unlockbits, lockbits, and try-finally | [
"",
"c#",
".net",
""
] |
I make a lot of web applications and from time to time I need a color picker. What's one that I can use like an API and doesn't require a lot of code to plug in? I also need it to work in all browsers. | [Farbtastic](http://acko.net/dev/farbtastic) is a nice jQuery color picker
But apparently doesn't work in IE6
[Here](http://www.eyecon.ro/colorpicker/#about) is another jQuery color picker that looks nice, not sure about it compatibility though. | I like [jscolor](http://jscolor.com/try.php) the most, lightweight and lots of options. | What's a good JavaScript plugin color picker? | [
"",
"javascript",
"color-picker",
""
] |
I have an ant build that makes directories, calls javac and all the regular stuff. The issue I am having is that when I try to do a clean (delete all the stuff that was generated) the delete task reports that is was unable to delete some files. When I try to delete them manually it works just fine. The files are appare... | I encountered this problem once.
It was because the file i tried to delete was a part of a **classpath** for another task. | It depends ...
* The Ant process doesn't have enough permissions to delete the files (typically because they were created by a different user, perhaps a system user). Try running your Ant script as an administrative user, using Run As.
* Windows is really bad at cleaning up file locks when processes die or are killed;... | Ant is not able to delete some files on windows | [
"",
"java",
"windows",
"ant",
"build-automation",
""
] |
I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the `this` pointer is being used. From the behavior of the program, I have deduced that the `this` pointer is referring to the class on which the meth... | Cannibalized from another post of mine, here's more than you ever wanted to know about *this*.
Before I start, here's the most important thing to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes (ES6 `class` is [syntactic sugar](https://stackoverflow... | ## Function calls
Functions are just a type of Object.
All Function objects have [call](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call) and [apply](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply) methods which execute the Functio... | How does "this" keyword work within a function? | [
"",
"javascript",
"this",
"language-design",
"language-features",
""
] |
Am looking for C# open source NMEA parser. | Well, I'm not familiar with it myself, but some quick searches show one on [CodeProject](http://www.codeproject.com/KB/cs/NMEAtoOSG.aspx), which links to 2 other such, [here](http://www.codeproject.com/KB/mobile/WritingGPSApplications1.aspx) and [here](http://www.codeproject.com/KB/mobile/WritingGPSApplications2.aspx).... | check out [sharpGPS](http://www.codeplex.com/SharpGPS) . there are several other gps and nmea related projects o codeplex too | C# open source NMEA parser | [
"",
"c#",
"nmea",
""
] |
I am trying to take a rather large CSV file and insert it into a MySQL database for referencing in a project. I would like to use the first line of the file to create the table using proper data types and not varchar for each column. The ultimate goal is to automate this process as I have several similar files but the ... | Building on [Nouveau](https://stackoverflow.com/questions/173498/using-php-to-take-the-first-line-of-a-csv-file-and-create-a-mysql-table-with-th#173526)'s code you could do this
```
for($i = 0; $i <= count($fieldList); $i++)
{
if (is_numeric($fieldList[$i]))
{
if (strpos($fieldList[$i],'.') !== false){... | Try casting the value and comparing it with the original one:
```
define('DECIMAL_SEPARATOR', '.');
switch ($fieldList[$i])
{
case (string)(int)$fieldList[$i]:
$typeInfo = (strpos($fieldList[$i], DECIMAL_SEPARATOR) === false) ? 'int(11)' : 'float';
break;
case (string)(float)$fieldList[$i]:
... | Using PHP to take the first line of a CSV file and create a MySQL Table with the data | [
"",
"php",
"mysql",
"file-io",
"csv",
""
] |
I recently wrote a parser in Python using Ply (it's a python reimplementation of yacc). When I was almost done with the parser I discovered that the grammar I need to parse requires me to do some look up during parsing to inform the lexer. Without doing a look up to inform the lexer I cannot correctly parse the strings... | An option you may consider, if an LL parser is ok to you, is to give [ANTLR](http://www.antlr.org/wiki/display/ANTLR3/Antlr3PythonTarget) a try, it can generate python too (actually it is LL(\*) as they name it, \* stands for the quantity of lookahead it can cope with). | I believe that [pyparsing](http://pyparsing.wikispaces.com/ "PyParsing web site") is based on the same principles as parsec. | Python implementation of Parsec? | [
"",
"python",
"parsing",
"parsec",
"combinators",
""
] |
I have a couple of triggers on a table that I want to keep ***separate*** and would like to priortize them.
I could have just one trigger and do the logic there, but I was wondering if there was an easier/logical way of accomplishing this of having it in a pre-defined order ? | Use sp\_settriggerorder. You can specify the first and last trigger to fire depending on the operation.
[sp\_settriggerorder on MSDN](http://msdn.microsoft.com/en-us/library/ms186762.aspx)
From the above link:
**A. Setting the firing order for a DML trigger**
The following example specifies that trigger uSalesOrd... | Rememebr if you change the trigger order, someone else could come by later and rearrange it again. And where would you document what the trigger order should be so a maintenance developer knows not to mess with the order or things will break? If two trigger tasks definitely must be performed in a specific order, the on... | How do you priortize multiple triggers of a table? | [
"",
"sql",
"sql-server-2005",
"t-sql",
"triggers",
""
] |
I've got a "little" problem with Zend Framework Zend\_Pdf class. Multibyte characters are stripped from generated pdf files. E.g. when I write aąbcčdeę it becomes abcd with lithuanian letters stripped.
I'm not sure if it's particularly Zend\_Pdf problem or php in general.
Source text is encoded in utf-8, as well as t... | `Zend_Pdf` supports UTF-8 in version 1.5 of Zend Framework. However, the standard PDF fonts support only the Latin1 character set. This means you can't use `Zend_Pdf_Font::FONT_TIMES_BOLD` or any other "built-in" font. To use special characters you must load another TTF font that includes characters from other characte... | I believe Zend\_Pdf got UTF-8 support in 1.5 - What version of Zend Framework are you running?
Also - what font are you trying to render with? Have you tried alternate fonts? | How to generate pdf files _with_ utf-8 multibyte characters using Zend Framework | [
"",
"php",
"zend-framework",
"pdf",
"unicode",
""
] |
Is there any framework for querying XML SQL Syntax, I seriously tire of iterating through node lists.
---
Or is this just wishful thinking (if not idiotic) and certainly not possible since XML isn't a relational database? | [XQuery](http://www.w3schools.com/xquery/default.asp) and XPath... XQuery is more what you are looking for if a SQL structure is desirable. | .Net Framework provides LINQ to do this or you can use the .Net System.Data namespace to load data from XML files.
You can even create queries that have joins among the tables, etc.
For example, System.Data.DataTable provides a `ReadXml()` method. | Querying XML like SQL? | [
"",
"sql",
"xml",
"language-agnostic",
"frameworks",
""
] |
I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the **window.onload** event), but it's different for every browser.
Is there a definitive way to do this on all the browsers?
So far I know of:
* **DOMContentLoaded** : On Mozilla,... | There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.
Mozilla, Opera, and modern WebKit support the `DOMContentLoaded` event. IE and Safari need weird hacks like scrolling the window or checking stylesheets.... | I found this page, which shows a compact self-contained solution. It seems to work on every browser and has an explanation on how:
<http://www.kryogenix.org/days/2007/09/26/shortloaded> | Getting notified when the page DOM has loaded (but before window.onload) | [
"",
"javascript",
"dom",
""
] |
I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the... | Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern() your Strings:
```
final String firstkey = "Data-" + email;
final String key = firstkey.intern();
```
Two Strings with the same value are otherwise not necessarily the same object.
Note that this may in... | Synchronizing on an intern'd String might not be a good idea at all - by interning it, the String turns into a global object, and if you synchronize on the same interned strings in different parts of your application, you might get really weird and basically undebuggable synchronization issues such as deadlocks. It mig... | Synchronizing on String objects in Java | [
"",
"java",
"multithreading",
"synchronization",
"thread-safety",
"synchronized",
""
] |
I am writing a very specialized app in C# that floats as a mostly transparent window over the entire desktop. I want to be able to create and pass mouse events to applications behind mine, and have them appear to operate "normally", responding to those events. It would also be preferable if the window manager could res... | After looking at System hooks and other low level solutions I found a much simpler method.
First, set the TransparencyKey and BackColor of the form to be the same. This didn't make any visual difference to me as my form was visually transparent already, but this will help in letting mouse events through.
Second, the ... | Sounds like you want to do something like filtering user input.
Maybe you just need an keyboard/mouse hook.
You maybe want to take a look at the windows API call SetWindowsHookEx.
There should also be enough samples how to do that in C# available, the first thing i found was [this link](http://blogs.msdn.com/toub/ar... | How to pass mouse events to applications behind mine in C#/Vista? | [
"",
"c#",
"events",
"windows-vista",
"mouse",
""
] |
In MSVC, [DebugBreak()](http://msdn.microsoft.com/en-us/library/ms679297.aspx) or [\_\_debugbreak](http://msdn.microsoft.com/fr-fr/library/f408b4et.aspx) cause a debugger to break. On x86 it is equivalent to writing "\_asm int 3", on x64 it is something different. When compiling with gcc (or any other standard compiler... | What about defining a conditional macro based on #ifdef that expands to different constructs based on the current architecture or platform.
Something like:
```
#ifdef _MSC_VER
#define DEBUG_BREAK __debugbreak()
#else
...
#endif
```
This would be expanded by the preprocessor the correct debugger break instruction bas... | A method that is portable to most POSIX systems is:
```
raise(SIGTRAP);
``` | Is there a portable equivalent to DebugBreak()/__debugbreak? | [
"",
"c++",
"portability",
"debugbreak",
""
] |
I have seen the official demos on lwjgl.org but I would like to see some more tutorial level examples. | Google "import org.lwjgl" to find lots of examples, as all code that uses LWJGL must contain that string to import parts of the package. | If it still does matter: <http://nehe.gamedev.net/>
All tutorials are ported to LWJGL too. | Where can I find sample uses of LWJGL? | [
"",
"java",
"opengl",
"openal",
"lwjgl",
""
] |
I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in '... | For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search.
```
Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', '%fran%');
List results = crit.list();
``` | ```
Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', 'fran', MatchMode.ANYWHERE);
List results = crit.list();
``` | Case-insensitive search using Hibernate | [
"",
"sql",
"hibernate",
"select",
"case-sensitive",
""
] |
Most often the cleanup rules (Preferences > Java > Code Style > Clean Up) in Eclipse work perfectly and create nice-looking code.
But sometimes, especially with comments and concatenated string snippets (like inline SQL queries), the cleanup just messes things up, and destroys my formatting.
Is there a way to say to ... | I assume you do not really mean ‘Clean Up’, but the ‘Format source code’ option hidden within. It is configured in Preferences > Java > Code Style > Formatter. And, indeed, there is an option called ‘On/Off Tags’. Sadly, it’s off by default. You would now write it like so:
```
// @formatter:off
StringBuilder sql = new... | I have experienced the same problem, and while I don't have a solution, I can tell you how I work around the problem.
Because of how formatting works, I deliberately avoid lines of code that are excessively long. In general, when I keep lines short, it makes better decisions as to how to format the code. This can even... | Can I Define Exceptions to Eclipse cleanup rules? | [
"",
"java",
"eclipse",
""
] |
If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.
Today our signal handle... | This [table](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948) lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.
By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the tric... | FWIW, 2 is standard error on Windows also, but you're going to need some conditional compilation because their write() is called \_write(). You'll also want
```
#ifdef SIGUSR1 /* or whatever */
```
etc around all references to signals not guaranteed to be defined by the C standard.
Also, as noted above, you don't wa... | Portable way to catch signals and report problem to the user | [
"",
"c++",
"c",
"posix",
"signals",
"reentrancy",
""
] |
At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web s... | From: <https://www.php.net/manual/en/mysqli.close.php>
> "Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resourc... | Just because you redirect doesn't mean the script stops executing. A redirect is just a header being sent. If you don't exit() right after, the rest of your script will continue running. When the script does finish running, it will close off all open connections (or release them back to the pool if you're using persist... | What happens if MySQL connections continually aren't closed on PHP pages? | [
"",
"php",
"mysql",
""
] |
I have the following situation:
```
class A
{
public:
A(int whichFoo);
int foo1();
int foo2();
int foo3();
int callFoo(); // cals one of the foo's depending on the value of whichFoo
};
```
In my current implementation I save the value of `whichFoo` in a data member in the constructor and use a `sw... | How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?
In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually *measure* the different choices. ... | You can write this:
```
class Foo {
public:
Foo() {
calls[0] = &Foo::call0;
calls[1] = &Foo::call1;
calls[2] = &Foo::call2;
calls[3] = &Foo::call3;
}
void call(int number, int arg) {
assert(number < 4);
(this->*(calls[number]))(arg);
}
void call0(int arg) {
cout<<"call0("<<arg<<")... | What is the cost of using a pointer to member function vs. a switch? | [
"",
"c++",
"function-pointers",
""
] |
Are the string literals we use inside functions automatic variables? Or are they allocated in heap which we have to free manually?
I've a situation like the code shown below wherein I'm assigning a string literal to a private field of the class (marked as ONE in the code) and retrieving it much later in my program and... | String literals will be placed in the initialized data or text (code) segment of your binary by the compiler, rather than residing in (runtime allocated) memory or the stack. So you should be using a pointer, since you're going to be referencing the string literal that the compiler has already produced for you. Note th... | It is undefined behaviour to modify a string literal, and is most likely the cause of the crash in your program (ISO C++: 2.13.4/2). The standard allows for a conversion from a string literal to `char*` for backwards compatibility to C and you should only have that conversion in your code if you absolutely need it.
If... | String literals inside functions: automatic variables or allocated in heap? | [
"",
"c++",
"c",
"memory",
"memory-management",
"memory-leaks",
""
] |
What is the most efficient way to clone a JavaScript object? I've seen `obj = eval(uneval(o));` being used, but [that's non-standard and only supported by Firefox](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval).
I've done things like `obj = JSON.parse(JSON.stringify(o));`... | # Native deep cloning
There's now a JS standard called ["structured cloning"](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), that works experimentally in Node 11 and later, will land in browsers, and which has [polyfills for existing systems](https://www.npmjs.com/package/@ungap/structured-clone).
... | Checkout this benchmark: <http://jsben.ch/#/bWfk9>
In my previous tests where speed was a main concern I found
```
JSON.parse(JSON.stringify(obj))
```
to be the slowest way to deep clone an object (it is slower than [jQuery.extend](https://api.jquery.com/jQuery.extend/) with `deep` flag set true by 10-20%).
jQuery.... | What is the most efficient way to deep clone an object in JavaScript? | [
"",
"javascript",
"object",
"clone",
""
] |
I want to filter a `java.util.Collection` based on a predicate. | Java 8 ([2014](https://www.oracle.com/java/technologies/javase/8-whats-new.html "What's New in JDK 8")) solves this problem using streams and lambdas in one line of code:
```
List<Person> beerDrinkers = persons.stream()
.filter(p -> p.getAge() > 16).collect(Collectors.toList());
```
Here's a [tutorial](http://zer... | Assuming that you are using [Java 1.5](http://java.sun.com/j2se/1.5.0/docs/index.html), and that you cannot add [Google Collections](https://code.google.com/p/guava-libraries/), I would do something very similar to what the Google guys did. This is a slight variation on Jon's comments.
First add this interface to your... | How to filter a Java Collection (based on predicate)? | [
"",
"java",
"collections",
"filter",
""
] |
What is the best way to handle a big team that has access to a stable but no so pretty code, that is easy to introduce bugs into?
I'm looking for something along the lines of SVN locking the file(s). | Write unit tests if you don't have them already. Then start refactoring, and keep doing regression tests upon every commit. | Tell them to leave it alone.
It works, what is the benefit of changing it other than prettying it up (and the potential cost is high) so you just need to explain the cost/benefit analysis.
I would hope your developers would be smart enough to understand this and, if not, you can use your source code control system lo... | how to handle code that is deemed dangerous to change, but stable? | [
"",
"c++",
"svn",
"refactoring",
""
] |
My C(++) program, written and compiled using Visual C(++)/Visual Studio, runs fine on my own machine, but refuses to run on another machine. The error message I get is "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem." | If you write a C++ program, it links dynamically to the C Runtime Library, or CRT for short. This library contains your printf, your malloc, your strtok, etcetera. The library is contained in the file called MSVCR80.DLL. This file is not by default installed on a Windows system, hence the application cannot run.
The s... | The problem here is a missing DLL dependency, such as the CRT (C Runtime Library). A good tool for diagnosing this sort of problem is Dependency Walker (depends.exe), which you can find here:
<http://www.dependencywalker.com/>
You would run this program on the computer that generates the error message you posted, and... | Visual C++/Studio: Application configuration incorrect? | [
"",
"c++",
"c",
"visual-studio",
"visual-c++",
""
] |
I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way?
For example, the format could be described as:
```
<Field1(8)><Field2(16)><Field3(12)>
```
And an example file with two record... | Substring sounds good to me. The only downside I can immediately think of is that it means copying the data each time, but I wouldn't worry about that until you prove it's a bottleneck. Substring is simple :)
You *could* use a regex to match a whole record at a time and capture the fields, but I think that would be ov... | Use [FileHelpers](http://www.filehelpers.net/).
Example:
```
[FixedLengthRecord()]
public class MyData
{
[FieldFixedLength(8)]
public string someData;
[FieldFixedLength(16)]
public int SomeNumber;
[FieldFixedLength(12)]
[FieldTrim(TrimMode.Right)]
public string someMoreData;
}
```
Then, it's a... | Read fixed width record from text file | [
"",
"c#",
".net",
"parsing",
"fixed-width",
""
] |
I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example:
```
a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy
```
I would like to calculate the width of text server-sid... | This would not only be impossible to do server-side, it would also not make sense. You don't what browser your client will be using, and you don't know what font settings on the client side will override whatever styling information you assign to a piece of HTML. You might think that you're using absolute positioning p... | How about overflow: scroll? | Rendered pIxel width data for each character in a browser's font | [
"",
"javascript",
"jquery",
"html",
"css",
"font-size",
""
] |
Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a `SetFont()` call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and wxPython In Action book don't discuss this.
Is there a way to easily apply the same `S... | You can do this by calling SetFont on the parent window (Frame, Dialog, etc) before adding any widgets. The child widgets will inherit the font. | Maybe try subclassing the text object and in your class `__init__` method just call SetFont()?
Or, do something like:
```
def f(C):
x = C()
x.SetFont(font) # where font is defined somewhere else
return x
```
and then just decorate every text object you create with with it:
```
text = f(wx.StaticText)
```
(of... | Applying a common font scheme to multiple objects in wxPython | [
"",
"python",
"fonts",
"wxpython",
""
] |
I saw this quote on the question: [What is a good functional language on which to build a web service?](https://stackoverflow.com/questions/105710)
> Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental lim... | This post: [Recursion or Iteration?](https://stackoverflow.com/questions/72209/recursion-or-loop#72522) might help.
In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would ... | The fundamental limitation is simply that the JVM does not provide tail calls in its byte code and, consequently, there is no direct way for a language built upon the JVM to provide tail calls itself. There are workarounds that can achieve a similar effect (e.g. trampolining) but they come at the grave cost of awful pe... | Does the JVM prevent tail call optimizations? | [
"",
"java",
"jvm",
"scala",
"tail-recursion",
""
] |
Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ...
Does multiple inheritance slow down a class? | Non-virtual function-calls have absolutely no performance hit at run-time, in accordance with the c++ mantra that you shouldn't pay for what you don't use.
In a virtual function call, you generally pay for an extra pointer lookup, no matter how many levels of inheritance, or number of base classes you have.
Of course t... | [Deep inheritance hierarchies] greatly increases the maintenance burden by adding unnecessary complexity, forcing users to learn the interfaces of many classes even when all they want to do is use a specific derived class. It can also have an impact on memory use and program performance by adding unnecessary vtables an... | Does several levels of base classes slow down a class/struct in c++? | [
"",
"c++",
"oop",
""
] |
*UPDATE: Focus your answers on hardware solutions please.*
What hardware/tools/add-in are you using to improve ASP.NET compilation and first execution speed? We are looking at solid state hard drives to speed things up, but the prices are really high right now.
I have two 7200rpm harddrives in RAID 0 right now and I'... | One of the important things to do is keeping projects of not-so-often changed assemblies unloaded. When a change occurs, load it, compile and unload again. It makes huge differences in large solutions. | First make sure your that you are using [Web Application Projects](http://msdn.microsoft.com/en-us/asp.net/aa336618.aspx) (WAP). In our experience, compared to Website Projects, WAP compiles roughly 10x faster.
Then, consider migrating all the logic (including complex UI components) into separate library projects. The... | What is the best way to improve ASP.NET/C# compilation speed? | [
"",
"c#",
".net",
"asp.net",
""
] |
I work on a large C# application (approximately 450,000 lines of code), we constantly have problems with desktop heap and GDI handle leaks. WPF solves these issues, but I don't know what is the best way to upgrade (I expect this is going to take a long time). The application has only a few forms but these can contain m... | You can start by creating a WPF host.
Then you can use the <WindowsFormHost/> control to host your current application. Then, I suggest creating a library of your new controls in WPF. One at a time, you can create the controls (I suggest making them custom controls, not usercontrols). Within the style for each control... | Do you use a lot of User controls for the pieces? WPF can host winform controls, so you could piecewise bring in parts into the main form. | What is the easiest way to upgrade a large C# winforms app to WPF | [
"",
"c#",
".net",
"wpf",
"upgrade",
""
] |
I wrote C++ for 10 years. I encountered memory problems, but they could be fixed with a reasonable amount of effort.
For the last couple of years I've been writing C#. I find I still get lots of memory problems. They're difficult to diagnose and fix due to the non-determinancy, and because the C# philosophy is that yo... | I use Scitech's [MemProfiler](http://memprofiler.com/) when I suspect a memory leak.
So far, I have found it to be very reliable and powerful. It has saved my bacon on at least one occasion.
The GC works very well in .NET IMO, but just like any other language or platform, if you write bad code, bad things happen. | Just for the forgetting-to-dispose problem, try [the solution described in this blog post](http://www.interact-sw.co.uk/iangblog/2004/03/23/locking). Here's the essence:
```
public void Dispose ()
{
// Dispose logic here ...
// It's a bad error if someone forgets to call Dispose,
// so... | What strategies and tools are useful for finding memory leaks in .NET? | [
"",
"c#",
".net",
"memory-management",
"memory-leaks",
""
] |
Let's say I have code like this:
```
$dbh = new PDO("blahblah");
$stmt = $dbh->prepare('SELECT * FROM users where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
```
The PDO documentation says:
> The parameters to prepared statements don't need to be quoted; the driver handles... | The short answer is **YES**, PDO prepares are secure enough if used properly.
---
I'm adapting [this answer](https://stackoverflow.com/a/12118602/338665) to talk about PDO...
The long answer isn't so easy. It's based off an attack [demonstrated here](http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-esc... | Prepared statements / parameterized queries are sufficient to prevent SQL injections, but only when used all the time, for the every query in the application.
If you use un-checked dynamic SQL anywhere else in an application it is still vulnerable to *2nd order* injection.
2nd order injection means data has been cycl... | Are PDO prepared statements sufficient to prevent SQL injection? | [
"",
"php",
"security",
"pdo",
"sql-injection",
""
] |
Are there any good configuration file reading libraries for C\C++ that can be used for applications written on the linux platform. I would like to have a simple configuration file for my application. At best i would like to steer clear of XML files that might potentially confuse users. | You could try [glib's key-value-file-parser](http://library.gnome.org/devel/glib/unstable/glib-Key-value-file-parser.html) | I would recommend '[libconfig](http://www.hyperrealm.com/libconfig/)'. | Linux configuration file libraries | [
"",
"c++",
"c",
"linux",
"configuration",
"file",
""
] |
I'd like to get at least one JRE/JDK level on my Windows machine where I have the JRE/JDK source that matches the exact level of the JRE/JDK. My purpose is to be able to go into the system classes while debugging. Any suggestions about how to do this? Thanks in advance. | Most of the useful source will be in the src.zip file in your JDK.
You can get source up to jdk 6u3 from [jdk6.dev.java.net](https://jdk6.dev.java.net/). On Linux you can get OpenJDK source and packages from [openjdk.java.net](http://openjdk.java.net/). | I had this problem for a long time; the source-download site must just not have been maintained for a while there.
It seems fixed now, though:
<http://download.java.net/jdk6/6u10/archive/>
(Has links for all the JDK 6 source downloads, not just 6u10.) | How to get JRE/JDK with matching source? | [
"",
"java",
""
] |
I have a Windows Form app written in C#. Its job is to send messages to a list of users. While those messages are being sent, I'd like to display status of the operation for each user. What I am doing (for each user) is creating a Label control and adding it to Panel. This works without a problem for a small set of use... | Given the size, I would consider displaying your status in a RichTextBox.
What is happening is that you are generating too many handles and the Framework can't handle them all. | Use DataGridView instead | Trouble when adding a lot of Controls to a .NET Windows Form (C#) | [
"",
"c#",
"winforms",
""
] |
Here's the very dumb way:
```
def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
```
The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)
I can find prime factors and their multiplicity fast enough.
... | Given your `factorGenerator` function, here is a `divisorGen` that should work:
```
def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
... | To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do `n / i`, and this will cover the whole problem space.
As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for gu... | What is the best way to get all the divisors of a number? | [
"",
"python",
"algorithm",
"math",
""
] |
I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:
1. No directories. JUST the file name.
2. File name needs to be all lowercase.
3. Whitespaces need to be replaced with underscores.
Shouldn't be hard, but I'... | And a simple combination of RegExp and other javascript is what I would recommend:
```
var a = "c:\\some\\path\\to\\a\\file\\with Whitespace.TXT";
a = a.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1");
a = a.replace(/\s/g,"_");
a = a.toLowerCase();
alert(a);
``` | If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at <http://regexlib.com/>.
Edit to say: [Here's one that might work for you](http://regexlib.com/REDetails.aspx?regexp_id=1934):
```
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
``` | What's the (JavaScript) Regular Expression I should use to ensure a string is a valid file name? | [
"",
"javascript",
"regex",
"filenames",
""
] |
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.
[Here's a good discussion](http://wiki.wxpython.org/LongRunningTasks) of how to do this in wxPython. To summarize, there are 3 ways:
1. Use threads
2. Use wxYield
3. Chunk the work an... | Threads. They're what I always go for because you can do it in every framework you need.
And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks. | Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple... | Keeping GUIs responsive during long-running tasks | [
"",
"python",
"user-interface",
"wxpython",
""
] |
I am looking to use a PHP library for uploading pictures to a web server so that I can use something that has been tested and hopefully not have to design one myself. Does anyone know of such a library?
Edit: I am aware that file uploads are built into PHP, I am looking for a library that may make the process simpler ... | I personally use [HTTP\_Upload](http://pear.php.net/package/HTTP_Upload) from PEAR. It works pretty well for our purposes (uplaoding media files into a development system and uploading arbitrary files for an educational system) | The cunningly name [upload class](http://www.verot.net/php_class_upload.htm) is very good and has a very responsive and supportive developer. Apart from uploading, it also has built-in support for lots of common image functions. | What is a good PHP library to handle file uploads? | [
"",
"php",
"file-upload",
""
] |
I would like to save data in cookies (user name, email address, etc...) but I don't the user to easily read it or modify it. I need to be able able to read the data back. How can I do that with php 5.2+?
It would be used for "welcome back bob" kind of feature. It is not a replacement for persistence or session storage... | We use mcrypt in our projects to achieve encryption. Below is a code sample based on content found on the internet:
```
<?php
class MyProjCrypt {
private $td;
private $iv;
private $ks;
private $salt;
private $encStr;
private $decStr;
/**
* The constructor initializes the cryptograp... | I suggest you not only encrypt but also sign the data. If you don't sign the data, you won't be able to tell reliably whether the user modified the data. Also, to avoid replay you may want to add some timestamp/validity period information into the data. | How to save encrypted data in cookie (using php)? | [
"",
"php",
"security",
"encryption",
"cookies",
""
] |
I miss it so much (used it a lot in C#). can you do it in C++? | Yes, you can. See [here](http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx).
```
#pragma region Region_Name
//Your content.
#pragma endregion Region_Name
``` | The Visual assist add-in for VC supports regions for c++. Don't know if 2008 has build in regions for C++ though. | Can you create collapsible #Region like scopes in C++ within VS 2008? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"pragma",
"readability",
""
] |
What's the best way to get a string containing a folder name that I can be certain does **not** exist? That is, if I call `DirectoryInfo.Exists` for the given path, it should return false.
EDIT: The reason behind it is I am writing a test for an error checker, the error checker tests whether the path exists, so I wond... | Name it after a GUID - just take out the illegal characters. | There isn't really any way to do precisely what you way you want to do. If you think about it, you see that even after the call to `DirectoryInfo.Exists` has returned false, some other program could have gone ahead and created the directory - this is a race condition.
The normal method to handle this is to create a ne... | What's the best way to get the name of a folder that doesn't exist? | [
"",
"c#",
"directory",
""
] |
I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.
I don't know if it depends on the technologies used, but I'll use Tomcat 5.5
---
I want to share a ... | I think what you're looking for here is request, session or application data.
In a servlet you can add an object as an attribute to the request object, session object or servlet context object:
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String shared = "shared";
reque... | Put it in one of the 3 different scopes.
request - lasts life of request
session - lasts life of user's session
application - lasts until applciation is shut down
You can access all of these scopes via the HttpServletRequest variable that is passed in to the methods that extend from the [HttpServlet class](http://j... | How can I share a variable or object between two or more Servlets? | [
"",
"java",
"web-applications",
"servlets",
""
] |
I've been searching around, and I haven't found how I would do this from C#.
I was wanting to make it so I could tell Google Chrome to go **Forward**, **Back**, **Open New Tab**, **Close Tab**, **Open New Window**, and **Close Window** from my C# application.
I did something similar with WinAmp using
```
[DllImport(... | Start your research at <http://dev.chromium.org/developers>
---
**EDIT**: Sending a message to a window is only half of the work. The window has to respond to that message and act accordingly. If that window doesn't know about a message or doesn't care at all you have no chance to control it by sending window message... | You can get the window name easily using Visual Studio's Spy++ and pressing CTRL+F, then finding chrome. I tried it and got
"Chrome\_VistaFrame" for the out window. The actual window with the webpage in is "Chrome\_RenderWidgetHostHWND".
As far as WM\_COMMAND goes - you'll need to experiment. You'll obviously want to... | C# - Sending messages to Google Chrome from C# application | [
"",
"c#",
"google-chrome",
"message",
""
] |
Consider a *hypothetical* method of an object that does stuff for you:
```
public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.CancelAsync();
//todo: Figure out a way to wait for BackgroundWorker to be cancelled.
... | If I understand your requirement right, you could do something like this (code not tested, but shows the general idea):
```
private BackgroundWorker worker = new BackgroundWorker();
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
worker.DoWork += worker... | There is a problem with [this](https://stackoverflow.com/questions/123661/net-how-to-wait-for-a-backgroundworker-to-complete#123791) response. The UI needs to continue to process messages while you are waiting, otherwise it will not repaint, which will be a problem if your background worker takes a long time to respond... | How to wait for a BackgroundWorker to cancel? | [
"",
"c#",
".net",
"multithreading",
"backgroundworker",
""
] |
At the moment we use [HSQLDB](http://www.hsqldb.org/) as an embedded database, but we search for a database with less memory footprint as the data volume grows.
[Derby / JavaDB](http://developers.sun.com/javadb/) is not an option at the moment because it stores properties globally in the system properties. So we thoug... | From the download, I see that the file tutorial.html has this
```
import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
``` | Yes, you can run H2 in embedded mode. You just use the JDBC driver and connect to an embedded url like this (their example):
> This database can be used in embedded
> mode, or in server mode. To use it in
> embedded mode, you need to:
>
> ```
> * Add h2.jar to the classpath
> * Use the JDBC driver class: org.h2.Driver... | Embedding the Java h2 database programmatically | [
"",
"java",
"database",
"embedding",
"h2",
""
] |
I am trying to read an Http response stream twice via the following:
```
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
RssReader reader = new RssReader(stream);
do
{
element = reader.Read();
if (element is RssChannel)
{
feed.Channels.Add((RssChannel... | Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like:
```
Stream responseStream = CopyAndClose(resp.GetResponseStream());
// Do something with the stream
responseStream.Position = 0;
// Do something with the stream again
private static Stream CopyAndClose(Stream inpu... | Copying the stream to a [MemoryStream](https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream?view=netframework-4.0) as suggested by [Iain](https://stackoverflow.com/a/147961/2484903) is the right approach. But since
.NET Framework 4 (released 2010) we have [Stream.CopyTo](https://learn.microsoft.com/en-us... | How can I read an Http response stream twice in C#? | [
"",
"c#",
"stream",
""
] |
When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them.
How do you keep everything manageable? | My advice:
* Read [Installing Python Modules](http://docs.python.org/install/index.html).
* Read [Distributing Python Modules](http://docs.python.org/distutils/index.html).
* Start using easy\_install from [setuptools](http://peak.telecommunity.com/DevCenter/setuptools). Read the documentation for setuptools.
* Always... | In addition to PEP8 and easy\_install, you should check out virtualenv. Virtualenv allows you to have multiple different python library trees. At work, we use virtualenv with a bootstrapping environment to quickly set up a development/production environment where we are all in sync w.r.t library versions etc. We genera... | How do you organize Python modules? | [
"",
"python",
"module",
""
] |
We run a medium-size site that gets a few hundred thousand pageviews a day. Up until last weekend we ran with a load usually below 0.2 on a virtual machine. The OS is Ubuntu.
When deploying the latest version of our application, we also did an apt-get dist-upgrade before deploying. After we had deployed we noticed tha... | The answer ended up being not-Apache related. As mentioned, we were on a virtual machine. Our user sessions are pretty big (think 500kB per active user), so we had a lot of disk IO. The disk was nearly full, meaning that Ubuntu spent a lot of time moving things around (or so we think). There was no easy way to extend t... | Seeing an accept() call from your Apache process isn't at all unusual - that's the webserver waiting for a new request.
First of all, you want to establish what the parameters of the load are. Something like
```
vmstat 1
```
will show you what your system is up to. Look in the 'swap' and 'io' columns. If you see any... | Apache uses excessive CPU | [
"",
"php",
"mysql",
"performance",
"apache",
""
] |
For example, I rarely need:
```
using System.Text;
```
but it's always there by default. I assume the application will use more memory if your code contains unnecessary [using directives](http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx). But is there anything else I should be aware of?
Also, does it mak... | It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference... | There **are** few reasons for removing unused using(s)/namespaces, besides coding preference:
* removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where ... | Why should you remove unnecessary C# using directives? | [
"",
"c#",
"assemblies",
"using",
""
] |
My client has a multi-page PDF file. They need it split by page. Does anyone know of a way to do this - preferably in C#. | [PDFSharp](http://www.pdfsharp.com/) is an open source library which may be what you're after:
> Key Features
>
> * Creates PDF documents on the fly from any .Net language
> * Easy to understand object model to compose documents
> * One source code for drawing on a PDF page as well as in a window or on the printer
> *... | I did this using [ITextSharp](http://itextsharp.sourceforge.net) -- there are commercial options that may have a good API but this is open source and free, and not hard to use.
Check out [this code](http://itextsharp.sourceforge.net/examples/Split.cs), it's one of their code samples -- it's pretty good. It splits a PD... | How can I split up a PDF file into pages (preferably C#) | [
"",
"c#",
"pdf",
""
] |
I'm a big fan of the Jadclipse plugin and I'd really like to upgrade to Eclipse 3.4 but the plugin currently does not work. Are there any other programs out there that let you use jad to view source of code you navigate to from Eclipse? (Very useful when delving into ambiguous code in stack traces). | I'm successfully using JadClipse with Eclipse 3.4
Eclipse 3.4.0.I20080617-2000
JadClipse 3.3.0
It just works!
EDIT:
Actually, see [OlegSOM's answer](https://stackoverflow.com/questions/122110/is-there-a-way-to-get-jadclipse-working-with-eclipse-3-4/224779#224779) below for the additional steps that you might need ... | Read attentively the documentation ... :
1. The JadClipse plug-in is not activated when I start Eclipse.
You'll need to launch Eclipse with the -clean flag to allow the
environment to detect the plug-in. Subsequent launching of
Eclipse won't require the -clean flag.
**eclipse -clean**
2. The Eclipse Class ... | Is there a way to get jadclipse working with Eclipse 3.4? | [
"",
"java",
"eclipse",
"plugins",
"eclipse-plugin",
"jad",
""
] |
If I safe an Array and reload it, is there a possibility to get the size if its unknown?
Thanks | It sounds like you're serializing and storing the individual objects in the array (after much reading between the lines). Use the ObjectOutputStream to store the array itself. If the objects stored in the array are serializable, they'll be stored too. When you deserialize you'll get the entire array back intact. | What do you mean by "unknown"? You can get the length of any java array with the length field.
```
int[] myArray = deserializeSomeArray();
int size = myArray.length;
``` | Java: Serializing unknown Arraysize | [
"",
"java",
"serialization",
"objectsize",
""
] |
I am creating an RSS reader as a hobby project, and at the point where the user is adding his own URL's.
I was thinking of two things.
* A plaintext file where each url is a single line
* SQLite where i can have unique ID's and descriptions following the URL
Is the SQLite idea to much of an overhead or is there a be... | What about as an [OPML](http://en.wikipedia.org/wiki/Opml) file? It's XML, so if you needed to store more data then the OPML specification supplies, you can always add your own namespace.
Additionally, importing and exporting from other RSS readers is all done via OPML. Often there is library support for it. If you're... | Why not XML?
If you're dealing with RSS anyway you mayaswell :) | Best way to store urls locally | [
"",
"c#",
"sqlite",
"plaintext",
""
] |
When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question.
I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look... | Use the *svnversion* command in your Ant script to get the revision number:
```
<exec executable="svnversion" outputproperty="svnversion" failonerror="true">
<env key="path" value="/usr/bin"/>
<arg value="--no-newline" />
</exec>
```
Then use the *${svnversion}* property somewhere in your EAR. We put it in the EA... | You'd want to provide the Subversion branch and repository number. As discussed in [How to access the current Subversion build number?](https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number), the `svn info` command will give you this information, which you can then use to build a ... | How best to store Subversion version information in EAR's? | [
"",
"java",
"svn",
"ant",
"release",
""
] |
I want to output the function name each time it is called, I can easily copy and paste the function name, however I wondered if there was a shortcut that would do the job for me?
At the moment I am doing:
```
SlideInfoHeader* lynxThreeFile::readSlideInfoHeader(QDataStream & in)
{
qDebug("lynxThreeFile::readSlideI... | "`__FUNCTION__`" is supported by both MSVC and GCC and should give you the information you need. | I see from your example that you are using [Qt](http://qt.nokia.com/). In which case your best bet is to use `Q_FUNC_INFO` found in `<QGlobal>`. Here's the description:
> Expands to a string that describe the
> function the macro resides in. How
> this string looks more specifically is
> compiler dependent. With GNU G... | How to get the function name while in a function for debug strings? | [
"",
"c++",
"debugging",
"qt",
""
] |
[Python for Unix and Linux System Administration](http://oreilly.com/catalog/9780596515829/) is aimed at sysadmins.
Any other favorites besides this. | Mark Pilgrim's <http://www.diveintopython.net/> is very good and clear. | First, you can start off the learn the basics of Python at Python documentation Index. Also of interest there would be the tutorial, library references. For sysadmin, some of the libraries you can use are , to name a few
1. shutil (moving/copying files)
2. os eg
os.walk() -> recursive directories looking for files ... | Which Python book would you recommend for a Linux Sysadmin? | [
"",
"python",
"linux",
"system-administration",
""
] |
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?
So something that would yield this kind of translation table:
```
\r --> \r\n
\n --> \r\n
\n\n --> \r... | I believe this will do what you need:
```
using System.Text.RegularExpressions;
// ...
string normalized = Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n");
```
I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct... | I'm with Jamie Zawinski on RegEx:
"Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems"
For those of us who prefer readability:
* Step 1
Replace \r\n by \n
Replace \n\r by \n (if you really want this, some posters seem to think not)
Replace \... | Normalize newlines in C# | [
"",
"c#",
".net",
""
] |
I'm trying to have my Struts2 app redirect to a generated URL. In this case, I want the URL to use the current date, or a date I looked up in a database. So `/section/document` becomes `/section/document/2008-10-06`
What's the best way to do this? | Here's how we do it:
In Struts.xml, have a dynamic result such as:
```
<result name="redirect" type="redirect">${url}</result>
```
In the action:
```
private String url;
public String getUrl()
{
return url;
}
public String execute()
{
[other stuff to setup your date]
url = "/section/document" + date;
return "... | One can also use `annotations` and the Convention plug-in to avoid repetitive configuration in struts.xml:
```
@Result(location="${url}", type="redirect")
```
The ${url} means "use the value of the getUrl method" | How to do dynamic URL redirects in Struts 2? | [
"",
"java",
"url",
"redirect",
"struts2",
""
] |
OK, first let me state that I have never used this control and this is also my first attempt at using a web service.
My dilemma is as follows. I need to query a database to get back a certain column and use that for my autocomplete. Obviously I don't want the query to run every time a user types another word in the te... | Why not keep track of the query executed by the user in a session variable, then use that to filter any further results?
The trick to preventing the database from overloading I think is really to just limit how frequently the auto updater is allowed to update, something like once per 2 seconds seems reasonable to me.
... | This question depends upon how transactional your data store is. Obviously if you are looking for US states (a data collection that would not change realistically through the life of the application) then I would either cache a System.Collection.Generic List<> type or if you wanted a DataTable.
You could easily set up... | Ajax autocomplete extender populated from SQL | [
"",
"sql",
"ajax",
""
] |
I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect `SERVER['argc']`, but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API. | Use the [`php_sapi_name()`](http://php.net/php_sapi_name) function.
```
if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
```
Here are some relevant notes from the docs:
> **php\_sapi\_name** — Returns the type of interface between web server and PHP
>
> Although not exhaustive, th... | This will always work. (If the PHP version is 4.2.0 or higher)
```
define('CLI', PHP_SAPI === 'cli');
```
Which makes it easy to use at the top of your scripts:
```
<?php PHP_SAPI === 'cli' or die('not allowed');
``` | What is the canonical way to determine commandline vs. http execution of a PHP script? | [
"",
"php",
"http",
"command-line",
"command-line-interface",
""
] |
This is a question you can read everywhere on the web with various answers:
```
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = c... | People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet [`pathinfo()`](http://php.net/manual/en/function.pathinfo.php):
```
$ext = pathinfo($filena... | [`pathinfo()`](http://uk.php.net/manual/en/function.pathinfo.php)
```
$path_info = pathinfo('/foo/bar/baz.bill');
echo $path_info['extension']; // "bill"
``` | How can I get a file's extension in PHP? | [
"",
"php",
"file-extension",
""
] |
I knew I should never have started using c++ io, the whole "type safety" argument is a red herring (does anyone *really* find that it's one of their most pressing problems?). Anyhow, I did, and discovered a strange difference between ifstreams and FILE\*s and plain old file descriptors: ifstreams cannot read from a dev... | The device is unbuffered and must be read from in 512 byte multiples. ifstream does it's own buffering and strangely decided to read *1023* bytes ahead, which fails with "Invalid argument". Interestingly, this ifstream is implemented on top of a FILE\*. However, FILE\* left to its own devices was reading ahead using a ... | Works fine for me, its not a problem inherent to c++ stream file I/O as you seem to think.
Maybe try adding `ios::in` to the openmode flags. According to 27.8.1.6 of the standard, it is required to or with ios::in so this probably won't do anything.
Try checking which bit is actually set - instead of calling good(), ... | Why can't c++ ifstreams read from devices? | [
"",
"c++",
"macos",
"gcc",
"fstream",
""
] |
When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:
```
namespace Lib {
class A {
};
A operator+(const A&, const A&)... | You should define them in the library namespace.
The compiler will find them anyway through argument dependant lookup.
No need to pollute the global namespace. | Putting it into the library namespace works because of [Koenig lookup](http://en.wikipedia.org/wiki/Argument_dependent_name_lookup). | Namespaces and Operator Overloading in C++ | [
"",
"c++",
"operator-overloading",
"namespaces",
""
] |
One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:
```
self.__value = 1
def value():
return self.__value
```
Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to si... | Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '\_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '\_\_value' attribute, the attribute is actually being stored as '`_ContainerThing__value`'. Ch... | "I know this seems to go against the general idea of private and public" Not really "against", just different from C++ and Java.
Private -- as implemented in C++ and Java is not a very useful concept. It helps, sometimes, to isolate implementation details. But it is way overused.
Python names beginning with two `__` ... | Subclassing a class with private members | [
"",
"python",
"oop",
"encapsulation",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.