Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
This may not really sound hard to do but it is currently killing me. Currently i have a Visual Studio 2008 C# Project that i use in conjunction with a DAL generator , its nothing fancy at all besides generating files that i can use in the project to access the database.
The problem i am having is that after the genera... | In VS2008:
1) Right click on your project node.
2) Select "Unload project".
3) Right click on the project node.
4) Select "Edit foo.csproj"
5) In the element add a element that includes your DAL files using wildcards like:
```
<Compile Include="DAL_*.cs" />
```
or
```
<Compile Include="DataAccessLayer\*.cs" />
... | I suppose the easiest way would be to write a tool to automatically modify the .csproj file, which is just XML, so that it includes your new items. | Auto Include Files In A C# Project | [
"",
"c#",
"windows",
"visual-studio-2008",
""
] |
If you haven't read the [first](https://stackoverflow.com/questions/510138/programming-skill-tester-problem) problem do so know to catch up to speed. Now then, how do I go about clearing these check boxes? I tried using the same approach that @colithium told me to use for checking the state of all the check boxes, but ... | I assume your method looks something like this:
```
private void clearButton_Click(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
cb.Checked = false;
}
```
In this case, the "Sender" is the clear button, not a check box.
Borrowing from Stormenet's answer:
```
private void clearButton_c... | I am guessing you are running a foreach over all your controls and forgot to look if the control is actually a checkbox.
```
foreach (Control c in this.Controls) {
CheckBox cb = c as CheckBox;
if (cb!=null) {
//do your logic
}
}
``` | Programming Skill Tester (Problem) v2.0 | [
"",
"c#",
"winforms",
""
] |
I am using MySQL and PHP. I have a table that contains the columns id and quantity. I would like to retrieve the id of the row that is the last to sum quantity as it reaches the number 40 at sum. To be more specific. I have 3 rows in the database. One with quantity 10, one with quantity 30 and one with quantity 20. So ... | I don't understand your question too well. Can you try rewording it more properly? From what I interpret, here's the structure of your database:
```
ProductID ArrivalDate
1 10
2 11
3 11
4 11
5 12
6 12
```
Now you are asking, "how would I know ... | Have a third column with a running total. Then you can simply return the last row where the running total <= your target value.
So your table should look like:
```
ID Quantity RunningTotal
1 10 10
2 30 40
3 20 60
```
NOTE: If you delete a row... | MySQL select records that sums | [
"",
"php",
"mysql",
"sum",
""
] |
What's the best way to discover a file's filetype within php? I heard that the browser may be tricked, so what's a better way of doing this? | You can use [finfo\_file](http://www.php.net/manual/en/function.finfo-file.php)
```
<?php
echo finfo_file(finfo_open(FILEINFO_MIME), "foo.png");
?>
``` | Look at "magic numbers." The first few bytes of files usually identify what type of file it is. For example, the firts few bytes of a GIF are either 47 49 46 38 37 61 or 47 49 46 38 39 61, ASCII for GIF89a or GIF87a. There are many other "magic numbers." See <http://en.wikipedia.org/wiki/Magic_number_(programming)#Magi... | Best way to recognize a filetype in php | [
"",
"php",
"file-type",
""
] |
I want to be able to run a regular expression on an entire file, but I'd like to be able to not have to read the whole file into memory at once as I may be working with rather large files in the future. Is there a way to do this? Thanks!
**Clarification:** I cannot read line-by-line because it can span multiple lines. | You can use mmap to map the file to memory. The file contents can then be accessed like a normal string:
```
import re, mmap
with open('/var/log/error.log', 'r+') as f:
data = mmap.mmap(f.fileno(), 0)
mo = re.search('error: (.*)', data)
if mo:
print "found error", mo.group(1)
```
This also works for big fi... | This depends on the file and the regex. The best thing you could do would be to read the file in line by line but if that does not work for your situation then might get stuck with pulling the whole file into memory.
Lets say for example that this is your file:
```
Lorem ipsum dolor sit amet, consectetur
adipiscing e... | How do I re.search or re.match on a whole file without reading it all into memory? | [
"",
"python",
"regex",
"performance",
"file",
""
] |
Are there inexpensive or free gateways from .NET to Java? I'm looking at some data acquisition hardware which has drivers for C/C++ and .NET -- I *really* don't want to do any programming in .NET.
Update: I haven't done what I originally wanted to do, but I've done something similar, using JNA to encapsulate some func... | You could also try to use [JNA](https://github.com/twall/jna) for accessing the native library. JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. If their API is fairly straight foward, this might be the path of ... | Well, there's [JNBridge](http://www.jnbridge.com/index.htm) and [EZ JCom](http://www.ezjcom.com/dotnet.html), just from a Google search.
You could also use [IKVM](http://www.ikvm.net/) which is a slightly different approach.
(Any reason for not wanting to learn .NET, out of interest? It's a nice platform, and C# is a... | Accessing .NET/dll libraries/components from Java? | [
"",
"java",
".net",
""
] |
How expensive is it to create gdi brushes and pens? Should I create them on an add needed basis and wrap them in a using so they are disposed quickly, or should I create a static class similar to System.Drawing.Brushes class? | IMO, they're efficient enough that you should usually not create long-lived instances that are used over several method calls, but inefficient enough that you should create each one only once within a particular method, instead of creating a new one each time you need to draw something.
In other words, don't store a c... | I've encountered exceptions when trying to custom draw images in a web application under load with a static brush.
I don't know the technical reasons, but I think Brushes and Pens are not thread safe, so I would create them as needed in a thread-safe manner and dispose of them within that scope, probably with a *using... | Guidelines for Using Brushes and Pens | [
"",
"c#",
".net",
"gdi",
""
] |
In My Asp.net webpage I need to display today's date into one of the textbox , so in my form load I wrote the following code
```
textbox1.text = System.DateTime.Today.ToShortDateString();
```
this line is giving me date like 1/7/09 but I want date like 01/07/09 , Is there anyway I can conver this date into mm/dd/yy f... | ```
DateTime.Today.ToString("MM/dd/yy")
```
Look at the docs for [custom date and time format strings](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole ... | > DateTime.Today.ToString("MM/dd/yy")
>
> Look at the docs for custom date and time format strings for more info.
>
> (Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to... | How to Convert date into MM/DD/YY format in C# | [
"",
"c#",
"date",
""
] |
Say I have an interface `IFoo` and I want all subclasses of `IFoo` to override Object's `ToString` method. Is this possible?
Simply adding the method signature to IFoo as such doesn't work:
```
interface IFoo
{
String ToString();
}
```
since all the subclasses extend `Object` and provide an implementation that w... | I don't believe you can do it with an interface. You can use an abstract base class though:
```
public abstract class Base
{
public abstract override string ToString();
}
``` | ```
abstract class Foo
{
public override abstract string ToString();
}
class Bar : Foo
{
// need to override ToString()
}
``` | Force subclasses of an interface to implement ToString | [
"",
"c#",
"oop",
""
] |
Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:
[getch()-like unbuffered character reading from stdin on both Windows and Unix](https://code.activestate.com/recipes/134892/)
```
class _Getch:
"""Gets a single character from standard input. Do... | ```
sys.stdin.read(1)
```
will basically read 1 byte from STDIN.
If you must use the method which does not wait for the `\n` you can use this code as suggested in previous answer:
```
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
tr... | How to read a single character from the user? | [
"",
"python",
"input",
""
] |
I have a filename that has the following format:
timestamp-username-1
This file is constantly etting written to, but before it gets too large I want to create a new file.
timestamp-username-2
How can I acheive this with using least amount of memory (ie, no or little variables)
here is my version:
```
priv... | I think you should just store the counter in an int. I understand that you want to save memory space but to be honest, an extra int is really in the "acceptable" category. I mean, the Int32 parser is probably wasting way much more memory. Don't forget that on x86, the memory space is spitted to 4096 byte pages so there... | "least amount of memory" is NOT equals to "no or little variables"
Local variables only takes little memory itself.
But object creation in heap takes a lot more, and they require GC to do cleanup.
In your example, your ToCharArray() and ToString() have created 4 object (indirect created object not included). | automatic incrementing filename | [
"",
"c#",
"string",
""
] |
I'm porting a library from Windows to \*NIX (currently OSX), does anyone now what function can I use instead of Microsoft's QueryPerformanceCounter and QueryPerformanceFrequency? | <http://www.tin.org/bin/man.cgi?section=3&topic=clock_gettime>
(and the other functions mentioned there)
- it's Posix! Will fall back to worse counters if HPET is not existent. (shouldn't be a problem though)
<http://en.wikipedia.org/wiki/High_Precision_Event_Timer>
Resolution should be about +10Mhz. | On OSX `mach_absolute_time` and `mach_timebase_info` are the best equivalents to Win32 QueryPerformance\* functions.
See <http://developer.apple.com/library/mac/#qa/qa1398/_index.html> | What's the equivalent of Windows' QueryPerformanceCounter on OSX? | [
"",
"c++",
"c",
"windows",
"unix",
"porting",
""
] |
How can you get the active users connected to a postgreSQL database via SQL? This could be the userid's or number of users. | (question) Don't you get that info in
> select \* from [pg\_user](http://www.postgresql.org/docs/current/interactive/user-manag.html#DATABASE-USERS);
or using the view [pg\_stat\_activity](http://www.postgresql.org/docs/current/interactive/monitoring-stats.html):
```
select * from pg_stat_activity;
```
**Added:**
... | Using balexandre's info:
```
SELECT usesysid, usename FROM pg_stat_activity;
``` | How can you get the active users connected to a postgreSQL database via SQL? | [
"",
"sql",
"postgresql",
"active-users",
""
] |
I have the following php code, which has been snipped for brevity. I am having trouble with the code after $lastImg is declared, specifically size never seems to get assigned any value, and the hence outputwidth and outputheight remain blank. I have been unable to spot the cause of this.
pic\_url is just a string in t... | First, to get the right error message, change your code to:
```
$size = getimagesize($lastImg);
echo "SIZE = ".$size."";
if ($size) {
$imageWidth = $size[0];
$imageHeight = $size[1];
$wRatio = $imageWidth / $maxWidth;
$hRatio = $imageHeight / $maxHeight;
$maxRatio = max($wRatio, $hRatio);
if ... | I'd have to say it looks like $row['PIC\_URL'] might not point to a valid image, thats the only reason getimagesize would fail. What does your database structure in AUCTIONS look like? | Image not displayed after resize | [
"",
"php",
"image",
"resize",
""
] |
For a number of reasons, the canonical source of some files I have can't be a working copy of the repository (the Subversion server is behind an inaccessible firewall, and the data doesn't natively exist in the file system in my preferred structure). So, I wrote a tool that downloads the data, generates a directory str... | For 1), it won't delete the revision history, but the new files will be treated as completely unrelated to the old ones. You still could get the old files back though.
For 2), that would be the recommended way. But after 'svn delete'ing the existing files and adding the new ones, you also have to 'svn add' those new f... | Subversion has a loose connection to the files. For files inside a folder, you can easily do a get/update, make massive changes (including deleting, replacing, or adding files), then commit the differences. That file-level behavior is typical Subversion usage.
The directories are slightly different. Subversion stores ... | Import to the same Subversion repository directory multiple times? | [
"",
"c#",
"svn",
"sharpsvn",
""
] |
How do you configure JBoss to debug an application in Eclipse? | You mean [remote debug JBoss](http://jmdesp.free.fr/billeterie/?p=95) from Eclipse ?
From [Configuring Eclipse for Remote Debugging](http://www.onjava.com/pub/a/onjava/2005/08/31/eclipse-jboss-remote-debug.html?page=6):
> Set the JAVA\_OPTS variable as follows:
```
set JAVA_OPTS= -Xdebug -Xnoagent
-Xrunjdwp:tran... | If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss. | JBoss debugging in Eclipse | [
"",
"java",
"eclipse",
"debugging",
"jboss",
""
] |
I need to determine if a user-supplied string is a valid file path (i.e., if `createNewFile()` will succeed or throw an Exception) but I don't want to bloat the file system with useless files, created just for validation purposes.
Is there a way to determine if the string I have is a valid file path without attempting... | This would check for the existance of the directory as well.
```
File file = new File("c:\\cygwin\\cygwin.bat");
if (!file.isDirectory())
file = file.getParentFile();
if (file.exists()){
...
}
```
It seems like file.canWrite() does not give you a clear indication if you have permissions to write to the directo... | Path class introduced in Java 7 adds new alternatives, like the following:
```
/**
* <pre>
* Checks if a string is a valid path.
* Null safe.
*
* Calling examples:
* isValidPath("c:/test"); //returns true
* isValidPath("c:/te:t"); //returns false
* isValidPath("c:/te?t"); //returns fa... | Is there a way in Java to determine if a path is valid without attempting to create a file? | [
"",
"java",
"validation",
"filesystems",
""
] |
**Is there a way of setting culture for a whole application? All current threads and new threads?**
We have the name of the culture stored in a database, and when our application starts, we do
```
CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.Curren... | In .NET 4.5, you can use the [`CultureInfo.DefaultThreadCurrentCulture`](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.defaultthreadcurrentculture.aspx) property to change the culture of an AppDomain.
For versions prior to 4.5 you have to use reflection to manipulate the culture of an AppDom... | This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or `ThreadPool` function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it. | Is there a way of setting culture for a whole application? All current threads and new threads? | [
"",
"c#",
"multithreading",
"cultureinfo",
""
] |
Please advise how to pass parameters into a function called using `setInterval`.
My example `setInterval(funca(10,3), 500);` is incorrect. | You need to create an anonymous function so the actual function isn't executed right away.
```
setInterval( function() { funca(10,3); }, 500 );
``` | Add them as parameters to setInterval:
```
setInterval(funca, 500, 10, 3);
```
The syntax in your question uses eval, which is not [recommended practice](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval). | Pass parameters in setInterval function | [
"",
"javascript",
"parameters",
"setinterval",
""
] |
My application I've recently inherited is FULL of deprecation warnings about the constructor:
```
Date d = new Date(int year, int month, int day)
```
Does anyone know or can point to a reason why something as simple as this was "replaced" with something like this:
```
Date d = null;
Calendar cal = GregorianCalendar.... | Originally, `Date` was intended to contain all logic concerning dates, but the API designers eventually realized that the API they had so far was woefully inadequate and could not be cleanly extended to deal correctly with issues such as timezones, locales, different calendars, daylight savings times, etc.
So they cre... | The Java Date APIs have long been critized, see for instance [this thread](https://stackoverflow.com/questions/87676/whats-the-best-way-to-manipulate-dates-and-timestamps-in-java).
You might want to check out [Joda-Time](http://joda-time.sourceforge.net/index.html) or [Apache Commons Lang](http://commons.apache.org/la... | Why was "new Date(int year, int month, int day)" deprecated? | [
"",
"java",
"date",
"deprecated",
""
] |
While trying to integrate Yahoo Media Player into my own website, I want to allow users to click on a link to add the clicked track to the playlist. YMP API has got a function for doing that (<http://mediaplayer.yahoo.com/api/#method_addTracks>). It takes a DOM element. Now how should I pass the dom element. My code lo... | As far as I understand from the API page, you should be using
```
YAHOO.MediaPlayer.addTracks(document.getElementById('track1'), null, true);
```
(the documentation says "HTML DOM element (possibly **contains** media anchor tags)") | You should place a reference to the DOM element you want to add, most likely by id like so:
```
<li id="track1">
<a id="trackelement" href="location of track" style="display:none">track1</a>
<a href="#" onclick="YAHOO.MediaPlayer.addTracks(document.getElementById('trackelement'), null, true);">Add this to the playlist... | How to pass DOM element to a API function? | [
"",
"javascript",
"dom",
""
] |
I'm going to learn Qt and I just want to know what parts of C++, OO design and other things I must have background in? Templates, RAII, Patterns, ....? | QT is no different from any other platform or library you can use. To use it properly you only need to know the basics of C++ and how to compile and build your code.
[This tutorial](http://doc.trolltech.com/4.3/tutorial.html) takes you through the basics of building a QT application.
Of course like any other programm... | I would suggest reading the book [C++ GUI Programming with Qt4](https://rads.stackoverflow.com/amzn/click/com/0132354160).
It covers almost all features of Qt, is easy to read for a beginner, and also includes an introduction to C++ and Java, explaining the basic concepts required for developing with Qt.
I really enj... | I want to start Qt development - what basic knowledge in C++ and OS do I have to own? | [
"",
"c++",
"qt",
""
] |
I'm trying to understand why this does not work. (Basic example with no validation yet)
When I test it, firebug states Product.addPage is not found.
```
var Product = function ()
{
var Page = function ()
{
var IMAGE = '';
return {
image : function ()
{
... | You're trying to reference the addPage property of the Product *function* (which in this case is a constructor), rather than on the returned object.
You probably want something like:
```
// Begin executing
$(document).ready(function ()
{
var product = new Product();
product.addPage().setImage('http://site/ima... | How about `Product.addPage`**`()`**`.setImage('http://site/images/small_logo.png');`?
---
Edit: Turns out I only caught half the problem. Look at dtsazza's answer for the whole thing. | What causes this code not to work? | [
"",
"javascript",
"closures",
""
] |
Consider the following snippet:
```
if(form1.isLoggedIn)
{
//Create a wait handle for the UI thread.
//the "false" specifies that it is non-signalled
//therefore a blocking on the waitone method.
AutoResetEvent hold = new AutoResetEvent(false);
filename = Path.Combine(Environment.Get... | I'm reading between the lines a bit here, but I think Rich is right - you need to move the background processing off the UI thread:
* Remove the form1.dispose call from the function above - I imagine that this is your only form, which is why once you dispose of it the application exits.
* Call the flow class asynchron... | I don't know what your Flow object is or what it does, but why can't it do it's work in another thread and not block the UI thread? I would think that the notify icon is a part of the UI and therefore required to be on the UI thread making it the wrong candidate for being run on another thread. In contrast, your Flow o... | running async operations in c#. - basic. | [
"",
"c#",
"timer",
""
] |
```
using (FileStream fileStream = new FileStream(path))
{
// do something
}
```
Now I know the using pattern is an implementation of IDisposable, namely that a Try/Catch/Finally is set up and Dispose is called on the object. My question is how the Close method is handled.
[MSDN](http://msdn.microsoft.com/e... | The `using` statement *only* knows about `Dispose()`, but `Stream.Dispose` calls `Close()`, as [documented in MSDN](http://msdn.microsoft.com/en-us/library/ms227422.aspx):
> Note that because of backward
> compatibility requirements, this
> method's implementation differs from
> the recommended guidance for the
> Disp... | using calls Dispose() only. The Dispose() method might call Close() if that is how it is implemented. | Disposable Using Pattern | [
"",
"c#",
""
] |
I have a solution with 2 projects. In the first project a I have a website with a Logon Control. In the second project I have a WCF project with an AuthenticatonService configured. What is the easiest way to integrate both? In other word, How do I call the Authentication Service from the login control?
EDIT:
OK, what... | OK,
Finally I got it working. This is what I did:
* Add a Service Reference to the WCF url:
<http://localhost:8080/servicios/MiServicio.svc>
* Resetted the Membership Provider property of the Login control. This in facts look for the default membershipprovider installed with VS 2008 (SQLEXPRESS).
* implement the A... | I believe this is what you're looking for: [Exposing WCF Services to Client Scripts](http://msdn.microsoft.com/en-us/library/bb514961.aspx) | How do I call an AuthenticationService from a login control? | [
"",
"c#",
"asp.net",
"wcf",
"authentication",
""
] |
I'm using [APC](https://www.php.net/apc) to cache user variables (with the apc\_store/apc\_fetch commands). I've also enabled APC for the CLI with the option "apc.enable\_cli = 1". However, the CLI version of PHP seems to access a different APC cache from the version used by Apache.
Is it possible to configure APC to ... | Not possible.. The only way to accomplish something like what your asking is to use something like memcacheD. Or run what you need to run through your webserver. What's running CLI that you cannot run via a web script with a cronjob? | You can use shm. This technology lend to access to Unix Shared memory. You can put some variable in shm and then in another scritp, even programmed in another languaje you can get the shared variables.
shm\_put\_var and shm\_get\_var.
It's slower than APC, but it's faster than memcached, redis, etc.
I hope It will h... | How can I get PHP to use the same APC cache when invoked on the CLI and the web? | [
"",
"php",
"linux",
"caching",
"command-line-interface",
"apc",
""
] |
I have a networking Linux application which receives RTP streams from multiple destinations, does very simple packet modification and then forwards the streams to the final destination.
How do I decide how many threads I should have to process the data? I suppose, I cannot open a thread for each RTP stream as there co... | It is important to understand the purpose of using multiple threads on a server; many threads in a server serve to decrease [latency](http://en.wikipedia.org/wiki/Latency_(engineering)) rather than to increase speed. You don't make the cpu more faster by having more threads but you make it more likely a thread will alw... | Classically the number of reasonable threads is depending on the number of execution units, the ratio of IO to computation and the available memory.
### Number of Execution Units (`XU`)
That counts how many threads can be active at the same time. Depending on your computations that might or might not count stuff like... | How many threads to create and when? | [
"",
"c++",
"linux",
"multithreading",
"networking",
""
] |
There are numerous post over the net that detail how relative paths don't work in Xcode. I do have an Xcode template that I downloaded where the relative paths DO work, however I have not been able to figure out why nor replicate it in other projects.
Firstly, I am using C++ in Xcode 3.1. I am not using Objective-C, n... | Took me about 5 hours of Google and trying different things to FINALLY find the answer!
```
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the ... | Do not depend on the current working directory in binary code. Just don't. You cannot trust the operating system or shell to set it to where you expect it to be set, on Mac, Windows, or Unix.
For straight C, use \_NSGetExecutablePath in dyld.h to get the path to your current executable, then you can go relative from t... | Relative Paths Not Working in Xcode C++ | [
"",
"c++",
"xcode",
"macos",
"path",
""
] |
In SQL one can write a query that searches for a name of a person like this:
```
SELECT * FROM Person P WHERE P.Name LIKE N'%ike%'
```
This query would run with unicode characters (assuming that the Name column and database were setup to handle unicode support).
I have a similar query in HQL that is run by Hibernate... | Have you tried with parameters:
```
IList<Person> people = session
.CreateQuery("from Person p where p.Name like :name")
.SetParameter("name", "%カタカ%")
.List<Person>();
```
They also have the advantage to protect your query against SQL injection. | I found a solution that works. I highly doubt it is the best solution. It is however the solution that I'm going to implement until I can authorize a rewrite of the entire query building section of the software that I'm working on.
In the instance:
```
SELECT P FROM SumTotal.TP.Models.Party.Person P join P.Demographi... | Unicode String in Hibernate Queries | [
"",
"c#",
"nhibernate",
"hibernate",
"unicode",
"hql",
""
] |
I have a string like this:
```
string s = "This is my string";
```
I am creating a Telerik report and I need to define a `textbox` that is the width of my string. However the size property needs to be set to a Unit (Pixel, Point, Inch, etc). How can I convert my string length into, say a Pixel so I can set the width?... | Without using of a control or form:
```
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
{
SizeF size = graphics.MeasureString("Hello there", new Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point));
}
```
Or in VB.Net:
```
Using graphics As System.Drawing.Gr... | ```
Size textSize = TextRenderer.MeasureText("How long am I?", font);
``` | How can I convert a string length to a pixel unit? | [
"",
"c#",
"telerik",
"telerik-reporting",
""
] |
My database schema has a 'locked' setting meaning that the entry can not be changed once it is set.
Before the locked flag is set we can update other attributes. So:
* Would you check the locked flag in code and then update the entry
or
* would it be better to combine that into a SQL query, if so, any examples?
ED... | You should do both. The database should use an update trigger to decide if a row can be updated - this would prevent any one updating the row from the back tables accidentally. And the application should check to see if it should be able to update the rows and act accordingly. | "how would you combine the update & check into one SQL statement?"
```
update table
set ...
where key = ...
and locked ='N';
```
That would not raise an error, but would update 0 rows - something you should be able to test for after the update.
As for which is better, my view is that if this locked flag is important... | validating data in database: sql vs code | [
"",
"sql",
""
] |
As documented in the blog post *[Beware of System.nanoTime() in Java](http://www.principiaprogramatica.com/2008/04/25/beware-of-systemnanotime-in-java/)*, on x86 systems, Java's System.nanoTime() returns the time value using a [CPU](http://en.wikipedia.org/wiki/Central_processing_unit) specific counter. Now consider th... | **This answer was written in 2011 from the point of view of what the Sun JDK of the time running on operating systems of the time actually did. That was a long time ago! [leventov's answer](https://stackoverflow.com/a/54566928/116639) offers a more up-to-date perspective.**
That post is wrong, and `nanoTime` is safe. ... | **Since Java 7, `System.nanoTime()` is guaranteed to be safe by JDK specification.** [`System.nanoTime()`'s Javadoc](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime()) makes it clear that all observed invocations within a JVM (that is, across all threads) are monotonic:
> The value returned re... | Is System.nanoTime() completely useless? | [
"",
"java",
"nanotime",
""
] |
Lets consider that I have a public property called AvatarSize like the following,
```
public class Foo
{
...
public Size AvatarSize
{
get { return myAvatarSize; }
set { myAvatarSize = value; }
}
...
}
```
Now if a target class wants to set this property, then they need to do it the following way,
... | `Size` is a structure. Being a ValueType it's immutable. If you change it's property like that, it will only modify an object instance in the stack, not the actual field. In your case `AvatarSize` property can only be set using a struct constructor: `new Size(20, 20)`. | The only way you can do what you want is by defining
```
public class MutableSize{
public int Height{get;set;}
public int Width{get;set;}
}
```
and then having AvatarSize return one of those instead of Size. | Setting property's property directly in C# | [
"",
"c#",
".net",
"properties",
""
] |
I'm trying to create my own error window for the project I am working on. When I show my error window I have no way to pass the error message, and user message to the Error window because the "ErrorMessage.Text" cannot be seen in the classes I make.
I went into the form designer generated code and tried to make the Te... | Yes! have a function made public that can receive this text:
```
pseudo: public void updateTextBox(string new_text)
```
and have the function update the textbox from there.
don't mix UI with logic. | I would just pass the message as a constructor parameter.
```
MyMessageBox messageBox = new MyMessageBox("My error message");
messageBox.Show();
``` | C# issue: How do I manipulate a Textbox on one form from another form? | [
"",
"c#",
".net",
"winforms",
""
] |
I have a post-build target in MSBuild to copy some build outputs.
This is linked in as a dependency to the `AfterBuild` target (exposed by `Microsoft.CSharp.targets`):
```
<Target Name="AfterBuild" DependsOnTargets="InstallUtil;CopyPostBuildFiles" />
```
Is there any way to avoid the files being copied if the build ... | Since you are overriding the AfterBuild target it will always execute after the build occurs. This is the case for a rebuild or a normal build. If you want to perform some actions after the rebuild (and not build) then you should extend the dependency property for the Rebuild target. So in your case to inject the targe... | I just googled this and found this years old answer. I found a way, to do this a bit easier, by stealing an Idea from core targets. Override both BeforeBuild and AfterBuild and do something like:
```
<Target Name="BeforeBuild">
<PropertyGroup>
<MyBeforeCompileTimestamp>%(IntermediateAssembly.ModifiedTime)
... | Suppressing AfterBuild targets when a csproj has not been built | [
"",
"c#",
"msbuild",
""
] |
In my years of C++ (MFC) programming in I never felt the need to use `typedef`, so I don't really know what is it used for. Where should I use it? Are there any real situations where the use of `typedef` is preferred? Or is this really more a C-specific keyword? | ## Template Metaprogramming
`typedef` is *necessary* for many [template metaprogramming](http://en.wikipedia.org/wiki/Template_metaprogramming) tasks -- whenever a class is treated as a "compile-time type function", a `typedef` is used as a "compile-time type value" to obtain the resulting type. E.g. consider a simple... | In Bjarne's book he states that you can use typedef to deal with portability problems between systems that have different integer sizes. (this is a paraphrase)
On a machine where `sizeof(int)` is 4 you can
```
typedef int int32;
```
Then use `int32` everywhere in your code. When you move to an implementation of C++ ... | When should I use typedef in C++? | [
"",
"c++",
"typedef",
""
] |
Hi I am trying to mount as a drive in vista I am using the following code from msdn example,
```
BOOL bFlag;
TCHAR Buf[BUFSIZE]; // temporary buffer for volume name
if( argc != 3 )
{
_tprintf( TEXT("Usage: %s <mount_point> <volume>\n"), argv[0] );
_tprintf( TEXT("For example, \"%s c:\\m... | `SetVolumeMountPoint` is for mounting a volume on a drive letter or in a folder. It does not allow you to mount a folder on a drive letter. This is the opposite of what you want.
To make a folder available as a drive letter, you want to do the equivalent of the `SUBST` utility. This uses `DefineDosDevice`, something l... | You need to be more specific! Where exactly in the code do you get that error?
You could try and execute the following command via system() and see if it works this way:
```
subst K: “c:\blabla"
``` | Mounting folder as a drive in vista | [
"",
"c++",
"api",
""
] |
Leading on from my previous questions I am going to try and clarify one of the problems I am facing.
I am trying to create a multiplayer version of PacMan.
A simple overview of how i've made my application is that I have a server which has a ServerSocket which is constantly listening on a specific port. Once a client... | Multithreading needs synchronisation. Are you using a synced stream (or syncing the access to the stream yourself)?
**Update:** The code sample given may very well be called from multiple threads. If multiple threads access the same stream, errors like the ones you are experiencing may very well occur.
I suggest havi... | This is hard to debug without the rest of the code, so I'm going to post my first through and play around a little. Why are you calling .reset() on your streams? That would move the read position in the stream back to the start, which isn't what you want I would think (never used ObjectInputStream).
---
OK, I took yo... | Java socket programming | [
"",
"java",
"sockets",
"networking",
""
] |
Does anybody know how to unbind set of event handlers, but memorize them in order to bind them again later? Any suggestions? | There is a events element in the data of the item. This should get your started, you can read your elements and store the handlers in an array before unbinding. Comment if you need more help. I got this idea from reading the $.fn.clone method so take a look at that as well.
```
$(document).ready(function() {
$('#t... | Here is how to achieve that, provides a `storeEvents` and a `restoreEvents` methods on a selection. `storeEvents` takes a snapshot of the events on the moment it is called. `restoreEvents` restores to the last previous snapshot. Might need to twist it a little for parameterizing the unbinding while restoring, maybe you... | jQuery: Unbind event handlers to bind them again later | [
"",
"javascript",
"jquery",
"events",
""
] |
As title says, how do I call a java class method from a jsp, when certain element is clicked (by example an anchor)? (Without reloading the page)
If this can be done, how I pass the method, some part of the html code of the page that invokes it?
Im using jsp, servlets, javascript, struts2 and java, over Jboss AS. | What you want to do is have javascript fire off an AJAX request when the said element is clicked. This AJAX request will go to the server which can then invoke any java code you want.
Now you can build this all yourself or you could use one of the many off the shelf solutions. I would recommend Googling around for a J... | As [Marko pointed out](https://stackoverflow.com/questions/516267/how-to-call-a-java-method-from-a-jsp-when-a-html-element-is-clicked/516293#516293), you might need to read some more about the client/server separation in web programming. If you want a framework to help you do remote Java invocation from Javascript, hav... | How to call a java method from a jsp when a html element is clicked? | [
"",
"java",
"jsp",
""
] |
I have a friefox sidebar extension. If its opened by clicking on the toolbar icon I load it with a webpage ( that I have authored ). Now, if the user clicks on the link on the webpage ( thats loaded into the sidebar ) I want the linked webpage to open up in a new tab of the main window. I tried with this in my webpage ... | Actually, there is no way to load a webpage ( whose link was in another webpage loaded into the sidebar extension ) onto a new tab in the browser. The only way is to use javascript. That has to execute under privileged conditions ( meaning as part of an extension ) like below:
```
gBrowser.addTab("http://www.google.co... | If you use target="\_blank" instead, FF (version 3) should open a new tab for it. Haven't tried it from a sidebar, but it's worth giving a shot. | Firefox sidebar extension link loaded into a new browser tab. How-To? | [
"",
"javascript",
"html",
"firefox",
"firefox-addon",
"sidebar",
""
] |
Is there any way to write a Visual Studio Project file easy or do i have to look at the xml format and write it by hand?
Is there any lib for this in .net framework(3.5)?
Im using vb.net but c# would also work.. | Visual Studio since version 2005 uses the [MSBuild](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx) format to store C# and VB project files.
You could read this primer <http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=472> or search the Web for further examples.
For programmatic access you could use... | I haven't tried this myself but you might want to look at <http://msdn.microsoft.com/en-us/library/microsoft.build.buildengine.project.aspx> | Write visual studio project from code | [
"",
"c#",
"xml",
"vb.net",
"visual-studio",
""
] |
I am having problems with implementing Observer pattern in my project.
The project has to be made as MVC in C#, like a Windows application.
In my domain model I have for example Country class and Country repository. I have a Country controller and views for seeing all countries(a list on a form), adding new country,... | You could create a 'ManageCountry' task, which lets you edit / add countries.
This task could have an event 'CountryChanged', where other views can subscribe to.
When you modify a country, or create a new country, you raise the event, and subscribers can react to it.
You just have to make sure that the event you raise... | In C# (or .NET generally) you can use events and delegates which are special observer/monitor/listener implementations.
I don't know about DDD, but I would add an "NewCountryAdded"-event or "CountryListChanged"-event or something like that. | MVC and Observer pattern | [
"",
"c#",
"model-view-controller",
"design-patterns",
"domain-driven-design",
"observer-pattern",
""
] |
We have a new application that requires glibc 2.4 (from gcc 4.1). The machine we have runs on has gcc 3.4.6. We can not upgrade, and the application must be run on this machine.
We installed gcc 4.1, however, when it comes to compile time it is using all the includes, etc, from 3.4.6.
How do we get around this?
Any ... | Refer "How to install multiple versions of GCC" [here](http://gcc.gnu.org/faq.html#multiple) in the GNU GCC FAQ.
There's also a white paper [here](http://www.tellurian.com.au/whitepapers/multiplegcc.php). | for Ubuntu it's pretty easy
`sudo add-apt-repository ppa:ubuntu-toolchain-r/test`
`sudo apt-get update`
and then install for example gcc version 6
`sudo apt-get install gcc-6` | How to use multiple versions of GCC | [
"",
"c++",
"linux",
"gcc",
"g++",
""
] |
I need a simple floating point rounding function, thus:
```
double round(double);
round(0.1) = 0
round(-0.1) = 0
round(-0.9) = -1
```
I can find `ceil()` and `floor()` in the math.h - but not `round()`.
Is it present in the standard C++ library under another name, or is it missing?? | It's available since C++11 in cmath (according to <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf>)
```
#include <cmath>
#include <iostream>
int main(int argc, char** argv) {
std::cout << "round(0.5):\t" << round(0.5) << std::endl;
std::cout << "round(-0.5):\t" << round(-0.5) << std::endl;
st... | > **Editor's Note:** The following answer provides a simplistic solution that contains several implementation flaws (see [Shafik Yaghmour's answer](https://stackoverflow.com/a/24348037/7941251) for a full explanation). Note that C++11 includes [`std::round`, `std::lround`, and `std::llround`](http://en.cppreference.com... | round() for float in C++ | [
"",
"c++",
"floating-point",
"rounding",
""
] |
I'm writing some excel-like C++ console app for homework.
My app should be able to accept formulas for it's cells, for example it should evaluate something like this:
```
Sum(tablename\fieldname[recordnumber], fieldname[recordnumber], ...)
tablename\fieldname[recordnumber] points to a cell in another table,
fieldnam... | Ok, nice homework question by the way.
It really depends on how heavy you want this to be. You can create a full expression parser (which is fun but also time consuming).
In order to do that, you need to describe the full grammar and write a frontend (have a look at lex and yacc or flexx and bison.
But as I see your... | For the parsing, I'd look at Recursive descent parsing. Then have a table that maps all possible function names to function pointers:
```
struct FunctionTableEntry {
string name;
double (*f)(double);
};
``` | Expression Evaluation in C++ | [
"",
"c++",
"regex",
"expression-evaluation",
""
] |
With a JTree, assuming the root node is level 0 and there may be up to 5 levels below the root, how can I easily expand all the level 1 nodes so that all level 1 & 2 branches and leafs are visible but levels 3 and below aren't? | Thanks for the quick response guys. However I have now found the simple solution I was looking for. For some reason I just couldn't see DefaultMutableTreeNode.getLevel() in the JavaDocs! FYI what I'm doing now is:
```
DefaultMutableTreeNode currentNode = treeTop.getNextNode();
do {
if (currentNode.getLevel() == 1)... | You have some Tree utility classes out there which do precisely that:
Like [this one](http://www.koders.com/java/fid73C19EA27E58706B007DAAF35EE56BF2AE0F3D8B.aspx?s=jtree+expand+level#L3):
```
public class SimpleNavigatorTreeUtil {
/**
* Expands/Collapse specified tree to a certain level.
*
* @param t... | Java JTree expand only level one nodes | [
"",
"java",
"swing",
"jtree",
""
] |
I have a Map which is to be modified by several threads concurrently.
There seem to be three different synchronized Map implementations in the Java API:
* `Hashtable`
* `Collections.synchronizedMap(Map)`
* `ConcurrentHashMap`
From what I understand, `Hashtable` is an old implementation (extending the obsolete `Dicti... | For your needs, use `ConcurrentHashMap`. It allows concurrent modification of the Map from several threads without the need to block them. `Collections.synchronizedMap(map)` creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).
Use the second option if you need to ensure ... | ```
╔═══════════════╦═══════════════════╦═══════════════════╦═════════════════════╗
║ Property ║ HashMap ║ Hashtable ║ ConcurrentHashMap ║
╠═══════════════╬═══════════════════╬═══════════════════╩═════════════════════╣
║ Null ║ allowed ║ not allowed ... | What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)? | [
"",
"java",
"dictionary",
"concurrency",
""
] |
I had this idea of creating a count down timer, like 01:02, on the screen (fullsize).
One thing is that I really don't have a clue on how to start.
I do know basic c/c++, win32 api and a bit of gdi.
Anyone have any pointers on how to start this? My program would be like making the computer into a big stopwatch (but w... | If you have some experience with windows message processing and the Win32 API, this should get you started.
```
LRESULT WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT r;
char szBuffer[200];
static int count = 120;
int seconds = 0;
int minutes = 0;
... | Create a timer, have your application respond to the timer event by sending a paint message to itself. Be sure to remove the timer when app exits. | Best way to create a timer on screen | [
"",
"c++",
"c",
"winapi",
"gdi",
""
] |
I have a CMS that uses a syntax based on HTML comments to let the user insert flash video players, slideshows, and other 'hard' code that the user could not easily write.
The syntax for one FLV movies looks like this:
`<!--PLAYER=filename.flv-->`
I use this code:
`$find_players = preg_match("/<!--PLAYER\=(.*)-->/si"... | You probably want the regex modifier U (PCRE\_UNGREEDY, to match ungreedily). This will fetch the shortest possible match, meaning that you won't match from the beginning of the first <!--PLAYER= to the end of the last -->
An abbreviated example:
```
<?php
$text = "blah\n<!-x=abc->blah<!-x=def->blah\n\nblah<!-x=ghi->... | When working with regular expressions, it's typically more performant to use a more specific expression rather than a "lazy dot", which generally causes excessive backtracking. You can use a negative lookahead to achieve the same results without overburdening the regex engine:
```
$find_players = preg_match("/<!--PLAY... | Regular expression to find and replace the content of HTML Comment Tags | [
"",
"php",
"html",
"regex",
"non-greedy",
""
] |
I mod\_rewrite my pages very similar to how SO does it. I have `www.example.com/users/login/` which will internally use `users.login.php` which acts as a controller. I want to pass in a parameter as a page to redirect to once the login is complete.
If you pass in a relative URL you end up with a very peculiar looking ... | I use hidden field in the login form that contains the url and it works for me. you can try that too.
1. create hidden input field.
2. set the value of the input field to `$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';`
3. get posted url and redirect user to that url.
Note: HTTP\_REFERER ... | Best practice for storing a previous page visted is to use the `$_SESSION` global. Using `HTTP_REFERER` for anything besides statistics is asking for user abuse since you can easily fake a referer.
Check out this link about storing multiple session IDs in a cookie. <http://bytes.com/groups/php/7630-handling-multiple-s... | How do you pass in a redirect URL into a mod_rewritten page | [
"",
"php",
"mod-rewrite",
"url-rewriting",
""
] |
I have an INI file that I want to read the line `DeviceName=PHJ01444-MC35` from group `[DEVICE]` and assign the value to a string.
```
[BEGIN-DO NOT CHANGE/MOVE THIS LINE]
[ExecList]
Exec4=PilotMobileBackup v1;Ver="1.0";NoUninst=1
Exec3=MC35 108 U 02;Ver="1.0.8";NoUninst=1
Exec2=FixMGa;Ver="1.0";Bck=1
Exec1=Clear Log ... | If you wanted the very simple but not very clean answer:
```
using System.IO;
StreamReader reader = new StreamReader(filename);
while(reader.ReadLine() != "[DEVICE]") { continue; }
const string DeviceNameString = "DeviceName=";
while(true) {
string line = reader.ReadLine();
if(line.Length < DeviceNameString.... | You could use Windows API for this. See <http://jachman.wordpress.com/2006/09/11/how-to-access-ini-files-in-c-net/>
**Edit**: As noted in the comments the page is no longer available on the original site, however it's still accessible on the [Wayback Machine](https://web.archive.org/web/20061120014725/http://jachman.w... | How can I read a value from an INI file in C#? | [
"",
"c#",
".net",
""
] |
I'm interested in providing an autocompletion box in a JFrame. The triggering mechanism will be based on mnemonics (I think), but I'm not really sure what to use for the "autocompletion box" (I would like results to be filtered as the user presses keys).
How would you implement this? Some sort of JFrame, or a JPopupMe... | There is an example for auto-completion for text area at
**[Sun's tutorials "Using Swing Components"](http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html)**.
It is done in the style of word processors (no pop ups, but the
suggested text is typed ahead of the cursor).
Just scroll down to **"An... | You might want to try the free AutoComplete component over at SwingLabs.
<http://swinglabs.org>
Edit: This site seems to have moved <http://java.net/projects/swinglabs>
There is an example how to implement this code at:
<http://download.java.net/javadesktop/swinglabs/releases/0.8/docs/api/org/jdesktop/swingx/autoco... | How could I implement autocompletion using Swing? | [
"",
"java",
"swing",
"autocomplete",
""
] |
So here is the deal. I want to call a class and pass a value to it so it can be used inside that class in all the various functions ect. ect. How would I go about doing that?
Thanks,
Sam | > I want to call a class and pass a value to it so it can be used inside that class
The concept is called "constructor".
As the other answers point out, you should use [the unified constructor syntax](http://php.net/manual/en/language.oop5.decon.php) (`__construct()`) as of PHP 5. Here is an example of how this looks... | In new versions of PHP (5 and up), the function \_\_constuct is called whenever you use "new {Object}", so if you want to pass data into the object, add parameters to the construct function and then call
```
$obj = new Object($some, $parameters);
class Object {
function __construct($one, $two) {}
}
```
Named con... | In php when initializing a class how would one pass a variable to that class to be used in its functions? | [
"",
"php",
"variables",
"class",
""
] |
I'd like for a subclass of a certain superclass with certain constructor parameters to load an XML file containing information that I'd then like to pass to the superconstructor. Is this impossible to achieve? | How about using a factory method instead? Maybe something like:
```
private MyObject(ComplexData data)
{
super(data);
}
public static MyObject createMyObject(String someParameter)
{
ComplexData data = XMLParser.createData(someParameter);
return new MyObject(data);
}
``` | You can call a static method in the super() call, e.g.
```
public Subclass(String filename)
{
super(loadFile(filename));
}
private static byte[] loadFile(String filename)
{
// ...
}
``` | Is it impossible to perform initialization before calling a superclass's constructor? | [
"",
"java",
"xml",
""
] |
I have a method which never returns a null object. I want to make it clear so that users of my API don't have to write code like this:
```
if(Getxyz() != null)
{
// do stuff
}
```
How can I show this intent? | Unfortunately there is no way built in to C#
You can document this fact, but this won't be automatically checked.
If you are using resharper, then it can be set up to check this properly when the method is marked with a [NotNull] attribute.
Otherwise you can use the [Microsoft Contracts](https://www.microsoft.com/en... | Unless you are using a type based on System.ValueType, I think you are out of luck. Its probably best to document this clearly in the XML/metadata comment for the function. | How can I show that a method will never return null (Design by contract) in C# | [
"",
"c#",
"design-by-contract",
""
] |
I have coded some JavaScript to perform an ajax call in an asp.net application. This triggers a method that calls a URL, sending some parameters in the POST.
The receiving page processes the data and updates our database.
We will be providing this code to customers to allow them to send us the data we need in their c... | You can use SOAP to pass a username/password with the request. SSL should be used to encrypt the data going over the wire. Here is some code that we use:
This is a class that will hold the Credentials that are sent with the request:
```
Imports System.Web.Services.Protocols
Public Class ServiceCredentials
Inherits S... | You should secure you're service using SSL
Edit : I forgot the most "basic" : HTTP authentication (using login/password)
I found a link but it's from 2003 : <http://www-128.ibm.com/developerworks/webservices/library/ws-sec1.html>
Edit 2 : As said in comments, I think the problem here fits in the purpose of REST web s... | Securing a remote ajax method call | [
"",
"javascript",
"ajax",
"security",
""
] |
Is there is any reason to make the permissions on an overridden C++ virtual function different from the base class? Is there any danger in doing so?
For example:
```
class base {
public:
virtual int foo(double) = 0;
}
class child : public base {
private:
virtual int foo(double);
}
```
The [C... | The problem is that the Base class methods are its way of declaring its interface. It is, in essence saying, "These are the things you can do to objects of this class."
When in a Derived class you make something the Base had declared as public private, you are taking something away. Now, even though a Derived object "... | You do get the surprising result that if you have a child, you can't call foo, but you can cast it to a base and then call foo.
```
child *c = new child();
c->foo; // compile error (can't access private member)
static_cast<base *>(c)->foo(); // this is fine, but still calls the implementation in child
```
I suppose y... | Overriding public virtual functions with private functions in C++ | [
"",
"c++",
"overriding",
"access-control",
"virtual-functions",
""
] |
There was an interesting question in a practice test that I did not understand the answer to. What is the output of the following code:
```
<?php
class Foo {
public $name = 'Andrew';
public function getName() {
echo $this->name;
}
}
class Bar extends Foo {
public $name = 'John';
public f... | $this to the object in whose context the method was called. So: $this is $a->getName() is $a. $this in $fooInstance->getName() would be $fooInstance. In the case that $this is set (in an object $a's method call) and we call a static method, $this remains assigned to $a.
Seems like quite a lot of confusion could come o... | Foo::getName() is using an older PHP4 style of [scope resolution operator](http://uk.php.net/manual/en/keyword.paamayim-nekudotayim.php) to allow an overridden method to be called.
In PHP5 you would use [parent](http://uk.php.net/manual/en/language.oop5.paamayim-nekudotayim.php)::getName() instead
It's useful if you ... | Calling Static Method from Class B(which extends Class A) of Class A | [
"",
"php",
"oop",
""
] |
Lets say I have an entity Foo, and it contains a list of another entity Bar. Should Bar have a direct reference to Foo? i.e...
```
public class Foo
{
public int Id {get; set;}
public IList<Bar> Bars {get; set;}
}
public class Bar
{
public int Id {get; set;}
public Foo parentFoo {get; set; //this will be ... | The correct approach is to ask the question "Does Bar need to reference Foo for some reason?" Don't just place the reference there if Bar has no need to do anything with it. | It really depends on the example. If there is a **need** to know the parent (for example, to perform bidirectional navigation - like `XmlNode` etc) then you'll need it. This only really works for a single parent.
If you just need change-notifications, then events might be more versatile - in particular, events allow f... | Domain Design - Referencing an Entity in a Sub Class | [
"",
"c#",
"domain-driven-design",
""
] |
These characters show fine when I cut-and-paste them here from the VisualStudio debugger, but both in the debugger, and in the TextBox where I am trying to display this text, it just shows squares.
说明\r\n海流受季风影响,3-9 月份其流向主要向北,流速为2 节,有时达3 节;10 月至次年4 月份其流向南至东南方向,流速为2 节。\r\n注意\r\n附近有火山爆发的危险,航行时严加注意\r\n
I thought that th... | I changed from using a TextBox to using a RichTextBox, and now the characters display in the RichTextBox. | You need to install and use a font which supports those characters. Not all fonts support all characters. the [] box character is the fonts representation of 'unsupported'
The textbox might be using MS Sans Serif by default, so change it to Arial or something else. | Unicode characters not showing in System.Windows.Forms.TextBox | [
"",
"c#",
"user-interface",
"forms",
"unicode",
"textbox",
""
] |
Is there any way to serialize a property with an internal setter in C#?
I understand that this might be problematic - but if there is a way - I would like to know.
**Example:**
```
[Serializable]
public class Person
{
public int ID { get; internal set; }
public string Name { get; set; }
public int Age {... | If it is an option, [`DataContractSerializer`](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=vs.110).aspx) (.NET 3.0) can serialize non-public properties:
```
[DataContract]
public class Person
{
[DataMember]
public int ID { get; internal set; }
[DataMember]... | You can implement [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx), unfortunately this negates the most important benefit of XmlSerializer (the ability to declaratively control serialization). [DataContractSerializer](http://msdn.microsoft.com/en-us/library/syst... | Can an internal setter of a property be serialized? | [
"",
"c#",
".net",
"serialization",
""
] |
Let's say I have an array in C++:
```
double* velocity = new double[100];
```
Using the GDB command line, I can view this array with the command:
```
> print *velocity @ 100
```
and it will print a nicely-formatted list of all the double values inside the array.
However, when using the Xcode debugger, the most it ... | You can use gdb syntax as expressions:
1. Use Run/Show/Expressions... menu to show the expressions window
2. Enter `'*velocity @ 100'` at the bottom of the window (Expression:) | I think that my answer will be a good addition for the old one.
New versions of Xcode use `lldb` debugger as default tool instead of `gdb`.
According this [page](https://developer.apple.com/library/mac/documentation/IDEs/Conceptual/gdb_to_lldb_transition_guide/document/Introduction.html):
> With the release of Xcode... | Viewing a dynamically-allocated array with the Xcode debugger? | [
"",
"c++",
"xcode",
"macos",
"gdb",
""
] |
Where is the best place to find information on binding redirects? or maybe just a basic explanation of where you put these redirects within a project? | Where you put it can only be configuration. Find details [here](http://msdn.microsoft.com/en-us/library/2fc472t2(vs.71).aspx). | Why not start from the [beginning](http://msdn.microsoft.com/en-us/library/2fc472t2(VS.80).aspx)?
after understood what it does, you will end up with something like:
```
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIden... | Binding redirects | [
"",
"c#",
"binding",
"redirect",
""
] |
I want to run the following code:
```
ajaxUpdate(10);
```
With a delay of 1 second between each iteration. How can I do this? | You can also do it with
```
setTimeout(function() {ajaxUpdate(10)}, 1000);
``` | ```
var i = window.setInterval( function(){
ajaxUpdate(10);
}, 1000 );
```
This will call ajaxUpdate every second, until such a time it is stopped.
And if you wish to stop it later:
```
window.clearInterval( i );
```
If you wish to only run it *once* however,
```
var i = window.setTimeout( function(){... | How to set a timer in javascript | [
"",
"javascript",
"jquery",
""
] |
Given this input: [1,2,3,4]
I'd like to generate the set of spanning sets:
```
[1] [2] [3] [4]
[1] [2] [3,4]
[1] [2,3] [4]
[1] [3] [2,4]
[1,2] [3] [4]
[1,3] [2] [4]
[1,4] [2] [3]
[1,2] [3,4]
[1,3] [2,4]
[1,4] [2,3]
[1,2,3] [4]
[1,2,4] [3]
[1,3,4] [2]
[2,3,4] [1]
[1,2,3,4]
```
Every set has all the elements of the or... | This should work, though I haven't tested it enough.
```
def spanningsets(items):
if not items: return
if len(items) == 1:
yield [[items[-1]]]
else:
for cc in spanningsets(items[:-1]):
yield cc + [[items[-1]]]
for i in range(len(cc)):
yield cc[:i] + [... | What about this? I haven't tested it yet, but I'll try it later…
I think this technique is called Dynamic Programming:
1. Take the first element `[1]`
What can you create with it? Only `[1]`
2. Take the second one `[2]`
Now you've got two possibilities: `[1,2]` and `[1] [2]`
3. Take the third one `[3]`
... | Algorithm to generate spanning set | [
"",
"python",
"algorithm",
""
] |
I need to match up two almost-the-same long freetext strings; i.e., to find index-to-index correspondences wherever possible.
Because this is freetext, the comparison should not be line-based as in code diffing.
Any suggestions for Java libraries?
A simple example (In real life , of course, there would not be extra ... | This one might be good [Diff Match Patch](https://github.com/google/diff-match-patch). | Depending on your exact requirements, the `StringUtils` class of the [Apache Commons Lang](http://commons.apache.org/lang/) component might be helpful, e.g.:
* StringUtils#difference: Compares two Strings, and returns the portion where they differ
* StringUtils#getLevenshteinDistance: Find the [Levenshtein distance](h... | Java library for free-text diff | [
"",
"java",
"string",
"text",
"comparison",
"diff",
""
] |
I use the following for a jQuery link in my `<script>` tags:
```
http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
```
Is there a link to the "latest" version? Something like the following (which doesn't work):
```
http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js
```
(Obviously not necessarily... | **Up until jQuery 1.11.1**, you could use the following URLs to get the latest version of jQuery:
* <https://code.jquery.com/jquery-latest.min.js> - jQuery hosted (minified)
* <https://code.jquery.com/jquery-latest.js> - jQuery hosted (uncompressed)
* <https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js> - Go... | DO NOT USE THIS ANSWER. The URL is pointing at jQuery 1.11 (and [always will](http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/)).
> Credits to Basic for above snippet
<http://code.jquery.com/jquery-latest.min.js> is the minified version, always up-to-date. | Is there a link to the "latest" jQuery library on Google APIs? | [
"",
"javascript",
"jquery",
"google-api",
""
] |
I've got an XElement deep within a document. Given the XElement (and XDocument?), is there an extension method to get its full (i.e. absolute, e.g. `/root/item/element/child`) XPath?
E.g. myXElement.GetXPath()?
**EDIT:
Okay, looks like I overlooked something very important. Whoops! The index of the element needs to b... | The extensions methods:
```
public static class XExtensions
{
/// <summary>
/// Get the absolute XPath to a given XElement
/// (e.g. "/people/person[6]/name[1]/last[1]").
/// </summary>
public static string GetAbsoluteXPath(this XElement element)
{
if (element == null)
{
... | I updated the code by Chris to take into account namespace prefixes. Only the GetAbsoluteXPath method is modified.
```
public static class XExtensions
{
/// <summary>
/// Get the absolute XPath to a given XElement, including the namespace.
/// (e.g. "/a:people/b:person[6]/c:name[1]/d:last[1]").
/// </s... | Get the XPath to an XElement? | [
"",
"c#",
"xml",
"xpath",
"xelement",
""
] |
I am using plone.app.blob to store large ZODB objects in a blobstorage directory. This reduces size pressure on Data.fs but I have not been able to find any advice on backing up this data.
I am already backing up Data.fs by pointing a network backup tool at a directory of repozo backups. Should I simply point that too... | Backing up "blobstorage" will do it. No need for a special order or anything else, it's very simple.
All operations in Plone are fully transactional, so hitting the backup in the middle of a transaction should work just fine. This is why you can do live backups of the ZODB. Without knowing what file system you're on, ... | It should be safe to do a repozo backup of the Data.fs followed by an rsync of the blobstorage directory, as long as the database doesn't get packed while those two operations are happening.
This is because, at least when using blobs with FileStorage, modifications to a blob always results in the creation of a new fil... | What is the correct way to backup ZODB blobs? | [
"",
"python",
"plone",
"zope",
"zodb",
"blobstorage",
""
] |
I am writing a small matrix library in C++ for matrix operations. However, my compiler complains, where before it did not. This code was left on a shelf for six months and in between I upgraded my computer from [Debian 4.0](https://en.wikipedia.org/wiki/Debian_version_history#Debian_4.0_(Etch)) (Etch) to [Debian 5.0](h... | You have declared your function as `friend`. It's not a member of the class. You should remove `Matrix::` from the implementation. `friend` means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for `Mat... | I am just telling you about one other possibility: I like using friend definitions for that:
```
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
[...]
}
};
}
```
The function will be auto... | How can I properly overload the << operator for an ostream? | [
"",
"c++",
"namespaces",
"operator-overloading",
"iostream",
"ostream",
""
] |
I'm attempting to pass a pointer to a function that is defined in one class into another class. After much research, I believe my syntax is correct, but I am still getting compiler errors. Here is some code which demonstrates my issue:
```
class Base
{
public:
BaseClass();
virtual ~BaseClass();
};
class Deriv... | your syntax is correct for a C style function pointer. Change it to this:
```
Derived(string (MainClass::*funPtr)(int)) : strFunction(funPtr) {}
```
and
```
string (MainClass::*strFunction)(int value);
```
remember to call `strFunction`, you will need an instance of a MainClass object. Often I find it useful to use... | You can learn more about the grave wickedness that is [C++ member function pointer syntax here](http://www.codeproject.com/KB/cpp/FastDelegate.aspx). | unable to pass a pointer to a function between classes | [
"",
"c++",
""
] |
I want to turn a program I have into a service so I can use it without logging it. Basically what it does is it backs up specified folders to a specified location using SSH. However the problem I'm running into is I don't know how to tell it these items. I only know how to start, stop, and run a custom command with onl... | Any service is capable of receiving command line arguments at start-up. | You can instantiate your service and pass command line arguments using the ServiceController class.
```
using (ServiceController serviceController = new ServiceController(serviceName))
{
string[] args = new string[1];
args[0] = "arg1";
serviceController.Start(args);
}
```
"arg1" will then be available as reg... | Passing a Windows Service Parameters for it to act on | [
"",
"c#",
".net",
"parameters",
"service",
""
] |
I have a case where I need to translate (lookup) several values from the same table. The first way I wrote it, was using subqueries:
```
SELECT
(SELECT id FROM user WHERE user_pk = created_by) AS creator,
(SELECT id FROM user WHERE user_pk = updated_by) AS updater,
(SELECT id FROM user WHERE user_pk = owne... | The UDF is a black box to the query optimiser so it's executed for every row.
You are doing a row-by-row cursor. For each row in an asset, look up an id three times in another table. This happens when you use scalar or multi-statement UDFs (In-line UDFs are simply macros that expand into the outer query)
One of many a... | As other posters have suggested, using joins will definitely give you the best overall performance.
However, since you've stated that that you don't want the headache of maintaining 50-ish similar joins or subqueries, try using an inline table-valued function as follows:
```
CREATE FUNCTION dbo.get_user_inline (@user... | Why is a UDF so much slower than a subquery? | [
"",
"sql",
"sql-server",
"performance",
"sql-server-2008",
"user-defined-functions",
""
] |
I have a winforms application in which I am using 2 Forms to display all the necessary controls. The first Form is a splash screen in which it tells the user that it it loading etc. So I am using the following code:
```
Application.Run( new SplashForm() );
```
Once the application has completed loading I want the Spl... | Probably you just want to close the splash form, and not send it to back.
I run the splash form on a separate thread (this is class SplashForm):
```
class SplashForm
{
//Delegate for cross thread call to close
private delegate void CloseDelegate();
//The type of form to be displayed as the splash screen.... | This is crucial to prevent your splash screen from stealing your focus and pushing your main form to the background after it closes:
```
protected override bool ShowWithoutActivation {
get { return true; }
}
```
Add this to you splash form class. | C# winforms startup (Splash) form not hiding | [
"",
"c#",
"winforms",
"show-hide",
""
] |
I have an asp.net mvc application and i am trying to assign value to my textbox dynamically, but it seems to be not working (I am only testing on IE right now). This is what I have right now..
`document.getElementsByName('Tue').Value = tue;` (by the way tue is a variable)
I have also tried this variation but it didnt... | It's [document.getElementById](https://developer.mozilla.org/En/DOM/Document.getElementById), not document.getElementsByID
I'm assuming you have `<input id="Tue" ...>` somewhere in your markup. | How to address your textbox depends on the HTML-code:
```
<!-- 1 --><input type="textbox" id="Tue" />
<!-- 2 --><input type="textbox" name="Tue" />
```
If you use the 'id' attribute:
```
var textbox = document.getElementById('Tue');
```
for 'name':
```
var textbox = document.getElementsByName('Tue')[0]
```
(Note ... | Why is my element value not getting changed? Am I using the wrong function? | [
"",
"javascript",
"textbox",
""
] |
How can I find out how many rows a MySQL query returns in Java? | From the [jdbc faq](http://java.sun.com/products/jdbc/faq.html#18):
> .18. There is a method getColumnCount in the JDBC API. Is there a similar method
> to find the number of rows in a result set?
>
> No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods ... | I don't think you can, except maybe by calling `ResultSet.last()` and then `ResultSet.getRow()` - but I don't know if that will actually work. I've always just processed each row at a time, and counted them afterwards. | How can I find out how many rows a MySQL query returns in Java? | [
"",
"java",
"mysql",
"jdbc",
""
] |
How to write one SQL query that selects a column from a table but returns two columns where the additional one contains an index of the row (a new one, starting with 1 to n). It must be without using functions that do that (like row\_number()).
Any ideas?
Edit: it must be a one-select query | You can do this on any database:
```
SELECT (SELECT COUNT (1) FROM field_company fc2
WHERE fc2.field_company_id <= fc.field_company_id) AS row_num,
fc.field_company_name
FROM field_company fc
``` | ```
SET NOCOUNT ON
DECLARE @item_table TABLE
(
row_num INT IDENTITY(1, 1) NOT NULL PRIMARY KEY, --THE IDENTITY STATEMENT IS IMPORTANT!
field_company_name VARCHAR(255)
)
INSERT INTO @item_table
SELECT field_company_name FROM field_company
SELECT * FROM @item_table
``` | Sql query that numerates the returned result | [
"",
"sql",
""
] |
Is there a way in Java's for-each loop
```
for(String s : stringArray) {
doSomethingWith(s);
}
```
to find out how often the loop has already been processed?
Aside from using the old and well-known `for(int i=0; i < boundary; i++)` - loop, is the construct
```
int i = 0;
for(String s : stringArray) {
doSomethin... | No, but you can provide your own counter.
The reason for this is that the for-each loop internally does not *have* a counter; it is based on the [Iterable](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html) interface, i.e. it uses an `Iterator` to loop through the "collection" - which may not be a collec... | There is another way.
Given that you write your own `Index` class and a static method that returns an `Iterable` over instances of this class you can
```
for (Index<String> each: With.index(stringArray)) {
each.value;
each.index;
...
}
```
Where the implementation of `With.index` is something like
```
c... | Is there a way to access an iteration-counter in Java's for-each loop? | [
"",
"java",
"loops",
"for-loop",
"foreach",
""
] |
I want to add seconds (00:00:02) or minutes (00:00:20) on datetime value (may be stored string type) but how? Examples:
```
13:30+02:02:02= 15:32:02 ,
13:30+00:00:01= 13:30:01 ,
13:30+00:01:00=13:31:00 or 13:30 (not important)
```
Can you help me? I need your cool algorithm :) Thanks again... | If you choose to use the TimeSpan, be aware about the Days part:
```
TimeSpan t1 = TimeSpan.Parse("23:30");
TimeSpan t2 = TimeSpan.Parse("00:40:00");
TimeSpan t3 = t1.Add(t2);
Console.WriteLine(t3); // 1.00:10:00
```
With DateTime:
```
DateTime d1 = DateTime.Parse("23:30");
DateTime d2 = DateTime.Parse("00:40:00");
... | ```
myDateTimeVariable.Add(new TimeSpan(2,2,2));
``` | Add or Sum of hours like 13:30+00:00:20=13:30:20 but how? | [
"",
"c#",
".net",
"algorithm",
"datetime",
""
] |
I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions.
Is this possible? | I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".
OK, if ... | > **Note**: eval() can be easily misused, let say that the request is intercepted by a third party and sends you not trusted code. Then with eval() you would be running this not trusted code. Refer here for the [dangers of eval()](https://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil).
---
Insi... | Calling a JavaScript function returned from an Ajax response | [
"",
"javascript",
"ajax",
"function",
""
] |
I'm working on a class that inherits from another class, but I'm getting a compiler error saying "Cannot find symbol constructor Account()". Basically what I'm trying to do is make a class InvestmentAccount which extends from Account - Account is meant to hold a balance with methods for withdrawing/depositing money and... | use `super(customer)` in `InvestmentAccount`s constructor.
Java can not know how to call the **only** constructor `Account` has, because it's not an *empty constructor*. You can omit `super()` only if your base class has an empty constuctor.
Change
```
public InvestmentAccount(Person customer, int sharePrice)
{
... | You have to invoke the superclass constructor, otherwise Java won't know what constructor you are calling to build the superclass on the subclass.
```
public class InvestmentAccount extends Account {
protected int sharePrice;
protected int numShares;
private Person customer;
public InvestmentAccount(P... | Inheritance in Java - "Cannot find symbol constructor" | [
"",
"java",
"inheritance",
"polymorphism",
""
] |
How can I convert markdown into html in .NET?
```
var markdown = "Some **bold** text";
var output = ConvertMarkdownToHtml(markdown)
// Output: <p>Some <strong>bold</strong> text</p>
```
I have Markdown text stored in a database that needs to be converted to html when it is displayed.
I know about StackOverflow's [WM... | [Markdown Sharp](https://github.com/StackExchange/MarkdownSharp) is what the site uses and is available on [NuGet](https://www.nuget.org/packages/MarkdownSharp/). | TL;DR: now it's 2021 use [markdig](https://github.com/xoofx/markdig)
I just came across this questions and the answers are all quite old. It appears that implementations based on [commonmark](https://commonmark.org/) are the suggested way to go now. Implementations for lots of languages (including C#) can be found [he... | Convert Markdown to HTML in .NET | [
"",
"c#",
"html",
".net",
"markdown",
""
] |
Compiler error [CS0283](http://msdn.microsoft.com/en-us/library/ms228656(VS.80).aspx) indicates that only the basic POD types (as well as strings, enums, and null references) can be declared as `const`. Does anyone have a theory on the rationale for this limitation? For instance, it would be nice to be able to declare ... | From the [C# specification, chapter 10.4 - Constants](http://msdn.microsoft.com/en-us/library/aa645749(VS.71%29.aspx):
*(10.4 in the C# 3.0 specification, 10.3 in the online version for 2.0)*
> A constant is a class member that represents a constant value: a value that can be computed at compile time.
This basicall... | > I believe that the concept of const is actually syntactic sugar in C#, and that it just replaces any uses of the name with the literal value
What does the compiler do with const objects in other languages?
You can use readonly for mutable types that me be evaluated at runtime. See [this article](http://en.csharp-on... | Why does C# limit the set of types that can be declared as const? | [
"",
"c#",
"constants",
"compiler-errors",
""
] |
**Note:**
* Using **raw Win32** CreateTheard() API
* No MFC
* An interface is simply a pointer to a vtable
**Question:**
* How to pass an interface pointer to a thread?
**Illustration:**
```
IS8Simulation *pis8 = NULL;
...
CoCreateInstance(
clsid,
NULL,
CLSCTX_L... | As was stated below, passing a `COM` interface pointer between threads in not safe.
Assuming you know what you are doing:
```
hThread = CreateThread(
NULL,
0,
SecondaryThread,
(LPVOID) pis8
0,
... | If the interface in your question is a COM interface, the approach given by Quassnoi might not be sufficient. You have to pay attention to the threading-model of the COM object in use. If the secondary thread will join a separate COM apartment from the one that your COM object was created in, and if that object is not ... | How to pass an interface pointer to a thread? | [
"",
"c++",
"multithreading",
"com",
"interface",
"marshalling",
""
] |
I have several somewhat separate programs, that conceptually can fit into a single project. However, I'm having trouble telling Eclipse to make several folders inside a project folder.
A simple form of the structure would be:
```
/UberProject
/UberProject/ProgramA/
/UberProject/ProgramA/com/pkg/NiftyReader.java
/Uber... | There are probably several ways to do this:
1) UberProject is your JavaProject. Right click ProgramA -> Build Path -> Use as source folder. Right click ProgramB -> Build Path -> Use as source folder. Both ProgramA and ProgramB will do incremental builds to the same directory.
2) Two java projects (ProgramA and Progra... | You can have multiple source directories in a single project, but your description makes it sound like you want multiple sub-projects in a project, which eclipse doesn't allow (as far as I know).
If you really just want multiple source directories, where `ProgramA`, `ProgramB`, etc. contain only java files and nothing... | How to set up multiple source folders within a single Eclipse project? | [
"",
"java",
"eclipse",
""
] |
There is a data file and some image files that I have to download to our local servers every night using asp.net. What is the best way to do this?
UPDATE
Ok, after viewing the responses I see my initial post of using asp.net is a poor choice. How would you write it for a console app in C#. I am not sure what classes ... | > > "How would you write it for a console app in C#."
Create a C# console application. Add a reference to System.Net.
```
using System;
using System.Net;
namespace Downloader
{
class Program
{
public static void Main(string[] args)
{
using (WebClient wc = new WebClient())
... | To download any file from remote URL you can use WebClient in C# inside System.Net namespace.
public FileResult Song(string song)
{
```
WebClient client = new WebClient();
var stream = client.OpenRead("http://www.jplayer.org/audio/mp3/Miaow-03-Lentement.mp3");
return File(stream, "audio/mpeg"... | Download files using asp.net | [
"",
"c#",
".net",
"asp.net",
"file",
"download",
""
] |
I encountered some code reading
```
typedef enum eEnum { c1, c2 } tagEnum;
typedef struct { int i; double d; } tagMyStruct;
```
I heard rumours that these constructs date from C. In C++ you can easily write
```
enum eEnum { c1, c2 };
struct MyStruct { int i; double d; };
```
Is that true? When do you need the firs... | First, both declarations are legal in both C and C++. However, in C, they have slightly different semantics. (In particular, the way you refer to the struct later varies).
The key concept to understand is that in C, structs exist in a separate namespace.
All built-in types, as well as typedefs exist in the "default" n... | In C, if you were to write
```
struct MyStruct { int i; double d; };
```
whenever you wanted to reference that type, you'd have to specify that you were talking about a struct:
```
struct MyStruct instanceOfMyStruct;
struct MyStruct *ptrToMyStruct;
```
With the typedef version:
```
typedef struct { int i; double d... | When don't I need a typedef? | [
"",
"c++",
"c",
"typedef",
""
] |
is it possible to make beep in WinCE ?
i try and i get an error | The .net framework methods for beeing are not available in the CF version of the framework. The best way to get a beep sound is to PInvoke into the MessageBeep function. The PInvoke signature for this method is pretty straight forward
```
[DllImport("CoreDll.dll")]
public static extern void MessageBeep(int code);
pub... | Yes. P/Invoke [PlaySound](http://msdn.microsoft.com/en-us/library/aa909766.aspx) or [sndPlaySound](http://msdn.microsoft.com/en-us/library/aa909803.aspx) or [MessageBeep](http://msdn.microsoft.com/en-us/library/aa930642.aspx). See [this](http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesvbcs/thread/8d96cca1-7... | beep in WinCE , it possible ? | [
"",
"c#",
"compact-framework",
"audio",
""
] |
(Title was: "How to write a unit test for a DBUS service written in Python?")
I've started to write a DBUS service using dbus-python, but I'm having trouble writing a test case for it.
Here is an example of the test I am trying to create. Notice that I have put a GLib event loop in the setUp(), this is where the prob... | With some help from Ali A's post, I have managed to solve my problem. The blocking event loop needed to be launched into a separate process, so that it can listen for events without blocking the test.
Please be aware my question title contained some incorrect terminology, I was trying to write a functional test, as op... | Simple solution: don't unit test through dbus.
Instead write your unit tests to call your methods directly. That fits in more naturally with the nature of unit tests.
You might also want some automated integration tests, that check running through dbus, but they don't need to be so complete, nor run in isolation. You... | How to write a functional test for a DBUS service written in Python? | [
"",
"python",
"unit-testing",
"dbus",
""
] |
```
<h:commandLink id="#{id}" value="#{value}" action="#{actionBean.getAction}" onclick="alert(this);"/>
```
In the previous simplified example, the 'this' keyword used in the Javascript function won't reference the generated A HREF element, but will reference to the global window, because JSF generates the follow... | EDIT:
Go here for a small library/sample code for getting the *clientId* from the *id*: [JSF: working with component IDs](http://illegalargumentexception.blogspot.com/2009/02/jsf-working-with-component-ids.html)
---
The HTML ID emitted by JSF controls is namespaced to avoid collisions (e.g. the control is a child of... | > var a=function(){alert(this)};var b=function(){if(typeof jsfcljs == 'function'){jsfcljs(document.forms['mainForm'],'generatedId,action,action','');}return false};return (a()==false) ? false : b();
Oh dear lord! That's violently horrible.
And no, it appears to be throwing away 'this' before you get a chance to look ... | How to reference 'this' from a javascript call in a JSF component? | [
"",
"javascript",
"jsf",
""
] |
I as of yet, have not had a need to create a dll in .NET as my programs tend to be distinct from one another (and I haven't programmed for too long). However I am starting to gather a library of regularly used methods now which tend to have copies in lots of my programs (or similar methods that could be made more gener... | "Good practice" in this case really relies on how much code-duplication you're cutting down on. If these dialogues are used throughout a lot of your programs and they take up a lot of code, then yes, it's probably a good idea to move them to a shared space.
But don't be tempted to throw everything in there. You'll fin... | To create a new dll, you just add new project (library) to your solution, and add it as a project reference to your main programme.
It is possible to put anything you want to this project. All dialog boxes, user controls, etc. are just classes, so you can share them as easily as any other class. I think it is good pra... | When to create your own dll what should be in it | [
"",
"c#",
"dll",
""
] |
I need to bind a method into a function-callback, except this snippet is not legal as discussed in [demote-boostfunction-to-a-plain-function-pointer](https://stackoverflow.com/questions/282372/demote-boostfunction-to-a-plain-function-pointer/512189#512189).
What's the simplest way to get this behavior?
```
struct C {... | You can make your own class to do the same thing as the boost bind function. All the class has to do is accept the function type and a pointer to the object that contains the function. For example, this is a void return and void param delegate:
```
template<typename owner>
class VoidDelegate : public IDelegate
{
publi... | Either you can shove that bound parameter into a global variable and create a static function that can pick up the value and call the function on it, or you're going to have to generate per-instance functions on the fly - this will involve some kind of on the fly code-gen to generate a stub function on the heap that ha... | raw function pointer from a bound method | [
"",
"c++",
"boost",
"delegates",
"callback",
""
] |
I need to concatenate 3 files using C#. A header file, content, and a footer file, but I want to do this as cool as it can be done.
Cool = really small code or really fast (non-assembly code). | ```
void CopyStream(Stream destination, Stream source) {
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while( (count = source.Read(buffer, 0, buffer.Length)) > 0)
destination.Write(buffer, 0, count);
}
CopyStream(outputFileStream, fileStream1);
CopyStream(outputFileStream, fileStream2);
CopyStream... | I support Mehrdad Afshari on his code being exactly same as used in [System.IO.Stream.CopyTo](http://msdn.microsoft.com/en-us/library/system.io.stream.copyto.aspx).
I would still wonder why did he not use that same function instead of rewriting its implementation.
```
string[] srcFileNames = { "file1.txt", "file2.txt"... | What would be the fastest way to concatenate three files in C#? | [
"",
"c#",
"file",
""
] |
```
function get_total_adults()
{
$sql = "SELECT SUM(number_adults_attending) as number_of_adults FROM is_nfo_rsvp";
$result = mysql_query($sql) or die(mysql_error());
$array = mysql_fetch_assoc($result);
return $array['number_of_adults'];
}
```
I know there is a way to write this with less code. ... | ```
function get_total_adults() {
$sql = 'SELECT SUM(number_adults_attending) FROM is_nfo_rsvp';
$result = mysql_query($sql) or die(mysql_error());
// I'd throw a catchable exception (see below) rather than die with a MySQl error
return mysql_result($result, 0);
}
```
As to how I'd rather handle error... | You can drop the "as number\_of\_adults" part of the query and use mysql\_result. | What is the most efficient way to rewrite this function? | [
"",
"php",
""
] |
I'm trying to add a space before every capital letter, except the first one.
Here's what I have so far, and the output I'm getting:
```
>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'
```
I want:
'This File Name.txt'
(It'd be nice if I could also get rid of .txt, but I can do that in ... | Key concept here is backreferences in regular expressions:
```
import re
text = "ThisFileName.txt"
print re.sub('([a-z])([A-Z])', r'\1 \2', text)
# Prints: "This File Name.txt"
```
For pulling off the '.txt' in a reliable way, I recommend `os.path.splitext()`
```
import os
filename = "ThisFileName.txt"
print os.path... | ```
re.sub('([a-z])([A-Z])', '\\1 \\2', 'TheFileName.txt')
```
EDIT: StackOverflow eats some \s, when not in 'code mode'... Because I forgot to add a newline after the code above, it was not interpreted in 'code mode' :-((. Since I added that text here I didn't have to change anything and it's correct now. | Python regex: Turn "ThisFileName.txt" into "This File Name.txt" | [
"",
"python",
"regex",
""
] |
I'm working on a web project that will (hopefully) be available in several languages one day (I say "hopefully" because while we only have an English language site planned today, other products of my company are multilingual and I am hoping we are successful enough to need that too).
I understand that the best practic... | Typically if you use a template engine such as [Sitemesh](http://www.opensymphony.com/sitemesh/) or [Velocity](http://velocity.apache.org/tools/devel) you can manage these smaller HTML building blocks as subtemplates more effectively.
By so doing, you can incrementally boil down the strings which are the purely intern... | As others have said, please never split the strings into segments. You will cause translators grief as they have to coerce their language syntax to the ad-hoc rules you inadvertently create. Often it will not be possible to provide a grammatically correct translation, especially if you reuse certain segments in differe... | Best practices in internationalizing text with lots of markup? | [
"",
"java",
"templates",
"internationalization",
"markup",
""
] |
I often read about dependency injection and I did research on google and I understand in theory what it can do and how it works, but I'd like to see an actual code base using it (Java/guice would be preferred).
Can anyone point me to an open source project, where I can see, how it's really used? I think browsing the c... | I understand you're in Java-land, but in the .NET space the are several open-source apps written using an inversion of control container. Check out [CodeCampServer](http://code.google.com/p/codecampserver/), in which the UI module doesn't have a reference to the dependency resolution module. There is an HttpModule that... | The [Wave Protocol Server](http://code.google.com/p/wave-protocol/source/browse/src/org/waveprotocol/wave/examples/fedone/) is my favourite example app. | Projects with browsable source using dependency injection w/ guice? | [
"",
"java",
"dependency-injection",
"design-patterns",
"guice",
""
] |
Given the following class definitions:
```
public class BaseClass
{
public string SomeProp1 { get; set; }
}
public class DerivedClass : BaseClass
{
public string SomeProp2 { get; set; }
}
```
How can I take a `List<BaseClass>` and convert it to a `List<DerivedClass>`?
In my real-world scenario `BaseClass` h... | ```
List<DerivedClass> result =
listBaseClass.ConvertAll(instance => (DerivedClass)instance);
```
Actually ConvertAll is good when you need to create new objects based on the original, when you just need to cast you can use the following
```
List<DerivedClass> result =
listBaseClass.Cast<DerivedClass>().ToL... | You can't convert the actual object, but it's easy to create a new list with the converted contents:
```
List<BaseClass> baseList = new List<BaseClass>(...);
// Fill it here...
List<DerivedClass> derivedList = baseList.ConvertAll(b => (DerivedClass) b);
```
Or if you're not using C# 3:
```
List<DerivedClass> derive... | Copying a List<BaseClass> to List<DerivedClass> | [
"",
"c#",
".net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.