Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm not sure why is this. I'm distributing a static \*.lib across multiple projects, but this static lib generates many \*.obj files. Seems like I need to distribute also those \*.obj files with the \*.lib. Otherwise, I get this error:
```
1>LINK : fatal error LNK1181: cannot open input file 'nsglCore.obj'
```
Why is this? Is there a way to include the data in the \*.obj files in the \*.lib? Maybe a switch in the compiler?
This is my config for the static library:
**C/C++**
```
/Od /GT /D "WIN32" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /MD /Yu"stdafx.hpp" /Fp"e:\Development\Projects\nsGameLib\Source\Core\Intermediate\nsglCore-Win32-Release.pch" /Fo"e:\Development\Projects\nsGameLib\Source\Core\Intermediate\\" /Fd"e:\Development\Projects\nsGameLib\Source\Core\Intermediate\vc90-Release.pdb" /W3 /nologo /c /Zi /TP /errorReport:prompt
```
**Librarian**
```
/OUT:"e:\Development\Projects\nsGameLib\Source\Core\Output\nsglCore-Win32-Release.lib" /NOLOGO /LTCG
```
This is my config for the project using the static library:
**C/C++**
```
/O2 /Oi /I "E:\Development\Projects\nsGameLib\Samples\\DummyEngine\\" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_UNICODE" /D "UNICODE" /FD /EHsc /MD /Gy /Fo"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\\" /Fd"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\vc90-Release.pdb" /W3 /nologo /c /Zi /TP /errorReport:prompt
```
**Linker**
```
/OUT:"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Output\SampleOnlyCore-Win32-Release.exe" /INCREMENTAL:NO /NOLOGO /LIBPATH:"E:\Development\Projects\nsGameLib\Samples\..\Deployment\Libraries" /MANIFEST /MANIFESTFILE:"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\SampleOnlyCore-Win32-Release.exe.intermediate.manifest" /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG /PDB:"e:\Development\Projects\nsGameLib\Samples\OnlyCore\Intermediate\SampleOnlyCore-Win32-Release.pdb" /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF /LTCG /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:PROMPT nsglCore kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
``` | I believe that your linker line is incorrect. The library should have a `.lib` suffix on it. So `nsglCore` should be `nsglCore-Win32-Release.lib` or maybe `nsglCore-$(TargetPlatform)-$(ConfigurationName).lib` or whatever the correct macro expansion is. | Generally, static libs do *not* generate object files. What you do is create object files and place them in a library, then the linker will search for the object files in those libraries.
I'll explain from a UNIXy command line point of view since that's the simpler to understande (I have no idea what machinations VS does before doing the basic stuff).
A sample command line for creating an executable is:
```
gcc -c -o prog.o prog.c
gcc -o prog prog.o -L/libdir -lstdc
```
The first line simply creates an object file from your `C` file. The second line creates the executable by pulling object files together, generally following a rule set like:
* All `.o` file listed explicitly are linked.
* Once that's done, you search the libraries for other objects which satisfy referenced-but-undefined symbols.
For example, say your `prog.c` contained the line `printf("hello\n");`. That will have resulted in your `prog.o` file containing a reference to `printf` that is not yet satisfied.
The linker will search your specified libraries until it satisfies that reference. In this case it will search all files of the form `/libdir/libstdc.ext` where:
* `/libdir` is from your `-L` option (a path to search for libraries in).
* `/lib` is a constant.
* `stdc` is the name of a library to search (from `-l`).
* `ext` is one or more extensions (`.a, .so, .sl`, etc).
Once the symbol is found, that object file is linked in to resolve it. This may result in *more* unsatisfied symbols appearing such as `/libdir/libstdc.a(printf.o)` having a reference to `/libdir/libstdc.a(putch.o)`.
Your particular problem may be caused by the fact that you're trying to link the object file directly rather than searching the libraries. VS should have project options to specify object files, library search paths *and* library names (I'm not sure of this for the latest versions but I know earlier versions of MSVC did). | Why do I need an *.obj file when statically linking? | [
"",
"c++",
"visual-studio-2008",
"static-linking",
""
] |
I've got a little udp example program written using ipv4. If I alter the code to ipv6 would I still be able to communicate with anyone using the listener with an ipv4 address? I was looking at porting examples at
<http://ou800doc.caldera.com/en/SDK_netapi/sockC.PortIPv4appIPv6.html>
I'm not sure if simply altering the code would ensure that it worked or if I'd have to write it in duel-stack mode. | Yes and no... IPv6 does contain completely different addressing, so you'll have to recode your app to use the alternative headers and structure sizes.
However, the IPv4 address range is available within IPv6, the syntax is to add two colons before the standard address (eg ::10.11.12.13). You can also [embed IPv4 addresses within IPv6 packets](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm). | Not without the assistance of an [IPv4/IPv6 gateway](https://datatracker.ietf.org/doc/html/draft-baker-behave-v4v6-framework) in the network, and even then communication will be limited by the [typical problems](https://www.rfc-editor.org/rfc/rfc3424) introduced by network address translating gateways. The traditional advice for programmers facing decisions like this is to recommend supporting both IPv4 and IPv6 at the same time. | is ipv6 backward compatible with ipv4? | [
"",
"c++",
"udp",
"ipv6",
"ipv4",
""
] |
Problem: I have a large database table (~500k records) which has a list of dates stored in a varchar2(15) column. These dates are stored in varying formats, ie. some are yyyy-mm-dd, some are mm/dd/yyyy, some are dd/mm/yy, some are mm/dd/yy, etc. Ie:
```
1994-01-13
01/13/1994
01/13/94
13/01/94
13/01/1994
etc
```
I need to be able to shift these dates slightly, for example to add 30 days to each date. (This is an oversimplification of my objective but it's easier to explain this way).
If all the dates were formatted consistently, I would achieve this as follows:
```
UPDATE history_table
SET some_date_col =
to_char(to_date(some_date_col, 'mm/dd/yyyy')+30, 'mm/dd/yyyy')
WHERE some_date_col IS NOT NULL;
```
Due to the size of the database, I cannot afford to loop through the values one by one and parse the date value. Can anyone suggest a means to accomplish this without loops, ie with a mass UPDATE statement? | well, you've got a real problem here.
07/07/1994 is valid for 'MM/DD/YYYY' and 'DD/MM/YYYY'
However, outside of that issue, you can try nesting decodes.
I entered the following dates into a varchar field:
> 01/12/2009, 01-12-2009, 2009-01-12, 01/12/09
and using the below, I was consistently returned 1/12/2009. You'll have to figure out all the patterns possible and keep nesting decodes. The other thing you could do is create a function to handle this. Within the function, you can check with a little more detail as to the format of the date. It will also be easier to read. You can use the function in your update statement so that should be faster than looping through, as you mentioned.
(for what its worth, looping through 500k rows like this shouldn't take very long. I regularly have to update row by row tables of 12 million records)
> select mydate,
> decode(instr(mydate,'-'),5,to\_date(mydate,'YYYY-MM-DD'),3,to\_date(mydate,'MM-DD-YYYY'),
> decode (length(mydate),8,to\_date(mydate,'MM/DD/YY'),10,to\_date(mydate,'MM/DD/YYYY')))
> from mydates;
and here is the update statement:
> update mydates set revdate = decode(instr(mydate,'-'),5,to\_date(mydate,'YYYY-MM-DD'),3,to\_date(mydate,'MM-DD-YYYY'),
> decode (length(mydate),8,to\_date(mydate,'MM/DD/YY'),10,to\_date(mydate,'MM/DD/YYYY'))) | Are the formats of these dates really that important? They should be datetime columns. Then you could just use date math functions on that field. | How to update dates stored as varying character formats (PL/SQL)? | [
"",
"sql",
"database",
"oracle",
"datetime",
"plsql",
""
] |
Simple question here, and I know there are lots of kludgy ways to do it :)
But I was hoping a SQL server expert had a script to easily script all the data out of a table? Or possibly all the tables in a DB?
I'm getting tired of copying and pasting data over RDC! :) | I had a similar requirement.
To script insert statements for each row in a table. Sometimes I needed the Identity column, other times I did not.
So, I wrote this:
```
CREATE PROCEDURE [dbo].[GenerateInsertScripts] (
@tableName varchar(100),
@tableSchema varchar(50) = 'dbo',
@skipIdentity bit = 1
)
AS
BEGIN
DECLARE @columnName varchar(800)
DECLARE @columnType varchar(20)
DECLARE @statementA varchar(MAX)
DECLARE @statementB varchar(MAX)
DECLARE @statement nvarchar(MAX)
DECLARE @isIdentity bit
DECLARE @commaFlag bit
SET @statementA = 'INSERT INTO [' + @tableSchema + '].[' + @tableName + '] ('
SET @statementB = ''' + '
DECLARE cols CURSOR FOR
SELECT
COLUMN_NAME,
DATA_TYPE,
(SELECT COLUMNPROPERTY(OBJECT_ID('[' + @tableSchema + '].[' + @tableName + ']'),
information_schema.columns.COLUMN_NAME, 'IsIdentity')) AS IsIdentity
FROM
information_schema.columns
WHERE
TABLE_NAME = @tableName
AND
TABLE_SCHEMA = @tableSchema
ORDER BY
ORDINAL_POSITION
OPEN cols
FETCH cols INTO @columnName, @columnType, @isIdentity
SET @commaFlag = 0
WHILE @@FETCH_STATUS = 0
BEGIN
IF NOT (@isIdentity = 1 AND @skipIdentity = 1) BEGIN
IF @commaFlag = 1 BEGIN
SET @statementA = @statementA + ', '
SET @statementB = @statementB + ' + '', '' + '
END
SET @commaFlag = 1
SET @statementA = @statementA + '[' + @columnName + ']'
SET @statementB = @statementB + 'CASE WHEN [' + @columnName + '] IS NULL THEN ''NULL'' ELSE ' +
CASE
WHEN @columnType = 'bigint' OR @columnType = 'int' OR @columnType = 'tinyint' OR @columnType = 'bit' THEN
'CAST([' + @columnName + '] AS varchar(MAX))'
WHEN @columnType = 'datetime' THEN
''''''''' + CONVERT(varchar, [' + @columnName + '], 121) + '''''''''
ELSE
''''''''' + REPLACE(CAST([' + @columnName + '] AS varchar(MAX)), '''''''', '''''''''''') + '''''''''
END
+ ' END'
END
FETCH cols INTO @columnName, @columnType, @isIdentity
END
SET @commaFlag = 0
CLOSE cols
DEALLOCATE cols
SET @statementB = @statementB + ' + '''
SET @statement = 'SELECT ''' + @statementA + ') VALUES (' + @statementB + ')'' [Statement] FROM [' + @tableSchema + '].[' + @tableName + ']'
EXEC sp_executesql @statement
END
``` | use this great script:
<http://vyaskn.tripod.com/code.htm#inserts>
but this is a bad way to move data, good to help fix a problem or move a little test data etc. | Script all data out of a single table or all tables in Sql Server 2005/8? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In python it's possible to use '.' in order to access object's dictionary items. For example:
```
class test( object ) :
def __init__( self ) :
self.b = 1
def foo( self ) :
pass
obj = test()
a = obj.foo
```
From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a parent namespace for 'foo' method assigned? For example, to change obj.b into 2? | ## Python 2.6+ (including Python 3)
You can use the [`__self__` property of a bound method](https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy) to access the instance that the method is bound to.
```
>> a.__self__
<__main__.test object at 0x782d0>
>> a.__self__.b = 2
>> obj.b
2
```
## Python 2.2+ (Python 2.x only)
You can also use the `im_self` property, but this is not forward compatible with Python 3.
```
>> a.im_self
<__main__.test object at 0x782d0>
``` | On bound methods, you can use three special read-only parameters:
* **im\_func** which returns the (unbound) function object
* **im\_self** which returns the object the function is bound to (class instance)
* **im\_class** which returns the class of *im\_self*
Testing around:
```
class Test(object):
def foo(self):
pass
instance = Test()
instance.foo # <bound method Test.foo of <__main__.Test object at 0x1>>
instance.foo.im_func # <function foo at 0x2>
instance.foo.im_self # <__main__.Test object at 0x1>
instance.foo.im_class # <__main__.Test class at 0x3>
# A few remarks
instance.foo.im_self.__class__ == instance.foo.im_class # True
instance.foo.__name__ == instance.foo.im_func.__name__ # True
instance.foo.__doc__ == instance.foo.im_func.__doc__ # True
# Now, note this:
Test.foo.im_func != Test.foo # unbound method vs function
Test.foo.im_self is None
# Let's play with classmethods
class Extend(Test):
@classmethod
def bar(cls):
pass
extended = Extend()
# Be careful! Because it's a class method, the class is returned, not the instance
extended.bar.im_self # <__main__.Extend class at ...>
```
There is an interesting thing to note here, that gives you a hint on how the methods are being called:
```
class Hint(object):
def foo(self, *args, **kwargs):
pass
@classmethod
def bar(cls, *args, **kwargs):
pass
instance = Hint()
# this will work with both class methods and instance methods:
for name in ['foo', 'bar']:
method = instance.__getattribute__(name)
# call the method
method.im_func(method.im_self, 1, 2, 3, fruit='banana')
```
Basically, *im\_self* attribute of a bound method changes, to allow using it as the first parameter when calling *im\_func* | Getting object's parent namespace in python? | [
"",
"python",
"python-datamodel",
""
] |
I'm working on a few report output scripts that need to do some rudimentary calculations on some money values.
I am aware of the limitations of floating point arithmetic for this purpose, however the input values are all in a decimal format, so if I use the arithmetic operators on them PHP will cast them to floats.
So what is the best way to handle the numbers? Should I use [BCMath](https://www.php.net/bc)? Is there something akin to [Decimal](http://msdn.microsoft.com/en-us/library/system.decimal.aspx) in .NET? Or is it safe to use the arithmetic operators if I cast back to int? | Don't work in Dollars ($1.54), work in cents: (154c). Unless you need to be performing tasks where fractions of a cent are important, then you'll be working with integers and all is well. If you are interested in tenths of a cent, then just multiply everything by ten! | If you use BCMath all values will be stored in strings and passed to the functions as strings, just as the result will be a string. So, you needn't do any casting but ensure that the number given to the function is a value numeric value. Personally, if the math *requires* a high amount of precision on the decimal side then use BCMath. | How do I safely perform money related calculations in PHP? | [
"",
"php",
"finance",
""
] |
Is there any way to have an XDocument print the xml version when using the ToString method? Have it output something like this:
```
<?xml version="1.0"?>
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...
```
I have the following:
```
var xdoc = new XDocument(new XDocumentType("Response", null, null, "\n"), ...
```
which will print this which is fine, but it is missing the "<?xml version" as stated above.
```
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...
```
I know that you can do this by outputting it manually my self. Just wanted to know if it was possible by using XDocument. | By using XDeclaration. This will add the declaration.
But with `ToString()` you will not get the desired output.
You need to use `XDocument.Save()` with one of his methods.
Full sample:
```
var doc = new XDocument(
new XDeclaration("1.0", "utf-16", "yes"),
new XElement("blah", "blih"));
var wr = new StringWriter();
doc.Save(wr);
Console.Write(wr.ToString());
``` | This is by far the best way and most managable:
```
var xdoc = new XDocument(new XElement("Root", new XElement("Child", "台北 Táiběi.")));
string mystring;
using(var sw = new MemoryStream())
{
using(var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
{
xdoc.Save(strw);
mystring = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
}
}
```
and i say that just because you can change encoding to anything by changing .UTF8 to .Unicode or .UTF32 | How to print <?xml version="1.0"?> using XDocument | [
"",
"c#",
"xml",
"linq-to-xml",
""
] |
I'm after a small jQuery script that will check the appropriate check box based on what value is selected in a Select element input.
eg. If the value 'P.J. Gallagher's Drummoyne' is selected in `select#CAT_Custom_70944` then `input#drummoyne-list.checkbox` is checked. The same goes for all the options in the select list:
* 'P.J. Gallagher's Drummoyne' checks `input#drummoyne-list.checkbox`
* 'P.J. Gallagher's Parramatta' checks `input#parramatta-list.checkbox`
* 'Union Hotel North Sydney' checks `input#union-list.checkbox`
Has anyone seen something like this done before? Sample HTML code:
```
<div class="item">
<label for="CAT_Custom_70944">Preferred GMH Hotel <span class="req">*</span></label><br />
<select name="CAT_Custom_70944" id="CAT_Custom_70944" class="cat_dropdown">
<option value=" " selected="selected">- Please Select -</option>
<option value="P.J. Gallagher's Drummoyne">P.J. Gallagher's Drummoyne</option>
<option value="P.J. Gallagher's Parramatta">P.J. Gallagher's Parramatta</option>
<option value="Union Hotel North Sydney">Union Hotel North Sydney</option>
</select>
</div>
<div class="item">
<input type="checkbox" id="drummoyne-list" class="checkbox" name="CampaignList_20320" /> <label>Subscribe to: P.J. Gallagher's Drummoyne Newsletter</label>
</div>
<div class="item">
<input type="checkbox" id="parramatta-list" class="checkbox" name="CampaignList_20321" /> <label>Subscribe to: P.J. Gallagher's Parramatta Newsletter</label>
</div>
<div class="item">
<input type="checkbox" id="union-list" class="checkbox" name="CampaignList_20322" /> <label>Subscribe to: The Union Hotel Newsletter</label>
</div>
``` | jQuery works great when there's a pattern to follow. For example if the option values in the dropdown where simple like "drummoyne", "parramatta" and "union", that could be easily matched to the IDs of the checkboxes.
In the absence of such a pattern, I created the code below which matches them based on the sequence in which they appear.
```
$(function(){
$('select.cat_dropdown').change(function(){
$('.item :checkbox').removeAttr('checked'); //uncheck the other boxes
$('.item :checkbox')[this.selectedIndex-1].checked = true;
});
});
``` | Create a function that is triggered by the "change" event on the select dropdown menu, which detects the chosen value and updates the correct box.
It would look something like this.
```
$("select#CAT_Custom_70944").change( function() {
var val = this.value;
if (val == "P.J. Gallagher's Drummoyne") {
// Code to check correct box...
} else if (val == "P.J. Gallagher's Parramatta") {
// Code to check correct box...
} else {
// Code to check correct box...
}
}
``` | Check Checkbox based on Select Value Using jQuery | [
"",
"javascript",
"jquery",
"html",
"forms",
""
] |
here is the html:
```
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr align="center" valign="middle">
<td width="10" class="pagestyle" onClick="pageNo(-1);" align="right">«</td>
<td id="pageNum" class="pagestyle">1/5</td>
<td width="10" class="pagestyle" onClick="pageNo(+1);" align="left">»</td>
</tr>
</table>
```
And here is the corrosponding javascript:
```
var page = 0;
function pageNo(off) {
if (((page + off) > -1) && ((page + off) < 6)) {
page = page + off;
parseRSS(page);
} else if ((page + off) === 6) {
page = 0;
parseRSS(page);
} else if ((page + off) === -1) {
page = 5;
parseRSS(page);
}
}
```
What this is supposed to do is start with page 1, which it does, and count up or down depending on the link clicked. However, when we get to page 5, I have to click twice to go back to page 1. What is causing the double-click behavior? | What is total number of pages?
Are you enumerate them from one to six or from zero to five?
Change your js function accordingly and simplify the js expression (mentioned you have pages from zero to five):
```
var page = 0;
var number_of_pages = 6;
function pageNo(off) {
page = (page + off + number_of_pages) % number_of_pages;
}
``` | Is the answer as simple as the fact that your javascript code is indexed from zero, but your rss pages are indexed from one?
In other words, you're treating your javascript code as though you have 6 pages (0 to 5 inclusive) & you've only actually got 5 pages of RSS? So when you're on the 5th page (page=4 in your javascript) and you click next, it takes you to the 6th page (page=5), but if your parseRSS function ignores this request or throws an error since it doesn't have a 6th page of data, it appears to do nothing. From there, obviously, clicking again will loop you back to page 1 (page=0). | Javascript function call not behaving the way I expect | [
"",
"javascript",
""
] |
I am trying to change the UserAgent of the WebBrowser control in a Winforms application.
I have successfully achieved this by using the following code:
```
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
public void ChangeUserAgent()
{
List<string> userAgent = new List<string>();
string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}
```
The only problem is that this only works once. When I try to run the ChangeUserAgent() method for the second time it doesn't work. It stays set to the first changed value. This is quite annoying and I've tried everything but it just won't change more than once.
Does anyone know of a different, more flexible approach?
Thanks | I'm not sure whether I should just copy/paste from a [website](http://wallerdev.com/2008/12/25/changing-the-user-agent-in-ie-net-webbrowser-control-via-csharp), but I'd rather leave the answer here, instead of a link. If anyone can clarify in comments, I'll be much obliged.
Basically, you have to extend the WebBrowser class.
```
public class ExtendedWebBrowser : WebBrowser
{
bool renavigating = false;
public string UserAgent { get; set; }
public ExtendedWebBrowser()
{
DocumentCompleted += SetupBrowser;
//this will cause SetupBrowser to run (we need a document object)
Navigate("about:blank");
}
void SetupBrowser(object sender, WebBrowserDocumentCompletedEventArgs e)
{
DocumentCompleted -= SetupBrowser;
SHDocVw.WebBrowser xBrowser = (SHDocVw.WebBrowser)ActiveXInstance;
xBrowser.BeforeNavigate2 += BeforeNavigate;
DocumentCompleted += PageLoaded;
}
void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
ref object postData, ref object headers, ref bool cancel)
{
if (!string.IsNullOrEmpty(UserAgent))
{
if (!renavigating)
{
headers += string.Format("User-Agent: {0}\r\n", UserAgent);
renavigating = true;
cancel = true;
Navigate((string)url, (string)targetFrameName, (byte[])postData, (string)headers);
}
else
{
renavigating = false;
}
}
}
}
```
Note: To use the method above you’ll need to add a COM reference to “Microsoft Internet Controls”.
He mentions your approach too, and states that the WebBrowser control seems to cache this user agent string, so it will not change the user agent without restarting the process. | The easiest way:
```
webBrowser.Navigate("http://localhost/run.php", null, null,
"User-Agent: Here Put The User Agent");
``` | Changing the user agent of the WebBrowser control | [
"",
"c#",
"winforms",
"webbrowser-control",
"user-agent",
""
] |
I'm just getting started with Hibernate, and all the examples I'm seeing so far look pretty much like the tutorial in the Hibernate documentation:
```
package org.hibernate.tutorial.domain;
import java.util.Date;
public class Event {
private Long id;
private String title;
private Date date;
public Event() {}
/* Accessor methods... */
}
```
Specifically: none of the fields are declared as `final`, and there must be a no-argument constructor so that the Hibernate framework can instantiate the class and set its fields.
But here's the thing - I **really** don't like making my classes mutable in any way whenever I can avoid it (Java Practices: Immutable Objects make a pretty strong argument for doing this). So *is there any way to get Hibernate to work even if I were to declare each of the fields 'final'*?
I understand that Hibernate uses Reflection to instantiate its classes and therefore needs to be able to invoke a constructor of some sort without taking the risk that it would pick the wrong constructor or pass the wrong value to one of its parameters, so it's probably safer to invoke the no-arg constructor and set each field one at a time. However, shouldn't it be possible to provide the necessary information to Hibernate so that it can safely instantiate immutable objects?
```
public class Event {
private final Long id;
private final String title;
private final Date date;
public Event(@SetsProperty("id") Long id,
@SetsProperty("title") String title,
@SetsProperty("date") Date date) {
this.id = id;
this.title = title;
this.date = new Date(date.getTime());
}
/* Accessor methods... */
}
```
The `@SetsProperty` annotation is of course fictitious, but doesn't seem like it should be out of reach. | This sounds like it is not a use case for Hibernate, since many operations it performs concern mutable state:
* merging objects
* dirty state checking
* flushing changes
That being said, if you're concerned about immutability you may choose to provide wrappers around your objects, with copy-constructors:
```
public class FinalEvent {
private final Integer id;
public FinalEvent(Event event) {
id = event.id;
}
}
```
It does mean extra work though.
---
Now that I'm thinking of it, hibernate sessions are usually thread-bound and this voids at least one the benefits of the final fields - safe publication.
What other the benefits of final fields are you looking for? | Actually in JDK 1.5+ hibernate can handle (through reflection) changing final fields. Create a protected default constructor() that sets the fields to some defaults/null etc... Hibernate can and will override those values when it instantiates the object.
This is all possible thanks to changes to Java 1.5 memory model - the changes of interest (allowing final to be not so final) where made to enable serialization/deserialization.
```
public class Event {
private final Long id;
private final String title;
private final Date date;
// Purely for serialization/deserialization
protected Event() {
id = null;
title = null;
date = null;
}
public Event(Long id, String title, Data date) {
this.id = id;
this.title = title;
this.date = date;
}
/* Accessor methods... */
```
} | Is there any way to declare final fields for Hibernate-managed objects? | [
"",
"java",
"hibernate",
"final",
"pojo",
""
] |
How do I pass information back and forth in an asp.net web application throught the html forms? I know how to do this in PHP, but I can't seem to think about it through the code-behind thing (i think that's what its called).
(note: i only started looking at asp.net a few hours ago. i decided to try it by recreating a simple page) | You can post to an ASP.NET page with a standard HTML form like this:
```
<form action="/MyPage.aspx" method="post">
<input type="text" name="name" />
</form>
```
Then in the code behind of MyPage.aspx, you can access the form elements like this:
```
protected void Page_Load(object sender, System.EventArgs e)
{
string name = Request.Form["name"];
}
```
It should also be noted that most ASP.NET books would probably teach posting back to the same page. You can then access the form items on the page via the objects, then do a Response.Redirect() to the next page you want to go to.
In this case the aspx would look like this:
```
<asp:TextBox runat="server" id="Name" />
```
And you would access the value from the codebehind like this:
```
protected void Page_Load(object sender, System.EventArgs e)
{
if(Page.IsPostBack)
{
string name = Name.Text;
}
}
``` | One of the biggest things to think about is the fact that you don't really have control of the form postbacks in classic ASP.NET WebForms. That was a big paradigm shift for me when I moved from PHP to ASP.NET. You do have one handy object, however, that can make things easier on you. In ASP.NET WebForms, you can access the [Session](http://msdn.microsoft.com/en-us/library/ms178581.aspx) object. You can store almost anything in the Session and it will be visible between forms. The only thing you need to be careful about is that [sessions expire](http://www.hanselman.com/blog/TroubleshootingExpiredASPNETSessionStateAndYourOptions.aspx). | ASP.NET to PHP conversion in web development | [
"",
"php",
"asp.net",
""
] |
I've seen "spaghetti" thrown about a lot and I just want a clear explanation on what **is** spaghetti code and what **isn't**. Just because I'd rather not be doing it.
References in PHP would help as that is my language of choice. | The term "spaghetti code" is not at all specific to PHP - it applies to all programming languages and should appear quite similar in most languages (at least of the same paradigm). Perhaps you understand this however, and just want an example in PHP.
The [Wikipedia article](http://en.wikipedia.org/wiki/Spaghetti_code) on this subject seems pretty clear:
> Spaghetti code is a pejorative term
> for source code which has a complex
> and tangled control structure,
> especially one using many GOTOs,
> exceptions, threads, or other
> "unstructured" branching constructs.
> It is named such because program flow
> tends to look like a bowl of
> spaghetti, i.e. twisted and tangled.
> Spaghetti code can be caused by
> several factors, including
> inexperienced programmers and a
> complex program which has been
> continuously modified over a long life
> cycle. Structured programming greatly
> decreased the incidence of spaghetti
> code.
This forum thread, [Top 100 Signs That I Am Writing Spaghetti Code in PHP](http://www.webmasterworld.com/forum88/2884.htm), might be of some use to you, as it relates specifically to PHP. | The difference is spaghetti code is written by other developers. Your code is never spaghetti code. | Definition of spaghetti php? | [
"",
"php",
"coding-style",
""
] |
Whenever i try to open my Entity Model, i get a not very helpful error message stating that "the operation could not be completed". So unfortunately i don't have more specific information. However, i have other models that open just fine, and i didn't make any significant changes to the model, other than renaming entities.
Are there any known workarounds for this behaviour? I restarted VS and my PC, removed and added the model again but nothing helped, so it must be something in the .edmx, i guess. But i didn't modify it by hand and everything compiles without errors or warnings. :-/ | I guess i fixed it...
I was using inheritance, which can cause errors if you have a 0..1|... association on a derived entity. The fix for it is usually to set the association to a 1|... association, then do the inheritance, then change it back.
However in my case that somehow broke it, but then i left the associations at 0..1|... first, then applied inheritance and after getting the error set it to 1|... , saved and then set it back again. Now it works. :)
I really can't wait for the next EF :-/
UPDATE:
I had the error again, this time i fixed it by opening the .edmx file and removing duplicate InheritanceConnectors in the EF Designer section. | Here is what I'd do. I would cut pieces of data from edmx (or whatever file is the source) file to see when the designer starts loading it again. This way I'd pinpoint the problem. | Entity Model does not load | [
"",
"c#",
".net",
"entity-framework",
""
] |
Trying to replace [this jquery code](http://jsbin.com/efidu) with some php server side magic:
```
$(document).ready(function() {
$('#text img').each(function(){
source = $(this).attr('src');
$(this).wrap($('<div class="caption '+ $(this).attr('class') + '"></div>')).removeAttr('class').removeAttr('height').removeAttr('width');
$(this).after('<p>' + $(this).attr('alt') + '</p>');
$(this).attr('src', '/system/tools/phpthumb/phpThumb.php?src=' + source + '&wl=200&hp=200&q=85&f=jpg');
});
});
```
All it does is take this:
```
<img class="right" src="blah.jpg" alt="My caption" width="100" height="200" />
```
And replaces it with:
```
<div class="caption right">
<img src="/system/tools/phpthumb/phpThumb.php?src=blah.jpg&wl=200&hp=200&q=85&f=jpg" alt="My caption" />
<p>My caption</p>
</div>
```
The images are scattered throughout a block of textile formated html between `<p>`'s. Something like this:
```
<p>My paragraph text</p>
<img src="image.jpg" />
<p>Another paragraph text <img src="another_image.jpg" /> with more text</p>
<p>And so on</p>
```
It enables users to float images left, right or center and thumbnails are automatically created using phpthumb. I'm assuming I'd need to use regular expressions. I'm new to php and only know frontend coding. How would you attack this? | Ended up using this:
```
<?php
$string = '{body}';
$documentSource = mb_substr($string,3,-4);
$doc = new DOMDocument();
$doc->loadHTML($documentSource);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//html/body/img') as $node) {
$node->removeAttribute('height');
$node->removeAttribute('width');
$source = $node->getAttribute('src');
$node->setAttribute('src', '/system/tools/phpthumb/phpThumb.php?src=' . $source . '&wl=200&hp=200&q=85&f=jpg');
$pElem = $doc->createElement('p', $node->getAttribute('alt'));
$divElem = $doc->createElement('div');
$divElem->setAttribute('class', 'caption '.$node->getAttribute('class'));
$node->removeAttribute('class');
$divElem->appendChild($node->cloneNode(true));
$divElem->appendChild($pElem);
$node->parentNode->replaceChild($divElem, $node);
}
?>
``` | I recommend you to use a parser such as [DOMDocument](http://docs.php.net/manual/en/class.domdocument.php). In addition with [DOMXPath](http://docs.php.net/manual/en/class.domxpath.php) you can translate the jQuery code nearly one by one:
```
$documentSource = '<div id="text"><img class="right" src="blah.jpg" alt="My caption" width="100" height="200" /></div>';
$doc = new DOMDocument();
$doc->loadHTML($documentSource);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//html/body/*[@id="text"]/img') as $node) {
// source = $(this).attr('src');
$source = $node->getAttribute('src');
// $(this).after('<p>' + $(this).attr('alt') + '</p>');
$pElem = $doc->createElement('p', $node->getAttribute('alt'));
// $('<div class="caption '+ $(this).attr('class') + '"></div>')
$divElem = $doc->createElement('div');
$divElem->setAttribute('class', 'caption '.$node->getAttribute('class'));
// $(this).wrap( … );
$divElem->appendChild($node->cloneNode(true));
$divElem->appendChild($pElem);
$node->parentNode->replaceChild($divElem, $node);
// $(this).removeAttr('class').removeAttr('height').removeAttr('width');
$node->removeAttribute('class');
$node->removeAttribute('height');
$node->removeAttribute('width');
// $(this).attr('src', '/system/tools/phpthumb/phpThumb.php?src=' + source + '&wl=200&hp=200&q=85&f=jpg');
$node->setAttribute('src', '/system/tools/phpthumb/phpThumb.php?src=' . $source . '&wl=200&hp=200&q=85&f=jpg');
}
echo $doc->saveXML();
``` | Wrap all <img>'s in <div>, take the alt attribute and add it into a <p> inside | [
"",
"php",
"regex",
"replace",
""
] |
I'm trying to install this PHP module from NYTimes (<http://code.nytimes.com/projects/xslcache>)
I unfortunately am falling at the last hurdle. I've installed it, added to my php.ini, but I am getting this error when running in my PHP code.
```
Fatal error: Class 'xsltCache' not found in...
```
My php code is as described by the NYTimes website
```
$xslt = new xsltCache;
```
Any ideas why that may happen?
My install script for the module is
```
cd ~
mkdir setups
cd setups
wget http://code.nytimes.com/downloads/xslcache.tar.gz
tar -xvf xslcache.tar.gz
cd xslcache
phpize && ./configure --with-xslcache=/usr/lib/libxslt.so --with-xsl-exsl-dir=/usr/lib/libexslt.so
make
make install
```
And it seems to work completely fine, no errors, php.ini is fine. Something I have notified, it doesn't show up in phpinfo(). | Check that you added the extension to the correct php.ini file.
If you have a PHP directory you may have one in there, but the one you want to add the extension to is likely in your server directory.
I.E. On my PC, the correct php.ini to modify is apache\bin\php.ini
P.S. Don't forget to restart your server. | It sounds like you haven't loaded the extension in you php.ini file with extension=xslcache.so. If you do have that line in your php.ini file, check your error logs and see if PHP had trouble loading the extension. | XSLT Cache problems | [
"",
"php",
"xslt",
"caching",
""
] |
I program mostly in PHP and have a site along with other samples in ASP I need to convert over to PHP. Is there some kind of "translator" tool that can either enter lines of code or full slabs that attempts to output a close PHP equivalent?
Otherwise, is there an extensive table that lists comparisons (such as [design215.com/toolbox/asp.php](http://www.design215.com/toolbox/asp.php)) | It isn't perfect, but [this](http://www.mikekohn.net/software/asp2php.php) will convert most code. | I think this is a poor way to do it. Sure, a quick-reference table helps a little. But really you need to be fluent in both ASP and current PHP best practices, and envision what a good PHP design would be. The naive transliteration will just give you PHP code that thinks it's ASP. A true port will be easier to understand and maintain. | Tool to convert ASP to PHP | [
"",
"php",
"asp-classic",
""
] |
In order to perform some testing, I'd like to check how my application behaves when some or all of the objects I have stored in a cache of SoftReference'd objects are disposed of.
In order to do this, I'd like to manually clear the references stored in the cached SoftReference objects - simulating the VM disposing of those objects - but only if nothing else currently has a strong reference to that object (which could be the case if another process had recently retrieved the referenced object from the cache).
My application is single-threaded, so I don't need to worry about the soft reachability of a cached object changing as this code is executing. This also means that I don't currently have any locking mechanisms - if I did have, I could possibly have used these to determine whether or not an object was 'being used' and hence strongly reachable, but alas I don't have need of such locking.
One approach I have tried is to create an additional SoftReference to every object stored in the cache which is registered with a ReferenceQueue. My hope was that in doing so, all of the softly reachable objects in the cache would have their additional SoftReference added to the queue, so all I had to do was loop over the queue, and remove those objects from my cache. However, it seems that the GC enqueues softly reachable objects to their respective queues at its leisure, so it is not guaranteed that anything will be added to the queue once I've finished iterating through the objects in the cache.
One thing that I have also looked at is the -XX:SoftRefLRUPolicyMSPerMB JVM option with a very small value. With judicious memory allocation, this will quite probably clear softly reachable objects from the cache for me the moment they are softly reachable, but I'd really like the app to run normally until I receive a request to clear the softly reachable objects from the cache. As a JVM option, I don't believe I can alter this value while my app is running.
So, does anyone have any ideas as to how I can determine whether or not an object is only softly reachable (and hence can be cleared)?
**Edit:** The a few extra points that may not have been clear:
* The app will probably be doing useful work at the times that I want to clear these softly reference objects out. So I'd prefer to not try and cause the GC to clear objects out for me.
* It would be preferable if I could select which softly reachable objects were cleared out.
* I would like to app to run normally, i.e. using production memory settings. Changing settings in code, which can then be reset back to their production values, is fine. | Mixing some answers: as Tom Hawtin said allocate memory till you go outOfMemory, for example with this code:
```
private void doOutOfMemory() {
try {
List<byte[]> list = new ArrayList<byte[]>();
while (true) {
list.add(new byte[200 * 1024 * 1024]);
}
} catch (OutOfMemoryError ex) {
}
}
```
If you wan't to control what objects are cleared, take a strong reference on the objects you want to keep.
You may also use weakReferences instead and only call System.gc() to clear there is no guarantee they will always be cleared... | IIRC, soft references are guaranteed (in some sense) to be cleared before an `OutOfMemoryError` is thrown. So, if you allocate lots of memory they should get cleared if the objects is not strongly referenced. (Not tested.) | Is there any way to determine if an object in Java is softly reachable? | [
"",
"java",
"soft-references",
""
] |
I'm trying to make a login page in Struts. The idea is to validate if the user exists, etc, and then if there is an error, return to the login page with the errors in red (the typical login or any form page validation).
I would like to know if someone knows an errors management tutorial in Struts. I'm looking specially for a tutorial (or example) of the
```
<html:errors>
```
tag, which I think would solve my problem. | Here's a quick summary. You have an `ActionForm` class, say `MyForm`:
```
<form-bean name="myForm" type="myapp.forms.MyForm"/>
```
You have an `Action` class, say `MyAction`:
```
<action path="/insert" type="myapp.actions.MyAction" name="myForm"
input="/insert.jsp" validate="true" />
<forward name="success" path="/insertDone.jsp"/>
</action>
```
"name" in the action refers to "name" in the form-bean. Because you have `validate="true"` your `ActionForm` class `MyForm` must define `validate()` method which will automatically be called:
```
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((username==null) || (username.length() < 1))
errors.add("username", new ActionError("error.username.required"));
return errors;
}
```
If it returns an empty ActionErrors object, Struts goes on to call your MyAction.execute(). Otherwise, Struts displays /insert.jsp (because that's the input= parm you gave) and expands the html.errors tag to display your errors from ActionErrors. | Here's one:
//struts.apache.org/1.3.5/struts-taglib/apidocs/org/apache/struts/taglib/html/package-summary.html#package\_description
Here I'm assuming Struts 1. I don't know if it has changed for Struts 2.
You can put an errors.header and errors.footer into your message resources file:
```
errors.header=<h3><font color="red">Errors:</font></h3><ul>
errors.footer=</ul>
```
The header and footer are displayed only if the ActionErrors object has any errors in it.
In your Action class, do this:
```
ActionErrors errors = new ActionErrors();
if (badInput) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.bad.input", badString); // key in messages resource file
// badString will replace {0} in message
}
```
Then before returning:
```
saveErrors(request, errors);
```
In your messages resource file:
```
error.bad.input=<li>Bad input: '{0}' is invalid.</li>
```
Now when the `<html:errors/>` tag is processed, it will turn into:
```
<h3><font color="red">Errors:</font></h3><ul>
<li>Bad input: 'xxyyzzz' is invalid.<li>
</ul>
``` | <html:errors> struts tutorial or example | [
"",
"java",
"jsp",
"struts",
"struts-validation",
""
] |
How can I alias the function "document.getElementById"
I've seen it done using $
Thanks | Possibly the easiest/shortest way:
```
function $(id) { return document.getElementById(id); };
``` | ```
var $ = document.getElementById.bind( document );
``` | Make alias to document.getElementById in Javascript | [
"",
"javascript",
"function",
"alias",
""
] |
I have a co-worker who is working on a table with an 'amount' column.
They would like to get the top 5 amounts and the sum of the amounts in the same query.
I know you could do this:
```
SELECT TOP 5 amount FROM table
UNION SELECT SUM(amount) FROM table
ORDER BY amount DESC
```
But this produces results like this:
```
1000 (sum)
100
70
50
30
20
```
When what they really need is this:
```
100 | 1000
70 | 1000
50 | 1000
30 | 1000
20 | 1000
```
My intuitive attempts to achieve this tend to run into grouping problems, which isn't such an issue when you are selecting a different column, but is when you want to use an aggregate function based on the column you are selecting. | You can use a CROSS JOIN for this:
```
SELECT TOP 5 a.amount, b.sum
FROM table a
CROSS JOIN (SELECT SUM(amount) sum FROM table) b
ORDER BY amount DESC
``` | This might work
```
SELECT TOP 5 amount, (SELECT SUM(amount) FROM table)
FROM table
ORDER BY amount DESC
``` | Simple SQL select sum and values of same column | [
"",
"sql",
"sql-server",
""
] |
Do you have any advices how to test a multithreaded application?
I know, threading errors are very difficult to catch and they may occur at anytime - or not at all. Tests are difficult and the results are never for sure. Certainly it is best to carefully design and program the concurrent modules.
Nevertheless - I do not want to leave out the test aspect. So running a lot of threads that are all working on the same items can invoke threading errors, sometimes.
Any ideas or best practices to get a high hit rate of hidden threading errors?
(I am using .Net/C#) | You can use some good tools to test all the threading issues like Data races, deadlocks, stalled threads etc.
[intel-thread-checker](http://software.intel.com/en-us/intel-thread-checker/) is one such good tool.
You can also try, [CHESS](http://research.microsoft.com/en-us/downloads/b23f8dc3-bb73-498f-bd85-1de121672e69/) by Microsoft Research | Try increasing the number of threads to a large number if possible, even beyond how many will be used in a release. With lots of threads running your program, an error will appear more often since more threads are running over the code.
Double check your declarations, locks, unlocks, semaphore counts, etc and make sure they make sense.
Create a test document or spreadsheet, and using your knowledge of the code, think about where possible race conditions or deadlocks could occur.
Grab some people from the hall and do a 'hallway usability test' (Joel on Software said that I think?). Generally, people who have no idea what your program does/is about will be able to break it easily. | How to test for thread safety | [
"",
"c#",
"multithreading",
"concurrency",
"testing",
""
] |
I'd like to add a command line interface to my MFC application so that I could provide command line parameters. These parameters would configure how the application started.
However, I can't figure out how to interface these two. How could I go about doing this, if it's even possible? | MFC has a CCommandLineInfo class for doing just that - see the [CCommandLineInfo](http://msdn.microsoft.com/en-us/library/zaydx040(VS.80).aspx) documentation. | Here's how I do it in MFC apps:
```
int option1_value;
BOOL option2_value;
if (m_lpCmdLine[0] != '\0')
{
// parse each command line token
char seps[] = " "; // spaces
char *token;
char *p;
token = strtok(m_lpCmdLine, seps); // establish first token
while (token != NULL)
{
// check the option
do // block to break out of
{
if ((p = strstr(strupr(token),"/OPTION1:")) != NULL)
{
sscanf(p + 9,"%d", &option1_value);
break;
}
if ((p = strstr(strupr(token),"/OPTION2")) != NULL)
{
option2_value = TRUE;
break;
}
}
while(0);
token = strtok(NULL, seps); // get next token
}
} // end command line not empty
``` | Interfacing MFC and Command Line | [
"",
"c++",
"command-line",
"mfc",
""
] |
If someone could explain to me the difference between Decimal and decimal in C# that would be great.
In a more general fashion, what is the difference between the lower-case structs like decimal, int, string and the upper case classes Decimal, Int32, String.
Is the only difference that the upper case classes also wrap functions (like Decimal.Divide())? | They are the same. The type decimal is an alias for System.Decimal.
So basically decimal is the same thing as Decimal. It's down to user's preference which one to use but most prefer to use int and string as they are easier to type and more familiar among C++ programmers. | As C# is a .NET language, all types must map to a .NET Framework Type.
To answer your first question, decimal is an Alias of the System.Decimal .NET Framework type. They may be used interchangeably.
To answer your second question, both Decimal and decimal should extend the same functions, including both from the created variable and from the "Structure" of the value type itself.
```
decimal FirstDec = 12;
Decimal SecondDec = 13;
decimal ThirdDec = decimal.Ceiling(FirstDec, SecondDec);
Decimal FourthDec = Decimal.Floor(ThirdDec);
bool isEqual = FirstDec.Equals(SecondDec) && FourthDec.Equals(ThirdDec);
```
The following [MSDN Page for Built-In Types](http://msdn.microsoft.com/en-us/library/ya5y69ds%28v=vs.110%29.aspx) will show you which `System.ValueType` each alias maps to. And for `Decimal` and `decimal` specifically, you can reference this [MSDN Page for Decimal](http://msdn.microsoft.com/en-us/library/system.decimal.aspx). | Difference between Decimal and decimal | [
"",
"c#",
"class",
""
] |
I have created a Queue class in javascript and I would like to store functions as data in a queue. That way I can build up requests (function calls) and respond to them when I need to (actually executing the function).
Is there any way to store a function as data, somewhat similar to
```
.setTimeout("doSomething()", 1000);
```
except it would be
```
functionQueue.enqueue(doSomething());
```
Where it would store doSomething() as data so when I retrieve the data from the queue, the function would be executed.
I'm guessing I would have to have doSomething() in quotes -> "doSomething()" and some how make it call the function using a string, anyone know how that could be done? | All functions are actually variables, so it's actually pretty easy to store all your functions in array (by referencing them without the `()`):
```
// Create your functions, in a variety of manners...
// (The second method is preferable, but I show the first for reference.)
function fun1() { alert("Message 1"); };
var fun2 = function() { alert("Message 2"); };
// Create an array and append your functions to them
var funqueue = [];
funqueue.push(fun1);
funqueue.push(fun2);
// Remove and execute the first function on the queue
(funqueue.shift())();
```
This becomes a bit more complex if you want to pass parameters to your functions, but once you've setup the framework for doing this once it becomes easy every time thereafter. Essentially what you're going to do is create a wrapper function which, when invoked, fires off a predefined function with a particular context and parameter set:
```
// Function wrapping code.
// fn - reference to function.
// context - what you want "this" to be.
// params - array of parameters to pass to function.
var wrapFunction = function(fn, context, params) {
return function() {
fn.apply(context, params);
};
}
```
Now that we've got a utility function for wrapping, let's see how it's used to create future invocations of functions:
```
// Create my function to be wrapped
var sayStuff = function(str) {
alert(str);
}
// Wrap the function. Make sure that the params are an array.
var fun1 = wrapFunction(sayStuff, this, ["Hello, world!"]);
var fun2 = wrapFunction(sayStuff, this, ["Goodbye, cruel world!"]);
// Create an array and append your functions to them
var funqueue = [];
funqueue.push(fun1);
funqueue.push(fun2);
// Remove and execute all items in the array
while (funqueue.length > 0) {
(funqueue.shift())();
}
```
This code could be improved by allowing the wrapper to either use an array or a series of arguments (but doing so would muddle up the example I'm trying to make). | > ## Canonical answer posted [here](https://stackoverflow.com/a/17528961/561731)
---
Here is a nice Queue class you can use **without** the use of timeouts:
```
var Queue = (function(){
function Queue() {};
Queue.prototype.running = false;
Queue.prototype.queue = [];
Queue.prototype.add_function = function(callback) {
var _this = this;
//add callback to the queue
this.queue.push(function(){
var finished = callback();
if(typeof finished === "undefined" || finished) {
// if callback returns `false`, then you have to
// call `next` somewhere in the callback
_this.next();
}
});
if(!this.running) {
// if nothing is running, then start the engines!
this.next();
}
return this; // for chaining fun!
}
Queue.prototype.next = function(){
this.running = false;
//get the first element off the queue
var shift = this.queue.shift();
if(shift) {
this.running = true;
shift();
}
}
return Queue;
})();
```
It can be used like so:
```
var queue = new Queue;
queue.add_function(function(){
//start running something
});
queue.add_function(function(){
//start running something 2
});
queue.add_function(function(){
//start running something 3
});
``` | How do I store javascript functions in a queue for them to be executed eventually | [
"",
"javascript",
"function",
"timeout",
"queue",
""
] |
What alternatives are there to pylab for plotting in Python? In particular, I'm looking for something that doesn't use the stateful model that [pylab](http://en.wikipedia.org/wiki/Matplotlib) does. | You can always use the object-oriented framework for [Matplotlib](http://en.wikipedia.org/wiki/Matplotlib) instead of the pylab interface. | [Plotly](https://plotly.com/) lets you make graphs using a [Python API](https://plotly.com/graphing-libraries/), [matplotlib](https://plotly.com/python/matplotlib-to-plotly-tutorial/), and [pandas](https://plotly.com/ipython-notebooks/big-data-analytics-with-pandas-and-sqlite/). Their [IPython gallery](https://plotly.com/ipython-notebooks/) has some example scientific graphs with the Python scripts that generated them.
Here's a sample:

## Some recent exciting open source offerings:
* [ggplot](https://github.com/yhat/ggpy) is based on R's ggplot2, with aesthetically pleasing defaults and a really concise api. **wants to be a matplotlib killer**

* [bokeh](https://docs.bokeh.org/en/latest/) makes interactive (html canvas) plots. **emphasis on interativity + handling big data**

* [vega](https://github.com/vega/vega) translates JSON "plot descriptions" into **SVG or Canvas-based interactive plots**, and [vincent](https://github.com/wrobstory/vincent) is a declarative interface for generating the JSON specifications.
[](https://i.stack.imgur.com/CZRcW.png)
(source: [fastly.net](https://github-camo.global.ssl.fastly.net/cf082a202b608048a1e5160f97eaa0597fd38e74/687474703a2f2f74726966616374612e6769746875622e636f6d2f766567612f696d616765732f626172312e706e67)) | Python plotting libraries | [
"",
"python",
"plot",
"matplotlib",
""
] |
nothing more frustrating than to see your code crash in the debugger on a method which exceptionned and you didn't try/catch it.
Is there an easy way to scan through your sources and tag all functions which can potentially throw exceptions?
Does the build in visual assist have some hidden option to colour these functions in a specific color?
thanks
R | I think redgate have some a tool for this "Exception Hunter"
They charge for it after a trial.
<http://www.red-gate.com/products/Exception_Hunter/index.htm> | All code but the most trivial could throw exceptions (out of memory, at the very least). You're probably better off writing your code defensively, with at least a global try/catch rather than trying to micromanage which sections of code will or won't throw exceptions. | Way to automatically see which functions can potentially return exception in c# | [
"",
"c#",
"exception",
"detection",
""
] |
I tried doing this with Apache Commons FileUpload:
```
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
PrintWriter out = null;
try {
response.setContentType("text/html;charset=UTF-8");
//MultipartFormDataRequest dataRequest = new MultipartFormDataRequest(request);
//get uploaded files
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
List files = null;
try {
files = upload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(ProcessUploadItem.class.getName()).log(Level.SEVERE, null, ex);
}
}
```
and it failed at `files = upload.parseRequest(request);`
any pointers?
sorry and thank you :)
Sorry I hadn't included these:
```
The log message is null.
java.lang.NullPointerException
at web.ProcessUploadItem.processRequest(ProcessUploadItem.java:156)
at web.ProcessUploadItem.doPost(ProcessUploadItem.java:193)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:290)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:206)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:150)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:272)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:637)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:568)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:813)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
java.lang.NullPointerException
at web.ProcessUploadItem.processRequest(ProcessUploadItem.java:156)
at web.ProcessUploadItem.doPost(ProcessUploadItem.java:193)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:411)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:290)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:271)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:202)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:206)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:150)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:632)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:577)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:571)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1080)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:272)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:637)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:568)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:813)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
```
I'm using Glassfish
Thank you | From the stacktrace it's clear that one of the items that you dereference on line 156 of your class is null. Although we don't have line numbers in the snippet provided, it looks like this is only really possible on the `upload.parseRequest` line (which you yourself have also identified as the failing part).
Strangely enough it looks like this can only happen if `upload` is null - but from the code you have given this seems impossible since it's assigned a non-null value from a constructor just a few lines up and now changed since then.
If you can attach a debugger then stepping through your method and inspecting the object values would be a good idea. Otherwise, it might be worth putting a few println statements in just before that point to verify what objects are null and which are non-null. | The message `The log message is null` indicates it is complaining about the following:
```
log(Level.SEVERE, null, ex);
```
Better to use:
```
log(Level.SEVERE, "Failed to parse upload request", ex);
``` | Apache Commons fileUpload problem in java servlet | [
"",
"java",
"servlets",
"request",
""
] |
I have a WCF service that needs to return a string of XML. But it seems like the writer only wants to build up a file, not a string. I tried:
```
string nextXMLstring = "";
using (XmlWriter writer = XmlWriter.Create(nextXMLstring))
```
This generates an error saying nextXMLstring doesnt have a file path. It wants something like:
```
using (XmlWriter writer = XmlWriter.Create("nextXMLstring.xml"))
```
How can I build up my XML and then return it as a string??
Thanks!! | You need to create a StringWriter, and pass that to the XmlWriter.
The string overload of the XmlWriter.Create is for a filename.
E.g.
```
using (var sw = new StringWriter()) {
using (var xw = XmlWriter.Create(sw)) {
// Build Xml with xw.
}
return sw.ToString();
}
``` | As Richard said, `StringWriter` is the way forward. There's one snag, however: by default, `StringWriter` will advertise itself as being in UTF-16. *Usually* XML is in UTF-8. You can fix this by subclassing StringWriter;
```
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
```
This will affect the declaration written by `XmlWriter`. Of course, if you then write the string out elsewhere in binary form, make sure you use an encoding which matches whichever encoding you fix for the `StringWriter`. (The above code always assumes UTF-8; it's trivial to make a more general version which accepts an encoding in the constructor.)
You'd then use:
```
using (TextWriter writer = new Utf8StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(writer))
{
...
}
return writer.ToString();
}
``` | XmlWriter to Write to a String Instead of to a File | [
"",
"c#",
"xml",
""
] |
I am presenting the user with some exam. Users are not to proceed into the actual site before they pass this exam. However, there will be some users who will have a choice to bypass the exam until some date (say month from current date). So these users have a window of a month to take the exam. until then they can click 'Proceed' on the exam page to just go into the site.
My Logic:
When normal users click submit on the exam form page I am doing all my logic and submitting info the the DB. When these 'special' users click proceed then I will be just harcoding a 'true' to the 'didPassExam()' method, if they are still in that one month window.
My question is:
to check which button the user clicked I am doing the following (Struts 2 code)
private String submit;
```
public void setSubmit(String submit) {
this.submit = submit;
}
```
And in the JSP:
```
<s:submit name="submit" value="Submit" />
<s:submit name="submit" value="Proceed" />
```
so basically when user clicks a button, my action class will know which button was clicked. But can some hacker intentionally change value of 'Submit' button to 'Proceed' and then bypass the exam even for normal users?
Would someone do this a different and more secure way? | Yes, any user could pass along the special "Proceed" and gain access.
Since you can (and do) already tell the difference between the types of users you should validate their button *at the server* based on that. Client-side checks can always be bypassed. | In general, you should not trust input from the client. You should validate on the server side that the particular user has the right to skip the exam. Presumably, you know who the user is from a log-in process and you know the correct logic to determine if they can skip the exam. So there's no reason to trust what the client tells you. | can what I am doing in my webapplication be hacked or broken into easily? | [
"",
"java",
"struts2",
"weblogic",
""
] |
I have a domain domain.com and subdomain sub.domain.com Those two domains have different ftp users (user1, user2) belonging to the same group (usergroup) on linux environment. Finally I have the same PHP application that uses sessions on both domains (one is live and other is testing environment).
When I go to domain.com without going first to sub.domain.com, PHP session file is created in default folder /tmp/ with proper permissions 600 and user1:usergroup, when I access sub.domain.com without going first to domain.com, a file is created with permissions 600 and user2:usergroup.
All is great for all browsers but IE (please do not focus on this). What I found out is that when I access sub.domain.com and then try domain.com PHP tries to read the same session file but has no permissions and page is loading indefinitely. Changing ownership of the file to user1 makes domain.com work but prevents sub.domain.com from working.
How to make Apache or PHP create different files for sessions or make them accessible from both domains.
P.S.
Like I said for some weird reason this happens only for IE and the error message from PHP is:
Uncaught PHP Error: session\_start() [function.session-start]: open(/tmp/sess\_t1..., O\_RDWR) failed: Permission denied (13) in file xxx.php on line 46
on line on line 46 is session\_start();
Thank you for any advice in this. | I just had this same problem. It appears to be a problem with the way Apache returns session data for IE7 and IE8, but most likely because IE7 and IE8 have an improper way of announcing the domain they're requesting session data for.
Here's my scenario:
Running Apache 1.3 with two domains, each has their own account with their own users:
```
Domain: mycompany.com
Session path: /tmp/
Webserver user: mycompanycom
Domain: support.mycompany.com
Session path: /tmp/
Webserver user: nobody
```
Here is what happens during a normal visit with Firefox/Safari/Chrome:
1. I visit mycompany.com and session file is created in `/tmp/` owned by the user `mycompanycom`.
2. I then visit support.mycompany.com, and second session file is created in `/tmp/` owned by user `nobody`.
3. Apache doesn't get confused and the correct session files are returned
However, here's what happens during a visit with IE7 and IE8:
1. I visit mycompany.com and session file is created in `/tmp/` owned by the user `mycompanycom`.
2. I then visit support.mycompany.com and, instead of creating second session file in `/tmp/` owned by the user `nobody`, Apache tries to return the session file for mycompany.com.
3. The session file for mycompany.com is owned by the user `mycompanycom`, so the web server, running as user `nobody` cannot access it. Permission is denied.
The solution was, as others have suggested, to create a separate directory in `/tmp/` to separate the stored session data for support.mycompany.com:
```
mkdir /tmp/mycompany
chown nobody:nobody /tmp/mycompany
```
I then added the following to an `.htaccess` file in the root web directory for support.mycompany.com:
```
php_value session.save_path '/tmp/mycompany'
```
And finally, I removed any existing session data in `/tmp/` to ensure the new session path would get used immediately:
```
rm -f /tmp/sess_*
```
And that's it! Now IE7 and IE8 work properly.
I'm fairly certain this problem has to do with how IE7 and IE8 request session data from Apache. They probably first request session data for mycompany.com and THEN request session data for support.mycompany.com, even though the latter was the only doman entered in the address bar. | Not sure if this is the best approach for your problem but you could try having PHP save session files in different directory for each domain.
Take a look on [session\_save\_path()](http://www.php.net/manual/en/function.session-save-path.php) documentation.
Keep in mind that you must set it BEFORE initializing the session.
Ideally, that should be one of the first things your script does. | Permissions to PHP session files | [
"",
"php",
"apache",
"file",
"session",
""
] |
Can someone please help me out with a query? In Microsoft SQL Server, I have the following query, which executes fine:
```
SELECT * FROM ControlPoint
INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID
INNER JOIN Site ON Site.SiteID = Project.SiteID
WHERE Project.ProjectName LIKE '%Flood%'
```
My problem is, when I try to execute this on Microsoft Access, it gives me some kind of syntax error. It's been forever since I've used Access, but if I remember right, I think the joins need to be in parenthesis or something. Any help would be useful! | You will need some parentheses in addition to changing the wild cards:
```
SELECT * FROM (ControlPoint
INNER JOIN Project ON ControlPoint.ProjectID = Project.ProjectID)
INNER JOIN Site ON Site.SiteID = Project.SiteID
WHERE Project.ProjectName LIKE '*Flood*'
```
Note that the asterisk is used in the Access query window and with DAO, percent is used with ADO. | Access uses different wildcard patterns.
In your case, it will be - LIKE '?Flood?' (replace question mark with asterisk).
I don't know formatting codes to apply here so that it shows it correctly.
See the link for details - <http://www.techonthenet.com/access/queries/like.php> | Microsoft Access SQL query | [
"",
"sql",
"sql-server",
"t-sql",
"ms-access",
""
] |
For design purposes, I want to copy the exact HTML that is created by some JavaScript after the page loads. Firebug shows me what's going on, of course, but I really just want some static text that I can copy and paste at will. | The "View Source" menu of the [Web Developer](http://chrispederick.com/work/web-developer/) Firefox Add-on offers the "View Generated Source" tool. | That can be done with the `innerHTML` or `outerHTML` properties. Or just in Firefox, select the part you want the source code from and select *View Selection Source* from the context menu. | How can I copy dynamically generated source HTML from the web? | [
"",
"javascript",
"html",
""
] |
How do I write a list to a file? `writelines()` doesn't insert newline characters, so I need to do:
```
f.writelines([f"{line}\n" for line in lines])
``` | Use a loop:
```
with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")
```
For Python <3.6:
```
with open('your_file.txt', 'w') as f:
for line in lines:
f.write("%s\n" % line)
```
For Python 2, one may also use:
```
with open('your_file.txt', 'w') as f:
for line in lines:
print >> f, line
```
If you're keen on a single function call, at least remove the square brackets `[]`, so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings. | What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?
If you are just trying to serialize a list to disk for later use by the same python app, you should be [pickleing](http://docs.python.org/library/pickle.html) the list.
```
import pickle
with open('outfile', 'wb') as fp:
pickle.dump(itemlist, fp)
```
To read it back:
```
with open ('outfile', 'rb') as fp:
itemlist = pickle.load(fp)
``` | Writing a list to a file with Python, with newlines | [
"",
"python",
"file",
"list",
"file-io",
"newline",
""
] |
I understand pointers are used to point to objects so you would have to the same around in a program. But were and how are pointer names stored. Would it be an overkill to declare a pointer name that occupies more resource than the object it points to for example:
```
int intOne = 0;
int *this_pointer_is_pointing_towards_intOne = &intOne;
```
I know this is a ridiculous example but i was just trying to get the idea across.
Edit: the name of the pointer has to be stored somewhere taking more bytes than the address of the pointed at object. | The length of the variable name doesn't have any effect on the size of your program, just the length of time it takes to write the program. | The name of local variables are only needed for the compiler to find the variables you want to refer to. After compiling, those names usually are erased and completely replaced by numeric symbols or equivalents. This happens for all names that have no linkage practically (of course if you do a debug build, things may be different). So, the same is true for function parameters.
The name of global variables, for example, can't be erased, because you may use it from another unit in your program, and the linker has to be able to look it up. But after your program has been linked, even the name of those can be erased.
And after all, these do not occupy runtime memory. Those names are stored in a reallocation table for the purpose of linking (see the `strip` program how to remove those names).
But anyway, we are talking about a few bytes which are already wasted by alignment and whatnot. Compare that to the hell-long names of template instantiations. Try out this:
```
readelf -sW /usr/lib/libboost_*-mt.so | awk '{ print length($0), $0 }' | sort -n
``` | C++ pointer names | [
"",
"c++",
"pointers",
""
] |
> **Possible Duplicate:**
> [Why Dictionary is preferred over hashtable in C#?](https://stackoverflow.com/questions/301371/why-dictionary-is-preferred-over-hashtable-in-c)
What is the difference between Dictionary and Hashtable. How to decide which one to use? | Simply, `Dictionary<TKey,TValue>` is a generic type, allowing:
* static typing (and compile-time verification)
* use without boxing
If you are .NET 2.0 or above, you should *prefer* `Dictionary<TKey,TValue>` (and the other generic collections)
A subtle but important difference is that `Hashtable` supports multiple reader threads with a single writer thread, while `Dictionary` offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use `ConcurrentDictionary<TKey, TValue>`. | Lets give an example that would explain the difference between hashtable and dictionary.
Here is a method that implements hashtable
```
public void MethodHashTable()
{
Hashtable objHashTable = new Hashtable();
objHashTable.Add(1, 100); // int
objHashTable.Add(2.99, 200); // float
objHashTable.Add('A', 300); // char
objHashTable.Add("4", 400); // string
lblDisplay1.Text = objHashTable[1].ToString();
lblDisplay2.Text = objHashTable[2.99].ToString();
lblDisplay3.Text = objHashTable['A'].ToString();
lblDisplay4.Text = objHashTable["4"].ToString();
// ----------- Not Possible for HashTable ----------
//foreach (KeyValuePair<string, int> pair in objHashTable)
//{
// lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
//}
}
```
The following is for dictionary
```
public void MethodDictionary()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
//dictionary.Add(1, -2); // Compilation Error
foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
}
}
``` | Difference between Dictionary and Hashtable | [
"",
"c#",
"collections",
""
] |
I've read several articles and posts that say that `lock(this)`, `lock(typeof(MyType))`, `lock("a string")` are all bad practice because another thread could lock on the same key and cause a deadlock. In order to understand this problem, I was trying to create some sample code to illustrate the deadlock but have been unable to wrap my head around this.
Can someone write a concise bit of code that illustrates this classic problem? Please keep it short, I can digest code in smaller chunks only.
**Edit:**
I think lassevk sums it up well; that the real problem is that you have lost control over your locks. Once that happens, you cannot control the order the locks are called, and you are allowing a potential deadlock situation.
`lock(this)`, `lock(typeof(MyType))`, etc all are situations where you have chosen a lock that is impossible to control. | A deadlock will only occur if you have more than one lock. You need a situation where both threads hold a resource that the other needs (which means there has to be a least two resources, and the two threads have to attempt to acquire them in a different order)
So a simple example:
```
// thread 1
lock(typeof(int)) {
Thread.Sleep(1000);
lock(typeof(float)) {
Console.WriteLine("Thread 1 got both locks");
}
}
// thread 2
lock(typeof(float)) {
Thread.Sleep(1000);
lock(typeof(int)) {
Console.WriteLine("Thread 2 got both locks");
}
}
```
Assuming both threads are started within a second of each others, they will both have time to grab the first lock before anyone gets to the inner lock. Without the Sleep() call, one of the threads would most likely have time to get and release both locks before the other thread even got started. | The idea is that you should never lock on something you cannot control who has access to.
Type objects are singletons visible to every .net piece of code and you cannot control who locks on your "this" object from the outside.
Same thing is for strings: since strings are immutable, the framework keeps just one instance of "hard coded" strings and puts them in a pool (the string is said to be interned), if you write two times in your code the string "hello", you will always get the same abject.
Consider the following example: you wrote just Thread1 in your super private call, while Thread2 is called by some library you are using in a background thread...
```
void Thread1()
{
lock (typeof(int))
{
Thread.Sleep(1000);
lock (typeof(long))
// do something
}
}
void Thread2()
{
lock (typeof(long))
{
Thread.Sleep(1000);
lock (typeof(int))
// do something
}
}
``` | Sample code to illustrate a deadlock by using lock(this) | [
"",
"c#",
".net",
"multithreading",
"deadlock",
""
] |
The [NetBeans](http://www.netbeans.org/) IDE still seems to offer [Maven](http://maven.apache.org) Archetypes only for [Apache MyFaces](http://myfaces.apache.org/) or the "deprecated" [WoodStock JSF framework](https://woodstock.dev.java.net/index.html). For future development or migration of existing Woodstock projects, Sun is officially endorsing ICEfaces as the replacement technology for Woodstock.
I have not yet found a Maven Archetype which would set up a new Maven project with the [ICEFaces](http://www.icefaces.org/) [JSF](http://java.sun.com/javaee/javaserverfaces/) framework (for NetBeans or [Eclipse](http://www.eclipse.org/)). Have you found one or information about 'work in progress'? | Someone's created an [ICEFaces/Seam archetype](http://ctpjava.blogspot.com/2009/07/jboss-seam-archetype-now-with-icefaces.html), it's not available on any standard repositories to my knowledge though. The blog provides details of how to connect to their repository, which is backed by [googlecode.com](http://ctpjava.googlecode.com/svn/trunk/repository).
Is this what you're after or are you looking for a standalone ICEfaces archetype?
If you can provide a bit more detail for what you're interested in I might be able to help. | Not a real archetype yet,but maybe an example how to do it in context to AppFuse:
<http://icefusion.googlecode.com> | Is there a ICEfaces Maven archetype for NetBeans or Eclipse? | [
"",
"java",
"netbeans",
"maven-2",
"icefaces",
"maven-archetype",
""
] |
How can a C# program detect it is being compiled under a version of C# that does not contain support for the language features used in that program?
The C# compiler will reject the program, and produce some error message, on encountering the features of the language it does not support. This does not address the issue, which is to state that the program is being compiled with too old a version of the C# compiler, or a C# compiler that does not support the required version of C#
Ideally, it would be as simple as
```
#if CS_VERSION < 3
#error CSharp 3 or later is required
#end
``` | I don't believe you can do that with a C# file, but if you're using MSBuild then the project/solution tools version number can stop it from being built with an older version of MSBuild.
Can you give the exact context of this? One "human" solution rather than a technical one might be to try compiling the code with all the "old" versions, and create a document with: "If you get an error like *this* it probably means you're using the wrong version..."
Another option you might want to consider to make that even simpler is to have a single "required features" file. This would be unused by your main app, but ask users to compile that first. If it works, the rest of your build should work. If it doesn't, it's due to using the wrong version. That's likely to produce a smaller range of errors from different versions (in particular it doesn't have the problem that the compiler could list errors from different files in a random order). | According to [this list](http://msdn.microsoft.com/en-us/library/ed8yd1ha(vs.71).aspx) of preprocessor directives, it doesn't seem possible. We usually can tell by using generics (detects 2.0), using auto properties (3.0) or dynamic (4.0) | How can compilation of C# code be made to require a given language or compiler version? | [
"",
"c#",
""
] |
Thanks to this thread [How to download and save a file from Internet using Java?](https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java)
I know how to download a file, now my problem is that I need to authenticate on the sever from which I'm dowloading. It's an http interface to a subversion server. Which field do I need to look up into ?
Using the code posted in the last comment, I get this exception:
```
java.io.IOException: Server returned HTTP response code: 401 for URL: http://myserver/systemc-2.0.1.tgz
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1305)
at java.net.URL.openStream(URL.java:1009)
at mypackage.Installer.installSystemc201(Installer.java:29)
at mypackage.Installer.main(Installer.java:38)
```
Thanks, | You extend the [Authenticator](http://java.sun.com/j2se/1.5.0/docs/api/java/net/Authenticator.html) class and register it. The javadocs at the link explain how.
I don't know if this works with the nio method that got the accepted answer to the question, but it for sure works for the old fashioned way that was the answer under that one.
Within the authenticator class implementation, you are probably going to use a [PasswordAuthentication](http://java.sun.com/j2se/1.5.0/docs/api/java/net/PasswordAuthentication.html) and override the getPasswordAuthentication() method of your Authenticator implementation to return it. That will be the class which is passed the user name and password you need.
Per your request, here is some sample code:
```
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
private final PasswordAuthentication authentication;
public MyAuthenticator(Properties properties) {
String userName = properties.getProperty(USERNAME_KEY);
String password = properties.getProperty(PASSWORD_KEY);
if (userName == null || password == null) {
authentication = null;
} else {
authentication = new PasswordAuthentication(userName, password.toCharArray());
}
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
```
And you register it in the main method (or somewhere along the line before you call the URL):
```
Authenticator.setDefault(new MyAuthenticator(properties));
```
The usage is simple, but I find the API convoluted and kind of backwards for how you typically think about these things. Pretty typical of singleton design. | This is some code I wrote that fetches a website and displays the contents to System.out. It uses Basic authentication:
```
import java.net.*;
import java.io.*;
public class foo {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.MY_URL.com");
String passwdstring = "USERNAME:PASSWORD";
String encoding = new
sun.misc.BASE64Encoder().encode(passwdstring.getBytes());
URLConnection uc = yahoo.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
InputStream content = (InputStream)uc.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println (line);
}
in.close();
}
```
Problems with the above code:
1. This code isn't production-ready (but it gets the point across.)
2. The code yields this compiler warning:
```
foo.java:11: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
sun.misc.BASE64Encoder().encode(passwdstring.getBytes());
^ 1 warning
```
One really should use the Authenticator class, but for the life of me, I could not figure out how and I couldn't find any examples either, which just goes to show that the Java people don't actually like it when you use their language to do cool things. :-P
So the above isn't a *good* solution, but it does work and could easily be modified later. | Download a file from the internet using java : How to authenticate? | [
"",
"java",
"authentication",
"httpwebrequest",
"download",
"basic-authentication",
""
] |
I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:
1. load the PSD
2. edit the text in said layer
3. flatten all layers in the image
4. save as a web-friendly format like PNG or JPG
I immediately thought of [ImageMagick](http://www.imagemagick.org/), but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.
After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject? | If you don't like to use the officially supported AppleScript, JavaScript, or VBScript, then there is also the possibility to do it in Python. This is explained in the article [Photoshop scripting with Python](http://techarttiki.blogspot.com/2008/08/photoshop-scripting-with-python.html), which relies on Photoshop's COM interface.
I have not tried it, so in case it does not work for you:
If your text is preserved after [conversion to SVG](http://www.google.de/search?hl=de&q=photoshop+svg+plugin&revid=1305924600&ei=4h4JSqDpJsPj-Ab308jmCw&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=3) then you can simply replace it by whatever tool you like. Afterwards, convert it to PNG (eg. by `inkscape --export-png=...`). | The only way I can think of to automate the changing of text inside of a PSD would be to use a regex based substitution.
1. Create a very simple picture in Photoshop, perhaps a white background and a text layer, with the text being a known length.
2. Search the file for your text, and with a hex editor, search nearby for the length of the text (which may or may not be part of the file format).
3. Try changing the text, first to a string of the same length, then to something shorter/longer.
4. Open in Photoshop after each change to see if the file is corrupt.
This method, if viable, will only work if the layer in question contains a known string, which can be substituted for your other value. Note that I have no idea whether this will work, as I don't have Photoshop on this computer to try this method out. Perhaps you can make it work?
As for converting to png, I am at a loss. If the replacing script is in Python, you may be able to do it with the Python Imaging Library (PIL, [which seems to support it](http://effbot.org/imagingbook/format-psd.htm)), but otherwise you may just have to open Photoshop to do the conversion. Which means that it probably wouldn't be worth it to change the text pragmatically in the first place. | Editing Photoshop PSD text layers programmatically | [
"",
"python",
"perl",
"image",
"photoshop",
"psd",
""
] |
I am trying to find a way to extract information about my tables in SQL Server (2008).
The data I need needs to include the **description of the table** (filled from the Description property in the Properties Window), a **list of fields** of that table and their respective **data types**.
Is there any way I can extract such meta-data? I presume I have to use some `sys` sp but I'n not sure which one. | To get the description data, you unfortunately have to use sysobjects/syscolumns to get the ids:
```
SELECT u.name + '.' + t.name AS [table],
td.value AS [table_desc],
c.name AS [column],
cd.value AS [column_desc]
FROM sysobjects t
INNER JOIN sysusers u
ON u.uid = t.uid
LEFT OUTER JOIN sys.extended_properties td
ON td.major_id = t.id
AND td.minor_id = 0
AND td.name = 'MS_Description'
INNER JOIN syscolumns c
ON c.id = t.id
LEFT OUTER JOIN sys.extended_properties cd
ON cd.major_id = c.id
AND cd.minor_id = c.colid
AND cd.name = 'MS_Description'
WHERE t.type = 'u'
ORDER BY t.name, c.colorder
```
You can do it with info-schema, but you'd have to concatenate etc to call OBJECT\_ID() - so what would be the point? | Generic information about tables and columns can be found in these tables:
```
select * from INFORMATION_SCHEMA.TABLES
select * from INFORMATION_SCHEMA.COLUMNS
```
The table description is an extended property, you can query them from sys.extended\_properties:
```
select
TableName = tbl.table_schema + '.' + tbl.table_name,
TableDescription = prop.value,
ColumnName = col.column_name,
ColumnDataType = col.data_type
FROM information_schema.tables tbl
INNER JOIN information_schema.columns col
ON col.table_name = tbl.table_name
AND col.table_schema = tbl.table_schema
LEFT JOIN sys.extended_properties prop
ON prop.major_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND prop.minor_id = 0
AND prop.name = 'MS_Description'
WHERE tbl.table_type = 'base table'
``` | SQL Server: Extract Table Meta-Data (description, fields and their data types) | [
"",
"sql",
"sql-server",
"metadata",
""
] |
I'd like to be able to get a char array of all the printable characters in C#, does anybody know how to do this?
**edit:**
By printable I mean the visible European characters, so yes, umlauts, tildes, accents etc. | This will give you a list with all characters that are not considered control characters:
```
List<Char> printableChars = new List<char>();
for (int i = char.MinValue; i <= char.MaxValue; i++)
{
char c = Convert.ToChar(i);
if (!char.IsControl(c))
{
printableChars.Add(c);
}
}
```
You may want to investigate the other [Char.IsXxxx](http://msdn.microsoft.com/en-us/library/system.char_members.aspx) methods to find a combination that suits your requirements. | Here's a LINQ version of Fredrik's solution. Note that `Enumerable.Range` yields an `IEnumerable<int>` so you have to convert to chars first. `Cast<char>` would have worked in 3.5SP0 I believe, but as of 3.5SP1 you have to do a "proper" conversion:
```
var chars = Enumerable.Range(0, char.MaxValue+1)
.Select(i => (char) i)
.Where(c => !char.IsControl(c))
.ToArray();
```
I've created the result as an array as that's what the question asked for - it's not necessarily the best idea though. It depends on the use case.
Note that this also doesn't consider full Unicode characters, only those in the basic multilingual plane. I don't know what it returns for high/low surrogates, but it's worth at least knowing that a single `char` doesn't really let you represent everything :( | How do I get a list of all the printable characters in C#? | [
"",
"c#",
""
] |
I been searching for this and I just seem to run into the same articles, in this code:
```
try
{
//some code
}
catch(Exception $e){
throw $e;
}
```
Where does $e gets stored or how the webmaster see it? Should I look for a special function? | An [Exception object](http://www.php.net/manual/en/language.exceptions.extending.php) (in this case, $e) thrown from inside a catch{} block will be caught by the next highest try{} catch{} block.
Here's a silly example:
```
try {
try {
throw new Exception("This is thrown from the inner exception handler.");
}catch(Exception $e) {
throw $e;
}
}catch(Exception $e) {
die("I'm the outer exception handler (" . $e->getMessage() . ")<br />");
}
```
The output of the above is
> I'm the outer exception handler (This is thrown from the inner exception handler.) | One nice thing is that Exception implements \_\_toString() and outputs a call stack trace.
So sometimes in low-level Exceptions that I know I'm gonna want to see how I got to, in the catch() I simply do
```
error_log($e);
``` | Exception handling in PHP: where does $e goes? | [
"",
"php",
"exception",
""
] |
I have plenty experience creating ASP.NET Websites in the Visual Studio. But there is an alternative way to do the same thing that is through Web Applications, which have slightly different file structure.
Since I created my first Web Application I couldn't use classes (.cs files) in the App\_Code folder anymore, they were not seen by the ASPX and ASHX classes unless were moved to the same file.
It happens that I use the same classes across many files and I don't want to have multiple copies of them. Where do I put those classes? There is any solution without creating another project? | We have been using Web Application project type in VS 2008 for all our projects and put our common classes in AppCode folder instead of App\_Code folder. It works absolutely fine, we access our classes across all the pages in the application without any problem at all. | With Web Application Projects you have a lot more freedom. Just create subfolders under your project to hold your classes. For example, you could have a folder named "DAL" to hold the Data Access Layer items.
Optionally, you can create an assembly project and put your classes in there and just reference it from your WAP.
Ultimately the structure is going to boil down to how many classes you will have. | Where do I put classes when using Web Application project type of Visual Studio .NET instead of Website? (ASP.NET) | [
"",
"c#",
".net",
"asp.net",
"visual-studio-2008",
"web-applications",
""
] |
How to write a code (in any programming language, preferably in java), which calculates the average loading time of any website (including all embedded elements such as images, Javascript, CSS, etc.) ? | I had used [souptag](http://home.ccil.org/~cowan/XML/tagsoup/) framework to parse html page and then found individual src attribute of all the tags, Then individually found size of each page mentioned in src attribute and then according to my internet speed found out average loading time. | I'd just use [YSlow](http://developer.yahoo.com/yslow/) | How to find average loading time for website? | [
"",
"java",
"algorithm",
""
] |
What kind of sql tricks you use to enter data into two tables with a circular reference in between.
```
Employees
EmployeeID <PK>
DepartmentID <FK> NOT NULL
Departments
DepartmentID <PK>
EmployeeID <FK> NOT NULL
```
The employee belongs to a department, a department has to have a manager (department head).
Do I have to disable constraints for the insert to happen? | **Q:** Do I have to disable constraints for the insert to happen?
**A:** In Oracle, no, not if the foreign key constraints are `DEFERRABLE` (see example below)
**For Oracle:**
```
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO Departments values ('foo','dummy');
INSERT INTO Employees values ('bar','foo');
UPDATE Departments SET EmployeeID = 'bar' WHERE DepartmentID = 'foo';
COMMIT;
```
Let's unpack that:
* (autocommit must be off)
* defer enforcement of the foreign key constraint
* insert a row to Department table with a "dummy" value for the FK column
* insert a row to Employee table with FK reference to Department
* replace "dummy" value in Department FK with real reference
* re-enable enforcement of the constraints
NOTES: disabling a foreign key constraint takes effect for ALL sessions, DEFERRING a constraint is at a transaction level (as in the example), or at the session level (`ALTER SESSION SET CONSTRAINTS=DEFERRED;`)
Oracle has allowed for foreign key constraints to be defined as DEFERRABLE for at least a decade. I define all foreign key constraints (as a matter of course) to be DEFERRABLE INITIALLY IMMEDIATE. That keeps the default behavior as everyone expects, but allows for manipulation without requiring foreign keys to be disabled.
see AskTom: <http://www.oracle.com/technology/oramag/oracle/03-nov/o63asktom.html>
see AskTom: <http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:10954765239682>
see also: <http://www.idevelopment.info/data/Oracle/DBA_tips/Database_Administration/DBA_12.shtml>
[EDIT]
**A:** In Microsoft SQL Server, you can't defer foreign key constraints like you can in Oracle. Disabling and re-enabling the foreign key constraint is an approach, but I shudder at the prospect of 1) performance impact (the foreign key constraint being checked for the ENTIRE table when the constraint is re-enabled), 2) handling the exception if (when?) the re-enable of the constraint fails. Note that disabling the constraint will affect all sessions, so while the constraint is disabled, other sessions could potentially insert and update rows which will cause the reenable of the constraint to fail.
With SQL Server, a better approach is to remove the NOT NULL constraint, and allow for a NULL as temporary placeholder while rows are being inserted/updated.
**For SQL Server:**
```
-- (with NOT NULL constraint removed from Departments.EmployeeID)
insert into Departments values ('foo',NULL)
go
insert into Employees values ('bar','foo')
go
update Departments set EmployeeID = 'bar' where DepartmentID = 'foo'
go
```
[/EDIT] | I assume your Departments.EmployeeID is a department head. What I'd do is make that column nullable; then you can create the department first, then the employee. | Dealing with circular reference when entering data in SQL | [
"",
"sql",
""
] |
I am validating some check boxes and would like for the user to be able to select only 4 (from 7 possible) and disable the others if the current box is being checked(if there are already 3 checked) or enable the everything if the current box is being unchecked. I'm really not sure where's the problem. This is my first experience with JavaScript...
```
function verify_selected(selected_check_box_id) {
var count = 0;
var selected_check_boxes = new Array();
var check_boxes = new Array();
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get current checkbox
for( var i in check_boxes ) if( check_boxes[i].id == selected_check_box_id ) var current_check_box = check_boxes[i];
var current_check_box_is_checked = current_check_box.checked;
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
selected_check_boxes.push( check_boxes[i] );
count += 1;
}
}
if( current_check_box_is_checked ) {
// checking
if( count < 4 ) {
current_check_box.checked = true;
// count = 4 - disabling
if( count == 4 ) {
for( var i in check_boxes ) {
if( !check_boxes[i].checked ) check_boxes[i].disabled = true;
}
}
}
else current_check_box.checked = false;
} else {
// unchecking
// count is < 4 -> enabling
for( var i in check_boxes ) {
check_boxes[i].disabled = false;
}
}
}
```
Any help is welcome,
thanks in advance. | There were a couple of things wrong. Lets give the good version first.
I also put up a demo at: <http://jsbin.com/ajimi>
```
function verify_selected(currentCheckbox) {
var count = 0;
var selected_check_boxes = []; // this will be fine...
var check_boxes [];
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
count += 1;
}
}
if( currentCheckbox.checked && (count == 4)) {
for( var i in check_boxes )
if( !check_boxes[i].checked )
check_boxes[i].disabled = true;
} else {
for( var i in check_boxes )
check_boxes[i].disabled = false;
}
}
```
In the original version, you've got a piece of code which looked like:
```
if (count < 4) {
if (count == 4) {
```
Not gonna happen. So, that was corrected.
As you saw also in another answer, we changed the function to take out looking for an ID. Rather than figuring out the ID in some separate function (I assume you're tracking the "last clicked" by some other function which occurs), just use the this modifier to pass it into the function.
Alright, last but not least, what this would look like in jQuery. Hopefully this will help a little as to understanding how it works and why it's worth using:
(see example: <http://jsbin.com/ihone>)
```
function limitSelected(e) {
// get all of your checkboxes
var checkBoxes = $(e.currentTarget).parent().children().filter('input:checkbox');
// get the number of checkboxes checked, if 4, we'll disable
var disableCheckBoxes = (checkBoxes.filter(':checked').length == 4);
// enable checkboxes if we have < 4, disable if 4
checkBoxes.filter(':not(:checked)').each(function() {
this.disabled = disableCheckBoxes;
});
}
// when the document is ready, setup checkboxes to limit selection count
// if you have a particular div in which these checkboxes reside, you should
// change the selector ("input:checkbox"), to ("#yourDiv input:checkbox")
$(function() {
$('input:checkbox').click(limitSelected);
});
```
The other thing I will note about this version is that it works on the group of checkboxes within a div, as opposed to your version which will pick up checkboxes on the entire page. (which is limiting. | From a brief skim, your code seems much too complex for the task.
Can I suggest using something like [jquery](http://jquery.com)? You can quite easily select the relevant check boxes using the psudeo-selector '[:checked](http://docs.jquery.com/Selectors/checked)'. Also, have a look at this [check box tutorial](http://abeautifulsite.net/notebook/50).
If you don't want to use a library, I'd suggest first creating a function that can count the number of checked check boxes. Then create a function that can disable or enable all unchecked check boxes. Finally, combine the two, and register a function to trigger on the click event for the check boxes. | Check and control the number of checked check boxes with JavaScript | [
"",
"javascript",
""
] |
I have a site with anchor navigation (like gmail, when the anchor value changes a new content for a page is loaded with ajax). In Firefox, when I change the anchor (with js or with a page) a new item in the history is created and works perfectly. But in IE6 it doesn't stores this new item and the back button doesn't work as expected.
Is there anyway to add this new item using javascript?
This is possible because gmail does it but I don't know how it does it. | I've done a *lot* of work with history and using the hash. Almost all of the existing history plugins have some sort of gap in them. The one I've used that's pretty close to perfect is this one which is a jQuery plugin:
<http://www.mikage.to/jquery/jquery.history.js>
It was updated in March of this year handles IE 8 issues and it also deals with IE6 pretty successfully. One thing I've noticed is that IE really hates having ? in the hash after the #. It stops properly handling the hash when the ? is present. Even this one I think needs a little patch for the ?, I really need to send that along to Mikage. The way to handle this is instead of using `location.hash` in the plugin when referencing the hash, use this function:
```
function getHash(loc) {
loc = loc.toString();
if (loc.indexOf("#") != -1)
return loc.substring(loc.indexOf("#"));
else return "";
}
```
So in those spots where you need the hash, pass `location` the to function...
```
getHash(location)
```
...instead of using location.href. But note that for IE, because it's using the iframe, you want to use iframe.location instead.
```
getHash(iframe.location)
```
**Yahoo's Bug**
You can see that Yahoo doesn't gracefully handle ?'s in IE when looking at this URL:
<http://developer.yahoo.com/yui/examples/history/history-tabview.html#tabview=tab1?7236471234>
It should just ignore the non-existent module, (which it does for other names which have no ?'s in them). But it raises a JavaScript error when a ? is in the URL.
(I will extend this list in a moment)
**Really Simply History**
Frankly, it's primary issue seems to be it's gone dormant. I've experienced [this issue](http://code.google.com/p/reallysimplehistory/issues/detail?id=33) and just didn't want to dig through it:
> Also, even though no changes appear to
> take place on the page while I travel
> backward through the history, the back
> functionality will return once I hit
> the pages that I had been navigating
> before the one using RSH. So, if I
> clicked on four links in the RSH page,
> back functionality will return after
> I have clicked on the back button four
> times. I hope that makes sense. | I think you may have a different problem. IE6 certainly handles # links in history as it should for me on any given test page, so I believe either you have broken this in some way or you have a bug with your particular version of IE.
I suggest you try a few different copies and versions of IE6 on other machines to rule out the latter, and then try simplifying your code and rebuilding it to see if and when the problem appears. Turning off JS may (html depending) be a fast way to test this.
If all else fails I suggest you look at **[Really Simple History](http://code.google.com/p/reallysimplehistory/)** which (last time I checked) solves almost all JS/history problems you can throw at it. | Save the anchor in the ie6 history | [
"",
"javascript",
"internet-explorer",
""
] |
I have these strings in an ArrayList of String in no particular order but when I invoke Collections.sort(listReference), the sorted result is incorrect, why do 10 and 11 (the last 2 characters) come before 07, 08, 09?
```
12880 20090506054200001
12880 20090506054200002
12880 20090513070200003
12880 20090513070200004
12880 20090520202600005
12880 20090520202600006
12880 20090520232900010
12880 20090520232900011
12880 20090520232900007
12880 20090520232900008
12880 20090520232900009
``` | It works fine for me:
```
import java.util.*;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("12880 20090506054200001");
list.add("12880 20090506054200002");
list.add("12880 20090513070200003");
list.add("12880 20090513070200004");
list.add("12880 20090520202600005");
list.add("12880 20090520202600006");
list.add("12880 20090520232900010");
list.add("12880 20090520232900011");
list.add("12880 20090520232900007");
list.add("12880 20090520232900008");
list.add("12880 20090520232900009");
Collections.sort(list);
for (String x : list) {
System.out.println(x);
}
}
}
```
Output:
```
12880 20090506054200001
12880 20090506054200002
12880 20090513070200003
12880 20090513070200004
12880 20090520202600005
12880 20090520202600006
12880 20090520232900007
12880 20090520232900008
12880 20090520232900009
12880 20090520232900010
12880 20090520232900011
```
Are you absolutely sure that your 7/8/9 entries don't have something "odd" in them elsewhere (e.g. a different element of whitespace between 12880 and the timestamp)?
If not, can you produce a short but complete program that demonstrates the problem? | Okay, let's start with the basic premise that `Collections.sort` works (see ["select" isn't broken](http://www.pragprog.com/the-pragmatic-programmer/extracts/tips)).
Your strings should not sort that way, and so far several people have confirmed that they do not. So what could be causing yours to sort like that?
* Did you pass a custom `Comparator` to `sort()`?
* Are the strings really exactly like you showed? Are the whitespace characters all spaces?
Can you post the exact code that produces this result? | What's wrong with Collections.sort? | [
"",
"java",
"arrays",
"sorting",
"collections",
"arraylist",
""
] |
I was wondering if it's faster to process data in MySQL or a server language like PHP or Python. I'm sure native functions like ORDER will be faster in MySQL due to indexing, caching, etc, but actually calculating the rank (including ties returning multiple entries as having the same rank):
# Sample SQL
```
SELECT TORCH_ID,
distance AS thisscore,
(SELECT COUNT(distinct(distance))+1 FROM torch_info WHERE distance > thisscore) AS rank
FROM torch_info ORDER BY rank
```
# Server
...as opposed to just doing a `SELECT TORCH_ID FROM torch_info ORDER BY score DESC` and then figure out rank in PHP on the web server. | **Edit:** Since posting this, my answer has changed completely, partly due to the experience I've gained since then and partly because relational database systems have gotten significantly better since 2009. Today, 9 times out of 10, I would recommend doing as much of your data crunching in-database as possible. There are three reasons for this:
1. Databases are *highly* optimized for crunching data—that's their entire job! With few exceptions, replicating what the database is doing at the application level is going to be slower unless you invest a lot of engineering effort into implementing the same optimizations that the DB provides to you for free—*especially* with a relatively slow language like PHP, Python, or Ruby.
2. As the size of your table grows, pulling it into the application layer and operating on it there becomes prohibitively expensive simply due to the sheer amount of data transferred. Many applications will never reach this scale, but if you do, it's best to reduce the transfer overhead and keep the data operations as close to the DB as possible.
3. In my experience, you're far more likely to introduce consistency bugs in your application than in your RDBMS, since the DB can enforce consistency on your data at a low level but the application cannot. If you don't have that safety net built-in, so you have to be more careful to not make mistakes.
---
**Original answer:** MySQL will probably be faster with most non-complex calculations. However, 90% of the time database server is the bottleneck, so do you really want to add to that by bogging down your database with these calculations? I myself would rather put them on the web/application server to even out the load, but that's your decision. | In general, the answer to the "Should I process data in the database, or on the web server question" is, "It depends".
1. It's easy to add another web server. It's harder to add another database server. If you can take load off the database, that can be good.
2. If the output of your data processing is much smaller than the required input, you may be able to avoid a lot of data transfer overhead by doing the processing in the database. As a simple example, it'd be foolish to `SELECT *`, retrieve every row in the table, and iterate through them on the web server to pick the one where x = 3, when you can just `SELECT * WHERE x = 3`
3. As you pointed out, the database is optimized for operation on its data, using indexes, etc. | MySQL vs Web Server for processing data | [
"",
"php",
"mysql",
"optimization",
"query-optimization",
""
] |
My application is storing contact information. User can edit them through DataGridView and so on. I'm saving those contact info through serializable class which looks like that:
```
[Serializable]
public class Contact : INotifyPropertyChanged
{
private string _fName;
private string _lName;
private string _pNumber;
public event PropertyChangedEventHandler PropertyChanged;
public Contact(string firstName, string lastName, string phoneNumber, bool fromOutlook){...}
public Contact(){...}
public string FirstName{...}
public string LastName{...}
public string PhoneNumber{...}
private void NotifyPropertyChanged(string name){...}
}
```
But I'm affraid it's not the most efficient / neat format (if I just serialize the class).
Does anyone had similar task and solved it in a better manner? | There's nothing wrong with using `Serializable`; it's a great way to get an object to and from disk. If you're worried about making the format human-readble, use [`XmlSerialize`r](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) instead. | I strongly recommend VCard for following reasons.
1.) Universal protocol for contacts. Makes your data right away consumable with other VCard compatible apps. like MS Outlook.
2.) Can be transferred on mobile phones.
3.) Can be used for synchronization. [check out SyncML Contacts Sync.]
4.) You do not need to write a VCard parser your own. Just check this out [here](http://www.codeproject.com/KB/dotnet/vCardReader.aspx)
Link Txt: <http://www.codeproject.com/KB/dotnet/vCardReader.aspx>
5.) Serializable. | What is the best format to store contact / adress type of info without database? | [
"",
"c#",
"serialization",
"data-structures",
""
] |
I've been trying to get this problem solved, but I can't seem to figure it out without some serious workarounds.
if I have the following HTML:
```
<ul>
<li class="parent"> headertext </li>
<li> text </li>
<li> text </li>
<li> text </li>
<li class="parent"> headertext </li>
<li> text </li>
<li> text </li>
</ul>
```
Now, how do I now just select the `<li>` tags following the first parent (or second, for that matter)? Basically selecting an `<li>` with `class="parent"` and the following siblings until it reaches another `<li>` with the parent class.
I could restructure the list with nested lists, but I don't want to do that. Any suggestions? | The root of your problem is that the `<li>`s you have classed as parent really are NOT parents of the `<li>`s "below" them. They are siblings. jQuery has many, many functions that work with actual parents. I'd suggest fixing your markup, really. It'd be quicker, cleaner, easier to maintain, and more semantically correct than using jQuery to cobble something together. | actually, you can easily do this using nextUntil().
no need to write your own "nextUntil" since it already exists.
ex. -
```
$(".a").nextUntil(".b");
```
or as suggested by Vincent -
```
$(".parent:first").nextUntil(".parent");
``` | jquery next siblings | [
"",
"javascript",
"jquery",
"selector",
"traversal",
"siblings",
""
] |
It needs to have good code completion support, debugger, and a nice way to browse code (click to go to documentation).
Since I got spoiled by Java IDEs (Eclipse), it would be cool if it supported refactoring, reference search and some form of on the fly compilation, but maybe I'm asking too much.
So far I tried Eclipse C++ plugin, Qt Creator and Code Blocks. Eclipse plugin feels sluggish, Code Blocks has much worse completion then Qt Creator and Qt Creator is great for Qt stuff, but kinda hard to use for free form projects.
What are other options and first hand experience with them, since trying something for few hours and using something on a daily basis are two different things? | I have been using Code Lite for some time now. It provides support for auto completion. It has a code explorer and outline, though I find myself using "find resource" to open files. It has a plugin for UnitTest++ and some primitive refactoring capabilities.
[link text](http://www.codelite.org/ "Code Lite") | I'm very happy with Eclipse. It's not fast, but if you get a good enough workstation, it runs just fine, and considering how much your time is worth, a good workstation is actually pretty cheap. It also has a feature list a mile long (*good* features, not just bullet points), which I tried to summarize in [this answer](https://stackoverflow.com/questions/308450/netbeans-or-eclipse-for-c/308657#308657). It's also being actively developed; CDT 5.0 is a huge improvement over 4.0, and the next version (due out this month) adds even more nifty features (like syntax highlighting that can distinguish between overloaded and non-overloaded operators). | What is the good cross platform C++ IDE? | [
"",
"c++",
"ide",
"cross-platform",
""
] |
Lately, I have been doing this in an effort to speed up performance (and sometimes it helps with maintainability)
```
var objectToReference = $('div .complicated #selector ul:last');
```
So what does `objectToReference` really hold? Sometimes things have bitten me, so I've gone back to using the full selector and it has worked.
So does the variable hold a reference, a pointer, etc (I'm not sure the exact definition of those terms)
Thanks | A best practice that many people use when they create a variable like this is to name it starting with $, to indicate that it is a jquery object. So you could name the variable $o, and you can directly call other jQuery chain functions after it, without having to put $() around the variable.
```
$o.hide();
```
It is a good idea to start with the surrounding element for the area you are manipulating, to avoid having to search the entire document. For example, to get all links within a single section of the document (without having to search the whole document):
```
var $o = $('#mysection');
var $links = $('a', $o); // equiv to $o.find('a')
```
Finally, it never hurts to pass a jQuery object back through jQuery:
```
$o === $($o)
```
This has a nice side effect - you can write a function that accepts any of the following as an argument: a selector, an element, or a jQuery object:
```
function myFunc(e) {
var $e = $(e);
}
// All of the following will work:
myFunc('#mysection');
myFunc(document.getElementById('mysection'));
myFunc($('#mysection a'));
``` | The return value of a **[jQuery selector](http://docs.jquery.com/Selectors)** is an array of jQuery elements. If the selector does not find any matches, then it contains an array with 0 elements.
Each element in the array is essentially a reference to the matching DOM element in the HTML document. This is what allows you to traverse and manipulate them as needed. | A jQuery question about variables and selectors | [
"",
"javascript",
"jquery",
""
] |
I am trying to save a List<Foo> using ApplicationSettingsBase, however it only outputs the following even though the list is populated:
```
<setting name="Foobar" serializeAs="Xml">
<value />
</setting>
```
Foo is defined as follows:
```
[Serializable()]
public class Foo
{
public String Name;
public Keys Key1;
public Keys Key2;
public String MashupString
{
get
{
return Key1 + " " + Key2;
}
}
public override string ToString()
{
return Name;
}
}
```
How can I enable ApplicationSettingsBase to store List<Foo>? | Agreed with Thomas Levesque:
The following class was correctly saved/read back:
```
public class Foo
{
public string Name { get; set; }
public string MashupString { get; set; }
public override string ToString()
{
return Name;
}
}
```
Note: I didn't need the `SerializableAttribute`.
**Edit:** here is the xml output:
```
<WindowsFormsApplication1.MySettings>
<setting name="Foos" serializeAs="Xml">
<value>
<ArrayOfFoo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Foo>
<Name>Hello</Name>
<MashupString>World</MashupString>
</Foo>
<Foo>
<Name>Bonjour</Name>
<MashupString>Monde</MashupString>
</Foo>
</ArrayOfFoo>
</value>
</setting>
</WindowsFormsApplication1.MySettings>
```
And the settings class I used:
```
sealed class MySettings : ApplicationSettingsBase
{
[UserScopedSetting]
public List<Foo> Foos
{
get { return (List<Foo>)this["Foos"]; }
set { this["Foos"] = value; }
}
}
```
And at last the items I inserted:
```
private MySettings fooSettings = new MySettings();
var list = new List<Foo>()
{
new Foo() { Name = "Hello", MashupString = "World" },
new Foo() { Name = "Bonjour", MashupString = "Monde" }
};
fooSettings.Foos = list;
fooSettings.Save();
fooSettings.Reload();
``` | In XML serialization :
* Fields are not serialized, only properties
* Only public properties are serialized
* Read-only properties are not serialized either
So there is nothing to serialize in your class... | Storing generic List<CustomObject> using ApplicationSettingsBase | [
"",
"c#",
".net",
"serialization",
"applicationsettingsbase",
""
] |
I am currently reading *Albahari*'s [C# 3.0 in a Nutshell](https://rads.stackoverflow.com/amzn/click/com/0596527578) and on pg. 241, whilst talking about Array indexing, he says this:
> Nonzero-based arrays are not
> CLS (Common Language Specification)-compliant
What does it mean exactly, for nonzero arrays to not be **CLS compliant** ? And what implications does it have on your code?
**[Update]**
[Here](http://books.google.com.mt/books?id=_Y0rWd-Q2xkC&pg=PA241&lpg=PA241&dq=c%23+3.0+in+a+nutshell+Nonzero-based+arrays+are+not+CLS+(Common+Language+Specification)-compliant&source=bl&ots=R7ExO7UHWh&sig=OxLJ0tc3gByD8tsI3b394u_9aks&hl=mt&ei=HjQpSoiwEITG-AamuenqCA&sa=X&oi=book_result&ct=result&resnum=2) is a link to the page of the book. | The CLS (Common Language Specification) lays the groundwork for a common set of rules for compliance that guarantees that other languages (VB.NET, F#, etc.) can use assemblies that you have built with C#. A nonzero-based array would not be compliant as other languages expect arrays to be zero-based.
Here is an example that is easier to understand:
```
class Foo
{
public void Bar() { }
public void bar() { }
}
```
This type would *not* be CLS compliant since it contains two members that differ in name only by type. How would someone using VB.NET disambiguate between `Bar` and `bar` since the VB.NET compiler is not case-sensitive?
So basically the CLS is a bunch of rules like this to guarantee interoperability between languages. | CLS compliance is mostly about making sure that your code is as broadly compatible with other languages as possible. It includes things like not exposing public members which differ only by case (which would confuse VB, which is case-insensitive). See this [MSDN article](http://msdn.microsoft.com/en-us/library/bhc3fa7f.aspx) for more information, along with the [common language specification](http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx) itself. | C#: Nonzero-based arrays are not CLS-compliant | [
"",
"c#",
"arrays",
"cls-compliant",
""
] |
Does anyone know of a good tool for refactoring resources in a visual studio 2008 solution?
We have a number of resource files with translated text in an assembly used for localizing our application. But they have gotten a bit messy... I would like to rename some of the keys, and move some of them into other resource files. And I would like those changes be done in my code, and the translated versions of the resource files as well. Maybe a some analysis on what strings are missing in the translated versions, and what strings have been removed from the original as well...
Does anyone know of a good visual studio extension or ReSharper plugin that can help me with this? Right now it is kind of a pain, because I have to first rename the key in the base resource file, then in the localized versions. And then compile to get all the compile errors resulting from the key which now have a different name, and then go through and fix them all... very annoying =/ | Seems to be some new features in ReSharper 5 that helps with this
> **[Localizing your Applications with ReSharper 5](http://www.jetbrains.com/resharper/demos/presentation/localization/localization.html)**
>
> This demo shows how ReSharper 5 helps you make strings in your code localizable quickly, without breaking your regular workflow. Working with resource files is no more a developer's nightmare with ReSharper 5. | I just stumbled across this question which prompted me to blog about what I use for this problem here [Moving and renaming resource keys in a .resx file](http://matthewmanela.com/blog/moving-and-renaming-resource-keys-in-a-resx-file/).
I have two PowerShell scripts, one which renames a resource key and one which moves a resource key from one resource file to another.
Using these scripts I am able to rename a resource key:
```
.\RenameResource.ps1 oldKey newKey
```
And I can move a resource with key “keyName” from a file named “ResourceFile1.resx” to “ResourceFile2.resx”:
```
.\MoveResource.ps1 ResourceFile1 ResourceFile2 keyName
``` | C#: Resource file refactoring | [
"",
"c#",
"visual-studio-2008",
"localization",
"resx",
""
] |
I am revisiting a project and need to limit it to Java 1.4 (unfortunately). I was interested in introducing a MVC framework to improve ease of maintenance in the future.
**Besides Struts 1, what options do I have?** The lightweight the framework, the better.
Not to dismiss Struts off hand, I've just heard a lot of bad things about it. If anyone wants to defend it here, please do so.
Additionally the framework has to be able to run on Jrun, which may limit my choices. I can not, for example, get Spring MVC to work. | I found this question while looking for something else, so I apologize that this answer may not find you in time.
There is a great option for your needs! The MVC framework is Induction, it is written using JDK 1.4. Induction controllers are multi-action, like Spring MVC 2.5, but Induction does not use annotations or XML, the controller get auto-wired by default.
Induction is an extremely light-weight and fast MVC framework (7.7K lines) but has many features absent in the major MVC frameworks, such as:
* dynamic reloading during development when you change the controllers, views, models
* file uploads so simple (not much different that a string input)
* no configuration required for controllers
* capability to analyze dependencies between your Models, Views and Controllers using your IDE
* regular expression based URL mappings
* best support for managing redirects of any MVC framework
Check out the getting started tutorial here: <http://www.inductionframework.org/getting-started-tutorial.html>
Good luck! | Spring MVC is extremely lightweight. You can use as much of Spring, or as little of Spring, as you want. | Recommendations for a Java 1.4 MVC framework for Jrun? | [
"",
"java",
"model-view-controller",
"frameworks",
"jrun",
"java1.4",
""
] |
I saw [this question](https://stackoverflow.com/questions/943795/difference-between-and) and I am wondering about the same thing in JavaScript.
If you use the character ' or the character " when making strings in JavaScript, the application seems to behave the same. So what is the difference between these two characters?
The only advantage I have seen in using ' to build strings is that I can do stuff like:
```
var toAppend = '<div id="myDiv1"></div>';
```
Instead of:
```
var toAppend = "<div id=\"myDiv1\"></div>";
```
Is there any significant difference between them that I should be aware of? | They are equivalent for all intents and purposes. If you want to use either one inside a string, it is a good idea to use the other one to create the string, as you noted. Other than that, it's all the same. | Although not technically a difference in Javascript, its worth noting that single quoted strings are [not valid JSON](http://json.org), per se. I think that people automatically assume that since JSON is valid JS, that valid JS strings are also valid JSON, [which isn't necessarily true](http://jsonlint.com).
E.g., `{'key': 'Some "value"'}` is not valid JSON, whereas `{"key": "Some 'value'"}` is. | What is the difference between ' and " in JavaScript? | [
"",
"javascript",
"string",
""
] |
Consider the following:
```
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
```
How would you go about taking out the sitemap line with regex in **python**?
```
<a href="/sitemap">Sitemap</a>
```
The following can be used to pull out the anchor tags.
```
'/<a(.*?)a>/i'
```
However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either? | Don't use a regex. Use [BeautfulSoup](http://www.crummy.com/software/BeautifulSoup/), an HTML parser.
```
from BeautifulSoup import BeautifulSoup
html = \
"""
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>"""
soup = BeautifulSoup(html)
soup.findAll("div",id="hotlink")[2].a
# <a href="/sitemap">Sitemap</a>
``` | Parsing HTML with regular expression is a bad idea!
Think about the following piece of html
```
<a></a > <!-- legal html, but won't pass your regex -->
<a href="/sitemap">Sitemap<!-- proof that a>b iff ab>1 --></a>
```
There are many more such examples. Regular expressions are good for many things, but not for parsing HTML.
You should consider using [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) python HTML parser.
Anyhow, a ad-hoc solution using regex is
```
import re
data = """
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
"""
e = re.compile('<a *[^>]*>.*</a *>')
print e.findall(data)
```
Output:
```
>>> e.findall(data)
['<a href="foo1.com">Foo1</a>', '<a href="/">Home</a>', '<a href="/extract">Extract</a>', '<a href="/sitemap">Sitemap</a>']
``` | Python -- Regex -- How to find a string between two sets of strings | [
"",
"python",
"regex",
"string",
"tags",
""
] |
I'm trying to figure out a way to pull all tweets of a specific search term via PHP and the Twitter search api.
So functionality would include
1. Include a search term
2. Pull terms from each page.
3. Only pull new terms from last search
4. Export to a db or a flat file.
I'm pretty clear on all of these except for traversing across multiple pages | The twitter API takes a page number parameter. In the atom results, there are link elements, with rel attributes for next and previous. This will be your best indicator as to whether you should go looking for a 2nd page and so on. The href attribute of that tag will even tell you the URL you should request.
The query you create also takes a since\_id parameter. You'll want to store the largest id number you see in your responses and use it in subsequent requests so that you don't have to filter duplicates.
As for data storage, your selection is probably best guided by what you plan to do with the results... if you're going to be doing any querying, you should probably file it away in a database, i.e. MySQL. If you're just logging, flat file should do you fine. | The search API has a `page` parameter:
> page: Optional. The page number (starting at 1) to return, up to a max of roughly 1500 results (based on rpp \* page. Note: there are pagination limits.
>
> Example: <http://search.twitter.com/search.atom?q=devo&rpp=15&page=2>
Does that help? | Pulling multiples pages of search terms from Twitter | [
"",
"php",
"twitter",
""
] |
How do you say `if (A == 0) OR (B == 0)`? | ```
if (A == 0 || B == 0)
```
or
```
if ((A == 0) || (B == 0))
```
Check out [Control Structures](http://en.wikibooks.org/wiki/JavaScript/Control_Structures) and [Operators](http://en.wikibooks.org/wiki/JavaScript/Operators) on Wikibooks | Just to be snarky:
```
if (A === 0 || B === 0)
``` | Javascript syntax | [
"",
"javascript",
""
] |
Does anyone know the syntax for this? I've been looking everywhere and all I can find is C++ code for this. I'm trying to password protect an excel file programatically using the System.IO.Packaging namespace.
Any ideas?
Additional notes:
I'm NOT using the Excel interop--but instead the System.IO.Packaging namespace to encrypt and password protect the excel file. | If you want an Excel password all you need is something like this:
```
using Microsoft.Office.Interop.Excel
//create your spreadsheet here...
WorkbookObject.Password = password;
WorkbookObject.SaveAs("spreadsheet.xls")
```
This requires Excel to be installed.
That's nothing to do with `System.IO.Packaging` of course, so you might need to restate your question... | It's not possible using `System.IO.Packaging`. You will have to use `Microsoft.Office.Interop.Excel` using the [`Worksheet.SaveAs`](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.saveas(VS.80).aspx) method. This requires Excel being installed on your target system. | Password Protecting an Excel file in C# | [
"",
"c#",
"excel",
"passwords",
"password-protection",
""
] |
I don't think this is possible, but I would like to be proved otherwise.
I have written a simple report viewing class to output the results of various database queries. For the purpose of improving the display, when I have a report with grouped data, I would like to display the field value only on the first row of each unique value - and I would like to do this at the query level, or it would necessitate additional logic in my class to determine these special values.
It will probably help to illustrate my requirements with a simple example. Imagine this dataset:
```
Year Quarter Total
2008 Q1 20
2008 Q2 25
2008 Q3 35
2008 Q4 40
2009 Q1 15
2009 Q2 20
2009 Q3 30
2009 Q4 35
```
If possible, I would like the dataset returned as:
```
Year Quarter Total
2008 Q1 20
Q2 25
Q3 35
Q4 40
2009 Q1 15
Q2 20
Q3 30
Q4 35
```
Is there any way of doing this progammatically in MySQL? | ```
SELECT CASE WHEN @r = year THEN NULL ELSE year END AS year,
quarter,
total,
@r := year
FROM (
SELECT @r := 0
) vars,
mytable
ORDER BY
year
```
`@r` here is a session variable. You can use these in `MySQL` like any variable in any procedural language.
First, it's initialized to zero inside the subquery.
Second, it's checked in the `SELECT` clause. If the current value of `@r` is not equal to `year`, then the `year` is output, else `NULL` is output.
Third, it's updated with current value of `year`. | Why would you want to do this? What about existing records where the Year column is empty or null?
Beautifying the output belongs inside the report logic. In pseudocode it would be sth. like:
```
var lastYear = 0
foreach (record in records)
{
if (record.Year == lastYear)
{
print " "
}
else
{
print record.Year
lastYear = record.Year
}
// print the other columns
}
``` | MySQL - show field value only in first instance of each grouped value? | [
"",
"sql",
"mysql",
"dataset",
"group-by",
"grouping",
""
] |
I have something similar to this:
```
// Declarations:
List<SomeType> list1 = new List<SomeType>();
List<SomeType> list2 = new List<SomeType>();
...
SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);
...
list1[indexOfSomething] = new SomeType("SomeOtherName");
```
And the object in list2 isn't changed... Is that the expected result? | Yes, but nothing's cloned. Before the assignment, the same object is in both lists. After the assignment, you have two unique objects in two lists.
Do This:
```
list1[indexOfSomething].name = "SomeOtherName";
```
and the object in `list2` will change, too. | ```
// Declarations:
List<SomeType> list1 = new List<SomeType>();
List<SomeType> list2 = new List<SomeType>();
...
SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);
```
Remember, when you add an object to a list, you're really just adding a pointer to the object. In this case, list1 and list2 both point to the same address in memory.
```
list1[indexOfSomething] = new SomeType("SomeOtherName");
```
Now you've assigned the element list1 to a different pointer.
You're not really cloning objects themselves, you're copying the pointers which just happen to be pointing at the same object. If you need proof, do the following:
```
SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);
list1[someIndex].SomeProperty = "Kitty";
bool areEqual = list1[someIndex].SomeProperty == list2[someIndex].SomeProperty;
```
`areEqual` should be true. Pointers rock! | C#: When adding the same object to two List<object> variables, is the object cloned in the process? | [
"",
"c#",
"collections",
""
] |
I am trying to bind a new customer menu dialog box to a newCustomer button in my application. Any ideas? | Well to bind actions in java you add [`ActionListener`](http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html)s.
When constructing your button you need to add an ActionListener to it. That way, when the click event happens, the button knows what to do.
```
newCustomerButon.add(new ActionListener(){
public void actionPerformed(ActionEvent e){
// This is where you put the code for popping up the form.
yourForm.setVisible(true); // Or something similar.
}
});
``` | As far as I know, there are several add() methods which are inherited from Component, but none of which will add an ActionListener to a JButton. Do you mean [addActionListener()](http://java.sun.com/javase/6/docs/api/javax/swing/AbstractButton.html#addActionListener(java.awt.event.ActionListener)) instead? | Swing bind a dialog box to a JButton | [
"",
"java",
"swing",
"dialog",
""
] |
Any suggestions on how to do browser caching within a asp.net application. I've found some different methods online but wasn't sure what would be the best. Specifically, I would like to cache my CSS and JS files. They do change, however, it is usually once a month at the most. | Another technique is to stores you static images, css and js on another server (such as a [CDN](http://en.wikipedia.org/wiki/Content_Delivery_Network)) which has the Expires header set properly. The advantage of this is two-fold:
1. The expires header will encourage browsers and proxies to cache these static files
2. The CDN will offload from your server serving up static files.
3. By using another domain name for your static content, browsers will download faster. This is because [serving resources from four or five different hostnames increases parallelization of downloads](http://code.google.com/speed/page-speed/docs/rtt.html).
4. If the CDN is configured properly and uses [cookieless domain](http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain) then you don't have unnecessary cookies going back and forth. | Its worth bearing in mind that even without Cache-Control or Expires headers most browsers will cache content such as JS and CSS. What should happen though is the browser *should* request the resource every time its needed but will typically get a "304 Unmodified" response and the browser then uses the cached item. This is can still be quite costly since its a round trip to the server but the resource itself isn't sent so the bytes transfered is limited.
IE left with no specific instructions regarding caching will by default use its own heuristics to determine if it should even bother to re-request an item its cached. This despite not being explicitly told that it can cache a resource. Its hueristics are based on the Last-Modified date of the resource, the older its the less likely it'll have changed now is its typical reasoning. Very wooly.
Frankly if you want to make a site perfomant you need to have control over such cache settings. If you don't have access to these settings then don't wouldn't worry about performance. Just inform the sponsor that it may not perform well because they haven't facilitated a platform that lets you deliver that. | Browser Caching in ASP.NET application | [
"",
"asp.net",
"javascript",
"css",
"iis",
"caching",
""
] |
I have a Window with several Frame controls and would like to find the Bounds/Rectangle of the controls at runtime. They go into a grid on the window using XAML with Height/Width/Margin attributes.
The Frame control doesn't have Bounds, Rect, Top or Left properties.
The purpose is to test each frame to see if the mouse is inside when other events occur. My current work around is to set/clear boolean flags in the MouseEnter and MouseLeave handlers but there must be a better way. It could be obvious because I am new to C# WPF and .NET. | Why don't you just test the IsMouseOver or IsMouseDirectlyOver properties ? | Although others have met the need, as usual nobody answered the blasted question. I can think of any number of scenarios that require bounds determination. For example, displaying HTML can be done with an IFRAME in the host HTML page, and being able to position it according to the rendered bounds of a panel would allow you to integrate it nicely into your UI.
You can determine the origin of a control using a GeneralTransform on Point(0,0) to the root visual coordinate system, and ActualHeight and ActualWidth are surfaced directly.
```
GeneralTransform gt =
TransformToVisual(Application.Current.RootVisual as UIElement);
Point offset = gt.Transform(new Point(-1, -1));
myFrame.SetStyleAttribute("width", (ActualWidth + 2).ToString());
myFrame.SetStyleAttribute("height", (ActualHeight + 2).ToString());
myFrame.SetStyleAttribute("left", offset.X.ToString());
myFrame.SetStyleAttribute("top", offset.Y.ToString());
myFrame.SetStyleAttribute("visibility", "visible");
```
In the sample above I have transformed (-1, -1) and added 2 to both height and width to compensate for the single pixel border region around an IFRAME - this code is lifted from a working application that uses an IFRAME to render "embedded" HTML when browser hosted.
Also, there's more than one way to skin a cat and for hit testing you may find VisualTreeHelper interesting.
```
IEnumerable<UIElement> VisualTreeHelper
.FindElementsInHostCoordinates(Point intersectingPoint, UIElement subtree)
```
This returns every UIElement under a point (typically from the mouse). There is an overload that takes a Rect instead. | How can I determine bounds of a WPF control in C# at runtime? | [
"",
"c#",
".net",
"wpf",
""
] |
I'd like to work on a 2-3 month long project (full time) that involves coding in C++ and is related to networks (protocol stacks). I was considering writing my own network stack but that doesn't seem as interesting. It would be great to find an idea to implement a tcp/ip-like stack for distributed system/GPUs that is better as far as network performance goes. I have been googling this for 3 hours but haven't come across anything that seems worth spending 2 months on. Open source projects like netperf seem beyond my scope. I'd really like a relatively small stand alone project that I can work on, at my own pace.
The intent of this project is to utilize my free time on a project (that I might later release under open source license) and gain expertise and hands-on experience in C++, networks, parallel programming, GPU, distributed systems etc.
I seem to have hit a roadblock while finding ideas (or perhaps I am not too clear on what I exactly what to do). So any suggestions would be really appreciated.
Thanks! | If you are specifically interested in doing network programming with an emphasis on distribution and GPU/graphics stuff, you may want to check out the open source (GPL) [CIGI project](http://cigi.sourceforge.net/index.php) ([sourceforge project site](http://sourceforge.net/projects/cigi/):
> CIGI is an open simulation protocol for communication between a host device and IG (image generator).
> The Common Image Generator Interface (CIGI) is an interface designed to promote a standard
> way for a host device to communicate with an image generator (IG) in the simulation industry.
CIGI is a [fairly active project on sourceforge](http://sourceforge.net/project/stats/index.php?group_id=39061&ugn=cigi), initiated and backed by [BOEING](http://www.sisostds.org/index.php?tg=articles&idx=Print&topics=114&article=452), and is multi-platform software:
> The goal of the Common Image Generator Interface (CIGI) SG is to evaluate
> industry and government interest in developing a standard image generator
> interface. Typically, today's Image Generator (IG) vendors have their own
> closed, proprietary run-time interfaces. At I/ITSEC'02, Boeing
> proposed their Open Source Common Image Generator Interface (CIGI) as a
> run-time interface that could be adopted by the simulation community.
> Boeing indicated that they would like to see a standards organization adopt
> CIGI and develop it into a robust and broadly accepted simulation industry
> image generator run-time interface standard. The SG is discussing this
> proposal, evaluating alternatives, and generating recommendations and a
> proposed action plan.
[Here's some wireshark-based info on CIGI](http://wiki.wireshark.org/CIGI) | Have you tried Ace Wrappers. <http://www.cs.wustl.edu/~schmidt/ACE.html>
It provide well tested pattern based C++ implementation for distributed network programming. | suggestions on a project in C++ / distributed systems / networks | [
"",
"c++",
"networking",
"distributed-computing",
"gpu",
""
] |
I want to do something like the following
```
class A:
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
```
I want this to be equivalent to `A.static_method()`. Is this possible? | Sure. Classes are first-class objects in Python.
Although, in your example, you should use the `@classmethod` (class object as initial argument) or `@staticmethod` (no initial argument) decorator for your method. | You should be able to do the following (note the `@staticmethod` decorator):
```
class A:
@staticmethod
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
``` | Can you pass a class (not an object) as a parameter to a method in python? | [
"",
"python",
"static",
"parameters",
""
] |
Another question which has me perplexed:
I have a table which enables users to enter as many rows as they like based on their userid and unique id (auto incremental).
I need to be able to get this information from mysql and place the previously entered information into the fields on the web application (they may need to be edited before confirming that they're correct).
I store the total number of records for that user so far in one variable, and the total number of records for all users in another variable.
The question is: how do I get the range of ids for the records the user has already enterered.
Example: User 1 has 2 records in the database and there is 7 in total (5 by another user). How would I get the unique IDs of the 2 records that already exist?
Thanks for any suggestions you may have! | I decided to use MIN(id) in the select statement, counting how many rows there are and then populating the form fields accordingly, starting with the min value and adding the counted rows. Works well ;) | I'm not entirely sure what you mean, so this may or may not be helpful.
This SQL should give you the record ids:
```
SELECT id FROM tableofuserrows WHERE userid = [User Id]
```
You can then fetch this from the database with PHP, e.g.
```
$q = mysql_query('SELECT id FROM tableofuserrows WHERE userid = ' . (int) $_GET['userid']) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($q)) {
$result[] = $row['id'];
}
mysql_free_result($q);
echo json_encode($result);
```
So if you wanted to fetch these IDs from the browser using jQuery:
```
$.getJSON("http://url", { userid: 3 }, //set userid properly
function(data){
$.each(data, function(i,id){
//do something with the recordid
alert(id);
});
}
);
``` | Jquery - finding range between two unique id's in mysql | [
"",
"php",
"jquery",
"mysql",
""
] |
Are there any good C# focused blogs and/or podcasts out there? | [Eric Lippert](http://blogs.msdn.com/ericlippert/) works on the C# team and often talks about language design choices. As for podcasts, I would check out [.NET Rocks!](http://www.dotnetrocks.com/default.aspx) not exactly c# or even always .NET specific, but still might help you out some. | Audio Podcasts:
* [.NET Rocks](http://www.dotnetrocks.com/)
* [CodeCast](http://feeds.feedburner.com/codemag/codecast)
* [Coding QA](http://www.codingqa.com/rss)
* [Deep Fried Bytes](http://feeds.feedburner.com/deepfriedbytes)
* [Hanselminutes](http://feeds.feedburner.com/Hanselminutes)
* [Herding Code](http://herdingcode.com/?feed=rss2)
* [Jesse Liberty YapCast](http://feeds.feedburner.com/jesselibertyyapcast)
* [Pluralcast](http://feeds.feedburner.com/pluralcast)
* [TheSmackdown](http://feeds.feedburner.com/TheSmackdown)
* [Spaghetti Code Podcasts](http://feeds.feedburner.com/SpaghettiCodePodcasts)
* [Ms Dev Show](http://msdevshow.com) | Good C# focused blogs and/or podcasts? | [
"",
"c#",
"blogs",
"podcast",
""
] |
Are there any good [WPF](http://en.wikipedia.org/wiki/Windows_Presentation_Foundation) focused blogs and/or podcasts out there? | Jaime Rodriguez, a WPF Technical Evangelist at Microsoft (you'll see him on a handful of Channel 9 videos), maintains a pretty [exhaustive list of WPF bloggers](http://blogs.msdn.com/jaimer/pages/wpf-bloggers.aspx), broken down into Microsoft and non-Microsoft. Right now, it's 79 blogs long, and includes every major high-quality WPF blog I can think of. | My favorite WPF blog has to be [Bea Stollnitz's](http://www.beacosta.com/blog/). I've found it very useful on numerous occasions. | Good WPF focused blogs and/or podcasts? | [
"",
"c#",
"wpf",
"blogs",
"podcast",
""
] |
I am using the repository pattern and was wondering about what data type I should return. In my database I have a string that is variable length that needs to be broken up based off of fixed lengths. I was initially thinking of passing out the string and letting the service layer do the parsing based on the lengths of the configured columns. I dont really like the idea of passing a string out of the repository layer, would rather pass out a complete object. Passing out the string seems like not enough separation of responsibility, but having the repository having to go to another method to get how the string should be parsed and doing the parsing seems like too much work for the repo. Any suggestions of what should be the responsibility of the repo and service in this case? | Since the Repository is supposed to act as a collection of in memory objects, it should return an instance of whatever type of object your application is expecting to deal with. If your application expects a parsed object, you should return that.
Relying on some service to do the parsing is all a part of your infrastructure anyway. In most Repository implementations you have to do something with your persisted data before you return it, so this is a good thing.
For example, if your Repository is returning a Domain layer object, but your persistence is using L2S, you might want to map the L2S data to the domain object. You would need to rely on something outside the repository to do this. Call it a service or whatever, you probably don't want to kluge the repository code with the mapping. | The Repository should definitely return the Business Object.
As for who should do the parsing, you could do a number of things. Maybe you could use a helper function or something similar to parse the string into the correct format. If it's not going to be useful outside of the repo, you could just refactor the code to make it more readable.
You are correct in asserting that you shouldn't have your Repository class reach out to your service layer, so whatever method of refactoring you take to clean up the repository it should be done at that layer, not any higher. | Repository pattern and data type returned | [
"",
"c#",
".net",
"repository-pattern",
"ddd-repositories",
""
] |
I have read lots of articles on Ant that explain all sorts of options, and I've read much of the documentation for Ant, but I don't really know the "right" way to do many things. Can anyone recommend a Good Example illustrating how to use Ant? Something that is not too complicated but also not too simple.
I found [this one](http://kl93.blogspot.com/2007/04/youll-need-following-to-run-this.html) by Doug Sparling (specifically related to Hibernate) and it looks pretty good but was wondering if you folks could comment on it, because I don't want to adopt the style of someone who has questionable habits, but it seems good to me. | You might want to also look at the [Ant Usage Guides](http://wiki.apache.org/ant/AntUsageGuides) from the [Ant Wiki.](http://wiki.apache.org/ant/FrontPage) | I suggest you look at the ant scripts of open source implementations that use ant for their build script. Typically the ant scripts don't get tremendous love, but they are more robust than a typical in-house job because they are distributed to so many developers that are expected to just run them in a variety of environments.
I would argue that it is a best practice to not worry about your build script beyond the point where it gets the job done and is reasonably maintainable. It is, after all, not the goal of most projects to produce a good build script. Of course, as with any best practice, there are exceptions.
Off hand, the one I looked at for [JSR-310](https://jsr-310.dev.java.net/) was decent. | a Good Example of ant best practices | [
"",
"java",
"ant",
""
] |
`async="async"` attribute of a `<script>` tag in HTML, What does it mean?
```
<script async="async" src="...."></script>
```
Can be see used [here](http://samaxes-demos.appspot.com/samaxesjs/toc-jquery.html) for example | If the async attribute is set on an external script (one with src=), browsers that support it will download that script in the background without blocking the rest of the content on the page. The script will execute whenever it is finished downloading.
<http://dev.w3.org/html5/spec/Overview.html#attr-script-async>
As I mentioned in a comment, setting async=true, async=false or async=anything all mean the same thing. They enable the async behavior. The only way to make a script non-async is to completely omit the attribute.
<http://dev.w3.org/html5/spec/Overview.html#boolean-attributes> | In XHTML it is needed to consequently note attributes as attributes and their values whereas HTML does not. I like the conformity of that principle so I always use it in the form of:
```
async="async"
```
This way I can serve my documents as application/xhtml+xml.
If this is not of any interest for you because you are of the opinion that serving your document as text/html is good enough, then you can always use:
```
async
``` | async="async" attribute of a <script> tag in html, What does it mean? | [
"",
"javascript",
"html",
""
] |
I need to count a lot of different items. I'm processing a list of pairs such as:
```
A34223,34
B23423,-23
23423212,16
```
What I was planning to do was hash the first value (the key) into a 32bit integer which will then be a key to a sparse structure where the 'value' will be added (all start at zero) number and be negative.
Given that they keys are short and alphanumeric, is there an way to generate a hash algorithm that is fast on 32bit x86 architectures? Or is there an existing suitable hash?
I don't know anything about the design of hashes, but was hoping that due to the simple input, there would be a way of generating a high performance hash that guarantees no collision for a given key length of "X" and has high dispersion so minimizes collisions when length exceeds "X". | As you are using C++, the first thing you should do is to create a trivial implimentation using std::map. Is it fast enough (it probably will be)? If so, stick with it, otherwise investigate if your C++ implementation provides a hash table. If it does, use it to create a trivial implementation, test, time it. Is it fast enough (almost certainly yes)?
Only after you hav eexhausted these options should you think of implementing your own hash table and hashing function. | A guarantee for no collisions is difficult.
In your case, the keys
```
A34223
B23423
23423212
```
can be translated to 32-bit integers with little effort.
And here is a good function that generate hashes from strings:
```
/**
* "The Practice of Programming", Hash Tables, section 2.9, pg. 57
*
* computes hash value of string
*/
DWORD
strhash( char* str )
{
//#define MULTIPLIER 31 or 37
unsigned int h;
unsigned char* p;
h = 0;
for ( p=(unsigned char*)str; *p != '\0'; p++ )
h = 31 * h + *p; // <- FIXED MULTIPLIER
return h;
}
``` | specialised hash table c++ | [
"",
"c++",
"hash",
"hashtable",
""
] |
I need to get a reference to an iterator of a reference. However, my compiler is choking on this code:
```
template <typename InputIterator> size_t iLongestBegin(InputIterator first, InputIterator last)
{
typedef typename std::iterator_traits<InputIterator>::reference SequenceT;
//Problem is next line
typedef typename std::iterator_traits<typename SequenceT::iterator>::reference T;
for(size_t idx; idx < first->length(); idx++)
{
T curChar = (*first)[idx];
for (InputIterator cur = first; cur != last; cur++)
{
if (cur->length() < idx)
return idx;
if (_tolower(cur->at(idx)) != _tolower(curChar))
return idx;
}
}
return first->length();
}
```
Any ideas on how to fix it? The error is
```
error C2825: 'SequenceT': must be a class or namespace when followed by '::'
``` | Actually, just solved it :)
Problem is that SequenceT is a reference, not a type. Since you can't generally take the address of a reference type, the compiler won't generate iterators for it. I need to use value\_type instead of reference:
```
template <typename InputIterator> size_t iLongestBegin(InputIterator first, InputIterator last)
{
typedef typename std::iterator_traits<InputIterator>::reference SequenceT;
typedef typename std::iterator_traits<std::iterator_traits<InputIterator>::value_type::iterator>::reference T;
for(size_t idx; idx < first->length(); idx++)
{
typename T curChar = (*first)[idx];
for (InputIterator cur = first; cur != last; cur++)
{
if (cur->length() < idx)
return idx;
if (_tolower(cur->at(idx)) != _tolower(curChar))
return idx;
}
}
return first->length();
}
``` | Did you miss specifying `SequenceT` in the template argument list - Where is it defined? Or maybe you must indicate that it's a type with `typename SequenceT`. | Getting the reference of a template iterator reference | [
"",
"c++",
"iterator",
""
] |
Here is the example that I have run. It has the same Mode, Padding, BlockSize, KeySize. I am using the same init vector, key and data.
Using the RijndaelManaged produces an encrypted value of:
0x8d,0x81,0x27,0xc6,0x3c,0xe2,0x53,0x2f,0x35,0x78,0x90,0xc2,0x2e,0x3b,0x8a,0x61,
0x41,0x47,0xd6,0xd0,0xff,0x92,0x72,0x3d,0xc6,0x16,0x2b,0xd8,0xb5,0xd9,0x12,0x85
Using the AesCryptoServiceProvider produces an encrypted value of:
0x8d,0x9f,0x6e,0x99,0xe9,0x54,0x8b,0x12,0xa9,0x88,0x1a,0x3d,0x65,0x23,0x9c,0x4e,
0x18,0x5a,0x89,0x31,0xf5,0x75,0xc5,0x9e,0x0d,0x43,0xe9,0x86,0xd4,0xf3,0x64,0x3a
Here is the code I used to generate these results
```
public partial class AesTest
{
private SymmetricAlgorithm mEncryptionType;
private byte[] mPrivateKey;
private byte[] mInitializationVector;
private byte[] mData;
public AesTest()
{
mPrivateKey = new byte[32]
{
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22
};
mInitializationVector = new byte[16]
{
0x33, 0x33, 0x33, 0x33,
0x33, 0x33, 0x33, 0x33,
0x33, 0x33, 0x33, 0x33,
0x33, 0x33, 0x33, 0x33
};
mData = new byte[16]
{
0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44
};
mEncryptionType = new RijndaelManaged();
mEncryptionType.Mode = CipherMode.CFB;
mEncryptionType.Padding = PaddingMode.PKCS7;
mEncryptionType.BlockSize = 128;
mEncryptionType.KeySize = 256;
byte[] rij_encrypted_data = Encrypt(mData);
mEncryptionType = new AesCryptoServiceProvider();
mEncryptionType.Mode = CipherMode.CFB;
mEncryptionType.Padding = PaddingMode.PKCS7;
mEncryptionType.BlockSize = 128;
mEncryptionType.KeySize = 256;
byte[] aes_encrypted_data = Encrypt(mData);
}
public virtual byte[] Encrypt(byte[] unencryptedData)
{
return TransformData(unencryptedData, mEncryptionType.CreateEncryptor(mPrivateKey, mInitializationVector));
}
private byte[] TransformData(byte[] dataToTransform, ICryptoTransform cryptoTransform)
{
byte[] result = new byte[0];
if (dataToTransform != null && cryptoTransform != null && dataToTransform.Length > 0)
{
// Create the memory stream to store the results
MemoryStream mem_stream = new MemoryStream();
// Create the crypto stream to do the transformation
CryptoStream crypto_stream = new CryptoStream(mem_stream, cryptoTransform, CryptoStreamMode.Write);
// bytes are transformed on a write
crypto_stream.Write(dataToTransform, 0, dataToTransform.Length);
// Flush the final block
crypto_stream.FlushFinalBlock();
// Convert the transformed memory stream back to a byte array
result = mem_stream.ToArray();
// Close the streams
mem_stream.Close();
crypto_stream.Close();
}
return result;
}
}
```
I guess I'm just wondering if I missed something.
**Update:** Turns out that [AesManaged](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx) will throw a CryptographicException ("The specified cipher mode is not valid for this algorithm") if you try and set the CipherMode to CFB. I feel that the [AesCryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aescryptoserviceprovider.aspx) should do that same, but it doesnt. Seems funny that the FIPS Certified class allows invalid cipher modes. | Response from Microsoft:
`RijndaelManaged` class and
`AesCryptoServiceProvider` class are two
different implementations.
`RijndaelManaged` class is a kind of
implementation of Rijndael algorithm
in .net framework, which was not
validated under NIST (National
Institute of Standards and Technology)
Cryptographic Module Validation
Program (CMVP).
However,
`AesCryptoServiceProvider` class calls
the Windows Crypto API, which uses
RSAENH.DLL, and has been validated by
NIST in CMVP. Although Rijndael
algorithm was the winner of the NIST
competition to select the algorithm
that would become AES, there are some
differences between Rijndael and
official AES. Therefore,
RijndaelManaged class and
`AesCryptoServiceProvider` class have
subtle differences on implementation.
In addition, `RijndaelManaged` class
cannot provide an equivalent
implementation with AES. There is
another class implemented in .net
framework, `AesManaged` class. This
class just wrapped `RijndaelManaged`
class with a fixed block size and
iteration count to achieve the AES
standard. However, it does not support
the feedback size, especially, when
the mode is set as CFB or OFB, the
`CryptographicException` will be thrown.
For more information, please refer to
the following MSDN documents.
[AesManaged Class](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx) and [AesManaged.Mode Property](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.mode.aspx)
If you want to pick up standard AES as
security algorithm in your
application, we recommend using the
`AesCryptoServiceProvider` class. If you
want to mix the `RijndaelManged` class
and `AesCryptoServiceProvider` class in
your application, we suggest using CBC
mode instead of CFB mode in your
program, since the implementation of
the CBC mode in both classes is the
same. | I think it has to do with the CipherMode.CFB. See [this post](http://blogs.msdn.com/shawnfa/archive/2007/01/17/new-crypto-algorithms-in-orcas.aspx) describing [AesManaged](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx):
> AesManaged is actually just a wrapper
> around RinjdaelManaged with some code
> added to make sure that you do not
> setup the algorithm to operate in a
> non-AES compatible way. For instance,
> AesManaged does not allow you to
> change the block size. (It will also
> disallow the use of CFB and OFB mode
> because of the way that
> RijndaelManaged works with those
> modes).
Note that if you use CipherMode.ECB or CipherMode.CBC, you'll see identical results. Any reason why you need CFB and not CBC? | Why are RijndaelManaged and AesCryptoServiceProvider returning different results? | [
"",
"c#",
".net",
"encryption",
"rijndaelmanaged",
"aescryptoserviceprovider",
""
] |
How can I include one java file into another java file?
For example:
If I have 2 java file one is called `Person.java` and one is called `Student.java`. How can I include `Person.java` into `Student.java` so that I can extend the class from `Person.java` in `Student.java` | Just put the two files in the same directory. Here's an example:
Person.java
```
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
```
Student.java
```
public class Student extends Person {
public String somethingnew;
public Student(String name) {
super(name);
somethingnew = "surprise!";
}
public String toString() {
return super.toString() + "\t" + somethingnew;
}
public static void main(String[] args) {
Person you = new Person("foo");
Student me = new Student("boo");
System.out.println("Your name is " + you);
System.out.println("My name is " + me);
}
}
```
Running Student (since it has the main function) yields us the desired outcome:
```
Your name is foo
My name is boo surprise!
``` | What's missing from all the explanations is the fact that Java has a strict rule of *class name = file name*. Meaning if you have a class "Person", is must be in a file named "Person.java". Therefore, if one class tries to access "Person" the filename is not necessary, because it has got to be "Person.java".
Coming for C/C++, I have exact same issue. The answer is to create a new class (in a new file matching class name) and create a public string. This will be your "header" file. Then use that in your main file by using "extends" keyword.
Here is your answer:
1. Create a file called Include.java. In this file, add this:
```
public class Include {
public static String MyLongString= "abcdef";
}
```
2. Create another file, say, User.java. In this file, put:
```
import java.io.*;
public class User extends Include {
System.out.println(Include.MyLongString);
}
``` | Extend a java class from one file in another java file | [
"",
"java",
"import",
"include",
""
] |
I have to split a huge file into many smaller files. Each of the destination files is defined by an offset and length as the number of bytes. I'm using the following code:
```
private void copy(string srcFile, string dstFile, int offset, int length)
{
BinaryReader reader = new BinaryReader(File.OpenRead(srcFile));
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
byte[] buffer = reader.ReadBytes(length);
BinaryWriter writer = new BinaryWriter(File.OpenWrite(dstFile));
writer.Write(buffer);
}
```
Considering that I have to call this function about 100,000 times, it is remarkably slow.
2. Is there a way to make the Writer connected directly to the Reader? (That is, without actually loading the contents into the Buffer in memory.) | I don't believe there's anything within .NET to allow copying a section of a file without buffering it in memory. However, it strikes me that this is inefficient anyway, as it needs to open the input file and seek many times. If you're *just* splitting up the file, why not open the input file once, and then just write something like:
```
public static void CopySection(Stream input, string targetFile, int length)
{
byte[] buffer = new byte[8192];
using (Stream output = File.OpenWrite(targetFile))
{
int bytesRead = 1;
// This will finish silently if we couldn't read "length" bytes.
// An alternative would be to throw an exception
while (length > 0 && bytesRead > 0)
{
bytesRead = input.Read(buffer, 0, Math.Min(length, buffer.Length));
output.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
```
This has a minor inefficiency in creating a buffer on each invocation - you might want to create the buffer once and pass that into the method as well:
```
public static void CopySection(Stream input, string targetFile,
int length, byte[] buffer)
{
using (Stream output = File.OpenWrite(targetFile))
{
int bytesRead = 1;
// This will finish silently if we couldn't read "length" bytes.
// An alternative would be to throw an exception
while (length > 0 && bytesRead > 0)
{
bytesRead = input.Read(buffer, 0, Math.Min(length, buffer.Length));
output.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
```
Note that this also closes the output stream (due to the using statement) which your original code didn't.
The important point is that this will use the operating system file buffering more efficiently, because you reuse the same input stream, instead of reopening the file at the beginning and then seeking.
I *think* it'll be significantly faster, but obviously you'll need to try it to see...
This assumes contiguous chunks, of course. If you need to skip bits of the file, you can do that from outside the method. Also, if you're writing very small files, you may want to optimise for that situation too - the easiest way to do that would probably be to introduce a [`BufferedStream`](http://msdn.microsoft.com/en-us/library/system.io.bufferedstream.aspx) wrapping the input stream. | The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:
<http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/> | How to write super-fast file-streaming code in C#? | [
"",
"c#",
"performance",
"streaming",
"cpu",
"utilization",
""
] |
I want to measure the performance and scalability of my DB application. I am looking for a tool that would allow me to run many SQL statements against my DB, taking the DB and script (SQL) file as arguments (+necessary details, e.g. host name, port, login...).
Ideally it should let me control parameters such as number of simulated clients, duration of test, randomize variables or select from a list (e.g. SELECT FROM ... WHERE value = @var, where var is read from command line or randomized per execution). I would like to test results to be saved as CSV or XML file that I can analyze and plot them. And of course in terms of pricing I prefer "free" or "demo" :-)
Surprisingly (for me at least) while there are dozens of such tools for web application load testing, I couldn't find any for DB testing!? The ones I did see, such as pgbench, use a built-in DB based on some TPC scenario, so they help test the DBMS configuration and H/W but I cannot test MY DB! Any suggestions?
Specifically I use Postgres 8.3 on Linux, though I could use any DB-generic tool that meets these requirements. The H/W has 32GB of RAM while the size of the main tables and indexes is ~120GB. Hence there can be a 1:10 response time ratio between cold vs warm cache runs (I/O vs RAM). Realistically I expect requests to be spread evenly, so it's important for me to test queries against different pieces of the DB.
Feel free to also contact me via email.
Thanks!
-- Shaul Dar (info@shauldar.com) | [JMeter](http://jakarta.apache.org/jmeter/index.html) from Apache can handle different server types. I use it for load tests against web applications, others in the team use it for DB calls. It can be configured in many ways to get the load you need. It can be run in console mode and even be clustered using different clients to minimize client overhead ( and so falsifying the results).
It's a java application and a bit complex at first sight. But still we love it. :-) | [k6.io](https://k6.io/) can stress test a few relational databases with the [xk6-sql extension](https://github.com/imiric/xk6-sql).
For reference, a test script could be something like:
```
import sql from 'k6/x/sql';
const db = sql.open("sqlite3", "./test.db");
export function setup() {
db.exec(`CREATE TABLE IF NOT EXISTS keyvalues (
id integer PRIMARY KEY AUTOINCREMENT,
key varchar NOT NULL,
value varchar);`);
}
export function teardown() {
db.close();
}
export default function () {
db.exec("INSERT INTO keyvalues (key, value) VALUES('plugin-name', 'k6-plugin-sql');");
let results = sql.query(db, "SELECT * FROM keyvalues;");
for (const row of results) {
console.log(`key: ${row.key}, value: ${row.value}`);
}
}
```
Read more on this [short tutorial](https://k6.io/blog/load-testing-sql-databases-with-k6/). | DB (SQL) automated stress/load tools? | [
"",
"sql",
"database",
"testing",
"load",
"stress",
""
] |
I got the above error in my app. Here is the original code
```
public string GetCustomerNumber(Guid id)
{
string accountNumber =
(string)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidmyApp,
CommandType.StoredProcedure,
"GetCustomerNumber",
new SqlParameter("@id", id));
return accountNumber.ToString();
}
```
I replaced with
```
public string GetCustomerNumber(Guid id)
{
object accountNumber =
(object)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidCRM,
CommandType.StoredProcedure,
"spx_GetCustomerNumber",
new SqlParameter("@id", id));
if (accountNumber is System.DBNull)
{
return string.Empty;
}
else
{
return accountNumber.ToString();
}
}
```
Is there a better way around this? | A shorter form can be used:
```
return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()
```
EDIT: Haven't paid attention to `ExecuteScalar`. It does really return null if the field is absent in the return result. So use instead:
```
return (accountNumber == null) ? string.Empty : accountNumber.ToString()
``` | With a simple generic function you can make this very easy. Just do this:
```
return ConvertFromDBVal<string>(accountNumber);
```
using the function:
```
public static T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value)
{
return default(T); // returns the default value for the type
}
else
{
return (T)obj;
}
}
``` | Unable to cast object of type 'System.DBNull' to type 'System.String` | [
"",
"c#",
"asp.net",
"database",
"null",
""
] |
I was once asked by a current employee how I would develop a frequency-sorted list of the ten thousand most-used words in the English language. Suggest a solution in the language of your choosing, though I prefer C#.
Please provide not only an implementation, but also an explanation.
Thanks | ```
IEnumerable<string> inputList; // input words.
var mostFrequentlyUsed = inputList.GroupBy(word => word)
.Select(wordGroup => new { Word = wordGroup.Key, Frequency = wordGroup.Count() })
.OrderByDescending(word => word.Frequency);
```
Explanation: I don't really know if it requires further explanation but I'll try. `inputList` is an array or any other collection providing source words. `GroupBy` function will group the input collection by some similar property (which is, in my code the object itself, as noted by the lambda `word => word`). The output (which is a set of groups by a specified key, the word) will be transformed to an object with `Word` and `Frequency` properties and sorted by `Frequency` property in descending order. You could use `.Take(10000)` to take the first 10000. The whole thing can be easily parallelized by `.AsParallel()` provided by PLINQ. The query operator syntax might look clearer:
```
var mostFrequentlyUsed =
(from word in inputList
group word by word into wordGroup
select new { Word = wordGroup.Key, Frequency = wordGroup.Count() })
.OrderByDescending(word => word.Frequency).Take(10000);
``` | As a first cut, absent further definition of the problem (just what do you mean by the most-used words in English?) -- I'd buy [Google's n-gram data](http://googleresearch.blogspot.com/2006/08/all-our-n-gram-are-belong-to-you.html), intersect the 1-grams with an English dictionary, and pipe that to `sort -rn -k 2 | head -10000`. | How would you develop a frequency-sorted list of the ten thousand most-used words in the English language? | [
"",
"c#",
"algorithm",
""
] |
Hey everyone, I'm new to persistence / hibernate and I need your help.
Here's the situation. I have a table that contains some stuff. Let's call them Persons.
I'd like to get all the entries from the database that are in that table.
I have a Person class that is a simple POJO with a property for each column in the table (name, age,..)
Here's what I have :
```
Query lQuery = myEntityManager.createQuery("from Person")
List<Person> personList = lQuery.getResultList();
```
However, I get a warning saying that this is an unchecked conversion from `List` to `List<Person>`
I thought that simply changing the code to
```
Query lQuery = myEntityManager.createQuery("from Person")
List<Person> personList = (List<Person>)lQuery.getResultList();
```
would work.. but it doesn't.
Is there a way to do this ? Does persistence allow me to set the return type of the query ? (Through generics maybe ? ) | As a newcomer to JPA was taking this as the definitive answer but then I found a better one via this question: [Why in JPA EntityManager queries throw NoResultException but find does not?](https://stackoverflow.com/questions/1579560/why-in-jpa-entitymanager-queries-throw-noresultexception-but-find-does-not)
Its as simple as as using TypedQuery instead of Query e.g.:
```
TypedQuery<Person> lQuery = myEntityManager.createQuery("from Person", Person.class);
List<Person> personList = lQuery.getResultList();
``` | **Note: This answer is outdated as of JPA 2.0, which allows you to specify the expected type. See [this answer](https://stackoverflow.com/questions/957394/java-persistence-cast-to-something-the-result-of-query-getresultlist#12157248).**
---
Suppressing the warning with
```
@SuppressWarnings("unchecked")
List<MyType> result = (List<MyType>) query.getResultList();
```
is the only solution to this problem I have ever seen. The suppression is ugly, but you can trust JPA to return the right type of object, so there is no need to check manually.
If you use polymorphisms and don't know the exact result type, the use of Generics with a bounded `Class` parameter is also a common pattern:
```
public List<T extends MyBaseType> findMyType(Class<T> type) {
@SuppressWarnings("unchecked")
List<T> result = (List<T>) this.entityManager.createQuery(
"FROM " + type.getName())
.getResultList();
return result;
}
``` | Java Persistence: Cast to something the result of Query.getResultList()? | [
"",
"java",
"hibernate",
"casting",
"persistence",
""
] |
I've got some code I'm maintaining that has a good deal of machine generated comments and machine generated regions. (or created by a particularly misled developer)
These are comments exclusively repeating the method metadata and space expansions of pascal cased names:
```
#region methods
/// <summary>
/// Implementation of a public method foo bar, returning a void
/// </summary>
/// <param name="value">A string parameter named value input</param>
public void fooBar(string valueInput)
{
}
#endregion
```
Is there a plug in or feature of Resharper for stripping out the comments and #region tags in bulk? | Why not use the regex find & replace in Visual Studio?
For triple slash comments:
```
///.*
```
For region tags:
```
[#]region.*
[#]endregion
``` | These parts were likely hand-typed:
> Implementation of a public method foo bar, returning a void
and
> A string parameter named value input
If this is in a class library project, I wouldn't get rid of the xml comments - they are what will show up in the intellisense prompts for those items. Removing them could make other developers very mad at you; for all the text here isn't very good, the default prompts are cryptic and even worse. | How to strip out robo-comments and #region from C#? | [
"",
"c#",
"visual-studio",
"comments",
"resharper",
"visual-studio-addins",
""
] |
What SQL would I need to use to list all the stored procedures on an Oracle database?
If possible I'd like two queries:
1. list all stored procedures by name
2. list the code of a stored procedure, given a name | The `DBA_OBJECTS` view will list the procedures (as well as almost any other object):
```
SELECT owner, object_name
FROM dba_objects
WHERE object_type = 'PROCEDURE'
```
The `DBA_SOURCE` view will list the lines of source code for a procedure in question:
```
SELECT line, text
FROM dba_source
WHERE owner = ?
AND name = ?
AND type = 'PROCEDURE'
ORDER BY line
```
**Note:** Depending on your privileges, you may not be able to query the `DBA_OBJECTS` and `DBA_SOURCE` views. In this case, you can use `ALL_OBJECTS` and `ALL_SOURCE` instead. The `DBA_` views contain **all** objects in the database, whereas the `ALL_` views contain only those objects that you may access. | Here is a simpler SQL `SELECT * FROM User_Procedures;` | What SQL would I need to use to list all the stored procedures on an Oracle database? | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
I have two lists of two different kinds of objects representing data rows from two sql queries. The first list contains data, and the second contains more detailed data. So as an example:
```
List1: List2:
1 Alice 1 15
2 Bob 1 19
3 Carol 2 5
4 Dave 2 7
2 20
4 16
```
I want to insert rows into List2 so that everyone in List1 has at least one row in List2. So when no rows exist in List2 for a certain person, I want to insert a single one with a default value. In the example case I would have to insert one row for Carol, so I would end up with:
```
List1: List2:
1 Alice 1 15
2 Bob 1 19
3 Carol 2 5
4 Dave 2 7
2 20
3 0
4 16
```
Does anyone have a clever, clean and efficient way of doing this?
I know that to join these tables together into one I would have to use an Outer Join, for example like in this [Outer Join Sample](http://www.hookedonlinq.com/OuterJoinSample.ashx). But I don't want a new result set. I just want those missing rows to be inserted into List2.
***Note:*** Yes, I know the question\title is kind of... blah... but I don't know how to formulate it better. Someone please fix it if you can.
***Note 2:*** I can not use SQL. I can not insert those rows in the original table. I am reporting on data, which means I do not touch any of the data. I just read it out. The data is to be used in a master-detail report, and my issue is that when no details exist for a certain master row, then you end up with just an empty space. Which is not good. So I want to insert rows with sensible info so that the user can see that there was nothing to show here. | Assuming your lists are sorted by the *Key* value like in your example (in this case an integer), something like this should work:
```
int i = 0;
foreach (var item in List1)
{
// Skip any items in List2 that don't exist in List1
// (not sure this is needed in your case), or that we've
// already passed in List1
while (List2[i].Key < item.Key)
i++;
if (List2[i].Key > item.Key)
{
// Create new item in List2
List2.Add(new List2Item(item.Key, 0));
}
}
// TODO: resort List2
```
Depending on how many items you expect to be missing, you might want to *Insert* into List2 instead, eliminating the need for the resorting. If you expect a lot of items to be missing however, this method will be faster. Alternatively, you could use a linked list for List2.
Note that this will fail if there are duplicate Key entries in List1. You'd need to check for that seperately to prevent multiple new items from being created in List2. | ```
var lst1 = new List<int>() { 1, 2, 3, 4 };
var lst2 = new List<int>() { 1, 1, 2, 2, 2, 4 };
lst2.AddRange(lst1.Except(lst2));
``` | C#: Creating objects that does not exist in a different list | [
"",
"c#",
"linq",
"list",
""
] |
Imagine the following XML document:
```
<root>
<person_data>
<person>
<name>John</name>
<age>35</age>
</person>
<person>
<name>Jim</name>
<age>50</age>
</person>
</person_data>
<locations>
<location>
<name>John</name>
<country>USA</country>
</location>
<location>
<name>Jim</name>
<country>Japan</country>
</location>
</locations>
</root>
```
I then select the person node for Jim:
```
XmlNode personNode = doc.SelectSingleNode("//person[name = 'Jim']");
```
And now from this node with a single XPath select I would like to retrieve Jim's location node. Something like:
```
XmlNode locationNode = personNode.SelectSingleNode("//location[name = {reference to personNode}/name]");
```
Since I am selecting based on the personNode it would be handy if I could reference it in the select. Is this possible?.. is the connection there?
Sure I could put in a few extra lines of code and put the name into a variable and use this in the XPath string but that is not what I am asking. | This is not very efficient, but it should work. The larger the file gets, the slower will this be.
```
string xpath = "//location[name = //person[name='Jim']/name]";
XmlNode locationNode = doc.SelectSingleNode(xpath);
```
Here is why this is inefficient:
* The "`//`" shorthand causes a document-wide scan of all nodes.
* The "`[]`" predicate runs in a loop, once for each `<person>` matched by "`//person`".
* The second "`//`" causes a causes a document-wide scan again, this time once for each `<person>`.
This means you get quadratic O(n²) worst-case performance, which is bad. If there are n `<person>`s and n `<location>`s in your document, n x n document wide scans happen. All out of one innocent looking XPath expression.
I'd recommend against that approach. A two-step selection (first, find the person, then the location) will perform better. | You are not selecting the `location` node based on the `person` node, rather you are selecting it based on the *value* of the node. The value is just a string and in this case, it can be used to formulate a predicate condition that selects the `location` node based on the value within ("Jim"). | Relative XPath node selection with C# XmlDocument | [
"",
"c#",
"xpath",
"xmldocument",
""
] |
Example:
```
CREATE TABLE ErrorNumber
(
ErrorNumber int,
ErrorText varchar(255),
)
```
This can result in queries that look like:
```
SELECT ErrorNumber FROM ErrorNumber WHERE ErrorNumber=10
``` | I'm assuming that ErrorNumber as a column in the table is a primary key? In this case you could name the table column ErrorNumberID.
I don't know about it being a poor coding practice, but I can't imagine it is doing anything for readability. The example you provided is great at showing how confusing the queries can end up being.
The other thing I'm not sure of is if this (column names being the same as table names) would cause an error? I'm sure it varies from vendor to vendor. | ```
CREATE TABLE Errors (
Number int,
Description varchar(255)
)
```
I feel the above is a better naming scheme because:
* The table name now represents what it
is.
* The columns do not need the word
"Error" in them because of the table
they're in. | Is it poor coding practice to have a SQL table that contains a column with the same name? | [
"",
"sql",
"coding-style",
"conventions",
"readability",
""
] |
Do you know if there's a way?
I've used [this library](http://www.codeproject.com/KB/IP/NetPopMimeClient.aspx%20) to access a pop3 server, but it doesn't work with an exchange server.
Do you know of any other library or piece of code that'll show me how to do it?
I cannot change any settings on the server. | Depends on the Exchange version. [WebDAV](http://msdn.microsoft.com/en-us/library/aa143161(EXCHG.65).aspx) works with 2000 thru 2007, but [Web Services](http://msdn.microsoft.com/en-us/library/aa565934.aspx) requires 2007+.
Those are probably the easiest to get working. CDO is another option, but [it's not supported from C#](http://blogs.msdn.com/mstehle/archive/2007/10/03/fyi-why-are-mapi-and-cdo-1-21-not-supported-in-managed-net-code.aspx) - so you'll have to go [out of proc](http://blogs.msdn.com/mstehle/archive/2007/07/27/howto-delete-search-folders-and-interop-with-cdo-1-21-from-managed-net-code.aspx).
Exchange also has an [OLEDB provider](http://msdn.microsoft.com/en-us/library/aa142634(EXCHG.65).aspx), but I've never used it - it is [supported from .NET](http://support.microsoft.com/?kbid=813349), however. | If you use Exchange 2007 and have web services enabled, this is pretty easy. I added a 2.0-style classic Web Reference to my VS2008 project, and I can get mail messages like this:
```
// exchange 2007 lets us use web services to check mailboxes.
using (ExchangeServiceBinding exchangeServer = new ExchangeServiceBinding())
{
ICredentials creds = new NetworkCredential("user","password");
exchangeServer.Credentials = creds;
exchangeServer.Url = "https://myexchangeserver.com/EWS/Exchange.asmx";
FindItemType findItemRequest = new FindItemType();
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
// define which item properties are returned in the response
ItemResponseShapeType itemProperties = new ItemResponseShapeType();
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
findItemRequest.ItemShape = itemProperties;
// identify which folder to search
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;
// add folders to request
findItemRequest.ParentFolderIds = folderIDArray;
// find the messages
FindItemResponseType findItemResponse = exchangeServer.FindItem(findItemRequest);
// read returned
FindItemResponseMessageType folder = (FindItemResponseMessageType)findItemResponse.ResponseMessages.Items[0];
ArrayOfRealItemsType folderContents = new ArrayOfRealItemsType();
folderContents = (ArrayOfRealItemsType)folder.RootFolder.Item;
ItemType[] items = folderContents.Items;
// if no messages were found, then return null -- we're done
if (items == null || items.Count() <= 0)
return null;
// FindItem never gets "all" the properties, so now that we've found them all, we need to get them all.
BaseItemIdType[] itemIds = new BaseItemIdType[items.Count()];
for (int i = 0; i < items.Count(); i++)
itemIds[i] = items[i].ItemId;
GetItemType getItemType = new GetItemType();
getItemType.ItemIds = itemIds;
getItemType.ItemShape = new ItemResponseShapeType();
getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
getItemType.ItemShape.BodyType = BodyTypeResponseType.Text;
getItemType.ItemShape.BodyTypeSpecified = true;
GetItemResponseType getItemResponse = exchangeServer.GetItem(getItemType);
ItemType[] messages = new ItemType[getItemResponse.ResponseMessages.Items.Count()];
for (int j = 0; j < messages.Count(); j++)
messages[j] = ((ItemInfoResponseMessageType)getItemResponse.ResponseMessages.Items[j]).Items.Items[0];
return messages;
}
```
The "messages" variable will be an array of ItemType objects returned from exchange that have all the properties you'd expect for a mail message (Body, Attachments, etc.). I hope this helps! | Access exchange e-mail in C# | [
"",
"c#",
".net",
"exchange-server",
""
] |
I am trying to make a Dictionary lookup table in C#. I need to resolve a 3-tuple of values to one string. I tried using arrays as keys, but that did not work, and I don't know what else to do. At this point I am considering making a Dictionary of Dictionaries of Dictionaries, but that would probably not be very pretty to look at, though it is how I would do it in javascript. | If you are on .NET 4.0 use a Tuple:
```
lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
```
If not you can define a `Tuple` and use that as the key. The Tuple needs to override `GetHashCode`, `Equals` and `IEquatable`:
```
struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>>
{
readonly T first;
readonly U second;
readonly W third;
public Tuple(T first, U second, W third)
{
this.first = first;
this.second = second;
this.third = third;
}
public T First { get { return first; } }
public U Second { get { return second; } }
public W Third { get { return third; } }
public override int GetHashCode()
{
return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Equals((Tuple<T, U, W>)obj);
}
public bool Equals(Tuple<T, U, W> other)
{
return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third);
}
}
``` | If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (`Tuple<T1, …>`) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the `IEquatable<T>` interface needed for the dictionary.
```
var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();
``` | Tuples (or arrays) as Dictionary keys in C# | [
"",
"c#",
"dictionary",
"hashtable",
"tuples",
""
] |
I have a report that use a multi-value parameter into a "in" statement in a query. For example (with @areas as the multi-value parameter):
```
select * from regions where areas in (@areas)
```
It works perfectly but now I need to send the same parameter to a function in the SQL Server 2005 database:
```
select name, myFunction(@areas) from regions where areas in (@areas)
```
The @areas parameter in the function are going to be used in a "in" statement as well. I tried to receive it with a varchar parameter but this causes an error. When I use the SQL Profiler, I see that the parameter is passed in this format:
```
N''1'',N''2'',N''3''
```
The specific questions here are, what data type the function parameter @areas must be? And how can I use that parameter into a "in" statement in the function?
Thanks | Generally if you are going to be passing in a list of some type as a parameter, you are going to want to pass it in as a varchar of a large enough length to handle the entirety of it. You could also pass it in as an XML parameter, but I've always preferred using the varchar route and parsing it that way. | For sql 2008 there are table valued params as mentioned. Otherwise your only options are to pass it as a packed value (either comma separated variety in varchar or xml), or else populate a temp table and have the function read from the temp table. If you are calling multiple functions with the same large input, the temp table is likely the best route so you don't have to keep parsing it. If the native input is xml (i.e. you have some input from an external partner like facebook) then it's usually best to keep it as xml. If it is just a modest list of ints then a list of comma separated values isn't bad. | How to send a Reporting Services multi-value parameter to a SQL Server function? | [
"",
"sql",
"sql-server",
"reporting-services",
""
] |
I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's `locale` module provides a `strcoll` function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it.
The problem is that I can't seem to actually set the locale. The [documentation](http://docs.python.org/library/locale.html) for the `locale` module gives this example:
```
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
```
When I run that, I get this:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\Lib\locale.py", line 494, in setlocale
locale.Error: unsupported locale setting
```
What am I doing wrong? | It seems you're using Windows. The locale strings are different there. Take a more precise look at the doc:
```
locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform
```
On Windows, I think it would be something like:
```
locale.setlocale(locale.LC_ALL, 'deu_deu')
```
MSDN has a list of [language strings](https://learn.microsoft.com/en-us/cpp/c-runtime-library/language-strings) and of [country/region strings](https://learn.microsoft.com/en-us/cpp/c-runtime-library/country-region-strings) | You should **not pass an explicit locale** to setlocale, it is wrong. Let it find out from the environment. You have to pass it an empty string
```
import locale
locale.setlocale(locale.LC_ALL, '')
``` | What is the correct way to set Python's locale on Windows? | [
"",
"python",
"windows",
"localization",
"internationalization",
""
] |
I have an editable `JComboBox` which contains a list of single letter values. Because of that the combobox is very small.
Every letter has a special meaning which sometimes isn't clear to the user in case of rarely used letters. Because of that I've created a custom `ListCellRenderer` which shows the meaning of each letter in the dropdown list.
Unfortunately this explanation doesn't fit into the dropdown because it is to small, because it has the same width as the combobox.
Is there any way to make the dropdown list wider than the combobox?
This is what I want to achieve:
```
---------------------
| Small JCombobox | V |
--------------------------------------------
| "Long item 1" |
--------------------------------------------
| "Long item 2" |
--------------------------------------------
| "Long item 3" |
--------------------------------------------
```
I cannot change the width of the combobox because the application is a recreation of an old legacy application where some things have to be exactly as they were before. (In this case the combobox has to keep it's small size at all costs) | I believe the only way to do this with the public API is to write a custom UI (there are [two](https://bugs.java.com/bugdatabase/view_bug?bug_id=4880218) [bugs](https://bugs.java.com/bugdatabase/view_bug;jsessionid=b0c3d5c7ecf91ffffffffc9ef87cbec542a2?bug_id=4618607) dealing with this).
If you just want something quick-and-dirty, I found this way to use implementation details to do it ([here](http://forums.java.net/jive/message.jspa?messageID=61267)):
```
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
JComboBox box = (JComboBox) e.getSource();
Object comp = box.getUI().getAccessibleChild(box, 0);
if (!(comp instanceof JPopupMenu)) return;
JComponent scrollPane = (JComponent) ((JPopupMenu) comp).getComponent(0);
Dimension size = new Dimension();
size.width = box.getPreferredSize().width;
size.height = scrollPane.getPreferredSize().height;
scrollPane.setPreferredSize(size);
// following line for Tiger
// scrollPane.setMaximumSize(size);
}
```
Put this in a [`PopupMenuListener`](http://java.sun.com/javase/6/docs/api/javax/swing/event/PopupMenuListener.html) and it *might* work for you.
Or you could use the code from the [first linked bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=4880218):
```
class StyledComboBoxUI extends BasicComboBoxUI {
protected ComboPopup createPopup() {
BasicComboPopup popup = new BasicComboPopup(comboBox) {
@Override
protected Rectangle computePopupBounds(int px,int py,int pw,int ph) {
return super.computePopupBounds(
px,py,Math.max(comboBox.getPreferredSize().width,pw),ph
);
}
};
popup.getAccessibleContext().setAccessibleParent(comboBox);
return popup;
}
}
class StyledComboBox extends JComboBox {
public StyledComboBox() {
setUI(new StyledComboBoxUI());
}
}
``` | Here is a great solution by Santhosh Kumar, without the need to mess with UI's and other nasty stuff like that!
<http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough>
```
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
// got this workaround from the following bug:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4618607
public class WideComboBox extends JComboBox{
public WideComboBox() {
}
public WideComboBox(final Object items[]){
super(items);
}
public WideComboBox(Vector items) {
super(items);
}
public WideComboBox(ComboBoxModel aModel) {
super(aModel);
}
private boolean layingOut = false;
public void doLayout(){
try{
layingOut = true;
super.doLayout();
}finally{
layingOut = false;
}
}
public Dimension getSize(){
Dimension dim = super.getSize();
if(!layingOut)
dim.width = Math.max(dim.width, getPreferredSize().width);
return dim;
}
}
``` | How can I change the width of a JComboBox dropdown list? | [
"",
"java",
"swing",
"combobox",
""
] |
I'm creating my own UserControl and I have two different DataTemplates under the **UserControl.Resources** section in my XAML. I want to choose between these two datatemplates depending on the value of a property on objects displayed in a listview. I do this by creating a custom **DataTemplateSelector** class and overriding the **SelectTemplate** method which is supposed to return the DataTemplate I wish to use. However, I have no idea how to "find" my datatemplates that are located in the UserControls resource section, all the examples I've seen only fetches datatemplates from **Window.Resources**. In this example they fetch the current **MainWindow** and then use **FindResource** to find the **DataTemplate**, how do I fetch my **UserControl** in a similar manner?:
```
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
if (item != null && item is AuctionItem)
{
AuctionItem auctionItem = item as AuctionItem;
Window window = Application.Current.MainWindow;
switch (auctionItem.SpecialFeatures)
{
case SpecialFeatures.None:
return
window.FindResource("AuctionItem_None")
as DataTemplate;
case SpecialFeatures.Color:
return
window.FindResource("AuctionItem_Color")
as DataTemplate;
}
}
return null;
}
```
The example above is from here: [ItemsControl.ItemTemplateSelector Property](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplateselector.aspx) | I usually instantiate my DataTemplateSelector from code behind with the UserControl as parameter in the constructor of the DataTemplateSelector, like so:
```
public class MyUserControl : UserControl
{
public MyUserControl()
{
Resources["MyDataTemplateSelector"] = new MyDataTemplateSelector(this);
InitializeComponent();
}
}
public class MyDataTemplateSelector : DataTemplateSelector
{
private MyUserControl parent;
public MyDataTemplateSelector(MyUserControl parent)
{
this.parent = parent;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
parent.DoStuff();
}
}
```
Not the most prettiest girl in town, but it get the job done ;)
Hope this helps! | Try this:
```
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null && item is AuctionItem)
{
AuctionItem auctionItem = item as AuctionItem;
switch (auctionItem.SpecialFeatures)
{
case SpecialFeatures.None:
return
((FrameworkElement)container).FindResource("AuctionItem_None")
as DataTemplate;
case SpecialFeatures.Color:
return
((FrameworkElement)container).FindResource("AuctionItem_Color")
as DataTemplate;
}
}
return null;
}
``` | How to find a resource in a UserControl from a DataTemplateSelector class in WPF? | [
"",
"c#",
".net",
"wpf",
"resources",
"wpf-controls",
""
] |
I am implementing the bubble sort algorithm and I want it to be able to accept both `Integer` and `String` parameters. I cast all input as Strings and use the `compareTo` method to compare the integers casted as strings to the strings. I am getting an incorrect answer when using `compareTo` to compare the casted integers. What am I doing wrong? | Integer.compareTo sorts numbers numerically. This is what you want.
String.compareTo sorts strings lexicographically; that is, in alphabetical order.
I remember in Windows 3.1 that the folder of photos from my digital camera was ordered like this: PHOTO1, PHOTO10, PHOTO100, PHOTO2, PHOTO20, PHOTO3, ... and so on. Windows XP sorts them more like you would expect: PHOTO1, PHOTO2, PHOTO3, ... etc. This is because it has special sorting rules for strings that represent numbers.
In lexicographical ordering, each character in one string A is compared to the corresponding character in another string B. For each corresponding character in the two strings:
* If A's current character is lexicographically less than (comes before in the alphabet) B's character, then A comes before B.
* If B's character is less than A's character, then B comes before A.
* If the two characters are the same, then we don't know yet. The next one is checked.
* If there are no more characters left in one of the strings, then the shorter one comes before the longer one.
* If there are no more character left in both strings, then they are the same string.
The fourth point here is why you are getting incorrect answers, assuming Eddie's analysis of your problem is correct.
Consider the strings "10" and "2". Lexicographical ordering would look at the first characters of each, '1' and '2' respectively. The character '1' comes before '2' in the character set that Java uses, so it sorts "10" before "2", in the same way that "bare" is sorted before "hare" because 'b' comes before 'h'.
I suggest you cast your strings to integers before sorting. Use Integer.parseString to do this. | are you sure you want to mix Integers and Strings in the same list? if so, are Integers less or greater than Strings? what is this particular sorting criteria?
you can also make a bubble sort method which sorts distinct lists of Integer and lists of String (and lists of any other class). to do so, you can use Generics. for example:
```
public static <T> void bubbleSort(List<T> elements, Comparator<T> comparator) {
// your implementation
}
```
you use the `comparator` parameter to compare the `elements`, that's why they can be Integers or Strings (not both at the same time). the compiler won't let you [without any warning] pass a list of objects of one class and a comparator of a different class, so the comparison will always work. | Java compareTo for String and Integer arguments | [
"",
"java",
"compareto",
""
] |
I want to group rows with SQL, my result set is following
name size date
data1 123 12/03/2009
data1 124 15/09/2009
data2 333 02/09/2010
data2 323 02/11/2010
data2 673 02/09/2014
data2 444 05/01/2010
I want to group result set like this one:
data1
123 12/03/2009
124 15/09/2009
data2
333 02/09/2010
323 02/11/2010
673 02/09/2014
444 05/01/2010
is it possible to do this with pure SQL?
Cheers. | `GROUP BY WITH ROLLUP` (you're not really grouping - so you would actaully `GROUP BY` every column)
<http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html>
<http://chiragrdarji.wordpress.com/2008/09/09/group-by-cube-rollup-and-sql-server-2005/>
<http://databases.about.com/od/sql/l/aacuberollup.htm>
<http://www.adp-gmbh.ch/ora/sql/group_by/group_by_rollup.html>
<http://msdn.microsoft.com/en-us/library/bb522495.aspx>
Based on Lieven's code:
```
DECLARE @Table TABLE (
name varchar(32)
,Size integer
,Date datetime
)
INSERT INTO @Table
VALUES ('data1', 123, GETDATE())
INSERT INTO @Table
VALUES ('data1', 124, GETDATE())
INSERT INTO @Table
VALUES ('data2', 333, GETDATE())
INSERT INTO @Table
VALUES ('data2', 323, GETDATE())
INSERT INTO @Table
VALUES ('data2', 673, GETDATE())
INSERT INTO @Table
VALUES ('data2', 444, GETDATE())
SELECT *
FROM (
SELECT *
FROM @Table
GROUP BY NAME
,size
,date
WITH ROLLUP
) AS X
WHERE NAME IS NOT NULL
AND (
(
Size IS NOT NULL
AND Date IS NOT NULL
)
OR (
Size IS NULL
AND date IS NULL
)
)
ORDER BY NAME
,size
,date
``` | Michael Todd is definitly right when he says this should be done on the client side but for the fun of it, this is one option
```
DECLARE @Table TABLE (name VARCHAR(32), Size INTEGER, Date DATETIME)
INSERT INTO @Table VALUES ('data1', 123, getdate())
INSERT INTO @Table VALUES ('data1', 124, getdate())
INSERT INTO @Table VALUES ('data2', 333, getdate())
INSERT INTO @Table VALUES ('data2', 323, getdate())
INSERT INTO @Table VALUES ('data2', 673, getdate())
INSERT INTO @Table VALUES ('data2', 444, getdate())
INSERT INTO @Table
SELECT DISTINCT name, NULL, NULL
FROM @Table
SELECT
CASE WHEN Size IS NULL THEN Name ELSE NULL END
, Size
, Date
FROM @Table
ORDER BY Name, Size
``` | Sql group rows with same value, and put that value into header? | [
"",
"sql",
""
] |
I have a string that may have whitespace characters around it and I want to check to see whether it is essentially empty.
There are quite a few ways to do this:
```
1 if (myString.Trim().Length == 0)
2 if (myString.Trim() == "")
3 if (myString.Trim().Equals(""))
4 if (myString.Trim() == String.Empty)
5 if (myString.Trim().Equals(String.Empty))
```
I'm aware that this would usually be a clear case of premature optimization, but I'm curious and there's a chance that this will be done enough to have a performance impact.
**So which of these is the most efficient method?**
**Are there any better methods I haven't thought of?**
---
**Edit:** Notes for visitors to this question:
1. There have been some amazingly detailed investigations into this question - particularly from Andy and Jon Skeet.
2. If you've stumbled across the question while searching for something, it's well worth your while reading at least Andy's and Jon's posts in their entirety.
It seems that there are a few very efficient methods and the *most* efficient depends on the contents of the strings I need to deal with.
If I can't predict the strings (which I can't in my case), Jon's `IsEmptyOrWhiteSpace` methods seem to be faster generally.
Thanks all for your input. I'm going to select Andy's answer as the "correct" one simply because he deserves the reputation boost for the effort he put in and Jon has like eleventy-billion reputation already. | **Edit: New tests:**
```
Test orders:
x. Test name
Ticks: xxxxx //Empty String
Ticks: xxxxx //two space
Ticks: xxxxx //single letter
Ticks: xxxxx //single letter with space
Ticks: xxxxx //long string
Ticks: xxxxx //long string with space
1. if (myString.Trim().Length == 0)
ticks: 4121800
ticks: 7523992
ticks: 17655496
ticks: 29312608
ticks: 17302880
ticks: 38160224
2. if (myString.Trim() == "")
ticks: 4862312
ticks: 8436560
ticks: 21833776
ticks: 32822200
ticks: 21655224
ticks: 42358016
3. if (myString.Trim().Equals(""))
ticks: 5358744
ticks: 9336728
ticks: 18807512
ticks: 30340392
ticks: 18598608
ticks: 39978008
4. if (myString.Trim() == String.Empty)
ticks: 4848368
ticks: 8306312
ticks: 21552736
ticks: 32081168
ticks: 21486048
ticks: 41667608
5. if (myString.Trim().Equals(String.Empty))
ticks: 5372720
ticks: 9263696
ticks: 18677728
ticks: 29634320
ticks: 18551904
ticks: 40183768
6. if (IsEmptyOrWhitespace(myString)) //See John Skeet's Post for algorithm
ticks: 6597776
ticks: 9988304
ticks: 7855664
ticks: 7826296
ticks: 7885200
ticks: 7872776
7. is (string.IsNullOrEmpty(myString.Trim()) //Cloud's suggestion
ticks: 4302232
ticks: 10200344
ticks: 18425416
ticks: 29490544
ticks: 17800136
ticks: 38161368
```
And the code used:
```
public void Main()
{
string res = string.Empty;
for (int j = 0; j <= 5; j++) {
string myString = "";
switch (j) {
case 0:
myString = "";
break;
case 1:
myString = " ";
break;
case 2:
myString = "x";
break;
case 3:
myString = "x ";
break;
case 4:
myString = "this is a long string for testing triming empty things.";
break;
case 5:
myString = "this is a long string for testing triming empty things. ";
break;
}
bool result = false;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i <= 100000; i++) {
result = myString.Trim().Length == 0;
}
sw.Stop();
res += "ticks: " + sw.ElapsedTicks + Environment.NewLine;
}
Console.ReadKey(); //break point here to get the results
}
``` | (EDIT: See bottom of post for benchmarks on different micro-optimizations of the method)
Don't trim it - that might create a new string which you don't actually need. Instead, look through the string for any characters that *aren't* whitespace (for whatever definition you want). For example:
```
public static bool IsEmptyOrWhitespace(string text)
{
// Avoid creating iterator for trivial case
if (text.Length == 0)
{
return true;
}
foreach (char c in text)
{
// Could use Char.IsWhiteSpace(c) instead
if (c==' ' || c=='\t' || c=='\r' || c=='\n')
{
continue;
}
return false;
}
return true;
}
```
You might also consider what you want the method to do if `text` is `null`.
Possible further micro-optimizations to experiment with:
* Is `foreach` faster or slower than using a `for` loop like the one below? Note that with the `for` loop you can remove the "`if (text.Length==0)`" test at the start.
```
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
// ...
```
* Same as above, but hoisting the `Length` call. Note that this *isn't* good for normal arrays, but *might* be useful for strings. I haven't tested it.
```
int length = text.Length;
for (int i = 0; i < length; i++)
{
char c = text[i];
```
* In the body of the loop, is there any difference (in speed) between what we've got and:
```
if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
{
return false;
}
```
* Would a switch/case be faster?
```
switch (c)
{
case ' ': case '\r': case '\n': case '\t':
return false;
}
```
**Update on Trim behaviour**
I've just been looking into how `Trim` can be as efficient as this. It seems that `Trim` will only create a new string if it needs to. If it can return `this` or `""` it will:
```
using System;
class Test
{
static void Main()
{
CheckTrim(string.Copy(""));
CheckTrim(" ");
CheckTrim(" x ");
CheckTrim("xx");
}
static void CheckTrim(string text)
{
string trimmed = text.Trim();
Console.WriteLine ("Text: '{0}'", text);
Console.WriteLine ("Trimmed ref == text? {0}",
object.ReferenceEquals(text, trimmed));
Console.WriteLine ("Trimmed ref == \"\"? {0}",
object.ReferenceEquals("", trimmed));
Console.WriteLine();
}
}
```
This means it's really important that any benchmarks in this question should use a mixture of data:
* Empty string
* Whitespace
* Whitespace surrounding text
* Text without whitespace
Of course, the "real world" balance between these four is impossible to predict...
**Benchmarks**
I've run some benchmarks of the original suggestions vs mine, and mine appears to win in everything I throw at it, which surprises me given the results in other answers. However, I've also benchmarked the difference between `foreach`, `for` using `text.Length`, `for` using `text.Length` once and then reversing the iteration order, and `for` with a hoisted length.
Basically the `for` loop is very slightly faster, but hoisting the length check makes it slower than `foreach`. Reversing the `for` loop direction is very slightly slower than `foreach` too. I strongly suspect that the JIT is doing interesting things here, in terms of removing duplicate bounds checks etc.
Code: (see [my benchmarking blog entry](http://msmvps.com/blogs/jon_skeet/archive/2009/01/26/benchmarking-made-easy.aspx) for the framework this is written against)
```
using System;
using BenchmarkHelper;
public class TrimStrings
{
static void Main()
{
Test("");
Test(" ");
Test(" x ");
Test("x");
Test(new string('x', 1000));
Test(" " + new string('x', 1000) + " ");
Test(new string(' ', 1000));
}
static void Test(string text)
{
bool expectedResult = text.Trim().Length == 0;
string title = string.Format("Length={0}, result={1}", text.Length,
expectedResult);
var results = TestSuite.Create(title, text, expectedResult)
/* .Add(x => x.Trim().Length == 0, "Trim().Length == 0")
.Add(x => x.Trim() == "", "Trim() == \"\"")
.Add(x => x.Trim().Equals(""), "Trim().Equals(\"\")")
.Add(x => x.Trim() == string.Empty, "Trim() == string.Empty")
.Add(x => x.Trim().Equals(string.Empty), "Trim().Equals(string.Empty)")
*/
.Add(OriginalIsEmptyOrWhitespace)
.Add(IsEmptyOrWhitespaceForLoop)
.Add(IsEmptyOrWhitespaceForLoopReversed)
.Add(IsEmptyOrWhitespaceForLoopHoistedLength)
.RunTests()
.ScaleByBest(ScalingMode.VaryDuration);
results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
results.FindBest());
}
public static bool OriginalIsEmptyOrWhitespace(string text)
{
if (text.Length == 0)
{
return true;
}
foreach (char c in text)
{
if (c==' ' || c=='\t' || c=='\r' || c=='\n')
{
continue;
}
return false;
}
return true;
}
public static bool IsEmptyOrWhitespaceForLoop(string text)
{
for (int i=0; i < text.Length; i++)
{
char c = text[i];
if (c==' ' || c=='\t' || c=='\r' || c=='\n')
{
continue;
}
return false;
}
return true;
}
public static bool IsEmptyOrWhitespaceForLoopReversed(string text)
{
for (int i=text.Length-1; i >= 0; i--)
{
char c = text[i];
if (c==' ' || c=='\t' || c=='\r' || c=='\n')
{
continue;
}
return false;
}
return true;
}
public static bool IsEmptyOrWhitespaceForLoopHoistedLength(string text)
{
int length = text.Length;
for (int i=0; i < length; i++)
{
char c = text[i];
if (c==' ' || c=='\t' || c=='\r' || c=='\n')
{
continue;
}
return false;
}
return true;
}
}
```
Results:
```
============ Length=0, result=True ============
OriginalIsEmptyOrWhitespace 30.012 1.00
IsEmptyOrWhitespaceForLoop 30.802 1.03
IsEmptyOrWhitespaceForLoopReversed 32.944 1.10
IsEmptyOrWhitespaceForLoopHoistedLength 35.113 1.17
============ Length=1, result=True ============
OriginalIsEmptyOrWhitespace 31.150 1.04
IsEmptyOrWhitespaceForLoop 30.051 1.00
IsEmptyOrWhitespaceForLoopReversed 31.602 1.05
IsEmptyOrWhitespaceForLoopHoistedLength 33.383 1.11
============ Length=3, result=False ============
OriginalIsEmptyOrWhitespace 30.221 1.00
IsEmptyOrWhitespaceForLoop 30.131 1.00
IsEmptyOrWhitespaceForLoopReversed 34.502 1.15
IsEmptyOrWhitespaceForLoopHoistedLength 35.690 1.18
============ Length=1, result=False ============
OriginalIsEmptyOrWhitespace 31.626 1.05
IsEmptyOrWhitespaceForLoop 30.005 1.00
IsEmptyOrWhitespaceForLoopReversed 32.383 1.08
IsEmptyOrWhitespaceForLoopHoistedLength 33.666 1.12
============ Length=1000, result=False ============
OriginalIsEmptyOrWhitespace 30.177 1.00
IsEmptyOrWhitespaceForLoop 33.207 1.10
IsEmptyOrWhitespaceForLoopReversed 30.867 1.02
IsEmptyOrWhitespaceForLoopHoistedLength 31.837 1.06
============ Length=1002, result=False ============
OriginalIsEmptyOrWhitespace 30.217 1.01
IsEmptyOrWhitespaceForLoop 30.026 1.00
IsEmptyOrWhitespaceForLoopReversed 34.162 1.14
IsEmptyOrWhitespaceForLoopHoistedLength 34.860 1.16
============ Length=1000, result=True ============
OriginalIsEmptyOrWhitespace 30.303 1.01
IsEmptyOrWhitespaceForLoop 30.018 1.00
IsEmptyOrWhitespaceForLoopReversed 35.475 1.18
IsEmptyOrWhitespaceForLoopHoistedLength 40.927 1.36
``` | What's the most efficient way to determine whether an untrimmed string is empty in C#? | [
"",
"c#",
"performance",
"optimization",
"coding-style",
"string",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.