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 generator has run and the files are created they never show up in my project (new files , old existing files are fine). To add them i have to show hidden files (In visual studio) then include all of the files manually. So is there anyway to automatically include these files into my project.
Thanks in advance | 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" />
```
6) File.Save
7) Right click on the project node.
8) Select "Reload project".
To learn more about this read up on MSBuild. | 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 when I ran the program and clicked clear I got the following runtime error:
Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.CheckBox'. | 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_click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
CheckBox cb = c as CheckBox;
if (cb != null)
{
cb.Checked = false;
}
}
}
``` | 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 if I sum the quantities to have the result 40, I would sum up the first two witch means: 10 + 30 = 40. That way, the last Id that is used to sum the number 40 is 2. I just want to know the id of the last row that is used to complete the sum of 40.
I would give further details if asked. THANK YOU!!
---
Let me put it this way:
I really have 6 products in my hand. The first one came to my possession on the date of 10, the next 3 came on the date of 11 and the last 2 came on 12.
Now, I want to sell 3 products from my stock. And want to sell them in the order that they came. So for the customer that wants 3 products I would sell him the product that came on 10 and 2 products from the ones that came on 11.
For the next customer that wants 2 products, I would sell him one product from the date of 11 that remains from the last order of 3 products, and another one from the ones on 12.
The question is how would I know which price had each product I sold ? I thought that if I can find out which rows sums up every requested quantity, I would know where to start the sum every time I want to deliver an order. So first I would look which rows sums up 3 products and keep the entry id. For the next order I would start the count from that ID and sum until it sums up the second order of 2 products and so on. I thought that this way, I can keep track of the incoming prices that each product had. So I won't sell the products from the date of 12 at a price made up using the first prices.
I hope you understand. I just need to know what price had any of my products so I would know that the first products would have one price but as the product prices raises, I must raise my prices too...So the last products that came must be sold for a higher price. I can only achieve that if I keep track of this...
Thank you very much.
---
Nobody ? Or, even easier: MySQL should select the needed rows for SUM(`quantity`) to be higher or equal with 40 for example. And then to get me the id of the last row that participated at the sum process. | 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 **which** price had each product I sold"? Which sorta confuses me, since each value in the database has no price attribute. Shouldn't your database look like this:
```
ProductID ArrivalDate Price
1 10 100
2 11 200
3 11 300
4 11 300
5 12 400
6 12 400
```
Personally, I think your idea to find out price sold is flawed. It would make more sense to add a few more fields to your database:
```
ProductID ArrivalDate Price InStock DateSold
1 10 100 Yes 17
2 11 200 Yes 17
3 11 300 Yes 18
4 11 300 Yes 18
5 12 400 no
6 12 400 no
```
In changing your database, you can easily keep track of when a product arrives, the date sold, its price, maybe quantity (I can't tell if its an actual field or not).
Furthermore, you can simplify and make your life easier by separating the sql queries, or even adding some code to do some of the work for you. | 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 in the table, remember to update all subsequent rows `RunningTotal -= DeletedRow.Quantity`! | 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)#Magic_numbers_in_files>
EDIT: I believe this is more reliable than MIME functions on PHP. | 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 files, the file content is internally loaded from disk as needed. | 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 elit. Ut fringilla pede blandit
eros sagittis viverra. Curabitur facilisis
urna ABC elementum lacus molestie aliquet.
Vestibulum lobortis semper risus. Etiam
sollicitudin. Vivamus posuere mauris eu
nulla. Nunc nisi. Curabitur fringilla fringilla
elit. Nullam feugiat, metus et suscipit
fermentum, mauris ipsum blandit purus,
non vehicula purus felis sit amet tortor.
Vestibulum odio. Mauris dapibus ultricies
metus. Cras XYZ eu lectus. Cras elit turpis,
ultrices nec, commodo eu, sodales non, erat.
Quisque accumsan, nunc nec porttitor vulputate,
erat dolor suscipit quam, a tristique justo
turpis at erat.
```
And this was your regex:
```
consectetur(?=\sadipiscing)
```
Now this regex uses [positive lookahead](http://www.regular-expressions.info/lookaround.html) and will only match a string of "consectetur" if it is immediately followed by any whitepace character and then a string of "adipiscing".
So in this example you would have to read the whole file into memory because your regex is depending on the entire file being parsed as a single string. This is one of many examples that would require you to have your entire string in memory for a particular regex to work.
I guess the unfortunate answer is that it all depends on your situation. | 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 functions from a DLL, in order to control a USB hardware device from Java. (the DLL comes from the device manufacturer) It works really nicely. Thanks! | 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 least resistance.
See their [getting started guide](https://github.com/twall/jna/blob/master/www/GettingStarted.md) where they call some native code (printf and GetSystemTime). | 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 lovely language...) | 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 custom brush in your class that you use to paint your text on every `OnPaint` call, but also don't create a new brush for every line of text you draw within that OnPaint call, either. | 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 format in C#? | ```
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 month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.) | > 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 go "middle/low/high" in terms of scale like that.)
Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...
To resolve that problem i do someting like this:
```
IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
return date.ToString("MM/dd/yy", yyyymmddFormat);
``` | 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 way, so the compiler doesn't complain about it. Any suggestions? | 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. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
``` | ```
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):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
```
(*taken from* [*http://code.activestate.com/recipes/134892/*](http://code.activestate.com/recipes/134892/)) | 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:
```
private void Split() {
char[] strArr = FlowArgs.Filename.ToCharArray();
int num;
//get the last number
if(Int32.TryParse(strArr[strArr.Length - 1].ToString(), out num)) {
num += 1;
}
//replace the old number with the new number
char.TryParse(num.ToString(), out strArr[strArr.Length - 1]);
FlowArgs.Filename = strArr.ToString();
}
```
Edit:
I have added a "version" property (int) in the FlowArgs class. However my new problem is that how can I append this at the end of thefilename | 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 is much more memory wasted than these 4 bytes.
**EDIT**: You probably want to have a method like GetNextFileName() in your class that generates you the next filename (being able to refactor your code into small bits is important, much more important than saving memory space):
```
private int nextFileNumber = 0;
private string GetNextFileName(string userName)
{
return String.Format("{0}-{1}-{2}", DateTime.Now, userName,
nextFileNumber++);
}
``` | "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:**
the view says:
> One row per server process, showing database OID, database name, process ID, user OID, **user name**, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and **client's address and port number**. The columns that report data on the current query are available unless the parameter stats\_command\_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.
can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...
something like that. | 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 the database, and definitely points to a valid image. When I run my page without the code to resize, the image is displayed perfectly.
```
<?php
header("Content-Type: text/html; charset=utf-8");
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost", "someuser", "notreal");
if(!$con)
{
die('Connection failed because of' . mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("somedb",$con);
if($cmd == "GetAuctionData")
{
$sql="SELECT * FROM AUCTIONS WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM AUCTIONS WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$columns = array('FINISHED', 'WATCH', 'PRIVATE_AUCTION', 'REVISED', 'PAYPAL_ACCEPT', 'PRE_TERMINATED', 'PIC_XXL', 'PIC_DIASHOW');
foreach($columns as $column)
{
$$column = $row[$column] ? 'YES' : 'NO';
}
$lastImg = $row['PIC_URL'];
$maxWidth = 250;
$maxHeight = 300;
$size = getimagesize($_SERVER['DOCUMENT_ROOT'] . $lastImg);
var_dump($size);
echo "SIZE = ".$size."";
if ($size) {
$imageWidth = $size[0];
$imageHeight = $size[1];
$wRatio = $imageWidth / $maxWidth;
$hRatio = $imageHeight / $maxHeight;
$maxRatio = max($wRatio, $hRatio);
else {
die(print_r(error_get_last())); }
else if ($maxRatio > 1) {
$outputWidth = $imageWidth / $maxRatio;
$outputHeight = $imageHeight / $maxRatio;
} else {
$outputWidth = $imageWidth;
$outputHeight = $imageHeight;
}
}
echo "<h1>".$row['ARTICLE_NAME']."</h1>
<div id='rightlayer'>
<img src='".$lastImg."' width='".$outputWidth."' height='".$outputHeight."'>
</div>";
}
}
mysql_free_result($result);
``` | 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 ($maxRatio > 1) {
$outputWidth = $imageWidth / $maxRatio;
$outputHeight = $imageHeight / $maxRatio;
} else {
$outputWidth = $imageWidth;
$outputHeight = $imageHeight;
}
} else {
die(print_r(error_get_last()));
}
```
After that, we can look at the error and try to investigate further. | 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 structure from it, and then uses SharpSvn to import the result into the repository. This works… the first time. The second time, of course, a directory of that name already exists in the repository, and I can't import again.
Instead, I could:
1. Delete the directory, *then* import. I haven't tested this, but aside from sounding stupid, it probably also deletes the revision history of the respective files, regarding the new ones as entirely different.
2. See if the directory exists, check it out, remotely delete the files that no longer exist in the canonical source, then replace the remainder and commit. This would probably work, but sounds error-prone and needlessly difficult.
Is my assumption correct that deleting files will mark new ones of the same ways as *different* files? Is there an easier way than the second approach? | 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 files before committing.
But it seems you should consider using the svn-load-dirs.pl script. You can read about this in the Subversion book, chapter "[Vendor branches](http://svnbook.red-bean.com/en/1.1/ch07s05.html)". | 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 the repository information at the folder level. So, if you create a new folder, it won't automatically have a connection to Subversion. (Using something like TortoiseSvn, it takes care of much of that for you.)
If you are going to be adding and deleting directories during the generation process, you'll have some slightly different issues than with the files themselves. But, you can still accomplish your goal through the command-line, SharpSvn, TortoiseSvn, or other similar tools. | 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:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%
```
> or:
```
JAVA_OPTS="-Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n $JAVA_OPTS"
```
In the Debug frame, select the Remote Java Application node.
In the Connection Properties, specify `localhost` as the Host and specify the Port as the port that was specified in the run batch script of the JBoss server, `8787`.
 | 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 to create the file?
I know the definition of "valid file path" varies depending on the OS, but I was wondering if there was any quick way of accepting `C:/foo` or `/foo` and rejecting `banana`.
A possible approach may be attempting to create the file and eventually deleting it if the creation succeeded, but I hope there is a more elegant way of achieving the same result. | 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 directory. | 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 false
* isValidPath("c/te*t"); //returns false
* isValidPath("good.txt"); //returns true
* isValidPath("not|good.txt"); //returns false
* isValidPath("not:good.txt"); //returns false
* </pre>
*/
public static boolean isValidPath(String path) {
try {
Paths.get(path);
} catch (InvalidPathException | NullPointerException ex) {
return false;
}
return true;
}
```
Edit:
Note Ferrybig's
[comment](https://stackoverflow.com/questions/468789/is-there-a-way-in-java-to-determine-if-a-path-is-valid-without-attempting-to-cre/35452697#comment98546017_35452697) : "The only disallowed character in a file name on Linux is the NUL character, this does work under **Linux**." | 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.CurrentUICulture = ci;
```
But, of course, this gets "lost" when we want to do something in a new thread. Is there a way of setting that `CurrentCulture` and `CurrentUICulture` for the whole application? So that new threads also gets that culture? Or is it some event fired whenever a new thread is created that I can hook up to? | 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 AppDomain. There is a private static field on `CultureInfo` (`m_userDefaultCulture` in .NET 2.0 mscorlib, `s_userDefaultCulture` in .NET 4.0 mscorlib) that controls what `CurrentCulture` returns if a thread has not set that property on itself.
This does not change the native thread locale and it is probably not a good idea to ship code that changes the culture this way. It may be useful for testing though. | 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.getInstance();
cal.set(1900 + year, month, day);
d = cal.getTime();
```
Now, obviously deprecation warnings are not a problem in themselves, but can you imagine the millions of LOC that would be crying out in agony if this constructor was ever removed?
In my brief little play at benchmarking, the latter takes about 50% more time to execute. | 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 created `Calendar` to deal with all that complexity, and relegated `Date` to a simple timestamp, deprecating all its functionality that dealt with formatting, parsing and individual date fields.
BTW, internally these methods such as `Date(int, int, int)` constructor now call `Calendar`, so if you see a difference in speed, then you're doing something wrong when calling `Calendar`.
The bottomline: It's not Java's `Calendar` API that is overly complex, it's the human concept of dates, and the only problem with `Calendar` is that it offers not much in the way of shortcuts to the most common usages. | 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/lang/) for alternative Date/Time utilities. | 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 looks like this right now:
...
```
<li id="track1">
<a href="location of track" style="display:none">track1</a>
<a href="#" onclick="YAHOO.MediaPlayer.addTracks(WHAT SHOULD I PUT HERE?, null, true);">Add this to the playlist</a>
</li>
```
if anyone has worked with YMP or has any idea about this please help. | 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</a>
</li>
``` | 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 programming endeavor, the more you know about the language and tools you're using, the better. | 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 enjoyed this book. | 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 ()
{
return IMAGE;
},
setImage : function (imageSrc_)
{
IMAGE = '<img id="image" src="' + imageSrc_ + '" height="100%" width="100%">';
}
};
};
var PAGES = [];
return {
addPage : function ()
{
var len = PAGES.length + 1;
PAGES[len] = new Page();
return PAGES[len];
},
page : function (pageNumber_)
{
var result = PAGES[pageNumber_];
return result;
}
};
};
// Begin executing
$(document).ready(function ()
{
Product.addPage.setImage('http://site/images/small_logo.png');
alert(Product.page(1).image());
});
``` | 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/images/small_logo.png');
alert(product.page(1).image());
});
```
which also adds the brackets to the addPage call (though this is not the problem that FireBug will have been complaining about as it will not be able to find that method anyway). | 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.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username);
Flow palm = new Flow(new FlowArguments(form1.username, filename), hold);
System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
System.Windows.Forms.ContextMenuStrip notificationIconContext = new System.Windows.Forms.ContextMenuStrip();
//Create a context menu strip
ToolStripMenuItem contextAbout = new ToolStripMenuItem("About");
ToolStripMenuItem contextExit = new ToolStripMenuItem("Exit");
//properties of notifyicon that SO dosnt care for including a event handler for the mouse click events.
//wait for the background thread to finish.
hold.WaitOne(Timeout.Infinite);
MessageBox.Show("Thankyou, exiting...");
form1.Dispose();
}
```
As you see **The FLOW class is pretty simple. It just has a Threading.Timer which is run. Therefore on the UI thread i have to call WaitHandle.WaitOne() method, because otherwise the UI thread finishes and therefore ending the application..**
My goal: Since there's no GUI, i want to create a notify icon. It works and everything,except I can't click on it and its not responsive, this is because it is created on the UI thread. I can't put it in the flow class because the Flow class is also on the UI thread (the timer in the Flow class is in background thread).
So how can I keep my notifyicon responsive while running the timer in the Flow class? I thought waithandle was my solution but since its a blocking method it doesn't work.
Any other ideas/solutions?
edit: response to Rich's answer: The Flow class is on the background thread and everything runs the way it should. But if I don't add the waithandle in the UI thread, the main() finishes on the UI thread therefore terminating the whole program. (even though the timer is enabled on the background thread). Is there another solution to waithandle? because I have to leave it in for the Flow class to do its thing. If I take it out, the program ends, if I leave it in it blocks the UI thread therefore my notifyicon dosnt work. | 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 asynchronously - the simplest way to do this is to call ThreadPool.QueueUserWorkItem() on a delegate which calls the function (although you're not really supposed to use thread pool threads for long running operations, but I doubt it will hurt in this case)
* Once the flow method is done, call back to the UI thread to let it know. You can do this by calling form1.Invoke with a suitable delegate
* In the function which is then called (i.e. on the UI thread) close the form and exit your application
So the end result looks like 3 functions:
* the function above, which starts the processing in the background and then returns without waiting
* the background processing function, executed on a seperate thread
* the function called on the UI thread when processing is complete, which closes the application | 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 object seems to be executing the logic of your application which would make more sense to be spawned on another thread. | 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/en-us/library/yh598w02.aspx) says that it is not called, but I have read otherwise.
I know that the FileStream inherrits from Stream which is explained [here](http://msdn.microsoft.com/en-us/library/ms227422.aspx). Now that says not to override Close() because it is called by Dispose().
So do some classes just call Close() in their Dispose() methods or does the using call Close()? | 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
> Dispose pattern. This method calls
> Close, which then calls
> Stream.Dispose(Boolean). | 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 I mean is that by default, you can set the *MembershipProvider* property in a login control for authentication. This property refers to a locally defined provider in machine.config or web.config.
what I want is to stop using that provider defined locally and call the remote WCF authentication service instead. Sorry for not making myself clear. | 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 Authenticate event. This has to be done in order to override the default behavior of authenticating with the default membership provider and do a custom authentication. In this event, create an instance of the proxy authenticationservice class and call Login method.
`proteted void login_Authenticate(object sender, AuthenticateEventArgse){
AuthenticationServiceClient client = new AuthenticationServiceClient();
e.Authenticated = client.Login(login.UserName, login.Password, "", true);
}` | 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 use the same cache for both CLI and web invocations? | 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 help you, and I'm sorry for my English.... | 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 could be thousands. Should I take into account the number of CPU cores? What else matters?
Thanks. | 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 always appear at within a given period to handle a request.
Having a bunch of threads which just move data in parallel is a rather inefficient shot-gun (Creating one thread per request naturally just fails completely). Using the [thread pool](http://en.wikipedia.org/wiki/Thread_pool_pattern) pattern can be a more effective, focused approach to decreasing latency.
Now, in the thread pool, you want to have at least as many threads as you have CPUs/cores. You can have more than this but the extra threads will again only decrease latency and not increase speed.
Think the problem of organizing server threads as akin to organizing a line in a super market. Would you like to have a lot of cashiers who work more slowly or one cashier who works super fast? The problem with the fast cashier isn't speed but rather that one customer with a lot of groceries might still take up a lot of their time. The need for many threads comes from the possibility that a few request that will take a lot of time and block all your threads. By this reasoning, whether you benefit from many slower cashiers depends on whether your have the same number of groceries or wildly different numbers. Getting back to the basic model, what this means is that you have to play with your thread number to figure what is optimal given the particular characteristics of your traffic, looking at the time taken to process each request. | 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 hyperthreads -- mixed instruction workloads work better.
### Ratio of IO to Computation (`%IO`)
If the threads never wait for IO but always compute (%IO = 0), using more threads than XUs only increase the overhead of memory pressure and context switching. If the threads always wait for IO and never compute (%IO = 1) then using a variant of `poll()` or `select()` might be a good idea.
For all other situations `XU / %IO` gives an approximation of how many threads are needed to fully use the available XUs.
### Available Memory (`Mem`)
This is more of a upper limit. Each thread uses a certain amount of system resources (`MemUse`). `Mem / MemUse` gives you an approximation of how many threads can be supported by the system.
### Other Factors
The performance of the whole system can still be constrained by other factors even if you can guess or (better) measure the numbers above. For example, there might be another service running on the system, which uses some of the XUs and memory. Another problem is general available IO bandwidth (`IOCap`). If you need less computing resources per transferred byte than your XUs provide, obviously you'll need to care less about using them completely and more about increasing IO throughput.
For more about this latter problem, see this [Google Talk about the Roofline Model](http://www.youtube.com/watch?v=A2H_SrpAPZU). | 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, nor any Cocoa/Carbon frameworks, just pure C++.
Here is the code that works in my other Xcode template:
```
sound->LoadMusic( (std::string) "Resources/Audio/Pop.wav" );
```
This relative path works for me also in Windows. Running the following command gives me an absolute path to the application's full path:
```
std::cout << "Current directory is: " << getcwd( buffer, 1000) << "\n";
```
/Applications/myApp
How can we get relative paths to work in an Xcode .app bundle? | 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 Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
std::cout << "Current Path: " << path << std::endl;
#endif
// ----------------------------------------------------------------------------
```
I've thrown some extra include guards because this makes it compile Apple only (I develop cross platform) and makes the code nicer.
I thank the other 2 guys for your answers, your help ultimately got me on the right track to find this answer so i've voted you both up. Thanks guys!!!! | 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 there.
If you're just experimenting and want it to work, in Xcode choose Project > Edit Active Executable, and there's a panel there in which you can set the initial working directory to the project directory, the executable's parent directory, or any arbitrary directory. This should only be used for testing purposes. In the Mac OS, when you write a real app and launch it from the Finder, the working directory is /. And for Unix apps you have no control whatsoever over what the working directory is. | 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 (NHibernate). The generated query looks like:
```
SELECT P FROM SumTotal.TP.Models.Party.Person P join P.Demographics PD WHERE (PD.LastName LIKE '%カタカ%' )
```
Unfortunately, placing a 'N' in front of the literal in the HQL results in an error. I've tried escaping the unicode characters in the string and still no success.
The database is accepting and saving unicode characters from Hibernate. I've been able to successfully populate an object with a unicode string, save it with Hibernate, and verify it in the database. It would seem to me as a little odd that I cannot use unicode strings in custom queries (or I'm also assuming named queries).
Is this a known issue or limitation of Hibernate (Nhibernate)? How do you use unicode in HQL?
Several sites suggest using the Criteria queries. Due to constraints in the framework that I'm working in, this is not possible. | 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.Demographics PD WHERE (PD.LastName LIKE '%カタカ%')
```
The where clause contains this literal:
```
'%カタカ%'
```
This literal can be broken up into nchars which Hibernate (Nhibernate) will unknowingly pass through to the SQL it generates. Odd, but it works. Thus the previous query could be written as:
```
SELECT P FROM SumTotal.TP.Models.Party.Person P join P.Demographics PD WHERE (PD.LastName LIKE '%' + nchar(0x30AB) + nchar(0x30BF) + nchar(0x30AB)+ '%')
```
This solution is far from optimal because it would require going through each character and determining if it was a multibyte character. However, in the case of where this code lives in its app it is used in a dynamic query generator that processes multiple different criteria under different operations. In the example I give it is looking for unicode anywhere in the string. It is possible that this function may be returning the where clause portion for a column equaling a specific numeric value or it could be looking for the starting characters of a string. The method that builds the operator uses a operator type and the term to hand back a string. I could rewrite that but it would be a large task. The above fix will allow me to process a string passed into this method. I offer this solution because it does work, but darin's answer is probably the best way I could find. | 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?
**EDIT:** I have tried getting a reference to the graphics object, but this is done in a class that inherits from `Telerik.Reporting.Report`. | 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.Graphics = System.Drawing.Graphics.FromImage(New Bitmap(1, 1))
Dim size As SizeF = graphics.MeasureString("Hello there", New Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point))
End Using
``` | ```
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?
EDIT: how would you combine the update & check into one SQL statement? | 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 then:
* you **must** check/enforce it in the database to ensure it is never violated by any access method
* you **may** **also** check/enforce it in the application, if that is more user-friendly | 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 the following case I use to measure time of a call:
```
long time1= System.nanoTime();
foo();
long time2 = System.nanoTime();
long timeSpent = time2-time1;
```
Now in a multi-core system, it could be that after measuring time1, the thread is scheduled to a different processor whose counter is less than that of the previous CPU. Thus we could get a value in time2 which is *less* than time1. Thus we would get a negative value in timeSpent.
Considering this case, isn't it that System.nanotime is pretty much useless for now?
I know that changing the system time doesn't affect nanotime. That is not the problem I describe above. The problem is that each CPU will keep a different counter since it was turned on. This counter can be lower on the second CPU compared to the first CPU. Since the thread can be scheduled by the OS to the second CPU after getting time1, the value of timeSpent may be incorrect and even negative. | **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. There's a comment on the post which links to [a blog post by David Holmes](https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks), a realtime and concurrency guy at Sun. It says:
> System.nanoTime() is implemented using the QueryPerformanceCounter/QueryPerformanceFrequency API [...] The default mechanism used by QPC is determined by the Hardware Abstraction layer(HAL) [...] This default changes not only across hardware but also across OS versions. For example Windows XP Service Pack 2 changed things to use the power management timer (PMTimer) rather than the processor timestamp-counter (TSC) due to problems with the TSC not being synchronized on different processors in SMP systems, and due the fact its frequency can vary (and hence its relationship to elapsed time) based on power-management settings.
So, on Windows, this *was* a problem up until WinXP SP2, but it isn't now.
I can't find a part II (or more) that talks about other platforms, but that article does include a remark that Linux has encountered and solved the same problem in the same way, with a link to the [FAQ for clock\_gettime(CLOCK\_REALTIME)](http://juliusdavies.ca/posix_clocks/clock_realtime_linux_faq.html), which says:
> 1. Is clock\_gettime(CLOCK\_REALTIME) consistent across all processors/cores? (Does arch matter? e.g. ppc, arm, x86, amd64, sparc).
>
> It *should* or it's considered buggy.
>
> However, on x86/x86\_64, it is possible to see unsynced or variable freq TSCs cause time inconsistencies. 2.4 kernels really had no protection against this, and early 2.6 kernels didn't do too well here either. As of 2.6.18 and up the logic for detecting this is better and we'll usually fall back to a safe clocksource.
>
> ppc always has a synced timebase, so that shouldn't be an issue.
So, if Holmes's link can be read as implying that `nanoTime` calls `clock_gettime(CLOCK_REALTIME)`, then it's safe-ish as of kernel 2.6.18 on x86, and always on PowerPC (because IBM and Motorola, unlike Intel, actually know how to design microprocessors).
There's no mention of SPARC or Solaris, sadly. And of course, we have no idea what IBM JVMs do. But Sun JVMs on modern Windows and Linux get this right.
EDIT: This answer is based on the sources it cites. But i still worry that it might actually be completely wrong. Some more up-to-date information would be really valuable. I just came across to a link to a [four year newer article about Linux's clocks](http://geekwhisperer.blogspot.co.uk/2010/01/twisty-maze-of-linux-clocks-all.html) which could be useful. | **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 represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.
JVM/JDK implementation is responsible for ironing out the inconsistencies that could be observed when underlying OS utilities are called (e. g. those mentioned in [Tom Anderson's answer](https://stackoverflow.com/a/4588605/648955)).
The majority of other old answers to this question (written in 2009–2012) express FUD that was probably relevant for Java 5 or Java 6 but is no longer relevant for modern versions of Java.
It's worth mentioning, however, that despite JDK guarantees `nanoTime()`'s safety, there have been several bugs in OpenJDK making it to not uphold this guarantee on certain platforms or under certain circumstances (e. g. [JDK-8040140](https://bugs.openjdk.java.net/browse/JDK-8040140), [JDK-8184271](https://bugs.openjdk.java.net/browse/JDK-8184271)). There are no open (known) bugs in OpenJDK wrt `nanoTime()` at the moment, but a discovery of a new such bug or a regression in a newer release of OpenJDK shouldn't shock anybody.
With that in mind, *code that uses `nanoTime()` for timed blocking, interval waiting, timeouts, etc. should preferably treat negative time differences (timeouts) as zeros rather than throw exceptions.* This practice is also preferable because it is consistent with the behaviour of all timed wait methods in all classes in `java.util.concurrent.*`, for example [`Semaphore.tryAcquire()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/Semaphore.html#tryAcquire(int,long,java.util.concurrent.TimeUnit)), `Lock.tryLock()`, [`BlockingQueue.poll()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/BlockingQueue.html#poll(long,java.util.concurrent.TimeUnit)), etc.
Nonetheless, `nanoTime()` should still be preferred for implementing timed blocking, interval waiting, timeouts, etc. to `currentTimeMillis()` because the latter is a subject to the "time going backward" phenomenon (e. g. due to server time correction), i. e. *`currentTimeMillis()` is not suitable for measuring time intervals at all.* See [this answer](https://stackoverflow.com/a/351571/648955) for more information.
Instead of using `nanoTime()` for code execution time measurements directly, specialized benchmarking frameworks and profilers should preferably be used, for example [JMH](https://openjdk.java.net/projects/code-tools/jmh/) and [async-profiler](https://github.com/jvm-profiling-tools/async-profiler) in [wall-clock profiling mode](https://github.com/jvm-profiling-tools/async-profiler#wall-clock-profiling). | 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,
```
myFoo.AvatarSize = new Size(20, 20); //this is one possible way
```
But if I try to set it like this,
```
myFoo.AvatarSize.Height = 20; //.NET style
myFoo.AvatarSize.Width = 20; //error
```
the compiler get me an error stating that it cannot modify the return values. I know why it happens, but I would like it to support the second way also. Please help me with a solution.
P.S. Sorry if the title is absurd | `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 TextBox static, but that just breaks things. Can I make a TextBox public / static so I can change it from another form?
1. How do I make a TextBox Static Public so I can manipulate it across other forms, or is there another method for doing this?
**EDIT:**
Okay, for more information...
I have my own Form created. It is called "formErrorWindow." I need to display the form that i've pre-designed with the message set from another form. The only way I can do this is if I create a Function in the windows designer area for the form, and I set the variables with "this.errorMsg.text = error." The only way I can see that function is if I set it to static. If I set the function to Static, when I try and put "this.errorMsg.Text = error" I get this error: *An object reference is required for the non-static field, method, or property.*
Here is what I've attempted:
```
namespace LCR_ShepherdStaffupdater_1._0
{
partial class formErrorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
public System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
///
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
// ********* HERE IS THE FUNCTION THAT IVE ADDED BELOW. THIS WOULD WORK BUT.... *********
public static void showError(string errorTitle, string usrMsg, string errorMsg)
{
formErrorWindow errorWindow = new formErrorWindow();
errorMsgItem.Text = errorMsg;
errorTitleItem.Text = "Error! : " + errorTitle;
usrMsgItem.Text = usrMsg;
errorWindow.ShowDialog();
}
// ********* HERE IS THE FUNCTION THAT IVE ADDED ABOVE. THIS WOULD WORK BUT.... *********
// ********* I get an error: "An object reference is required for the non-static field, method, or property." *********
public void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formErrorWindow));
this.usrMsgItem = new System.Windows.Forms.TextBox();
this.errorTitleItem = new System.Windows.Forms.Label();
this.errorMsgItem = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// usrMsgItem
//
this.usrMsgItem.Enabled = false;
this.usrMsgItem.Location = new System.Drawing.Point(13, 37);
this.usrMsgItem.Multiline = true;
this.usrMsgItem.Name = "usrMsgItem";
this.usrMsgItem.Size = new System.Drawing.Size(334, 81);
this.usrMsgItem.TabIndex = 0;
this.usrMsgItem.Text = "Undefined";
//
// errorTitleItem
//
this.errorTitleItem.AutoSize = true;
this.errorTitleItem.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.errorTitleItem.ForeColor = System.Drawing.Color.Red;
this.errorTitleItem.Location = new System.Drawing.Point(12, 9);
this.errorTitleItem.Name = "errorTitleItem";
this.errorTitleItem.Size = new System.Drawing.Size(152, 20);
this.errorTitleItem.TabIndex = 1;
this.errorTitleItem.Text = "Error! : Undefined";
//
// errorMsgItem
//
this.errorMsgItem.Enabled = false;
this.errorMsgItem.Location = new System.Drawing.Point(0, 21);
this.errorMsgItem.Multiline = true;
this.errorMsgItem.Name = "errorMsgItem";
this.errorMsgItem.Size = new System.Drawing.Size(329, 101);
this.errorMsgItem.TabIndex = 2;
this.errorMsgItem.Text = "Undefined";
//
// button1
//
this.button1.Location = new System.Drawing.Point(272, 256);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Continue";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.errorMsgItem);
this.panel1.Location = new System.Drawing.Point(12, 124);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(335, 126);
this.panel1.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(68, 1);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(189, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Technical Error Message";
//
// formErrorWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.ClientSize = new System.Drawing.Size(359, 290);
this.Controls.Add(this.panel1);
this.Controls.Add(this.button1);
this.Controls.Add(this.errorTitleItem);
this.Controls.Add(this.usrMsgItem);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "formErrorWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Error!";
this.VisibleChanged += new System.EventHandler(this.formErrorWindow_VisibleChanged);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.TextBox usrMsgItem;
public System.Windows.Forms.Label errorTitleItem;
public System.Windows.Forms.TextBox errorMsgItem;
}
}
```
Look for the function I've added above. How do I get that to compile and do what I want it to do WITHOUT that error I keep getting: **An object reference is required for the non-static field, method, or property.** | 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 didn't actually re-build?
For example, when the MSBuild dependency analysis asserts that the project doesn't need to be built because none of its source files have been updated, it doesn't build, but still executes my copy target. Is there any way to prevent this? | 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 targets after a rebuild occurs your project file should look something like:
```
<Project ...>
<!-- some content here -->
<Import Project="... Microsoft.Csharp.targets" />
<PropertyGroup>
<RebuildDependsOn>
$(RebuildDependsOn);
InstallUtil;
CopyPostBuildFiles
</RebuildDependsOn>
</PropertyGroup>
</Project>
```
This method extends the property which the Rebuild targets uses to declare what targets it depends on. I've detailed this in the article [Inside MSBuild](http://msdn.microsoft.com/en-us/magazine/cc163589.aspx), see section *Extending the build process*.
Also what you are trying to accomplish may be acheived by the AfterBuild target if you can specify what what files would "*trigger*" an update to occur. In other words you can specify a set of "inputs" into the target and a set of "outputs" which are both files. If all outputs were created after all inputs then the target would be considerd up to date and skipped. this concept is known as Incremental Building and I've coverd it in the article [MSBuild Best Practices Part 2](http://msdn.microsoft.com/en-us/magazine/dd483291.aspx). Also I have detailed this in my book, [Inside the Microsoft Build Engine: Using MSBuild and Team Foundation Build](https://rads.stackoverflow.com/amzn/click/com/0735626286).
**EDIT: Adding BuildDependsOn example**
If you want the target to only execute when the files are actually built and not just when the Rebuild target is executed. Then you should create your project to be like the following:
```
<Project ...>
<!-- some content here -->
<Import Project="... Microsoft.Csharp.targets" />
<PropertyGroup>
<BuildDependsOn>
$(BuildDependsOn);
CustomAfterBuild;
</BuildDependsOn>
</PropertyGroup>
<Target Name="CustomAfterBuild" Inputs="$(MSBuildAllProjects);
@(Compile);
@(_CoreCompileResourceInputs);
$(ApplicationIcon);
$(AssemblyOriginatorKeyFile);
@(ReferencePath);
@(CompiledLicenseFile);
@(EmbeddedDocumentation);
$(Win32Resource);
$(Win32Manifest);
@(CustomAdditionalCompileInputs)"
Outputs="@(DocFileItem);
@(IntermediateAssembly);
@(_DebugSymbolsIntermediatePath);
$(NonExistentFile);
@(CustomAdditionalCompileOutputs)">
<!-- Content here -->
</Target>
</Project>
```
I just copied the inputs and outputs from the **CoreCompile** target inside of Microsoft.CSharp.targets (*I'm assuming your are using C# here*) and pasted it here. What this means is that the target will be skipped whenever the **CoreCompile** target is executed. Also since I extended the BuildDependsOn we know that MSBuild will try and execute it whenever the project is built. | 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)
</MyBeforeCompileTimestamp>
</PropertyGroup>
</Target>
<Target Name="AfterBuild">
<CallTarget Condition="$(MyBeforeCompileTimestamp) !=
%(IntermediateAssembly.ModifiedTime)" Targets="MyTarget" />
</Target>
``` | 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 metafunction for converting a pointer type to its base type:
```
template<typename T>
struct strip_pointer_from;
template<typename T>
struct strip_pointer_from<T*> { // Partial specialisation for pointer types
typedef T type;
};
```
Example: the type expression `strip_pointer_from<double*>::type` evaluates to `double`. Note that template metaprogramming is not commonly used outside of library development.
## Simplifying Function Pointer Types
`typedef` is *helpful* for giving a short, sharp alias to complicated function pointer types:
```
typedef int (*my_callback_function_type)(int, double, std::string);
void RegisterCallback(my_callback_function_type fn) {
...
}
``` | 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++ where `sizeof(int)` is 2, then you can just change the `typdef`
```
typedef long int32;
```
and your program will still work on the new implementation. | 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:\\mnt\\fdrive\\ f:\\\"\n"), argv[0]);
return( -1 );
}
// We should do some error checking on the inputs. Make sure
// there are colons and backslashes in the right places, etc.
bFlag = GetVolumeNameForVolumeMountPoint(
argv[2], // input volume mount point or directory
Buf, // output volume name buffer
BUFSIZE // size of volume name buffer
);
if (bFlag != TRUE)
{
_tprintf( TEXT("Retrieving volume name for %s failed.\n"), argv[2] );
return (-2);
}
_tprintf( TEXT("Volume name of %s is %s\n"), argv[2], Buf );
bFlag = SetVolumeMountPoint(
argv[1], // mount point
Buf // volume to be mounted
);
if (!bFlag)
_tprintf (TEXT("Attempt to mount %s at %s failed.\n"), argv[2], argv[1]);
return (bFlag);
```
It always gives an error of parameter is incorrect , I also tried definedosdevice at first then get the name, It also didn't work. Any idea how to make it work? | `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 like this:
```
if (!DefineDosDevice(0, _T("Q:"), _T("C:\\Temp")))
_ftprintf(stderr, _T("DefineDosDevice failed: %d\n"), GetLastError());
```
If you want to make this persistent, I think that you'll need to write a Windows service that does it at boot time. I wrote one about 10 years ago. | 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 connects it creates a thread in which all the transferring of data takes place. It first listens for the Direction in which the client wants to move and then sends the updates back to the client. On the client side it's the reverse of this sending the direction and then waiting for the update to be received. This is done using ObjectOutput/Input Streams.
There is also a game class which has all the game logic and this has the game loop which each looping calls each of the connected players serverThread.exchangeDatas() method.
My game works ok with one client connected but as soon as another client joins (locally is all that i've tested, but this should work right?) It crashed my game in the Server thread producing the following error
java.io.StreamCorruptedException: invalid type code: 00.
Is the code that trips this exception
```
Object o = in.readObject();
if (o instanceof Direction)
{
// Get new location
player.setDirection((Direction) o);
//System.out.println("Got: " + (Direction)o + " new location: " + player.getNextLocation());
}
// Send gameState
//System.out.println("Sending data");
Data data = new Data(game.getGameState(), game.getScared(), game.getScareLeft(), player.getLives(), player.getScore());
out.flush();
out.writeObject(data);
out.flush();
out.reset();
```
[Server code](http://pastebin.com/m1e8de96b)
[ServerThread code (the one that crashes in the exchangeData method](http://pastebin.com/m459b43)
[Client Controller code](http://pastebin.com/m60c82176)
[Game loop code - line 42 is what calls the exchange data method](http://pastebin.com/m79a9a07)
Any help would be amazing with these.
<http://www.mediafire.com/download.php?nwwqmzywfom>
here's a download to both the client and the server (they are netbeans projects)
Sorry for my messy code =[ | 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 having a look at <http://java.sun.com/docs/books/tutorial/essential/concurrency/sync.html>.
By marking a method/class synchronized, the runtime will make sure that this method/class will be active in no more than 1 thread at the same time. This is actually a vast and difficult topic, so take some time to learn the basics and make sure you understand the basic problem. :) | 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 your code and hacked up some little stuff so it would compile, and it worked for me with the .reset(). It looks like what you were doing there is right.
I don't think I can help more without the rest of the code. Sorry.
PS: I assume that you have things Serializable, implementing Runnable, etc which the code you posted didn't have. But if you didn't have those things setup, then your code wouldn't compile in the first place.
---
After messing around with your code for 45 minutes, I can't get the error to happen. I had to hack a few things here and there to make it run (since it was missing a class or two and some of the code above) but I don't think I changed it (much). I'm not sure my changes would effect anything, it's a little hard to know.
I have two guesses as to what's happening. The first is going to be the .reset() thing again. If you haven't commented that out and see if it makes any difference.
So with that ignored, I'm going to take a different stab at what's going on here.
```
java.io.StreamCorruptedException: invalid type code: 00
```
I'm going to guess that the 00 might be a hint. My understanding is that there should be a signature byte being sent over (as proof that the object is what you say it is, so Strings don't get interpreted as doubles or PacManGameUIs) and obviously Java is unhappy because it's wrong.
But why 00? That's an interesting value. My guess (and this is a big guess) is that is the first byte of an integer (which is 4 bytes when sent with ObjectOutputStream.writeInt()). Perhaps you have an integer being sent that isn't being read before you call .readObject on the input stream? I'm not sure if that would cause the error, but it would be my best guess.
In a situation like this, there are two things to do. The first is to cut things down. Make two little class files that do nothing but start threads that communicate with each other in a cut down manner (without all the game management stuff) but using the same flow and logic. See if you can re-create the error there.
The other way (and this will be more instructive if you are daring) is to listen in on the conversation between the two program halves using something like [WireShark](http://www.wireshark.org) or [tcpdump](http://openmaniak.com/tcpdump.php). This will let you see the raw bytes you are sending across. While this can be confusing and hard to interpret, it should make figuring out if you are sending the wrong object easy. Sending an int will probably be around 4 bytes, but sending a large structure would take more. Through experimentation you should be able to figure it out. It's a pain, but it will let you know *exactly* what is being sent.
It may be hard to snoop on the loopback interface (when a computer talks to it's self), at least on Windows with WireShark (I don't remember it being that easy), so it's often easiest to do this with two computers (one as server, one as client) so you can easily peek into the packets.
Sorry again that I can't be more helpful. | 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() {
$('#test').click(function(e) {
alert('test');
var events = $('#test').data("events");
$('#test').unbind('click', events.click[0]);
});
});
<a id="test">test</a>
``` | 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'd like to keep the bound events after the last snapshot.
```
(function($){
function obj_copy(obj){
var out = {};
for (i in obj) {
if (typeof obj[i] == 'object') {
out[i] = this.copy(obj[i]);
}
else
out[i] = obj[i];
}
return out;
}
$.fn.extend({
storeEvents:function(){
this.each(function(){
$.data(this,'storedEvents',obj_copy($(this).data('events')));
});
return this;
},
restoreEvents:function(){
this.each(function(){
var events = $.data(this,'storedEvents');
if (events){
$(this).unbind();
for (var type in events){
for (var handler in events[type]){
$.event.add(
this,
type,
events[type][handler],
events[type][handler].data);
}
}
}
});
return this;
}
});
})(jQuery);
``` | 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 JSP Ajax tag library. Like this one <http://ajaxtags.sourceforge.net/> . | 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, have a look at [DWR](http://directwebremoting.org/). | 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 markup:
```
<a target="_content" href="http://www.google.com">Google</a>
```
But the link opens up in the tab that has focus and not in a new tab.
Please help.
Thanks. | 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.com/");
```
EDIT:
The above technique of adding a browser tab did not work in this case. According to [this article](https://developer.mozilla.org/En/Code_snippets/Tabbed_browser) code running in the sidebar does not have access to the main window. So first up I got access to the browser window before using gBrowser. Here is the code taken from the website that I used and works properly:
```
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
```
After I got access to the browser window I accessed gBrowser through the getBrowser function like below:
```
mainWindow.getBrowser().addTab("http://www.google.com/");
```
The opens up a new tab in the main window browser. | 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 the classes in the `Microsoft.Build.BuildEngine` namespace. Probably the `Project` class is of most interest to you. | 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, and editing existing country.
I don't know how many views will have to know about changes connected with changing Country. The thing is I have to use Observer pattern. And on the web I can find only examlpes when a Subject is Country and Observer is a form that is editing a country and all the examples are in console application.
I need that all my forms that have lists of countries know about adding new country, not just editing existing ones. How am I supposed to do that, should I make a repository a Subject? | 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, uses some custom EventArgs so that you can pass the Country object that has modified to the eventhandler.
What are you using to implement an MVC app ? Are you using some kind of framework for it ? | 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 suggestions on using 4.1 for just this application? | 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;
std::cout << "round(1.4):\t" << round(1.4) << std::endl;
std::cout << "round(-1.4):\t" << round(-1.4) << std::endl;
std::cout << "round(1.6):\t" << round(1.6) << std::endl;
std::cout << "round(-1.6):\t" << round(-1.6) << std::endl;
return 0;
}
```
Output:
```
round(0.5): 1
round(-0.5): -1
round(1.4): 1
round(-1.4): -1
round(1.6): 2
round(-1.6): -2
``` | > **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/w/cpp/numeric/math/round) as builtins already.
There's no round() in the C++98 standard library. You can write one yourself though. The following is an implementation of [round-half-up](https://en.wikipedia.org/wiki/Rounding#Round_half_up):
```
double round(double d)
{
return floor(d + 0.5);
}
```
The probable reason there is no round function in the C++98 standard library is that it can in fact be implemented in different ways. The above is one common way but there are others such as [round-to-even](http://en.wikipedia.org/wiki/Rounding#Round_half_to_even), which is less biased and generally better if you're going to do a lot of rounding; it's a bit more complex to implement though. | 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,
fieldname[recordnumber] points to a cell in current table
```
or
```
Sin(fieldname[recordnumber])
```
or
```
anotherfieldname[recordnumber]
```
or
```
"10" // (simply a number)
```
something like that.
functions are Sum, Ave, Sin, Cos, Tan, Cot, Mul, Div, Pow, Log (10), Ln, Mod
It's pathetic, I know, but it's my homework :'(
So does anyone know a trick to evaluate something like this? | 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 question you can limit yourself to three subcases:
* a simple value
* a lookup (possibly to an other table)
* a function which inputs are lookups
I think a little OO design can helps you out here.
I'm not sure if you have to deal with real time refresh and circular dependency checks. Else they can be tricky too. | 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)
myTree.expandPath(new TreePath(currentNode.getPath()));
currentNode = currentNode.getNextNode();
} while (currentNode != null);
``` | 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 tree jtree to expand to a certain level
* @param level the level of expansion
*/
public static void expandOrCollapsToLevel(JTree tree, TreePath treePath,int level,boolean expand) {
try {
expandOrCollapsePath(tree,treePath,level,0,expand);
}catch(Exception e) {
e.printStackTrace();
//do nothing
}
}
public static void expandOrCollapsePath (JTree tree,TreePath treePath,int level,int currentLevel,boolean expand) {
// System.err.println("Exp level "+currentLevel+", exp="+expand);
if (expand && level<=currentLevel && level>0) return;
TreeNode treeNode = ( TreeNode ) treePath.getLastPathComponent();
TreeModel treeModel=tree.getModel();
if ( treeModel.getChildCount(treeNode) >= 0 ) {
for ( int i = 0; i < treeModel.getChildCount(treeNode); i++ ) {
TreeNode n = ( TreeNode )treeModel.getChild(treeNode, i);
TreePath path = treePath.pathByAddingChild( n );
expandOrCollapsePath(tree,path,level,currentLevel+1,expand);
}
if (!expand && currentLevel<level) return;
}
if (expand) {
tree.expandPath( treePath );
// System.err.println("Path expanded at level "+currentLevel+"-"+treePath);
} else {
tree.collapsePath(treePath);
// System.err.println("Path collapsed at level "+currentLevel+"-"+treePath);
}
}
}
```
---
Basically, you need to explore the sub-nodes until your criteria (here the depth level) is met, and expand all nodes until that point. | 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 `Dictionary` class), which has been adapted later to fit the `Map` interface. While it *is* synchronized, it seems to have serious [scalability issues](http://www.ibm.com/developerworks/java/library/j-jtp07233.html) and is discouraged for new projects.
But what about the other two? What are the differences between Maps returned by `Collections.synchronizedMap(Map)` and `ConcurrentHashMap`s? Which one fits which situation? | 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 data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently. | ```
╔═══════════════╦═══════════════════╦═══════════════════╦═════════════════════╗
║ Property ║ HashMap ║ Hashtable ║ ConcurrentHashMap ║
╠═══════════════╬═══════════════════╬═══════════════════╩═════════════════════╣
║ Null ║ allowed ║ not allowed ║
║ values/keys ║ ║ ║
╠═══════════════╬═══════════════════╬═════════════════════════════════════════╣
║ Thread-safety ║ ║ ║
║ features ║ no ║ yes ║
╠═══════════════╬═══════════════════╬═══════════════════╦═════════════════════╣
║ Lock ║ not ║ locks the whole ║ locks the portion ║
║ mechanism ║ applicable ║ map ║ ║
╠═══════════════╬═══════════════════╩═══════════════════╬═════════════════════╣
║ Iterator ║ fail-fast ║ weakly consistent ║
╚═══════════════╩═══════════════════════════════════════╩═════════════════════╝
```
Regarding locking mechanism:
`Hashtable` [locks the object](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java#Hashtable.put%28java.lang.Object%2Cjava.lang.Object%29), while `ConcurrentHashMap` locks [only the bucket](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/ConcurrentHashMap.java#ConcurrentHashMap.putVal%28java.lang.Object%2Cjava.lang.Object%2Cboolean%29). | 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 with added features)
Not asking for code, just some ideas/primers on how to start this.
Doing mostly web stuff has made me a bit rusty in win programming.
Any ideas are welcomed
Thanks
Note: I think I have to do this with c/c++ because of speed. My stopwatch program would run in a very slow pc, something like a p3 800mhz, so speed is really important. | 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;
int hours = 0;
switch (message) {
case WM_CREATE:
// create a 1 second timer
SetTimer (hwnd, ID_TIMER, 1000, NULL);
return 0;
case WM_PAINT:
if(count > 0)
{
hdc = BeginPaint (hwnd, &ps);
GetClientRect (hwnd, &r);
hours = count / 3600;
minutes = (count / 60) % 60;
seconds = count % 60;
wsprintf (szBuffer, "Hours: %d Minutes: %d Seconds: %d", hours, minutes, seconds);
DrawText (hdc, szBuffer, -1, &r, DT_LEFT);
EndPaint (hwnd, &ps);
}
else
{
SendMessage (hwnd, WM_CLOSE, 0, 0L)
}
return 0;
case WM_TIMER:
count--;
InvalidateRect (hwnd, NULL, TRUE);
return 0;
case WM_DESTROY:
KillTimer (hwnd, ID_TIMER);
PostQuitMessage (0);
return 0;
} /* end switch */
}
```
Here's a good link on using timers:
[Using Timers](http://msdn.microsoft.com/en-us/library/ms644901(VS.85).aspx) | 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", $html_content, $match);`
This works great if there is only one player, $match[1] contains the filename (which is all I need)
My knowledge of regex is vanishing, so I'm not able to adjust this to grab more than one match.
If there are more on the page, it breaks totally, because it matches too greedily (from the first `<!--PLAYER` to the last `-->` | 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->\nblahblah" ;
$reg = "/<!-x=(.*)->/U" ;
preg_match_all( $reg, $text, $matches ) ;
print_r( $matches ) ;
```
Your code then becomes:
```
$find_players = preg_match_all("/<!--PLAYER=(.*)-->/Ui", $html_content, $matches);
// print $matches[1] ;
```
The 's' modifier (PCRE\_DOTALL) you're using probably isn't helpful, either; you're unlikely to have a filename with a linebreak in it.
EDIT: @Stevens suggests this syntax, which I agree is slightly clearer - moving the U modifier to the capturing parentheses.
```
$find_players = preg_match_all("/<!--PLAYER=(?U)(.*)-->/i", $html_content, $matches);
``` | 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("/<!--PLAYER=((?:[^-]+|-(?!->))*)-->/ig", $html_content, $match);
```
Mind you, it's unlikely that using the lazy dot will cause noticeable problems with a simple case like this, but it's a good habit to always tell the regex engine **exactly** what you mean. In this case, you want to collect as many characters as possible ("greedy") without passing a comment terminator. A terminator is a dash followed by another dash and a greater-than sign. So, we allow any number of any character *except* dash or dashes that *don't* start a comment terminator. | 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 URL because you are passing in something like `questions/` which looks like `users/login/questions/` instead of `login.php?redir=questions.php`
Does anyone have any comments or solutions for how this can be worked out nicely without polluting the URL horribly? I think the way SO handled it was to put the login form ON the "Ask Question" page. I suppose that is a solution but I'm looking for other possibilities.
**Edit:** It seems like using `$_SERVER['HTTP_REFERER']` is the best solution so far. Is there any reason not to use it? I realize you can fake the referer but will that actually cause any damages? | 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 is not always set. | 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-sessions> | 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 MC35;Ver="1.0";Bck=1
[Kiosk]
Menu8=\Program Files\PilotMobile\Pilot Mobile Backup.exe
MenuCount=8
AdminPwd=D85F72A85AE65A71BF3178CC378B260E
MenuName8=Pilot Mobile Backup
Menu7=\Windows\SimManager.exe
MenuName7=Sim Manager
UserPwd=AF2163B24AF45971
PasswordPolicy=C34B3DE916AA052DCB2A63D7DCE83F17
DisableBeam=0
DisableBT=0
DisableSDCard=0
EnableAS=1
ActionCount=0
Url=file://\Application\MCPortal.htz
AutoLaunch=0
Menu6=\Windows\solitare.exe
MenuName6=Solitare
Menu5=\Windows\bubblebreaker.exe
MenuName5=Bubble Breaker
Menu4=\Windows\wrlsmgr.exe
MenuName4=Communications
Menu3=\Windows\Calendar.exe
MenuName3=Calendar
Menu2=\Windows\tmail.exe
MenuName2=Text Messaging
Menu1=\Program Files\PilotMobile\Pilot.Mobile.exe
MenuName1=Pilot Mobile
ShowStartMenu=1
CustomTaskBar=0
IdleTimeout=0
NoTaskbar=0
PPCKeys=1111111111111111
On=1
[Status]
MCLastConn=2006/10/01 00:50:56
[Connection]
DeploySvr1=********
[Locations]
Backup=Backup
Install=\Application
[Comm]
RetryDelay=60000
NoInBoundConnect=0
TLS=0
Broadcast=1
[Info]
LID=090128-117
PWDID=081212-10
TimeSyncID={249CEE72-5918-4D18-BEA8-11E8D8D972BF}
TimeSyncErrorInterval=5
TimeSyncInterval=120
AutoTimeSync=1
SecondarySNTPServer=ntp1.uk.uu.net
DefaultSNTPServer=ntp0.uk.uu.net
DepServerTimeSyncType=4
TimeSyncServerType=1
DFID=080717-8
Platform=PPC
Method=39
SiteName=*****
[Device]
SyncTimer=4
Ver=1
DeviceID={040171BD-3603-6106-A800-FFFFFFFFFFFF}
ShowTrayIcon=1
DeviceIDType=2
DeviceClass=AADE7ECE-DF8C-4AFC-89D2-DE7C73B579D0
DeviceName=PHJ01444-MC35
NameType=2
[END-DO NOT CHANGE/MOVE THIS LINE]
``` | 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.Length) { continue; }
else if(line.Substring(0, DeviceNameString.Length) != DeviceNameString) { continue; }
return line.Substring(DeviceNameString.Length);
}
```
If you're only intending to read one value from the file, it's a plausible option. I would probably combine the loops and add for some end of file checking though myself if you're serious about using this code. | 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.wordpress.com/2006/09/11/how-to-access-ini-files-in-c-net/).
Additionally there is a more [recent article on MSDN](https://code.msdn.microsoft.com/windowsdesktop/Reading-and-Writing-Values-85084b6a) about accessing the required functions. | 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 JPopupMenu?
I would like to know how this is implemented, so please don't post links to available [J]Components. | 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 **"Another Example: TextAreaDemo"**
ant hit the Launch button! | 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/autocomplete/package-summary.html> | 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 like:
```
class Foo {
function __construct($init_parameter) {
$this->some_parameter = $init_parameter;
}
}
// in code:
$foo = new Foo("some init value");
```
---
**Notice** - There are so-called old style constructors that you might run into in legacy code. They look like this:
```
class Foo {
function Foo($init_parameter) {
$this->some_parameter = $init_parameter;
}
}
```
**This form is officially deprecated as of PHP 7 and you should no longer use it for new code.** | 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 constructors are being phased out of PHP in favor of the \_\_construct method. | 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-us/research/project/code-contracts/?from=https://research.microsoft.com/en-us/projects/contracts/&type=exact) library and add something similar to the following to your method, but this is quite a lot of extra verbiage for such a simple annotation.
```
Contract.Ensures(Contract.Result<string>() != null)
```
Spec# solved this problem by allowing a ! after the type to mark it as a non-null type, eg
```
string! foo
```
but Spec# can only be used to target .NET2, and has been usurped by the Code Contracts library. | 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 checkout process for each transaction.
Can anyone tell me if there is a way to prevent unauthorized access to this URL? Otherwise an unscrupulous developer could use this URL to add data to our database when they shouldn't be.
Thanks for any pointers.
---
The issue here is that I will be providing the code to our customers and they will be adding it to their website. So I don't have the option of them performing anything much more complex than adding a few lines of code to their site.
The code though, needs to perform a sending of data to our server, somehow securely?
Is this an impossible scenario or would I need to perform some sort of auditing after the processing has occurred?
Thank you everyone for some good suggestions. | 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 SoapHeader
Private _userName As String
Public Property UserName() As String
Get
Return _userName
End Get
Set(ByVal value As String)
_userName = value
End Set
End Property
Private _password As String
Public Property Password() As String
Get
Return _password
End Get
Set(ByVal value As String)
_password = value
End Set
End Property
Public Sub New()
End Sub
Public Sub NewUserInfo(ByVal ServiceUser As String, ByVal ServicePassword As String)
Me.UserName = ServiceUser
Me.Password = ServicePassword
End Sub
```
Add an attribute to the definition of your Web Service:
```
<WebMethod()> _
<SoapHeader("CredentialsHeader")> _
Function MyWebMethod(ByVal paremetersPassed as String)
'check permissions here
If PermissionsValid(CredentialsHeader) then
'ok!
.......
else
'throw a permission error
end if
End Function
```
And then from there, just create a function (in my example, PermissionsValid) to check the permissions:
```
Function PermissionsValid(byval Credentials as ServiceCredentials) as boolean
'check Credentials.Username and Credentials.Password here and return a boolean
End Function
```
This may seem like a bunch of work, but this way, when they send a request, you can check it against a database or whatever else you want. You can also turn off a username easily at your end.
A simpler way would be to restrict the IP addresses that are allowed to hit the service page. But, then you run into issues with IP addresses changing, etc.
BTW, much of this was typed as I did the post, so you may need to check over the code to make sure it compiles. :) | 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 services... I don't know anything about asp.net but you should look forward to REST tutorials and see the security alternatives you have from HTTP authentication to full WS-Security implementation | 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++ faq](https://isocpp.org/wiki/faq/proper-inheritance#hiding-inherited-public) says that it is a bad idea, but doesn't say why.
I have seen this idiom in some code and I believe that the author was attempting to make the class final, based on an assumption that it is not possible to override a private member function. However, [This article](http://www.gotw.ca/publications/mill18.htm) shows an example of overriding private functions. Of course [another part of the C++ faq](http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.4) recommends against doing so.
My concrete questions:
1. Is there any technical problem with using a different permission for virtual methods in derived classes vs base class?
2. Is there any legitimate reason to do so? | 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 "is-a" Base object, something that you should be able to do to a Base class object you cannot do to a Derived class object, breaking the [Liskov Substitution Prinicple](http://en.wikipedia.org/wiki/Liskov_substitution_principle)
Will this cause a "technical" problem in your program? Maybe not. But it will probably mean object of your classes won't behave in a way your users expect them to behave.
If you find yourself in the situation where this is what you want (except in the case of a deprecated method referred to in another answer), chances are you have an inheritance model where inheritance isn't really modeling "is-a," (e.g. Scott Myers's example Square inheriting from Rectangle, but you can't change a Square's width independent of its height like you can for a rectangle) and you may need to reconsider your class relationships. | 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 you might be able to contrive an example where you don't want a function exposed, except when you are treating it as an instance of the base class. But the very fact that that situation pops up would suggest a bad OO design somewhere along the line that should probably be refactored. | 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 function getName() {
Foo::getName();
}
}
$a = new Bar;
$a->getName();
?>
```
Initially, I thought this was produce an error because static methods can not reference $this (atleast in PHP5). I tested this myself and it actually outputs John.
I added Foo::getName(); at the end of the script and did get the error I was expecting. So, what changes when you call a static method from within a class that extends the class you're calling from?
Would anyone mind explaining in detail exactly what is going on here? | $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 out of using this feature. :) | 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 want to extend, rather than completely override the behaviour of the base class, e.g. this might make it clearer
```
class Bar extends Foo {
public $name = 'John';
public function getName() {
echo "My name is ";
parent::getName();
}
}
``` | 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 set to an the Foo entity on creation
}
```
or do I just leave out the reference to Foo in my Bar class?
I am leaning toward leaving that reference out, but was wondering what the correct approach is here? | 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 for multiple "parents" without prejudice.
If the child doesn't need to care about the parent, then don't bother. | 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 the TextBox supported Unicode text. Any idea how I can get this text to display in my application? | 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 { get; set; }
}
```
**Code that serializes an instance of the class *Person*:**
```
Person person = new Person();
person.Age = 27;
person.Name = "Patrik";
person.ID = 1;
XmlSerializer serializer = new XmlSerializer(typeof(Person));
TextWriter writer = new StreamWriter(@"c:\test.xml");
serializer.Serialize(writer, person);
writer.Close();
```
**Result (missing the ID property):**
```
<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Patrik</Name>
<Age>27</Age>
</Person>
``` | 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]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
...
static void Main()
{
Person person = new Person();
person.Age = 27;
person.Name = "Patrik";
person.ID = 1;
DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
XmlWriter writer = XmlWriter.Create(@"c:\test.xml");
serializer.WriteObject(writer, person);
writer.Close();
}
```
With the xml (re-formatted):
```
<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/">
<Age>27</Age>
<ID>1</ID>
<Name>Patrik</Name>
</Person>
``` | 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/system.runtime.serialization.datacontractserializer.aspx) (xml based) and [BinaryFormatter](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx) (binary based) could be used as alternatives to XmlSerializer each having its pros and cons. | 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 will do is treat this as a pointer to a single double value, and display velocity[0] in the variable list.
This makes it a real PITA to debug programs that contain large dynamically allocated array. There has got to be some way to tell Xcode "This is a pointer to an array of length 100", and have it display the thing as such. Anyone know what it is? | 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 5, the LLDB debugger becomes the foundation for the debugging experience on OS X.
So for Xcode since version 5 and up I use this `lldb` command:
```
memory read -t int -c8 `array_name`
```
where:
`8` - the number of elements in array
`array_name` - the name of array
`int` - the type of array
The result of execution of this command will be something like this:
```
(lldb) memory read -t int -c8 array
(int) 0x7fff5fbff870 = 7
(int) 0x7fff5fbff874 = 6
(int) 0x7fff5fbff878 = 9
(int) 0x7fff5fbff87c = 10
(int) 0x7fff5fbff880 = 1
(int) 0x7fff5fbff884 = 8
(int) 0x7fff5fbff888 = 4
(int) 0x7fff5fbff88c = 3
``` | 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>
<assemblyIdentity name="myAssembly"
publicKeyToken="32ab4ba45e0a69a1"
culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0"
newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
``` | 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(){
ajaxUpdate(10);
}, 1000 );
```
Will do the trick, and if you want to stop it running before it gets around to running once
```
window.clearTimeout(i);
```
The "window" prefix is not strictly nessecary, but its a good idea, because you never know when somebody else might like to create something else with the same name in visible scope that behaves differently.
For a complete reference on this, I always find MDC Very Helpful:
* [MDC: window.setInterval](https://developer.mozilla.org/en/DOM/window.setInterval)
* [MDC: window.clearInterval](https://developer.mozilla.org/en/DOM/window.clearInterval)
* [MDC: window.setTimeout](https://developer.mozilla.org/en/DOM/window.setTimeout)
* [MDC: window.clearTimeout](https://developer.mozilla.org/en/DOM/window.clearTimout)
Also, you may wish to read this article on timers by John Resig,
* [ejohn.org : How Javascript Timers work](http://ejohn.org/blog/how-javascript-timers-work/) | 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 original set, permuted to appear in unique subsets. What is the algorithm that produces these sets? I've tried Python generator functions using choose, permutation, combination, power set, and so on, but can't get the right combination.
20 Jan 2009
This is not a homework question. This is an improved answer I was working on for www.projecteuler.net problem # 118. I already had a slow solution but came up with a better way -- except I could not figure out how to do the spanning set.
I'll post my code when I get back from an Inauguration Party.
21 Jan 2009
This is the eventual algorithm I used:
```
def spanningsets(items):
if len(items) == 1:
yield [items]
else:
left_set, last = items[:-1], [items[-1]]
for cc in spanningsets(left_set):
yield cc + [last]
for i,elem in enumerate(cc):
yield cc[:i] + [elem + last] + cc[i+1:]
```
@Yuval F: I know how to do a powerset. Here's a straightforward implementation:
```
def powerset(s) :
length = len(s)
for i in xrange(0, 2**length) :
yield [c for j, c in enumerate(s) if (1 << j) & i]
return
``` | 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] + [cc[i] + [items[-1]]] + cc[i+1:]
for sset in spanningsets([1, 2, 3, 4]):
print ' '.join(map(str, sset))
```
Output:
```
[1] [2] [3] [4]
[1, 4] [2] [3]
[1] [2, 4] [3]
[1] [2] [3, 4]
[1, 3] [2] [4]
[1, 3, 4] [2]
[1, 3] [2, 4]
[1] [2, 3] [4]
[1, 4] [2, 3]
[1] [2, 3, 4]
[1, 2] [3] [4]
[1, 2, 4] [3]
[1, 2] [3, 4]
[1, 2, 3] [4]
[1, 2, 3, 4]
``` | 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]`
With the first of number 2 `[1,2]` one can create `[1,2,3]` and `[1,2] [3]`
With the second of number 2 `[1] [2]` one can create `[1,3] [2]` and `[1] [2,3]` and `[1] [2] [3]`
I hope it is clear enough what I tried to show. (If not, drop a comment!) | 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 whitespace to line things up, and there may be more complex challenges like entire clauses moved around.)
```
The quick brown fox jumped over the lazy dog.
|||||||||| ||||||||||||||||||||| |||||
The quick yellow fox jumped over the well-bred dog.
``` | 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](http://en.wikipedia.org/wiki/Levenshtein_distance) between two Strings | 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 a great plan to link your code to potentially changing libraries but useful in development.) | **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> - Google hosted (minified)
* <https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js> - Google hosted (uncompressed)
For example:
```
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
```
---
However, since jQuery 1.11.1, both jQuery and Google stopped updating these URLs; they will *forever* be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; [Don't use jquery-latest.js](http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/).
Both hosts support `https` as well as `http`, so change the protocol as you see fit (or use a [protocol relative URI](http://www.paulirish.com/2010/the-protocol-relative-url/))
See also: <https://developers.google.com/speed/libraries/devguide> | 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 be taken into account. See my last answer for the proposed corrected solution.** | 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)
{
throw new ArgumentNullException("element");
}
Func<XElement, string> relativeXPath = e =>
{
int index = e.IndexPosition();
string name = e.Name.LocalName;
// If the element is the root, no index is required
return (index == -1) ? "/" + name : string.Format
(
"/{0}[{1}]",
name,
index.ToString()
);
};
var ancestors = from e in element.Ancestors()
select relativeXPath(e);
return string.Concat(ancestors.Reverse().ToArray()) +
relativeXPath(element);
}
/// <summary>
/// Get the index of the given XElement relative to its
/// siblings with identical names. If the given element is
/// the root, -1 is returned.
/// </summary>
/// <param name="element">
/// The element to get the index of.
/// </param>
public static int IndexPosition(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (element.Parent == null)
{
return -1;
}
int i = 1; // Indexes for nodes start at 1, not 0
foreach (var sibling in element.Parent.Elements(element.Name))
{
if (sibling == element)
{
return i;
}
i++;
}
throw new InvalidOperationException
("element has been removed from its parent.");
}
}
```
And the test:
```
class Program
{
static void Main(string[] args)
{
Program.Process(XDocument.Load(@"C:\test.xml").Root);
Console.Read();
}
static void Process(XElement element)
{
if (!element.HasElements)
{
Console.WriteLine(element.GetAbsoluteXPath());
}
else
{
foreach (XElement child in element.Elements())
{
Process(child);
}
}
}
}
```
And sample output:
```
/tests/test[1]/date[1]
/tests/test[1]/time[1]/start[1]
/tests/test[1]/time[1]/end[1]
/tests/test[1]/facility[1]/name[1]
/tests/test[1]/facility[1]/website[1]
/tests/test[1]/facility[1]/street[1]
/tests/test[1]/facility[1]/state[1]
/tests/test[1]/facility[1]/city[1]
/tests/test[1]/facility[1]/zip[1]
/tests/test[1]/facility[1]/phone[1]
/tests/test[1]/info[1]
/tests/test[2]/date[1]
/tests/test[2]/time[1]/start[1]
/tests/test[2]/time[1]/end[1]
/tests/test[2]/facility[1]/name[1]
/tests/test[2]/facility[1]/website[1]
/tests/test[2]/facility[1]/street[1]
/tests/test[2]/facility[1]/state[1]
/tests/test[2]/facility[1]/city[1]
/tests/test[2]/facility[1]/zip[1]
/tests/test[2]/facility[1]/phone[1]
/tests/test[2]/info[1]
```
That should settle this. No? | 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]").
/// </summary>
public static string GetAbsoluteXPath(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
Func<XElement, string> relativeXPath = e =>
{
int index = e.IndexPosition();
var currentNamespace = e.Name.Namespace;
string name;
if (currentNamespace == null)
{
name = e.Name.LocalName;
}
else
{
string namespacePrefix = e.GetPrefixOfNamespace(currentNamespace);
name = namespacePrefix + ":" + e.Name.LocalName;
}
// If the element is the root, no index is required
return (index == -1) ? "/" + name : string.Format
(
"/{0}[{1}]",
name,
index.ToString()
);
};
var ancestors = from e in element.Ancestors()
select relativeXPath(e);
return string.Concat(ancestors.Reverse().ToArray()) +
relativeXPath(element);
}
/// <summary>
/// Get the index of the given XElement relative to its
/// siblings with identical names. If the given element is
/// the root, -1 is returned.
/// </summary>
/// <param name="element">
/// The element to get the index of.
/// </param>
public static int IndexPosition(this XElement element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
if (element.Parent == null)
{
return -1;
}
int i = 1; // Indexes for nodes start at 1, not 0
foreach (var sibling in element.Parent.Elements(element.Name))
{
if (sibling == element)
{
return i;
}
i++;
}
throw new InvalidOperationException
("element has been removed from its parent.");
}
}
``` | 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 tool at the blobstorage directory to backup my blobs?
What if the database is being repacked or blobs are being added and deleted while the copy is taking place? Are there files in the blobstorage directory that must be copied over in a certain order? | 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, I'd guess that it should work as intended. | 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 file named based on the object id and transaction id. So if new or updated blobs are written after the Data.fs is backed up, it shouldn't be a problem, as the files that are referenced by the Data.fs should still be around. Deletion of a blob doesn't result in the file being removed until the database is packed, so that should be okay too.
Performing a backup in a different order, or with packing during the backup, may result in a backup Data.fs that references blobs that are not included in the backup. | 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](https://en.wikipedia.org/wiki/Debian_version_history#Debian_5.0_(Lenny)) (Lenny) (g++ (Debian 4.3.2-1.1) 4.3.2). However, I have the same problem on a [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29) system with the same g++.
Here is the relevant part of my matrix class:
```
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
}
}
```
And the "implementation":
```
using namespace Math;
std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {
[...]
}
```
This is the error given by the compiler:
> matrix.cpp:459: error: 'std::ostream&
> Math::Matrix::operator<<(std::ostream&,
> const Math::Matrix&)' must take
> exactly one argument
I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those six months. :-) | 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 `Matrix` class which is wrong. | 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 automatically targeted into the surrounding namespace `Math` (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like `Math::Matrix<TypeA, N>`. | 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 Derived : public Base
{
public:
// assign strFunction to the function pointer passed in
Derived(string (*funPtr)(int)) : strFunction(funPtr);
~Derived();
private:
// pointer to the function that is passed in
string (*strFunction)(int value);
};
class MainClass
{
public:
MainClass()
{
// allocate a new Derived class and pass it a pointer to myFunction
Base* myClass = new Derived(&MainClass::myFunction);
}
string myFunction(int value)
{
// return a string
}
};
```
When I try to compile this code, the error I get is
> error: no matching function for call to 'Derived::Derived(string (MainClass::\*)(int))'
followed by
> note: candidates are: Derived::Derived(string (\*)(int))
Any idea what I might be doing wrong? | 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 typedefs.
```
typedef string (MainClass::*func_t)(int);
func_t strFunction;
```
and
```
Derived(func_t funPtr) : strFunction(funPtr) {}
``` | 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 only an integer with a parameter.
How can I do this?
**Windows Service, not a Web Service**
**edit**: The folders it backs up will not remain consistent and will be updated at every runtime | 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 regular command line arguments in main() when Windows starts up the service. | 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 = owned_by) AS owner,
[name]
FROM asset
```
As I'm using this subquery a lot (that is, I have about 50 tables with these fields), and I might need to add some more code to the subquery (for example, "AND active = 1" ) I thought I'd put these into a user-defined function [UDF](http://en.wikipedia.org/wiki/User-defined_function) and use that. But the performance using that UDF was abysmal.
```
CREATE FUNCTION dbo.get_user ( @user_pk INT )
RETURNS INT
AS BEGIN
RETURN ( SELECT id
FROM ice.dbo.[user]
WHERE user_pk = @user_pk )
END
SELECT dbo.get_user(created_by) as creator, [name]
FROM asset
```
The performance of #1 is less than 1 second. Performance of #2 is about 30 seconds...
Why, or more importantly, is there any way I can code in SQL server 2008, so that I don't have to use so many subqueries?
### Edit:
Just a litte more explanation of when this is useful. This simple query (that is, get userid) gets a lot more complex when I want to have a text for a user, since I have to join with profile to get the language, with a company to see if the language should be fetch'ed from there instead, and with the translation table to get the translated text. And for most of these queries, performance is a secondary issue to readability and maintainability. | 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 articles on the problem is "[Scalar functions, inlining, and performance: An entertaining title for a boring post](http://dataeducation.com/scalar-functions-inlining-and-performance-an-entertaining-title-for-a-boring-post/)".
The sub-queries can be optimised to correlate and avoid the row-by-row operations.
What you really want is this:
```
SELECT
uc.id AS creator,
uu.id AS updater,
uo.id AS owner,
a.[name]
FROM
asset a
JOIN
user uc ON uc.user_pk = a.created_by
JOIN
user uu ON uu.user_pk = a.updated_by
JOIN
user uo ON uo.user_pk = a.owned_by
```
Update Feb 2019
SQL Server 2019 starts to fix this problem. | 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_pk INT)
RETURNS TABLE AS
RETURN
(
SELECT TOP 1 id
FROM ice.dbo.[user]
WHERE user_pk = @user_pk
-- AND active = 1
)
```
Your original query would then become something like:
```
SELECT
(SELECT TOP 1 id FROM dbo.get_user_inline(created_by)) AS creator,
(SELECT TOP 1 id FROM dbo.get_user_inline(updated_by)) AS updater,
(SELECT TOP 1 id FROM dbo.get_user_inline(owned_by)) AS owner,
[name]
FROM asset
```
An [inline table-valued function](http://www.sommarskog.se/share_data.html#inlineUDF) should have better performance than either a scalar function or a multistatement table-valued function.
The performance should be roughly equivalent to your original query, but any future changes can be made in the UDF, making it much more maintainable. | 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 SplashForm to hide or me sent to the back and the main from to be show. I am currently using the following:
```
private void showMainForm()
{
this.Hide();
this.SendToBack();
// Show the GUI
mainForm.Show();
mainForm.BringToFront();
}
```
What I am seeing is that the MainForm is shown, but the SplashForm is still visible 'on top'. What I am currently doing is clicking on the MainForm to manually bring it to the front. Any ideas on why this is happening? | 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.
private static SplashForm splashForm;
static public void ShowSplashScreen()
{
// Make sure it is only launched once.
if (splashForm != null)
return;
Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm));
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
static private void ShowForm()
{
splashForm = new SplashForm();
Application.Run(splashForm);
}
static public void CloseForm()
{
splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));
}
static private void CloseFormInternal()
{
splashForm.Close();
splashForm = null;
}
...
}
```
and the main program function looks like this:
```
[STAThread]
static void Main(string[] args)
{
SplashForm.ShowSplashScreen();
MainForm mainForm = new MainForm(); //this takes ages
SplashForm.CloseForm();
Application.Run(mainForm);
}
``` | 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 work either.
`document.getElementsById('Tue').Value = tue;` (by the way tue is a variable)
Can someone where please tell me where I am going wrong with this? | 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 that getElementsByName() returns *all* elements with the name as array, therefore we use [0] to access the first one)
Then, use the 'value' attribute:
```
textbox.value = 'Foobar';
``` | 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 rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause. | 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) {
doSomethingWith(s);
i++;
}
```
the only way to have such a counter available in a for-each loop? | 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 collection at all, and may in fact be something not at all based on indexes (such as a linked list). | 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
```
class With {
public static <T> Iterable<Index<T>> index(final T[] array) {
return new Iterable<Index<T>>() {
public Iterator<Index<T>> iterator() {
return new Iterator<Index<T>>() {
index = 0;
public boolean hasNext() { return index < array.size }
public Index<T> next() { return new Index(array[index], index++); }
...
}
}
}
}
}
``` | 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");
DateTime d3 = d1.Add(d2.TimeOfDay);
Console.WriteLine(d3.TimeOfDay); // 00:10: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 you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:
1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a `<script>` block within an existing `<div>` element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must `eval()` your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.
Even if quite dummy, this code explains the idea:
```
<html>
<body>
<div id="div1">
</div>
<div id="div2">
<input type="button" value="Go!" onclick="go()" />
</div>
<script type="text/javascript">
var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
var e = document.getElementById('div1');
e.innerHTML = newsc;
eval(document.getElementById('sc1').innerHTML);
</script>
</body>
</html>
```
I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)
Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.
Finally, if I misunderstood your question, and you're talking about *contextual* invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach [described by krosenvold](https://stackoverflow.com/questions/510779/calling-a-javascript-function-returned-from-a-ajax-response/510818#510818), as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations. | > **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).
---
Inside the returned HTML/Ajax/JavaScript file, you will have a JavaScript tag. Give it an ID, like *runscript*. It's uncommon to add an id to these tags, but it's needed to reference it specifically.
```
<script type="text/javascript" id="runscript">
alert("running from main");
</script>
```
In the main window, then call the eval function by evaluating only that NEW block of JavaScript code (in this case, it's called *runscript*):
```
eval(document.getElementById("runscript").innerHTML);
```
And it works, at least in Internet Explorer 9 and Google Chrome. | 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 InvestmentAccount is similar, but the balance is stored in shares with a share price determining how many shares are deposited or withdrawn given a particular amount of money. Here's the first few lines (around where the compiler pointed out the problem) of the subclass InvestmentAccount:
```
public class InvestmentAccount extends Account
{
protected int sharePrice;
protected int numShares;
private Person customer;
public InvestmentAccount(Person customer, int sharePrice)
{
this.customer = customer;
sharePrice = sharePrice;
}
// etc...
```
The Person class is held in another file (Person.java). Now here's the first few lines of the superclass Account:
```
public class Account
{
private Person customer;
protected int balanceInPence;
public Account(Person customer)
{
this.customer = customer;
balanceInPence = 0;
}
// etc...
```
Is there any reason why the compiler isn't just reading the symbol constructor for Account from the Account class? Or do I need to define a new constructor for Account within InvestmentAccount, which tells it to inherit everything?
Thanks | 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)
{
this.customer = customer;
sharePrice = sharePrice;
}
```
to
```
public InvestmentAccount(Person customer, int sharePrice)
{
super(customer);
sharePrice = sharePrice;
}
```
that will work. | 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(Person customer, int sharePrice) {
super(customer);
this.customer = customer;
sharePrice = sharePrice;
}
}
``` | 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 [WMD Editor](https://meta.stackexchange.com/q/121981/209031) (now [PageDown](https://github.com/StackExchange/pagedown)), but that only converts client-side. | [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 [here](https://github.com/commonmark/commonmark-spec/wiki/List-of-CommonMark-Implementations) | 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 const values of other types, such as IntPtr.
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. For instance, given the following declaration, any reference to Foo would be replaced with "foo" at compile time.
```
const string Foo = "foo";
```
This would rule out any mutable types, so maybe they chose this limitation rather than having to determine at compile time whether a given type is mutable? | 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 basically says that you can only use expressions that consists solely of literals. Any calls to any methods, constructors (that cannot be represented as pure IL literals) cannot be used, as there is no way for the compiler to do that execution, and thus compute the results, at compile time. Also, since there is no way to tag a method as invariant (ie. there is a one-to-one mapping between input and output), the only way for the compiler to do this would be to either analyze the IL to see if it depends on things other than the input parameters, special-case handle some types (like IntPtr), or just disallow every call to any code.
IntPtr, as an example, though being a value type, is still a structure, and not one of the built-in literals. As such, any expression using an IntPtr will need to call code in the IntPtr structure, and this is what is not legal for a constant declaration.
The only legal constant value type example I can think of would be one that is initialized with zeroes by just declaring it, and that's hardly useful.
As for how the compiler treats/uses constants, it will use the computed value in place of the constant name in the code.
Thus, you have the following effect:
* No reference to the original constant name, class it was declared in, or namespace, is compiled into the code in this location
* If you decompile the code, it will have magic numbers in it, simply because the original "reference" to the constant is, as mentioned above, not present, only the value of the constant
* The compiler can use this to optimize, or even remove, unnecessary code. For instance, `if (SomeClass.Version == 1)`, when SomeClass.Version has the value of 1, will in fact remove the if-statement, and keep the block of code being executed. If the value of the constant is not 1, then the whole if-statement and its block will be removed.
* Since the value of a constant is compiled into the code, and not a reference to the constant, using constants from other assemblies will not automagically update the compiled code in any way if the value of the constant should change (which it should not!)
In other words, with the following scenario:
1. Assembly A, contains a constant named "Version", having a value of 1
2. Assembly B, contains an expression that analyzes the version number of assembly A from that constant and compares it to 1, to make sure it can work with the assembly
3. Someone modifies assembly A, increasing the value of the constant to 2, and rebuilds A (but not B)
In this case, assembly B, in its compiled form, will still compare the value of 1 to 1, because when B was compiled, the constant had the value 1.
In fact, if that is the only usage of anything from assembly A in assembly B, assembly B will be compiled without a dependency on assembly A. Executing the code containing that expression in assembly B will not load assembly A.
Constants should thus only be used for things that will never change. If it is a value that might or will change some time in the future, and you cannot guarantee that all other assemblies are rebuilt simultaneously, a readonly field is more appropriate than a constant.
So this is ok:
* public const Int32 NumberOfDaysInAWeekInGregorianCalendar = 7;
* public const Int32 NumberOfHoursInADayOnEarth = 24;
while this is not:
* public const Int32 AgeOfProgrammer = 25;
* public const String NameOfLastProgrammerThatModifiedAssembly = "Joe Programmer";
---
**Edit May 27th 2016**
OK, just got an upvote, so I re-read my answer here and this is actually slightly wrong.
Now, the *intention* of the C# language specification is everything I wrote above. You're not supposed to use something that cannot be represented with a literal as a `const`.
But can you? Well, yes....
Let's take a look at the `decimal` type.
```
public class Test
{
public const decimal Value = 10.123M;
}
```
Let's look at what this class looks like *really* when looked at with ildasm:
```
.field public static initonly valuetype [mscorlib]System.Decimal X
.custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(int8, uint8, uint32, uint32, uint32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 64 00 00 00 00 00 )
```
Let me break it down for you:
```
.field public static initonly
```
corresponds to:
```
public static readonly
```
That's right, a `const decimal` is actually a `readonly decimal`.
The real deal here is that the compiler will use that `DecimalConstantAttribute` to work its magic.
Now, this is the only such magic I know of with the C# compiler but I thought it was worth mentioning. | > 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-online.net/const,_static_and_readonly) for the differences. | 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_LOCAL_SERVER,
__uuidof(IS8Simulation),
(void **) &pis8);
...
hThread = CreateThread(
NULL,
0,
SecondaryThread,
//interface pointer pis8
0,
&dwGenericThreadID);
...
DWORD WINAPI SecondaryThread(LPVOID iValue)
{
//using iValue accordingly
//E.g.: iValue->Open
```
Regards | 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,
&dwGenericThreadID);
DWORD WINAPI SecondaryThread(LPVOID iValue)
{
((IS8Simulation*) iValue)->Open();
}
```
Thread safe version:
```
void MainThread()
{
IStream* psis8;
HRESULT res = CoMarshalInterThreadInterfaceInStream (IID_IS8SIMULATION, pis8, &psis8);
if (FAILED(res))
return;
hThread = CreateThread(
NULL,
0,
SecondaryThread,
(LPVOID) psis8
0,
&dwGenericThreadID
);
}
DWORD WINAPI SecondaryThread(LPVOID iValue)
{
IS8Simulation* pis8;
HRESULT res = CoGetInterfaceAndReleaseStream((IStream*) iValue, IID_IS8SIMULATION, &pis8);
if (FAILED(res))
return (DWORD) res;
pis8->Open();
}
``` | 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 *apartment-agile*, you'll need to marshal that interface pointer so that the secondary thread gets a proxy, and not a direct pointer to the object.
A COM object is normally made apartment-agile by using a special implementation of IMarshal. The simplest approach is to aggregate the Free Threaded Marshaler.
Some useful links...
* [CoMarshalInterThreadInterfaceInStream](http://msdn.microsoft.com/en-us/library/ms693316.aspx)
* [GlobalInterfaceTable (GIT)](http://msdn.microsoft.com/en-us/library/ms693729(VS.85).aspx)
* [CoCreateFreeThreadedMarshaler](http://msdn.microsoft.com/en-us/library/ms694500.aspx)
Update: About the Free-threaded Marshaler...
It's clear from comments on this topic that some people would recommend that you never touch the FTM. While "Effective COM" is an excellent book, I think some of its recommendations are open to interpretation. Item 33 says "Beware the FTM"; it does not say "Never use the FTM". Very wisely it advises caution particularly when your apartment-agile object holds references to other objects, because they might not be apartment-agile. So really the advice is: think carefully when building apartment-agile objects, whether or not they use the FTM to achieve their agility. If you're sure you can build an apartment-agile object, I see no reason why you wouldn't use the FTM to achieve that. | 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
/UberProject/ProgramB/
/UberProject/ProgramB/com/pkg/NiftyWriter.java
```
That is, `ProgramA` and `ProgramB` are both projects (in fact, they're currently existing Java projects), which conceptually fit into `UberProject`.
I don't think I'm supposed to make `UberProject` be a Java project; it's not a classpath, for instance. `ProgramA` and `ProgramB` *do* seem like they should be Java projects (they might use different build dependencies as well), but I see no way in Eclipse 3.3 to create two folders under `UberProject` that are intended to contain Java code. I thought about adding a .project file to each of the two sub-projects, but I'm not sure that's appropriate, either. Eclipse help isn't being helpful, and I didn't see anything on SO about this specific problem.
Just to be clear: assume as given the necessity of the existence of `UberProject`. `UberProject` can be a Java project, or not; it doesn't matter. (Incidentally, it does contain other folders that do not contain Java code.) | 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 ProgramB). You can use UberProject as your eclipse workspace which would be easiest or you can use an outside workspace and import ProgramA and ProgramB as external projects.
There are probably other ways as well (maven multi-module project). Your choice probably depends on whether you have cyclic dependencies between projects. It should be relatively easy to try both 1 and 2 and see what works best for you. | 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 else, then you can do this relatively easy. Right-click on your project in the package explorer, and select `Build Path -> Configure Build Path...`. In the dialog that pops up, make sure `Java Build Path` is selected in the left pane, click the `Source` tab, then click the `Add Folder...` button. Pick `ProgramA` from the list, and repeat for `ProgramB`, etc.
If you want each source folder to have its own output folder, just check the `Allow output folders for source folders` checkbox and edit the output folders as desired.
If that is not, in fact, what you want to do, then another option might be to group your projects into a working set. A working set is not an UberProject, but it does help keep your projects organized in the package explorer. | 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 I am using to connect and pull down files from the remote server.
Thanks | > > "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())
{
wc.DownloadFile("http://www.mydomain.com/resource.img", "c:\\savedImage.img");
}
}
}
}
``` | 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");
}
```
For downloading data every night you could use task scheduler.
<http://www.quartz-scheduler.net/> can help you for scheduling tasks | 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 first variant? | 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" namespace. That is, when I type `int`, the compiler only checks this "default" namespace. If I type "tagMyStruct" as in your example, the compiler also only checks this one namespace. But depending which type of declaration you use, the struct may not exist in that namespace.
Structs are different, and exist in a separate namespace. So if I make the following declaration:
```
struct mystruct {};
```
I can *not* simply refer to it as mystruct. Instead, I have to specify that I want the mystruct which exists in the struct namespace:
```
void foo(struct mystruct bar); // Declare a function which takes a mystruct as its parameter
```
Which gets a bit verbose and awkward in the long run. Instead, you can typedef it into the default namespace:
```
typedef struct mystruct mystruct; // From now on, 'mystruct' in the normal namespace is an alias for 'mystruct' in the struct namespace
```
and now, my function can be declared in the straightforward way:
```
void foo(mystruct bar);
```
So your first example simply merges these two steps together: Declare a struct, and put an alias into the regular namespace. And of course, since we're typedeffing it anyway, we don't need the "original" name, so we can make the struct anonymous. So after your declaration
```
typedef struct { int i; double d; } tagMyStruct;
```
we have a struct with no name, which has been typedef'ed to 'tagMyStruct' in the default namespace.
That's how C treats it. Both types of declarations are valid, but one does not create the alias in the "default" namespace, so you have to use the struct keyword every time you refer to the type.
In C++, the separate struct namespace doesn't exist, so they mean the same thing. (but the shorter version is preferred).
*Edit* Just to be clear, no, C does not have namespaces. Not in the usual sense.
C simply places identifiers into one of two predefined namespaces. The names of structs (and enums, as I recall) are placed in one, and all other identifiers in another. Technically, these are namespaces because they are separate "containers" in which names are placed to avoid conflicts, but they are certainly not namespaces in the C++/C# sense. | 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; } tagMyStruct;
```
you only have to write:
```
tagMyStruct instanceOfMyStruct;
tagMyStruct *ptrToMyStruct;
```
The other big advantage with the typedef'd version is that you can refer to the struct the same way in both C and C++, whereas in the second version they are refered to differently in C than in C++. | 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);
public static void MessageBeep() {
MessageBeep(-1); // Default beep code is -1
}
```
This blog post has an excellent more thorough example: [http://blog.digitforge.com/?p=4 (on archive.org)](http://web.archive.org/web/20090601181423/http://blog.digitforge.com/?p=4) | 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-7883-473b-92db-c6b9f928506d/) or [this](http://blogs.msdn.com/brada/archive/2004/06/03/148142.aspx) or [this](http://www.eggheadcafe.com/software/aspnet/29657361/the-old-cfnet-beep-que.aspx). It's amazing what 30 seconds with a search engine can turn up. | 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 problem hits:
```
import unittest
import gobject
import dbus
import dbus.service
import dbus.glib
class MyDBUSService(dbus.service.Object):
def __init__(self):
bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/test/helloservice')
@dbus.service.method('test.helloservice')
def hello(self):
return "Hello World!"
class BaseTestCase(unittest.TestCase):
def setUp(self):
myservice = MyDBUSService()
loop = gobject.MainLoop()
loop.run()
# === Test blocks here ===
def testHelloService(self):
bus = dbus.SessionBus()
helloservice = bus.get_object('test.helloservice', '/test/helloservice')
hello = helloservice.get_dbus_method('hello', 'test.helloservice')
assert hello() == "Hello World!"
if __name__ == '__main__':
unittest.main()
```
My problem is that the DBUS implementation requires you to start an event loop so that it can start dispatching events. The common approach is to use GLib's gobject.MainLoop().start() (although I'm not married to this approach, if someone has a better suggestion). If you don't start an event loop, the service still blocks, and you also cannot query it.
If I start my service in the test, the event loop blocks the test from completing. I know the service is working because I can query the service externally using the qdbus tool, but I can't automate this inside the test that starts it.
I'm considering doing some kind of process forking inside the test to handle this, but I was hoping someone might have a neater solution, or at least a good starting place for how I would write a test like this. | 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 opposed to a unit test. I was aware of the distinction, but didn't realise my mistake until later.
I've adjusted the example in my question. It loosely resembles the "test\_pidavim.py" example, but uses an import for "dbus.glib" to handle the glib loop dependencies instead of coding in all the DBusGMainLoop stuff:
```
import unittest
import os
import sys
import subprocess
import time
import dbus
import dbus.service
import dbus.glib
import gobject
class MyDBUSService(dbus.service.Object):
def __init__(self):
bus_name = dbus.service.BusName('test.helloservice', bus = dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/test/helloservice')
def listen(self):
loop = gobject.MainLoop()
loop.run()
@dbus.service.method('test.helloservice')
def hello(self):
return "Hello World!"
class BaseTestCase(unittest.TestCase):
def setUp(self):
env = os.environ.copy()
self.p = subprocess.Popen(['python', './dbus_practice.py', 'server'], env=env)
# Wait for the service to become available
time.sleep(1)
assert self.p.stdout == None
assert self.p.stderr == None
def testHelloService(self):
bus = dbus.SessionBus()
helloservice = bus.get_object('test.helloservice', '/test/helloservice')
hello = helloservice.get_dbus_method('hello', 'test.helloservice')
assert hello() == "Hello World!"
def tearDown(self):
# terminate() not supported in Python 2.5
#self.p.terminate()
os.kill(self.p.pid, 15)
if __name__ == '__main__':
arg = ""
if len(sys.argv) > 1:
arg = sys.argv[1]
if arg == "server":
myservice = MyDBUSService()
myservice.listen()
else:
unittest.main()
``` | 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 can have setup that starts a real instance of your server, in a separate process. | 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 following (simplified) code:
```
<a onclick="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();" href="#" id="generatedId">text</a>
```
So because JSF wraps the user defined onclick in a function, this will point to the global window. I don't have access to the id of the element because my code is used in a generic component that can be used in loops etc. and I don't use backing beans (Facelets + JSF).
So my question is, is there a way to access the A HREF element from within my onclick javascript function, without knowing the id? | 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 UIData and emitted multiple times, or the container is a [portlet](http://en.wikipedia.org/wiki/Java_Portlet_Specification) so the view can be rendered multiple times in one HTML page). This ID is known as the clientId, and is distinct from the ID set on the JSF control.
If you want to emit the clientId in the view, you can use a managed bean to do it.
```
public class JavaScriptBean {
public String getOnclickButton1() {
String id = "button1";
String clientId = getClientId(id);
return "alert('You clicked element id=" + clientId + "');";
}
public String getOnclickButton2() {
String id = "button2";
String clientId = getClientId(id);
return clientId;
}
private String getClientId(String id) {
FacesContext context = FacesContext.getCurrentInstance();
UIViewRoot view = context.getViewRoot();
UIComponent component = find(view, id);
return component.getClientId(context);
}
private UIComponent find(UIComponent component, String id) {
if (id.equals(component.getId())) {
return component;
}
Iterator<UIComponent> kids = component.getFacetsAndChildren();
while (kids.hasNext()) {
UIComponent kid = kids.next();
UIComponent found = find(kid, id);
if (found == null) {
continue;
}
return found;
}
return null;
}
}
```
This is configured in the application's [faces-config.xml](http://java.sun.com/javaee/5/docs/tutorial/doc/bnawp.html) and bound to the view using the expression language:
```
<f:view>
<h:form>
<h:commandButton id="button1" value="b1"
onclick="#{javaScriptBean.onclickButton1}" />
<h:commandButton id="button2" value="b2"
onclick="alert('You clicked element id=#{javaScriptBean.onclickButton2}');" />
</h:form>
</f:view>
``` | > 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 at it - it *should* have said "return (a.call(this)==false)? false : b()".
On IE only you could read the srcElement from window.event, but that's pretty ugly.
How about avoiding JSF's weird event mangling entirely, by using unobtrusive scripting? eg. omit the onclick and say:
```
document.getElementById('generatedId').onclick= function() {
alert(this);
return false; // if you want to not follow the link
}
```
If you need the link to continue into JSF's event handling, you'd have to save the old onclick event handler and call it at the end of the function, or use Element.addEventListener (attachEvent on IE) to put your scripting hooks in at an earlier stage than the onclick. | 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 generic).
As I understand it a dll should be created to share common methods between programs.
So I can put my methods in the dll, what about things like custom dialog boxes and common forms. I currently have a custom error form and a print preview dialog which are used in almost all my programs. Is it good practice to put these in a dll? | "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 find yourself having to override it and by that point you're probably writing more code than you were before. Keep things simple. Keep them generic. Keep them useful.
Before you start, though, be aware that you are creating a dependency tree. If you update your library chances are you'll have to put in some time maintaining your apps that use it... But this is no different from using a third-party lib. | 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 practise to share as much as possible. | 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 {
void m(int x) {
(void) x;
_asm int 3;
}};
typedef void (*cb_t)(int);
int main() {
C c;
boost::function<void (int x)> cb = boost::bind(&C::m, &c, _1);
cb_t raw_cb = *cb.target<cb_t>(); //null dereference
raw_cb(1);
return 0;
}
``` | 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
{
public:
VoidDelegate(void (owner::*aFunc)(void), owner* aOwner)
{
mFunction = aFunc;
mOwner = aOwner;
}
~VoidDelegate(void)
{}
void Invoke(void)
{
if(mFunction != 0)
{
(mOwner->*mFunction)();
}
}
private:
void (owner::*mFunction)(void);
owner* mOwner;
};
```
Usage:
```
class C
{
void CallMe(void)
{
std::cout << "called";
}
};
int main(int aArgc, char** aArgv)
{
C c;
VoidDelegate<C> delegate(&C::CallMe, &c);
delegate.Invoke();
}
```
Now, since `VoidDelegate<C>` is a type, having a collection of these might not be practical, because what if the list was to contain functions of class B too? It couldn't.
This is where polymorphism comes into play. You can create an interface IDelegate, which has a function Invoke:
```
class IDelegate
{
virtual ~IDelegate(void) { }
virtual void Invoke(void) = 0;
}
```
If `VoidDelegate<T>` implements IDelegate you could have a collection of IDelegates and therefore have callbacks to methods in different class types. | 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 has a static local variable set to the value you want, and then calls the function on it.
The first way is simple and easy to understand, but not at all thread-safe or reentrant. The second version is messy and difficult, but thread-safe and reentrant if done right.
Edit: I just found out that ATL uses the code generation technique to do exactly this - they generate thunks on the fly that set up the `this` pointer and other data and then jump to the call back function. [Here's a CodeProject article](http://www.codeproject.com/KB/atl/atl_underthehood_5.aspx) that explains how that works and might give you an idea of how to do it yourself. Particularly look at the last sample (Program 77).
Note that since the article was written DEP has come into existance and you'll need to use `VirtualAlloc` with `PAGE_EXECUTE_READWRITE` to get a chunk of memory where you can allocate your thunks and execute them. | 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(outputFileStream, fileStream3);
``` | 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", "file3.txt" };
string destFileName = "destFile.txt";
using (Stream destStream = File.OpenWrite(destFileName))
{
foreach (string srcFileName in srcFileNames)
{
using (Stream srcStream = File.OpenRead(srcFileName))
{
srcStream.CopyTo(destStream);
}
}
}
```
According to the disassembler ([ILSpy](http://wiki.sharpdevelop.net/ILSpy.ashx)) the default buffer size is 4096. CopyTo function has got an overload, which lets you specify the buffer size in case you are not happy with 4096 bytes. | 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. I'm just looking for the best way (without using something like ezSQL). | ```
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 errors:
```
function get_total_adults() {
$sql = 'SELECT SUM(number_adults_attending) FROM is_nfo_rsvp';
$result = mysql_query($sql);
if (!$result) {
throw new Exception('Failed to get total number of adults attending');
}
return mysql_result($result, 0);
}
try {
$total_adults = get_total_adults();
} catch(Exception $ex) {
die('Whoops! An error occurred: ' . $ex->getMessage());
// or even better, add to your template and dump the template at this point
}
// continue code
``` | 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 a separate operation.) | 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.splitext(filename)
# Prints: ('ThisFileName', '.txt')
``` | ```
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 practice (I'm using Java, Spring MVC, and Velocity here) is to put all text that the user will see in external files, and refer to them in the UI files by name, such as:
```
#in messages_en.properties:
welcome.header = Welcome to AppName!
#in the markup
<title>#springMessage("welcome.header")</title>
```
But, having never had to go through this process on a project myself before, I'm curious what the best way to deal with this is when you have some segments of the UI that are heavy on markup, such as:
```
<p>We are excited to announce that Company1 has been acquired by
<a href="http://www.companydivisionx.com" class="boldLink">Division X</a>,
a fast-growing division of <a href="http://www.company2.com" class="boldLink">Company 2</a>, Inc.
(Nasdaq: <a href="http://finance.google.com/finance?q=blah" class="boldLink">BLAH</a>), based in...
```
One option I can think of would be to store this "low-level" of markup in messages.properties itself for the message - but this seems like the worst possible option.
Other options that I can think of are:
* Store each non-markup inner fragment in messages.properties, such as `acquisitionAnnounce1`, `acquisitionAnnounce2`, `acquisitionAnnounce3`. This seems *very* tedious though.
* Break this message into more reusable components, such as `Company1.name`, `Company2.name`, `Company2.ticker`, etc., as each of these is likely reused in many other messages. This would probably account for 80% of the words in this particular message.
Are there any best practices for dealing with internationalizing text that is heavy with markup such as this? Do you just have to bite down and bear the pain of breaking up every piece of text? What is the best solution from any projects you've personally dealt with? | 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 internationalized ones into groups and make them relevant to those markup subtemplates. Having done this sort of work using templates for an app which spanned multi-languages in the same locale, as well as multiple locales, we never ever placed markup in our message bundles.
I'd suggest that a key good practice would be to avoid placing markup (even at a low-level as you put it) inside message properties files ***at all costs!*** The potential this has for unleashing hell is not something to be overlooked - biting the bullet and breaking things up correctly, is far less of a pain than having to manage many files with scattered HTML markup. Its important you can visualise markup as holistic chunks and scattering that everywhere would make everyday development a chore since:
* You would lose IDE color highlighting and syntax validation
* High possibility that one locale file or another can easily be missed when changes to designs / markup filter down
Breaking things down (to a realistic point, eg logical sentence structures but no finer) is somewhat hard work upfront but worth the effort.
Regarding string breakdown granularity, here's a sample of what we did:
```
comment.atom-details=Subscribe To Comments
comment.username-mandatory=You must supply your name
comment.useremail-mandatory=You must supply your email address
comment.email.notification=Dear {0}, the comment thread you are watching has been updated.
comment.feed.title=Comments on {0}
comment.feed.title.default=Comments
comment.feed.entry.title=Comment on {0} at {1,date,medium} {2,time,HH:mm} by {3}
comment.atom-details=Suscribir a Comentarios
comment.username-mandatory=Debes indicar tu nombre
comment.useremail-mandatory=Debes indicar tu direcci\u00f3n de correo electr\u00f3nico
comment.email.notification=La conversaci\u00f3n que estas viendo ha sido actualizada
comment.feed.title=Comentarios sobre {0}
comment.feed.title.default=Comentarios
comment.feed.entry.title=Comentarios sobre {0} a {1,date,medium} {2,time,HH:mm} por {3}
```
So you can do interesting things with how you string replace in the message bundle which may also help you preserve it's logical meaning but allow you to manipulate it mid sentence. | 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 different contexts.
**Do not remove the markup, either.**
Please do not assume professional translators work in Notepad :) Computer-aided translation (CAT) tools, such as the Trados suite, know about markup perfectly well. If the tagging is HTML, rather than some custom XML format, no special preparation is required. Trados will protect the tags from accidental modification, while still allowing changes where necessary. Note that certain elements of tags often need to be localized, e.g. alt text or some query strings, so just stripping all the markup won't do.
Best of all, unless you're working on a zero-budget personal project, consider contacting a localization vendor. Localization is a service just like web design. A competent vendor will help you pick the optimal solution/format for your project and guide you through the preparation of the source material and incorporating the localized result. And of course they and their translators will have all the necessary tools. (Full disclosure: I am a translator / localization specialist. And don't split up strings :) | 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 code and seeing the whole setup shows me more than the ususal snippets in the introduction articles you find around the web. Thanks in advance! | 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 does the work. (an HttpModule is just a external library you can plug in that handles events in ASP.NET, in CodeCampServer the UI project loads this DependencyRegistrarModule at run time, without any compile time reference to it.) | 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` has a whole bunch of properties that I don't want to have to copy over one-by-one (and then remember to maintain if an additional property gets added).
Adding a parameterised constructor to `BaseClass` is not an option as this class is defined by a WCF service reference. | ```
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>().ToList();
```
If not all of the items in your list can be cast to DerivedClass then use OfType instead
```
List<DerivedClass> result =
listBaseClass.OfType<DerivedClass>().ToList();
``` | 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> derivedList = baseList.ConvertAll<DerivedClass>(delegate
(BaseClass b) { return (DerivedClass) b; };
```
This assumes that the original list was actually full of instances of DerivedClass. If that's not the case, change the delegate to create an appropriate instance of DerivedClass based on the given BaseClass.
EDIT: I'm not sure why I didn't just post a LINQ solution:
```
List<DerivedClass> derivedList = baseList.Cast<DerivedClass>().ToList();
``` | 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.