Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I am working with an order system that has two tables Order and OrderLine pretty standard stuff. I want to work out an order line number for the order lines with respect to the order e.g.
Orderid Orderlineid linenumber
1 1 1
2 2 1
2 3 2
3 4 1
4 5 1
4 6 2
The OrderLineId is an identity column. I don't want to store the line number as data in the database for two reasons. First there are already a great many existing orders and lines in the system and retrospectively adding the data is a headache I wish to avoid. Second if the user deletes a line then I would need to recalculate the line numbers for the whole order.
In SQL 2005 I can do this easy peasy using the ROW\_NUMBER function.
```
Select Orderid, OrderLineid, ROW_NUMBER()
OVER(PARTITION BY Orderid ORDER BY Orderlineid) as LineNumber
FROM OrderLine
```
Is there anyway I can do this in SQL 2000?
The closest I found was a ranking function (see below) but this counts orders not lines.
```
SELECT x.Ranking, x.OrderId
FROM (SELECT (SELECT COUNT( DISTINCT t1.Orderid) FROM orderline t1 WHERE z.Orderid >= t1.Orderid)AS Ranking, z.orderid
FROM orderline z ) x
ORDER BY x.Ranking
```
|
You can use something like this:
```
select
ol1.orderId,
ol1.orderLineId,
count(*) as lineNumber
from
orderLine ol1
inner join orderLine ol2
on ol1.orderId = ol2.orderId
and ol1.orderLineId >= ol2.orderLineId
group by
ol1.orderId,
ol1.orderLineId
```
|
IMHO, calculating it every time you need it may end up being more of a headache than it's worth. And while it may be a pain to update the historical line numbers and save it to the database, you'd only be doing that once... and then would just need to write code to automate it later.
To handle the deletes, you'd just need to add code into the existing delete procedure and have it recalculate the line numbers for it.
|
How do I Compute an Order Line Number in SQL 2000
|
[
"",
"sql",
""
] |
In `SQL Server`, I can do something like this:
```
UPDATE tbl1
SET col2 = tbl2.col2
FROM table1 tbl1
INNER JOIN table2 tbl2
ON tbl1.col1 = tbl2.col1
```
I haven't bothered to look whether this is part of any SQL standard or not, and I'm sure there are other ways to do it, but it is *astoundingly* useful.
Here's my problem. I need to do something similar *in SQL* (i.e, not a host language) with SQLITE3. Can it be done?
|
This works for sqlite:
```
UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)
```
|
Just to emphasize Geogory Higley's post:
I have had problems with `UPDATE tbl1 SET col2 = (SELECT col2 FROM tbl2 WHERE tbl2.col1 = tbl1.col1)` where it updates columns in tbl1 that do not exist in tbl2.
see cheetah post at <http://sqlite.phxsoftware.com/forums/p/1708/7238.aspx> which points to:
<http://www.mail-archive.com/sqlite-users@sqlite.org/msg27207.html>
The code is:
```
insert or replace into foo (id, name, extra)
select bar.id, bar.name, foo.extra
from bar
left join foo
on bar.id = foo.id;
```
and this seems to work correctly. There seem to be many posts at different sites that recommend the first approach so it is a bit confusing. I would suggest you test your output very carefully if you use this method which does seem faster and may work with matched tables.
|
Cross-table UPDATE in SQLITE3
|
[
"",
"sql",
"sqlite",
"sql-update",
""
] |
In `java.util.Calendar`, January is defined as month 0, not month 1. Is there any specific reason to that ?
I have seen many people getting confused about that...
|
It's just part of the horrendous mess which is the Java date/time API. Listing what's wrong with it would take a very long time (and I'm sure I don't know half of the problems). Admittedly working with dates and times is tricky, but aaargh anyway.
Do yourself a favour and use [Joda Time](http://joda-time.sourceforge.net/) instead, or possibly [JSR-310](http://sourceforge.net/apps/mediawiki/threeten/index.php?title=ThreeTen).
EDIT: As for the reasons why - as noted in other answers, it could well be due to old C APIs, or just a general feeling of starting everything from 0... except that days start with 1, of course. I doubt whether anyone outside the original implementation team could really state reasons - but again, I'd urge readers not to worry so much about *why* bad decisions were taken, as to look at the whole gamut of nastiness in `java.util.Calendar` and find something better.
One point which *is* in favour of using 0-based indexes is that it makes things like "arrays of names" easier:
```
// I "know" there are 12 months
String[] monthNames = new String[12]; // and populate...
String name = monthNames[calendar.get(Calendar.MONTH)];
```
Of course, this fails as soon as you get a calendar with 13 months... but at least the size specified is the number of months you expect.
This isn't a *good* reason, but it's *a* reason...
EDIT: As a comment sort of requests some ideas about what I think is wrong with Date/Calendar:
* Surprising bases (1900 as the year base in Date, admittedly for deprecated constructors; 0 as the month base in both)
* Mutability - using immutable types makes it *much* simpler to work with what are really effectively *values*
* An insufficient set of types: it's nice to have `Date` and `Calendar` as different things,
but the separation of "local" vs "zoned" values is missing, as is date/time vs date vs time
* An API which leads to ugly code with magic constants, instead of clearly named methods
* An API which is very hard to reason about - all the business about when things are recomputed etc
* The use of parameterless constructors to default to "now", which leads to hard-to-test code
* The `Date.toString()` implementation which always uses the system local time zone (that's confused many Stack Overflow users before now)
|
Because doing math with months is much easier.
1 month after December is January, but to figure this out normally you would have to take the month number and do math
```
12 + 1 = 13 // What month is 13?
```
I know! I can fix this quickly by using a modulus of 12.
```
(12 + 1) % 12 = 1
```
This works just fine for 11 months until November...
```
(11 + 1) % 12 = 0 // What month is 0?
```
You can make all of this work again by subtracting 1 before you add the month, then do your modulus and finally add 1 back again... aka work around an underlying problem.
```
((11 - 1 + 1) % 12) + 1 = 12 // Lots of magical numbers!
```
Now let's think about the problem with months 0 - 11.
```
(0 + 1) % 12 = 1 // February
(1 + 1) % 12 = 2 // March
(2 + 1) % 12 = 3 // April
(3 + 1) % 12 = 4 // May
(4 + 1) % 12 = 5 // June
(5 + 1) % 12 = 6 // July
(6 + 1) % 12 = 7 // August
(7 + 1) % 12 = 8 // September
(8 + 1) % 12 = 9 // October
(9 + 1) % 12 = 10 // November
(10 + 1) % 12 = 11 // December
(11 + 1) % 12 = 0 // January
```
All of the months work the same and a work around isn't necessary.
|
Why is January month 0 in Java Calendar?
|
[
"",
"java",
"calendar",
""
] |
I had a discussion with a colleague at work, it was about SQL queries and sorting. He has the opinion that you should let the server do any sorting before returning the rows to the client. I on the other hand thinks that the server is probably busy enough as it is, and it must be better for performance to let the client handle the sorting after it has fetched the rows.
Anyone which strategy is best for the overall performance of a multi-user system?
|
In general, you should let the database do the sorting; if it doesn't have the resources to handle this effectively, you need to upgrade your database server.
First off, the database may already have indexes on the fields you want so it may be trivial for it to retrieve data in sorted order. Secondly, the client can't sort the results until it has all of them; if the server sorts the results, you can process them one row at a time, already sorted. Lastly, the database is probably more powerful than the client machine and can probably perform the sorting more efficiently.
|
It depends... Is there paging involved? What's the max size of the data set? Is the entire dataset need to be sorted the same one way all the time? or according to user selection? Or, (if paging is involved), is it only the records in the single page on client screen need to be sorted? (not normally acceptable) or does the entire dataset need to be sorted and page one of the newly sorted set redisplayed?
What's the distribution of client hardware compared to the processing requirements of this sort operation?
bottom line is; It's the overall user experience (measured against cost of course), that should control your decision... In general client machines are slower than servers, and may cause additional latency. ...
... But how often will clients request additional custom sort operations after initial page load? (client sort of data already on client is way faster than round trip...)
But sorting on client always requires that entire dataset be sent to client on initial load... That delays initials page display.. which may require lazy loading, or AJAX, or other technical complexities to mitigate...
Sorting on server otoh, introduces additional scalability issues and may require that you add more boxes to the server farm to deal with additional load... if you're doing sorting in DB, and reach that threshold, that can get complicated. (To scale out on DB, you have to implement some read-only replication scheme, or some other solution that allows multiple servers (each doing processing) to share read only data)..
|
Sorting on the server or on the client?
|
[
"",
"sql",
"database",
"performance",
"sorting",
""
] |
How can I draw something in JPanel that will stay the same and not be repainted, I am doing a traffic simulation program and I want the road to be drawn once because It will not change.
Thanks
|
I'm not sure you actually want your road to never be repainted - repaint events fire (for example) when your window is resized, or when it becomes visible following another window obstructing it. If your panel never repaints then it'll look peculiar.
As far as I remember, Swing will only fire appropriate paint events for these circumstances, so you should be OK following the usual method of subclassing JPanel with a suitable override:
```
public class RoadPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// your drawing code here
}
}
```
If you cache your road into an image or another graphics format (to save calculating the display data multiple times) once drawn once, this might save you some time on subsequent paints.
|
To my knowledge, no, unless there is a trick with transparent overlays.
Most graphical applications I saw (and did) just re-draw the whole panel on each repaint. Now, you can do that once, in a graphic buffer, and then just paint the whole background at once, quickly, by copying the graphic buffer to the JPanel. It should be faster than calling all graphical primitives to draw the road.
Or, the way some 2D games do, perhaps paint it once and update the moving parts, like sprites: it needs to erase the old place used by the sprites (restore the background there) and re-draw the sprites at the new place. So you still have a copy of the road in a graphic buffer but instead of re-drawing it whole each time, you update only some small parts. Can be slightly faster.
|
How can I draw something on a jPanel that will not be repainted?
|
[
"",
"java",
"jpanel",
""
] |
I typically use extension methods very sparingly. When I do feel compelled to write an extension method, I sometimes want to overload the method. My question is, what are your thoughts on extension methods calling other extension methods? Bad practice? It feels wrong, but I can't really define why.
For example, the second CaselessIs method calls the first:
```
public static bool CaselessIs(this string s, string compareTo)
{
return string.Compare(s, compareTo, true) == 0;
}
public static bool CaselessIs(this string s, IEnumerable<string> compareTo)
{
foreach(string comparison in compareTo)
{
if (s.CaselessIs(comparison))
{
return true;
}
}
return false;
}
```
Would it be more appropriate to not do this? The downside would be that it violates DRY.
```
public static bool CaselessIs(this string s, string compareTo)
{
return string.Compare(s, compareTo, true) == 0;
}
public static bool CaselessIs(this string s, IEnumerable<string> compareTo)
{
foreach(string comparison in compareTo)
{
if (string.Compare(s, comparison, true) == 0)
{
return true;
}
}
return false;
}
```
|
I would have to say that DRY controls here. Personally, I see nothing wrong with an extension method calling another extension method, especially if that other extension is contained within the same assembly. All-in-all, the method calls are just translated by the compiler from:
```
extended.ExtensionMethod(foo);
```
to:
```
StaticType.ExtensionMethod(extended, foo);
```
I don't see any problem chaining two static methods together, so transitively, I don't see a problem with chaining two extension methods.
|
I personally don't see a problem with it, the second scenario I think feels more wrong....
|
C# Extensions
|
[
"",
"c#",
"extension-methods",
""
] |
Suppose that I have a Java class with a static method, like so:
```
class A
{
static void foo()
{
// Which class invoked me?
}
}
```
And suppose further that class A has an arbitrary number of subclasses:
```
class B extends A { }
class C extends A { }
class D extends A { }
...
```
Now consider the following method invocations:
```
A.foo();
B.foo();
C.foo();
D.foo();
...
```
My question is, how can method `foo()` tell which class is invoking it?
|
It can't, and that's part of the problem with static methods. As far as the compiler is concerned `A.foo()` and `B.foo()` are exactly the same thing. In fact, they compile down to the same bytecode. You can't get more similar than that.
If you really need this sort of information, use a singleton and turn `foo()` into an instance method. If you still like the static syntax, you can build a facade `A.foo()`.
|
Although you can't find out which class the static method was *invoked on*, it is possible to find out which class actually *invoked* the method at runtime:
```
static void foo()
{
Throwable t = new Throwable();
StackTraceElement[] trace = t.getStackTrace();
String className = trace[1].getClassName();
Class whoCalledMe = null;
try
{
whoCalledMe = Class.forName( className );
}
catch( Exception e )
{
}
}
```
I'm not saying that this is good practice and its probably not great from a performance perspective either, but it should work. Don't know if that helps you any ...
|
Which class invoked my static method?
|
[
"",
"java",
"reflection",
""
] |
In HTML, I can find a file starting from the **web server's** root folder by beginning the filepath with "/". Like:
```
/images/some_image.jpg
```
I can put that path in any file in any subdirectory, and it will point to the right image.
With PHP, I tried something similar:
```
include("/includes/header.php");
```
...but that doesn't work.
I think that that [this page](https://www.php.net/manual/en/ini.core.php#ini.include-path) is saying that I can set `include_path` once and after that, it will be assumed. But I don't quite get the syntax. Both examples start with a period, and it says:
> Using a . in the include path allows for relative includes as it means the current directory.
Relative includes are exactly what I **don't** want.
**How do I make sure that all my includes point to the `root/includes` folder?** (Bonus: what if I want to place that folder outside the public directory?)
## Clarification
My development files are currently being served by XAMPP/Apache. Does that affect the absolute path? (I'm not sure yet what the production server will be.)
## Update
I don't know what my problem was here. The `include_path` thing I referenced above was exactly what I was looking for, and the syntax isn't really confusing. I just tried it and it works great.
One thing that occurs to me is that some people may have thought that "/some/path" was an "absolute path" because they assumed the OS was Linux. This server is Windows, so an absolute path would have to start with the drive name.
Anyway, problem solved! :)
|
What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;
```
define( 'ROOT_DIR', dirname(__FILE__) );
```
Then in all files, I know what the root of my project is and can do stuff like this
```
require_once ROOT_DIR.'/include/functions.php';
```
Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.
|
## One strategy
I don't know if this is the best way, but it has worked for me.
```
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");
```
|
How do I set an absolute include path in PHP?
|
[
"",
"php",
""
] |
Is it possible somehow to close StreamReader after calling ReadToEnd method in construction like this:
```
string s = new StreamReader("filename", Encoding.UTF8).ReadToEnd();
```
Any alternative elegant construction with the same semantics will be also accepted.
|
I think the method you're really after is [File.ReadAllText](http://msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx), if you're just trying to read all the text from a file in the shortest possible code.
If you don't specify the encoding, it will use UTF-8 automatically.
|
You could use a *[using](http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx)* statement, which *automatically* closes the stream:
```
string s = null;
using ( StreamReader reader = new StreamReader( "filename", Encoding.UTF8 ) { s = reader.ReadToEnd(); }
```
|
Closing StreamReader after ReadToEnd
|
[
"",
"c#",
".net",
"file-io",
""
] |
We are considering moving the win32 build of our cross-platform C++ application from MS Visual Studio 2003 to MS Visual Studio 2005. (Yes, very forward-looking of us ;)
Should we expect to many code changes to get it compiling and working?
|
I've just migrated a comparatively large codebase from VS2003 to VS2008 via VS2005 and the majority of issues I found were const/non-const issues like assigning the return value of a function that returns a const char \* to char \*. Both VS2005 and VS2008 are a lot more picky when it comes to const correctness and if your existing codebase is a bit sloppy, sorry, old school when it comes to const correctness, you'll see plenty of this.
A very welcome change was that the template support in VS2005 is noticeably better than it is in VS2003 (itself a big improvement on earlier versions), which enabled me to throw out several workarounds for template related issues that the team had been dragging around since the heady days of VC++ 4.x.
One issue that you are likely to encounter are tons of warnings about "deprecated" or "insecure" functions, especially if you are using the C string functions. A lot of these are "deprecated by Microsoft" (only that they left out the "by Microsoft" part) and are still perfectly usable, but are known potential sources for buffer overflows. In the projects I converted, I set the preprocessor define \_CRT\_SECURE\_NO\_WARNINGS and disabled the warning C4996 to turn off these somewhat annoying messages.
Another issue that we came across is that MS has changed the default size of time\_t either in VS2005 or in VS2008 (I apologise but I can't remember - it's definitely in VS2008 but it may already be in VS2005) so if you have to link with legacy libraries that use time\_t in the interface, you'll have to use \_USE\_32BIT\_TIME\_T to revert to the older compiler's behaviour.
If your solution contains several projects, you may find that the parallel build feature (which is turned on by default) will highlight missing build dependencies. so projects are suddenly built in the wrong order but magically build correctly if you revert from parallel build back to linear build.
Overall I do prefer VS2005/8 to VS2003, and I would recommend to upgrade to VS2008 if that is an option, as the compiler is "better" than VS2005 - MS seems to have made a massive effort in improving the native C++ compiler. Part of that was already noticeable in 2005 so you'll get at least some of the benefit even if you stick to 2005.
|
If your code is already quite clean and compiles without warning, it's not a big step.
Check [this article](http://www.devx.com/cplus/10MinuteSolution/28908/1954) and consider how big the impact of those changes would be on your existing code. Cleaning up for-loop conformance can be a bit of work.
You can get the free Express edition of Visual Studio 2005 [here](http://www.microsoft.com/express/2005/).
|
What code changes are required to migrate C++ from VS2003 to VS2005?
|
[
"",
"c++",
"visual-studio-2005",
"migration",
"visual-studio-2003",
""
] |
I'm developing a small tray-icon application for Windows and I need to display non-intrusive visual notifications similar to those that appear when you receive a new message in MSN Messenger or any other IM application.
I have looked at [Snarl](http://www.fullphat.net/index.php), but it seems to be a separate application that I need to install. I want something that could be bundled with my application in one installer, a library.
Which one do you recommend?
Python support is a huge plus.
|
You can do it by depending on a GUI library.
For example, with PyQt,it is possible :
* [PyQt QSystemTrayIcon Documentation](http://pyqt.sourceforge.net/Docs/PyQt4/qsystemtrayicon.html)
* [QSystemTrayIcon Class Reference](http://qt-project.org/doc/qt-4.8/qsystemtrayicon.html)
* [Example of QSystemTrayIcon](http://qt-project.org/doc/qt-4.8/desktop-systray.html) (in C++, easy to adapt to python)
|
I wrote one for .NET for the Genghis project ([link here](http://www.codeplex.com/genghis)) a while back. Looks like it is over at MS CodePlex now. Look for the "AniForm" class. [Here](http://www.sellsbrothers.com/tools/genghis/screenshots/AniForm.JPG) is a screenshot.
It has more of an older MSN Messenger look and feel but should get you started.
|
Notification Library for Windows
|
[
"",
"python",
"windows",
"notifications",
""
] |
Can LINQ to SQL query using **NOT IN**?
e.g., SELECT au\_lname, state FROM authors WHERE state NOT IN ('CA', 'IN', 'MD')
|
```
List<string> states = new List<string> { "CA", "IN", "MD" };
var q = from a in authors
where !states.Contains(a.state)
select new { a.au_lname, a.state };
```
or
```
var q = authors.Where( a => !states.Contains( a.state ) )
.Select( a => new { a.au_lname, a.state } );
```
|
You can do it with Contains:
```
var states = new[] {"CA", "IN", "MD"};
var query = db.Authors.Where(x => !states.Contains(x.state));
```
|
LINQ to SQL query using "NOT IN"
|
[
"",
"sql",
".net",
"linq",
"linq-to-sql",
""
] |
Is it possible to get the expiry `DateTime` of an `HttpRuntime.Cache` object?
If so, what would be the best approach?
|
I just went through the System.Web.Caching.Cache in reflector. It seems like everything that involves the expiry date is marked as internal. The only place i found public access to it, was through the Cache.Add and Cache.Insert methods.
So it looks like you are out of luck, unless you want to go through reflection, which I wouldn't recommend unless you really really need that date.
But if you wish to do it anyway, then here is some code that would do the trick:
```
private DateTime GetCacheUtcExpiryDateTime(string cacheKey)
{
object cacheEntry = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { cacheKey, 1 });
PropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);
DateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null);
return utcExpiresValue;
}
```
[Since .NET 4.5](https://stackoverflow.com/questions/53199635/cant-access-runtime-cache-using-reflection) the internal public getter of the `HttpRuntime.Cache` was replaced with a static variant and thus you will need to invoke/get the static variant:
```
object cacheEntry = Cache.GetType().GetMethod("Get").Invoke(null, new object[] { cacheKey, 1 });
```
|
As suggested by someone in comments that the accepted answer does not work in .NET 4.7
I had a lot of trouble trying to figure out what changes needs to be done to make it work in .NET 4.7
Here's my code for people using .NET 4.7
```
private DateTime GetCacheUtcExpiryDateTime(string cacheKey)
{
var aspnetcachestoreprovider = System.Web.HttpRuntime.Cache.GetType().GetProperty("InternalCache", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(System.Web.HttpRuntime.Cache, null);
var intenralcachestore = aspnetcachestoreprovider.GetType().GetField("_cacheInternal", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(aspnetcachestoreprovider);
Type TEnumCacheGetOptions = System.Web.HttpRuntime.Cache.GetType().Assembly.GetTypes().Where(d => d.Name == "CacheGetOptions").FirstOrDefault();
object cacheEntry = intenralcachestore.GetType().GetMethod("DoGet", BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Any, new[] { typeof(bool), typeof(string), TEnumCacheGetOptions }, null).Invoke(intenralcachestore, new Object[] { true, cacheKey, 1 }); ;
PropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);
DateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null);
return utcExpiresValue;
}
```
And for those who wants the code to function in multiple different environments (sandbox using .NET 4.5 and production using .NET 4.7), here's some patch work:
```
private DateTime GetCacheUtcExpiryDateTime(string cacheKey)
{
MethodInfo GetCacheEntryMethod = null;
Object CacheStore = null;
bool GetterFound = true;
GetCacheEntryMethod = System.Web.HttpRuntime.Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic);
if (GetCacheEntryMethod != null)
{
GetterFound = true;
CacheStore = System.Web.HttpRuntime.Cache;
}
else
{
var aspnetcachestoreprovider = System.Web.HttpRuntime.Cache.GetType().GetProperty("InternalCache", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(System.Web.HttpRuntime.Cache, null);
var intenralcachestore = aspnetcachestoreprovider.GetType().GetField("_cacheInternal", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(aspnetcachestoreprovider);
Type TEnumCacheGetOptions = System.Web.HttpRuntime.Cache.GetType().Assembly.GetTypes().Where(d => d.Name == "CacheGetOptions").FirstOrDefault();
GetCacheEntryMethod = intenralcachestore.GetType().GetMethod("DoGet", BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Any, new[] { typeof(bool), typeof(string), TEnumCacheGetOptions }, null);
GetterFound = false;
CacheStore = intenralcachestore;
}
dynamic cacheEntry;
if (GetterFound)
cacheEntry = GetCacheEntryMethod.Invoke(CacheStore, new Object[] { cacheKey, 1 });
else
cacheEntry = GetCacheEntryMethod.Invoke(CacheStore, new Object[] { true, cacheKey, 1 });
PropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);
DateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null);
return utcExpiresValue;
}
```
|
How can I get the expiry datetime of an HttpRuntime.Cache object?
|
[
"",
"c#",
"asp.net",
"caching",
""
] |
I have a databases table with ~50K rows in it, each row represents a job that need to be done. I have a program that extracts a job from the DB, does the job and puts the result back in the db. (this system is running right now)
Now I want to allow more than one processing task to do jobs but be sure that no task is done twice (as a performance concern not that this will cause other problems). Because the access is by way of a stored procedure, my current though is to replace said stored procedure with something that looks something like this
```
update tbl
set owner = connection_id()
where available and owner is null limit 1;
select stuff
from tbl
where owner = connection_id();
```
BTW; worker's tasks might drop there connection between getting a job and submitting the results. Also, I don't expect the DB to even come close to being the bottle neck unless I mess that part up (~5 jobs per minute)
Are there any issues with this? Is there a better way to do this?
Note: the ["Database as an IPC anti-pattern"](http://tripatlas.com/Database_as_an_IPC) is only slightly apropos here because
1. I'm not doing IPC (there is no process generating the rows, they all already exist right now) and
2. the primary gripe described for that anti-pattern is that it results in unneeded load on the DB as processes wait for messages (in my case, if there are no messages, everything can shutdown as everything is done)
|
Here's what I've used successfully in the past:
MsgQueue table schema
```
MsgId identity -- NOT NULL
MsgTypeCode varchar(20) -- NOT NULL
SourceCode varchar(20) -- process inserting the message -- NULLable
State char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL
CreateTime datetime -- default GETDATE() -- NOT NULL
Msg varchar(255) -- NULLable
```
Your message types are what you'd expect - messages that conform to a contract between the process(es) inserting and the process(es) reading, structured with XML or your other choice of representation (JSON would be handy in some cases, for instance).
Then 0-to-n processes can be inserting, and 0-to-n processes can be reading and processing the messages, Each reading process typically handles a single message type. Multiple instances of a process type can be running for load-balancing.
The reader pulls one message and changes the state to "A"ctive while it works on it. When it's done it changes the state to "C"omplete. It can delete the message or not depending on whether you want to keep the audit trail. Messages of State = 'N' are pulled in MsgType/Timestamp order, so there's an index on MsgType + State + CreateTime.
Variations:
State for "E"rror.
Column for Reader process code.
Timestamps for state transitions.
This has provided a nice, scalable, visible, simple mechanism for doing a number of things like you are describing. If you have a basic understanding of databases, it's pretty foolproof and extensible.
---
Code from comments:
```
CREATE PROCEDURE GetMessage @MsgType VARCHAR(8) )
AS
DECLARE @MsgId INT
BEGIN TRAN
SELECT TOP 1 @MsgId = MsgId
FROM MsgQueue
WHERE MessageType = @pMessageType AND State = 'N'
ORDER BY CreateTime
IF @MsgId IS NOT NULL
BEGIN
UPDATE MsgQueue
SET State = 'A'
WHERE MsgId = @MsgId
SELECT MsgId, Msg
FROM MsgQueue
WHERE MsgId = @MsgId
END
ELSE
BEGIN
SELECT MsgId = NULL, Msg = NULL
END
COMMIT TRAN
```
|
The best way to implement a job queue in a relational database system is to use [`SKIP LOCKED`](https://vladmihalcea.com/database-job-queue-skip-locked/).
`SKIP LOCKED` is a lock acquisition option that applies to both read/share (`FOR SHARE`) or write/exclusive (`FOR UPDATE`) locks and is widely supported nowadays:
* Oracle 10g and later
* PostgreSQL 9.5 and later
* SQL Server 2005 and later
* MySQL 8.0 and later
Now, consider we have the following `post` table:
[](https://vladmihalcea.com/database-job-queue-skip-locked/)
The `status` column is used as an `Enum`, having the values of:
* `PENDING` (0),
* `APPROVED` (1),
* `SPAM` (2).
If we have multiple concurrent users trying to moderate the `post` records, we need a way to coordinate their efforts to avoid having two moderators review the same `post` row.
So, `SKIP LOCKED` is exactly what we need. If two concurrent users, Alice and Bob, execute the following SELECT queries which lock the post records exclusively while also adding the `SKIP LOCKED` option:
```
[Alice]:
SELECT
p.id AS id1_0_,1
p.body AS body2_0_,
p.status AS status3_0_,
p.title AS title4_0_
FROM
post p
WHERE
p.status = 0
ORDER BY
p.id
LIMIT 2
FOR UPDATE OF p SKIP LOCKED
[Bob]:
SELECT
p.id AS id1_0_,
p.body AS body2_0_,
p.status AS status3_0_,
p.title AS title4_0_
FROM
post p
WHERE
p.status = 0
ORDER BY
p.id
LIMIT 2
FOR UPDATE OF p SKIP LOCKED
```
We can see that Alice can select the first two entries while Bob selects the next 2 records. Without `SKIP LOCKED`, Bob lock acquisition request would block until Alice releases the lock on the first 2 records.
|
The best way to use a DB table as a job queue (a.k.a batch queue or message queue)
|
[
"",
"sql",
"database",
"concurrency",
"locking",
"job-queue",
""
] |
I'm using the MessageBox class to show errors to users, and while that might not be the right behavior, it's very convenient. This is a touchscreen application, however, so I need the 'ok' button to be much larger than it is (curse my inordinately large fingers!).
I think that if I increase the font size in the dialog box, I should be ok. Is there a way to do that? Or really, is there any way to increase the dialog size?
Thanks
|
As far as I'm aware you can't, as the 'normal' dialog boxes are using your default system font settings.
Roll your own is probably the best way forward. It's fairly trivial to do, and much fun! And you can build in things that the standard dialog doesn't support (without PInvoke magic) such as centering in the middle of the screen etc.
|
please check out my free to use [FlexibleMessageBox](http://www.codeproject.com/Articles/601900/FlexibleMessageBox-A-flexible-replacement-for-the) which can be used instead of MessageBox and has a (static) FONT-Property.
Regards,
Jörg
|
MessageBox.Show-- font change?
|
[
"",
"c#",
"fonts",
"messagebox",
""
] |
I have a ListBox control that I want to change into having a toggle selection. i.e. Click once on an item selects it, click again it deselects it. Also, clicking another item in the list should do the default action of deselecting the previous item and selecting the new one.
What's the best way of achieving this?
|
What you want is a RadioButtonList. You can create one by creating an ItemDataTemplate and put a RadioButton inside it. Then you can modify the template of the RadioButton to looks like a button.
|
I would keep the standard ListBox as that way you will keep the default behaviour you want, then for deselecting an item could you just handle it in the mouse down event? i.e. use something like this:
```
Point newPoint = e.GetPosition(backgroundImage);
HitTestResult result = VisualTreeHelper.HitTest(this, newPoint);
if (result.VisualHit is ListBoxItem)
```
I'm not sure if this is the best way, the only other way I would go about doing this is to derive my own ListBox from the standard windows control and add in a dependency property to allow me to handle the deselection in the style. If you want to take this approach I shouldn't remove the default behaviour you want to keep either, I used this approach to create a ListBox that would display an image next to the text.
If you need any pointers on where to start, then just give me a shout.
|
Best way to change ListBox selection to be a toggle selection
|
[
"",
"c#",
".net",
"wpf",
"silverlight",
"listbox",
""
] |
I am trying to create a dialog box that will appear only if the browser selected is IE (any version) however I get this error:
> Message: HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917)
That's all in "Line/Char/Code" 0 so I do not know where is the error. The code I'm using is this:
```
<script type="text/javascript">
<!--
if(BrowserDetect.browser.contains("Explorer"))
{
var Nachricht = 'Hemos detectado que está utilizando ' + BrowserDetect.browser + ' ' +
BrowserDetect.version + '. Puede que algunas funciones no estén habilitadas. <p></p> Si desea experimentar todo el potencial del portal, por favor intente desde otro navegador (browser). <p></p>Gracias
showDialog('¡Aviso Importante!',Nachricht,'warning',10);
}
</script>
```
I've noticed if I remove the "BrowserDetect.browser" and .version it removes the error, but I need those to check =/...any ideas will be appreciated =).
|
You're modifying document while it's being loaded (when browser hasn't "seen" closing tag for this element) . This causes very tricky situation in the parser and in IE it's not allowed.
[IE blog](http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx) has explanation of this.
The solution is to modify another element that's earlier in the document and has been loaded completely (where browser already saw closing tag for it).
BTW: The string `</` is not allowed in `<script>` element. Use `<\/` which is a safe equivalent in JS strings.
|
I had this same problem. My issue was that I was calling a Javascript function before the containing `div` was closed.
To fix the problem, I call the Javascript function within the jQuery `ready` event handler:
```
$(document).ready(function(){
some_random_javascript_function();
});
```
|
Problem with HTML Parser in IE
|
[
"",
"javascript",
"html-parsing",
""
] |
How to create a windows toolbar-dockable application - like [Winamp Desk Band](http://www.winamp.com/plugins/details/82271) - in .NET?
|
# C# does Shell, Part 3
<http://www.codeproject.com/KB/shell/csdoesshell3.aspx>
# AppBar using C#
<http://www.codeproject.com/KB/dotnet/AppBar.aspx>
|
It sounds like you want to create an **AppBar**.
I suggest you first check out the AppBar implementation included with [the Genghis package](http://www.sellsbrothers.com/tools/genghis/). I couldn't say if it's any good since I never used it, but it looks promising.
Manually, you would have to use a few Win32 API calls to reserve/free the screen space and achieve the effect you're looking for, as detailed in [this article](http://www.codeproject.com/KB/dotnet/AppBar.aspx).
Good luck!
|
Windows ToolBar-dockable application
|
[
"",
"c#",
".net",
"dockable",
""
] |
can anyone show me how to get the users within a certain group using sharepoint?
so i have a list that contains users and or groups. i want to retrieve all users in that list. is there a way to differentiate between whether the list item is a group or user. if its a group, i need to get all the users within that group.
im using c#, and im trying to do thins by making it a console application.
im new to sharepoint and im really jumping into the deep end of the pool here, any help would be highly appreciated.
cheers..
|
The first thing you need to know is that when you have a list with a User / Group field you must be aware of its type. When you have one user or group within the item value, the field type is SPFieldUserValue. However, if the field has multiple user / group selection the field type is SPFieldUserValueCollection.
I'll assume that your field allows a single user / group selection and you already has the following objects:
```
SPSite site;
SPWeb web;
SPListItem item;
```
Now, we'll check the field value for a user / group and retrieve a list of users, independant of which kind it is (the field's name is *"Users"*).
```
SPFieldUserValue usersField = new SPFieldUserValue(mainWeb, item["Users"].ToString());
bool isUser = SPUtility.IsLoginValid(site, usersField.User.LoginName);
List<SPUser> users = new List<SPUser>();
if (isUser)
{
// add a single user to the list
users.Add(usersField.User);
}
else
{
SPGroup group = web.Groups.GetByID(usersField.LookupId);
foreach (SPUser user in group.Users)
{
// add all the group users to the list
users.Add(user.User);
}
}
```
I hope it helps you.
Tks,
Pedro José Batista
|
note: an SPUser object can also be an AD Group (that is to say, an SPUser object might exist for "DOMAIN\Domain Users"... which is why the SPUser object also contains the property IsDomainGroup.
From this information you can start to traverse through AD groups using the SPPrincipalInfo objects... however it's not always pleasant.
One thing worth keeping in mind is that the SPGroup object includes the ContainsCurrentUser property which can traverse AD groups... this assumes you've got an SPGroup object to work from, however.
Enjoy.
-Scott
|
get users by group in sharepoint
|
[
"",
"c#",
"sharepoint",
"moss",
"console",
"wss",
""
] |
What is the preferred/easiest way to manipulate TDesC strings, for example to obtain a substring.
I will give you an example of my scenario.
```
RBuf16 buf;
...
CEikLabel label;
...
label->SetTextL(buf); // (SetTextL takes a const TDesC&)
```
I want to get a substring from buf. So do I want to manipulate the RBuf16 directly and if so what is the best way?
Is there a way to convert to const char\* so I can just use standard C string manipulation.
Thanks in advance
|
Read descriptors.blogspot.com (scroll down once loaded).
You can use TDes::LeftTPtr, TDes::RightTPtr or TDes::MidTPtr which will give you a substring as a TPtr (i.e. a descriptor which manipulates the original data).
You can use the TDes::Copy function if you want to create a copy of your substring.
|
Best or not, I cannot comment, but I use the following methods to extract sub-strings from descriptors:
```
TDes::LeftTPtr()
TDes::MidTPtr()
TDes::RightTPtr()
```
or
```
TDesC::Left()
TDesC::Mid()
TDesC::Right()
```
with the difference between the two sets being that the former returns a new modifiable descriptor, the latter, a new non-modifiable descriptor, containing the sub-string.
While you develop on the Symbian platform, I would suggest highly to follow the Symbian conventions, and not to think of Symbian C++ from a standard C or C++ point of view all the time. Use the libraries that Symbian has specifically made available, instead of standard C/C++ libraries that Symbian may or may not directly support. Since the ultimate goal of an application developed on the Symbian is to run on a mobile device where reliability and robustness of applications matter the most, you should stick to what Symbian prefers and suggests.
|
Symbian C++ - Substring operations on descriptors
|
[
"",
"c++",
"symbian",
"substring",
"s60",
""
] |
Plone is very complex. [Zope](http://en.wikipedia.org/wiki/Zope)2, [Zope3](http://en.wikipedia.org/wiki/Zope_3), [Five](http://codespeak.net/z3/five/), [ZCML](http://wiki.zope.org/zope3/ZCML), [ZODB](http://en.wikipedia.org/wiki/Zope_Object_Database), [ZEO](http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO), a whole bunch of acronyms and abbreviations.
It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.
Does the steep learning curve pay of? Is this complexity still justified today?
Background: I need a platform. Customers often need a CMS. I'm currently reading "[Professional Plone Development](http://plone.org/news/book-professional-plone-development-now-shipping)", without prior knowledge of Plone.
The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "[If you want to see the complexity of Plone, you have to ask for it.](https://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692)" when you don't know the system good enough to plan.
|
If you want to see the complexity of Plone, you have to ask for it. For most people, it's just not there. It installs in a couple of minutes through a one-click installer. Then it's one click to log in, one click to create a page, use a WYSYWIG editor, and one click to save. Everything is through an intuitive web GUI. Plone is a product.
If you want to use it as a "platform," then the platform is a stack of over one million lines of code which implements a complete content management suite. No one knows it all. However, all those "acronyms" and "files" are evidence of a software which is factored in components so that no one need know it all. You can get as deep or shallow in it as you need. If there's something you need for some aspect of content management, it's already there, you don't have to create it from scratch, and you can do it in a way that's consistent with a wide practice and review.
|
It's hard to answer your question without any background information. Is the complexity justified if you just want a blog? No. Is the complexity justified if you're building a company intranet for 400+ people? Yes. Is it a good investment if you're looking to be a consultant? Absolutely! There's a lot of Plone work out there, and it pays much better than the average PHP job.
I'd encourage you to clarify what you're trying to build, and ask the Plone forums for advice. Plone has a very mature and friendly community — and will absolutely let you know if what you're trying to do is a poor fit for Plone. You can of course do whatever you want with Plone, but there are some areas where it's the best solution available, other areas where it'll be a lot of work to change it to do something else.
Some background:
The reason for the complexity of Plone at this point in time is that it's moving to a more modern architecture. It's bridging both the old and the new approach right now, which adds some complexity until the transition is mostly complete.
Plone is doing this to avoid leaving their customers behind by breaking backwards compatibility, which they take very seriously — unlike other systems I could mention (but won't ;).
You care about your data, the Plone community cares about their data — and we'd like you to be able to upgrade to the new and better versions even when we're transitioning to a new architecture. This is one of the Plone community's strengths, but there is of course a penalty to pay for modifying the plane while it's flying, and that's a bit of temporary, extra complexity.
Furthermore, Plone as a community has a strong focus on security (compare it to any other system on the vulnerabilities reported), and a very professional culture that values good architecture, testing and reusability.
As an example, consider the current version of Plone being developed (what will become 4.0):
* It starts up 3-4 times faster than the current version.
* It uses about 20% less memory than the current version.
* There's a much, much easier types system in the works (Dexterity), which will reduce the complexity and speed up the system a lot, while keeping the same level of functionality
* The code base is already 20% smaller than the current shipping version, and getting even smaller.
* Early benchmarks of the new types system show a 5× speedup for content editing, and we haven't really started optimizing this part yet.
— Alexander Limi, Plone co-founder (and slightly biased ;)
|
What could justify the complexity of Plone?
|
[
"",
"python",
"content-management-system",
"plone",
"zope",
""
] |
My simplified and contrived example is the following:-
Lets say that I want to measure and store the temperature (and other values) of all the worlds' towns on a daily basis. I am looking for an optimal way of storing the data so that it is just as easy to get the current temperature in all the towns, as it is to get all the temperature historically in one town.
It is an easy enough problem to solve, but I am looking for the best solution.
The 2 main options I can think of are as follows:-
# Option 1 - Same table stores current and historical records
Store all the current and archive records in the same table.
i.e.
```
CREATE TABLE [dbo].[WeatherMeasurement](
MeasurementID [int] Identity(1,1) NOT Null,
TownID [int] Not Null,
Temp [int] NOT Null,
Date [datetime] NOT Null,
)
```
This would keep everything simple, but what would be the most efficient query to get a list of towns and there current temperature? Would this scale once the table has millions of rows in? Is there anything to be gained by having some sort of IsCurrent flag in the table?
# Option 2 - Store all archive records in a separate table
There would be a table to store the current live measurements in
```
CREATE TABLE [dbo].[WeatherMeasurement](
MeasurementID [int] Identity(1,1) NOT Null,
TownID [int] Not Null,
Temp [int] NOT Null,
Date [datetime] NOT Null,
)
```
And a table to store historical archived date (inserted by a trigger perhaps)
```
CREATE TABLE [dbo].[WeatherMeasurementHistory](
MeasurementID [int] Identity(1,1) NOT Null,
TownID [int] Not Null,
Temp [int] NOT Null,
Date [datetime] NOT Null,
)
```
This has the advantages of keeping the main current data lean, and very efficient to query, at the expense of making the schema more complex and inserting data more expensive.
Which is the best option? Are there better options I haven't mentioned?
NOTE: I have simplified the schema to help focus my question better, but assume there will be alot of data inserted each day (100,000s of records), and data is current for one day. The current data is just as likely to be queried as the historical.
|
it DEPENDS on the applications usage patterns... If usage patterns indicate that the historical data will be queried more often than the current values, then put them all in one table... But if Historical queries are the exception, (or less than 10% of the queries), and the performance of the more common current value query will suffer from putting all data in one table, then it makes sense to separate that data into it's own table...
|
I would keep the data in one table *unless* you have a very serious bias for current data (in usage) or history data (in volume). A compound index with DATE + TOWNID (in that order) would remove the performance concern in most cases (although clearly we don't have the data to be sure of this at this time).
The one thing I would wonder about is if anyone will want data from both the current and history data for a town. If so, you just created at least one new view to worry about and possible performance problem in that direction.
This is unfortunately one of those things where you may need to profile your solutions against real world data. I personally have used compound indexes such as specified above in many cases, and yet there are a few edge cases where I have opted to break the history into another table. Well, actually another data file, because the problem was that the history was *so* dense that I created a new data file for it alone to avoid bloating the entire primary data file set. Performance issues are rarely solved by theory.
I would recommend reading up on query hints for index use, and "covering indexes" for more information about performance issues.
|
What is the best way to store historical data in SQL Server 2005/2008?
|
[
"",
"sql",
"sql-server",
"performance",
"t-sql",
"sql-server-2008",
""
] |
```
class MyBase
{
protected object PropertyOfBase { get; set; }
}
class MyType : MyBase
{
void MyMethod(MyBase parameter)
{
// I am looking for:
object p = parameter.PropertyOfBase; // error CS1540: Cannot access protected member 'MyBase.PropertyOfBase' via a qualifier of type 'MyBase'; the qualifier must be of type 'MyType' (or derived from it)
}
}
```
Is there a way to get a protected property of a parameter of a type from an extending type without reflection? Since the extending class knows of the property through its base type, it would make sense if possible.
|
No, you can't do this.
You're only allowed to access protected members of objects of the accessing type (or derived from it). Here, we don't know whether the parameter is of type MyType or SomeOtherCompletelyDifferentType.
EDIT: The relevant bit of the C# 3.0 spec is section 3.5.3:
> When a protected instance member is
> accessed outside the program text of
> the class in which it is declared, and
> when a protected internal instance
> member is accessed outside the program
> text of the program in which it is
> declared, the access must take place
> within a class declaration that
> derives from the class in which it is
> declared. Furthermore, the access is
> required to take place through an
> instance of that derived class type or
> a class type constructed from it. This
> restriction prevents one derived class
> from accessing protected members of
> other derived classes, even when the
> members are inherited from the same
> base class.
|
Last time I faced a similar problem, I used the solution of adding a protected static method to the base:
```
class MyBase
{
protected object PropertyOfBase { get; set; }
protected static object GetPropertyOfBaseOf(MyBase obj)
{
return obj.PropertyOfBase;
}
}
class MyType : MyBase
{
void MyMethod(MyBase parameter)
{
object p = GetPropertyOfBaseOf(parameter);
}
}
```
|
Is there a way to reach a `protected` member of another object from a derived type?
|
[
"",
"c#",
"oop",
""
] |
I have div containing a list of flash objects. The list is long so I've set the div height to 400 and overflow to auto.
This works fine on FF but on IE6 only the first 5 flash objects that are visible work. The rest of the flash objects that are initially outside the viewable area are empty when I scroll down. The swfs are loaded ok because I don't get the "movie not loaded". They also seem to be embedded correctly they are just empty ie. the content is never drawn.
Any ideas on how to fix this?
ps. The html elements involved are mainly floating in case that has an impact on this. The flash objects are embedded using the popular swfObject.
EDIT: It seems that the bug only occurs with the flash plugin "WIN 8,0,24,0"
Since I cant post a link I'll summarize the relevant code here:
```
<div style="overflow:auto; height:400px; float:left;">
<div id="item_1" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
...
<div id="item_7" style="float:left; clear:left; height:100px;">
<!-- swfObject Embed here -->
</div>
</div>
```
EDIT:
After trying to recreate this problem in a separate page I found that the bug is some how related to the flash objects being hidden initially. My container div has "display:none; visibility:hidden" when page is loaded. Later on the style is changed via javascript to visible. If I load the page so that everything is visible from the start all is fine.
|
I think I have a solution for this. I can't be absolutely sure as the page in question was restructured (because of this bug). Later on I stumbled on a similar issue with the same flash component on a different page.
The issue there was that sometimes flash gives a Stage.height=0 and Stage.width=0. This is most likely to happen when the flash is initiated outside the browser viewport. We are using the Stage dimensions to scale the contents (to width=0 and height=0 in this case).
The solution was to add an onEnterFrame handler that checks for Stage dimensions and only proceeds once they are > 0.
|
A few things that I'd try:
* remove all CSS temporarily to determine whether the issue is CSS-specific
* add pixel widths to the floated elements as well as their parent element
* add the wmode transparent param to swfobject
* add position:relative
I've heard of a bug in Flash that apparently only occurs if the flash loads with portions of it outside of the screen (i.e. body > #flash {margin-top:-50px}). Your problem could potentially be a variation of that.
Alternatively, you could drop the div with overflow altogether and try creating a container in flash with a scrollbar and load the individual SWFs into that one container flash file.
|
Flash inside a scrolling div - IE6 bug
|
[
"",
"javascript",
"html",
"flash",
"internet-explorer-6",
"swfobject",
""
] |
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?
Here's a simple example of what I would want to write:
```
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
```
So, if `class T` has `toString()` defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION\_EXISTS" part.
|
Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:
```
#include <iostream>
struct Hello
{
int helloworld() { return 0; }
};
struct Generic {};
// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
struct two { char x[2]; };
template <typename C> static one test( decltype(&C::helloworld) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
int main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}
```
I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.
|
This question is old, but with C++11 we got a new way to check for a functions existence (or existence of any non-type member, really), relying on SFINAE again:
```
template<class T>
auto serialize_imp(std::ostream& os, T const& obj, int)
-> decltype(os << obj, void())
{
os << obj;
}
template<class T>
auto serialize_imp(std::ostream& os, T const& obj, long)
-> decltype(obj.stream(os), void())
{
obj.stream(os);
}
template<class T>
auto serialize(std::ostream& os, T const& obj)
-> decltype(serialize_imp(os, obj, 0), void())
{
serialize_imp(os, obj, 0);
}
```
Now onto some explanations. First thing, I use [expression SFINAE](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2634.html) to exclude the `serialize(_imp)` functions from overload resolution, if the first expression inside `decltype` isn't valid (aka, the function doesn't exist).
The `void()` is used to make the return type of all those functions `void`.
The `0` argument is used to prefer the `os << obj` overload if both are available (literal `0` is of type `int` and as such the first overload is a better match).
---
Now, you probably want a trait to check if a function exists. Luckily, it's easy to write that. Note, though, that you need to write a trait *yourself* for every different function name you might want.
```
#include <type_traits>
template<class>
struct sfinae_true : std::true_type{};
namespace detail{
template<class T, class A0>
static auto test_stream(int)
-> sfinae_true<decltype(std::declval<T>().stream(std::declval<A0>()))>;
template<class, class A0>
static auto test_stream(long) -> std::false_type;
} // detail::
template<class T, class Arg>
struct has_stream : decltype(detail::test_stream<T, Arg>(0)){};
```
[Live example.](http://coliru.stacked-crooked.com/a/cd139d95d214c5c3)
And on to explanations. First, `sfinae_true` is a helper type, and it basically amounts to the same as writing `decltype(void(std::declval<T>().stream(a0)), std::true_type{})`. The advantage is simply that it's shorter.
Next, the `struct has_stream : decltype(...)` inherits from either `std::true_type` or `std::false_type` in the end, depending on whether the `decltype` check in `test_stream` fails or not.
Last, `std::declval` gives you a "value" of whatever type you pass, without you needing to know how you can construct it. Note that this is only possible inside an unevaluated context, such as `decltype`, `sizeof` and others.
---
Note that `decltype` is not necessarily needed, as `sizeof` (and all unevaluated contexts) got that enhancement. It's just that `decltype` already delivers a type and as such is just cleaner. Here's a `sizeof` version of one of the overloads:
```
template<class T>
void serialize_imp(std::ostream& os, T const& obj, int,
int(*)[sizeof((os << obj),0)] = 0)
{
os << obj;
}
```
The `int` and `long` parameters are still there for the same reason. The array pointer is used to provide a context where `sizeof` can be used.
|
How can you check whether a templated class has a member function?
|
[
"",
"c++",
"templates",
"template-meta-programming",
"sfinae",
""
] |
I'm launching a Weblogic application inside Eclipse via the BEA Weblogic Server v9.2 runtime environment. If this were running straight from the command-line, I'd do a ctrl-BREAK to force a thread dump. Is there a way to do it in Eclipse?
|
Indeed (thanks VonC to point to the SO thread), Dustin, in a comment to his message, points to [jstack](http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jstack.html "jstack - Stack Trace").
I have run a little Java application (with GUI) in Eclipse, I can see the related javaw.exe in Windows' process manager and its PID, 7088 (it is even simpler in Unix, of course).
If I type at a command prompt `jstack 7088`, I have the wanted stack dump per thread.
Cool.
Would be better if we could do that directly from Eclipse, but that's already useful as is.
|
You can do it when you are in debug mode: go to the debug view in the debug perspective, click on the process you have launched and click on pause, you will get a graphical stack of all your processes.
Note : this also works when using remote debugging, you do not need to launch weblogic from eclipse, you can launch it on its own, open the debugging ports and create a "remote java application debug configuration" for it.
|
How to Force Thread Dump in Eclipse?
|
[
"",
"java",
"eclipse",
"memory-leaks",
"weblogic",
""
] |
I have researched and haven't found a way to run INTERSECT and MINUS operations in MS Access. Does any way exist
|
INTERSECT is an inner join. MINUS is an outer join, where you choose only the records that don't exist in the other table.
---
**INTERSECT**
```
select distinct
a.*
from
a
inner join b on a.id = b.id
```
---
**MINUS**
```
select distinct
a.*
from
a
left outer join b on a.id = b.id
where
b.id is null
```
If you edit your original question and post some sample data then an example can be given.
EDIT: Forgot to add in the distinct to the queries.
|
INTERSECT is NOT an INNER JOIN. They're different. An INNER JOIN will give you duplicate rows in cases where INTERSECT WILL not. You can get equivalent results by:
```
SELECT DISTINCT a.*
FROM a
INNER JOIN b
on a.PK = b.PK
```
Note that PK must be the primary key column or columns. If there is no PK on the table (BAD!), you must write it like so:
```
SELECT DISTINCT a.*
FROM a
INNER JOIN b
ON a.Col1 = b.Col1
AND a.Col2 = b.Col2
AND a.Col3 = b.Col3 ...
```
With MINUS, you can do the same thing, but with a LEFT JOIN, and a WHERE condition checking for null on one of table b's non-nullable columns (preferably the primary key).
```
SELECT DISTINCT a.*
FROM a
LEFT JOIN b
on a.PK = b.PK
WHERE b.PK IS NULL
```
That should do it.
|
How can I implement SQL INTERSECT and MINUS operations in MS Access
|
[
"",
"sql",
"database",
"ms-access",
""
] |
This code is executed by many way. When it's executed by the form button it works (the button start a thread and in the loop it call this method = it works). BUT it doesn't work when I have a call to that method from my BackgroundWorker in the form.
With the following code:
```
private void resizeThreadSafe(int width, int height)
{
if (this.form.InvokeRequired)
{
this.form.Invoke(new DelegateSize(resizeThreadSafe),
new object[] { width, height });
}
this.form.Size = new Size(width, height); // problem occurs on this line
this.form.Location = new Point(0, 0); // dummy coordinate
}
```
Then on the line containing `this.form.Size = ...` I get the following exception:
```
InvalidOperationException was unhandled
Cross-thread operation not valid: Control 'Form1' accessed from a thread other
than the thread it was created on.
```
Why?
|
You need to return at the end of the if block - otherwise you'll resize it in the right thread, and then do it in the wrong thread as well.
In other words (if you'd cut and paste the code instead of a picture, this would have been easier...)
```
private void resizeThreadSafe(int width, int height)
{
if (this.form.InvokeRequired)
{
this.form.Invoke(new DelegateSize(resizeThreadSafe,
new object[] { width, height });
return;
}
this.form.Size = new Size(width, height);
this.form.Location = new Point(0, SystemInformation.MonitorSize // whatever comes next
}
```
Alternatively just put the second half of the method in an "else" block.
|
You need write this:
```
if ( this.form.InvokeRequired ) {
this.form.Invoke( ...... );
return;
}
this.form.Size = new Sizte( ... );
```
OR
```
if ( this.form.InvokeRequired ) {
this.form.Invoke( ...... );
}
else {
this.form.Size = new Sizte( ... );
}
```
|
Help me with that CrossThread?
|
[
"",
"c#",
".net",
"winforms",
"multithreading",
""
] |
I need to upload images using FileUpload without postback(using Ajax).I tried many examples.But in all postback is coming or they are using PHP.Can anyone help me to do single file upload or multi file upload using ajax in ASP.Net with C#.
|
SWFUpload
<http://demo.swfupload.org/v220beta3/simpledemo/index.php>
<http://swfupload.org/>
Javascript and Flash, there's no post-back :) and there's .NET implementations available on the site.
|
Hope you find this useful.
<http://aspalliance.com/1442_Building_AJAX_Enabled_File_Uploading_System_with_Progress_Bar_Using_ASPNET_20.all>
It's using asp.net and ajax.
|
FileUpload Using Ajax In ASP.NET With C#
|
[
"",
"javascript",
"jquery",
"ajax",
""
] |
I've written a Custom User Control which returns some user specific data.
To load the Custom User Control I use the following line of code:
```
UserControl myUC = (UserControl).Load("~/customUserControl.ascx");
```
But how can I access `string user` inside the User Control `myUC`?
|
Let's call your usercontrol "Bob"
If you Inherit from UserControl in Bob, then I guess it's safe to do this:
```
Bob b = (Bob).Load("~/customUserControl.ascx");
```
For the user part, I can't really follow what you want to do, is the "user" in the class were you create the "Bob" usercontrol and you want to set a property in the "Bob" usercontrol or is it the other way around?
For the first one you should create a property in your usercontrol.
```
class Bob : UserControl{
public string User { get; set;}
}
```
and then set it when after you create "Bob" instance.
```
b.User = theuser;
```
|
Suppose your custom user control's name is "MyUserControl"
Try this code:
```
MyUserControl myUC = (UserControl).Load("~/customUserControl.ascx") as MyUserControl;
string result = myUC.user;
```
|
How can I pass a data string to a programmatically loaded custom user control in C#
|
[
"",
"c#",
"controls",
"pass-data",
""
] |
**Is there a YAML driver for the Java [XStream](http://x-stream.github.io/) package?**
I'm already using XStream to serialise/deserialise both XML and JSON. I'd like to be able to do the same with YAML.
|
To parse a YAML document you can use this chain:
YAML -> SnakeYAML -> Java -> Your Application (-> XStream -> XML)
Emitting YAML is simpler and there are a couple of options:
1) Your Application -> XStream with Custom Writer -> YAML
2) Your Application -> SnakeYAML -> YAML
The second option does not require any additional development.
|
You might find that helpful to get a direction: [XStream - how to serialize objects to non XML formats](http://joe.truemesh.com/blog//000479.html)
|
Serialise to YAML using XStream in Java
|
[
"",
"java",
"yaml",
"xstream",
""
] |
I have a directory full (~103, 104) of XML files from which I need to extract the contents of several fields.
I've tested different xml parsers, and since I don't need to validate the contents (expensive) I was thinking of simply using xml.parsers.expat (the fastest one) to go through the files, one by one to extract the data.
1. Is there a more efficient way? (simple text matching doesn't work)
2. Do I need to issue a new ParserCreate() for each new file (or string) or can I reuse the same one for every file?
3. Any caveats?
Thanks!
|
The quickest way would be to match strings (with, e.g., regular expressions) instead of parsing XML - depending on your XMLs this could actually work.
But the most important thing is this: instead of thinking through several options, just implement them and time them on a small set. This will take roughly the same amount of time, and will give you real numbers do drive you forward.
EDIT:
* Are the files on a local drive or network drive? Network I/O will kill you here.
* The problem parallelizes trivially - you can split the work among several computers (or several processes on a multicore computer).
|
Usually, I would suggest using ElementTree's [`iterparse`](http://effbot.org/zone/element-iterparse.htm), or for extra-speed, its counterpart from [lxml](http://codespeak.net/lxml/). Also try to use [Processing](http://pypi.python.org/pypi/processing) (comes built-in with 2.6) to parallelize.
The important thing about `iterparse` is that you get the element (sub-)structures as they are parsed.
```
import xml.etree.cElementTree as ET
xml_it = ET.iterparse("some.xml")
event, elem = xml_it.next()
```
`event` will always be the string `"end"` in this case, but you can also initialize the parser to also tell you about new elements as they are parsed. You don't have any guarantee that all children elements will have been parsed at that point, but the attributes are there, if you are only interested in that.
Another point is that you can stop reading elements from iterator early, i.e. before the whole document has been processed.
If the files are large (are they?), there is a common idiom to keep memory usage constant just as in a streaming parser.
|
What is the most efficient way of extracting information from a large number of xml files in python?
|
[
"",
"python",
"xml",
"performance",
"large-files",
"expat-parser",
""
] |
I have a few text boxes and buttons on my form.
Lets say txtBox1 is next to btnSubmit1,
txtBox2 is next to btnSubmit2,
txtBox3 is next to btnSubmit3.
How can I set the focus on btnSubmit3 when the user starts to type something in txtBox3.
Meaning..... if a user type in a text box the program will know what button to fire when the user press the enter key.
|
If you use a panel, you should be able to set a defaultbutton. I´m not sure if it´s an win forms application or a web forms application, but this is how you should do it with web forms:
```
<asp:Panel id="panel1" runat="server" DefaultButton="Button1">
<asp:TextBox id="textbox1" runat="server" />
<asp:Button id="Button1" runat="server" Text="Button 1" />
</asp:Panel>
<asp:Panel id="panel2" runat="server" DefaultButton="Button2">
<asp:TextBox id="textbox2" runat="server" />
<asp:Button id="Button2" runat="server" Text="Button 2" />
</asp:Panel>
<asp:Panel id="panel3" runat="server" DefaultButton="Button3">
<asp:TextBox id="textbox3" runat="server" />
<asp:Button id="Button3" runat="server" Text="Button 3" />
</asp:Panel>
```
|
This is an easy solution if you know that the only browser being used is IE.
You just have to add to the Page load
```
txtBox1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnSubmit1.UniqueID + "','')");
txtBox2.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnSubmit2.UniqueID + "','')");
txtBox3.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnSubmit3.UniqueID + "','')");
```
The reason that this only works in IE is that it uses the Javascript "event" key word that doesn't work in Firefox.
|
Setting focus to a button from text box?
|
[
"",
"c#",
"asp.net",
"vb.net",
""
] |
I was once given this task to do in an RDBMS:
Given tables customer, order, orderlines and product. Everything done with the usual fields and relationships, with a comment memo field on the orderline table.
For one customer retrieve a list of all products that customer has ever ordered with product name, year of first purchase, dates of three last purchases, comment of the latest order, sum of total income for that product-customer combination last 12 months.
After a couple of days I gave up doing it as a Query and opted to just fetch every orderline for a customer, and every product and run through the data procedurally to build the required table clientside.
I regard this a symptom of one or more of the following:
* I'm a lazy idiot and should have seen how to do it in SQL
* Set operations are not as expressive as procedural operations
* SQL is not as expressive as it should be
Did I do the right thing? Did I have other options?
|
You definitely should be able to do this exercise without doing the work equivalent to a `JOIN` in application code, i.e. by fetching all rows from both orderlines and products and iterating through them. You don't have to be an SQL wizard to do that one. **`JOIN` is to SQL what a loop is to a procedural language** -- in that both are fundamental language features that you should know how to use.
One trap people fall into is thinking that the whole report has to be produced in a single SQL query. Not true! Most reports don't fit into a rectangle, as Tony Andrews points out. There are lots of rollups, summaries, special cases, etc. so it's both simpler and more efficient to fetch parts of the report in separate queries. Likewise, in a procedural language you wouldn't try do all your computation in a single line of code, or even in a single function (hopefully).
Some reporting tools insist that a report is generated from a single query, and you have no opportunity to merge in multiple queries. If so, then you need to produce multiple reports (and if the boss wants it on one page, then you need to do some paste-up manually).
To get a list of **all products ordered (with product name), dates of last three purchases, and comment on latest order** is straightforward:
```
SELECT o.*, l.*, p.*
FROM Orders o
JOIN OrderLines l USING (order_id)
JOIN Products p USING (product_id)
WHERE o.customer_id = ?
ORDER BY o.order_date;
```
It's fine to iterate over the result row-by-row to extract the dates and comments on the latest orders, since you're fetching those rows anyway. But make it easy on yourself by asking the database to return the results sorted by date.
**Year of first purchase** is available from the previous query, if you sort by the `order_date` and fetch the result row-by-row, you'll have access to the first order. Otherwise, you can do it this way:
```
SELECT YEAR(MIN(o.order_date)) FROM Orders o WHERE o.customer_id = ?;
```
**Sum of product purchases for the last 12 months** is best calculated by a separate query:
```
SELECT SUM(l.quantity * p.price)
FROM Orders o
JOIN OrderLines l USING (order_id)
JOIN Products p USING (product_id)
WHERE o.customer_id = ?
AND o.order_date > CURDATE() - INTERVAL 1 YEAR;
```
**edit:** You said in another comment that you'd like to see how to get the dates of the last three purchases in standard SQL:
```
SELECT o1.order_date
FROM Orders o1
LEFT OUTER JOIN Orders o2
ON (o1.customer_id = o2.customer_id AND (o1.order_date < o2.order_date
OR (o1.order_date = o2.order_date AND o1.order_id < o2.order_id)))
WHERE o1.customer_id = ?
GROUP BY o1.order_id
HAVING COUNT(*) <= 3;
```
If you can use a wee bit of vendor-specific SQL features, you can use Microsoft/Sybase `TOP` *n*, or MySQL/PostgreSQL `LIMIT`:
```
SELECT TOP 3 order_date
FROM Orders
WHERE customer_id = ?
ORDER BY order_date DESC;
SELECT order_date
FROM Orders
WHERE customer_id = ?
ORDER BY order_date DESC
LIMIT 3;
```
|
> Set operations are not as expressive as procedural operations
Perhaps more like: "Set operations are not as familiar as procedural operations to a developer used to procedural languages" ;-)
Doing it iteratively as you have done now is fine for small sets of data, but simply doesn't scale the same way. The answer to whether you did the right thing depends on whether you are satisfied with the performance right now and/or don't expect the amount of data to increase much.
If you could provide some sample code, we might be able to help you find a set-based solution, which will be faster to begin with and scale far, far better. As GalacticCowboy mentioned, techniques such as temporary tables can help make the statements far more readable while largely retaining the performance benefits.
|
When do you give up set operations in SQL and go procedural?
|
[
"",
"sql",
"language-agnostic",
"procedural",
""
] |
I'm bored with surrounding code with try catch like this..
```
try
{
//some boring stuff
}
catch(Exception ex)
{
//something even more boring stuff
}
```
I would like something like
```
SurroundWithTryCatch(MyMethod)
```
I know I can accomplish this behaviour by creating a delegate with the exact signature of the function, but creating a delegate for all the methods in my application it's just not an option.
I can also do this by injecting IL code but this is expensive in terms of performance as it creates an wrapper assembly around mine.
Any other valid ideeas?
|
Firstly, it sounds like you may be using try/catch too often - particularly if you're catching `Exception`. try/catch blocks should be relatively rare; unless you can really "handle" the exception, you should just let it bubble up to the next layer of the stack.
Now, assuming you really *do* want all of these try/catch blocks, why is it not an option to create a delegate? With anonymous methods and lambda expressions, as well as the Func/Action delegates in the `System` namespace, there's basically very little work to do. You write:
```
public void SurroundWithTryCatch(Action action)
{
try
{
action();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
```
and then your `SurroundWithTryCatch(MyMethod)` will work fine, if it takes no paramaters.
Alternatively, if you don't want to call a *different* method, just write:
```
public void MyMethod()
{
SurroundWithTryCatch(() =>
{
// Logic here
});
}
```
If you need to return from the method, you can do:
```
public int MyMethod()
{
return SurroundWithTryCatch(() =>
{
// Logic here
return 5;
});
}
```
with a generic overload of `SurroundWithTryCatch` like this:
```
public T SurroundWithTryCatch<T>(Func<T> func)
{
try
{
return func();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
```
Most of this would be fine in C# 2 as well, but type inference won't help you quite as much and you'll have to use anonymous methods instead of lambda expressions.
To go back to the start though: try to use try/catch less often. (try/finally should be much more frequent, although usually written as a using statement.)
|
Aspect Oriented Programming could also help you, but this may require that you add libraries to your project, [postsharp](http://www.postsharp.org) would help you in this case.
See this link <http://doc.postsharp.org/1.0/index.html#http://doc.postsharp.org/1.0/UserGuide/Laos/AspectKinds/OnExceptionAspect.html#idHelpTOCNode650988000>
|
How to get rid of try catch?
|
[
"",
"c#",
"error-handling",
""
] |
I have a right outer join, that almost does what I want...
```
SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr
```
The problem is, I want to add a
```
where credit_acc.type_acc = 'init'
```
But this gets rid of all users who don't have a row in credit\_acc... which is WHY I need a right outer join.
Is there a way to get this without having to do two queries and a union?
|
```
SELECT
users_usr.firstname_usr,
users_usr.lastname_usr,
credit_acc.given_credit_acc,
users_usr.created_usr,
users_usr.sitenum_usr,
users_usr.original_aff_usr,
users_usr.id_usr
FROM
credit_acc
right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr
WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc is NULL
```
Or, as @Tomalak pointed out:
```
WHERE COALESCE(credit_acc.type_acc, 'init') = 'init'
```
which *may* be faster (see comments).
|
If the row doesn't exist, *credit\_acc.type\_acc* should be null. You could try something like this:
```
WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc IS NULL;
```
That will only work if there are no null fields in *credit\_acc.type\_acc*.
|
query join question
|
[
"",
"sql",
"mysql",
"join",
""
] |
Does everyone just use XML in the message? Are there any good alternatives to XML? If you do use XML, do you define an XML Schema so clients know how to send messages to your service?
|
We use XML, but I think the important thing is to tailor the solution to the problem. The reason we use XML is that we are basically sending an object across in the message. There's no reason it can't be plain text, if applicable for the message you are sending, using headers to send along properties if appropriate.
---
We haven't defined an XSD or DTD for our XML messages, but we do have a formal document describing their composition so that other teams can use our feeds without bugging us.
|
XML is probably the most popular along with JSON a close second - but as others have said in this thread - XML, CSV, JSON or even HTML are fine.
XSDs are overrated really - their only real value is if you want your clients/customers to code generate marshalling code (e.g. using JAXB) or if you want to let folks use XSDs in their editors / IDE to get smart completion
|
How do you format the body of a JMS text message?
|
[
"",
"java",
"jms",
""
] |
I'm running tomcat and have some jsp pages that display a subset of a table. I show 20 rows at a time on a single page. When the table has large amounts of data, the jsp page doesn't render. I'm guessing that the ResultSet is using a client side cursor. I've worked with ASP in the past, and we always used server side forward only cursors, and never had any problems with large amounts of data. Our database is oracle 10g.
How can I specify a server-side forward-only cursor in JDBC?
|
The oracle driver implements server-side cursors via the FetchSize property.
Unfortunately, JDBC doesn't explicitly allow for setting client vs server-side cursors, so different drivers implement it in different ways. Here are the other links that helped:
[Fetch Size](http://blog.lishman.com/2008/03/jdbc-fetch-size.html)
[Cursors](http://wiki.gxtechnical.com/commwiki/servlet/hwiki?Client+and+server+cursors+-+using+MySQL)
[Oracle Driver](http://www.rakeshv.org/docs/oracle/jdbc3.0/oracle/jdbc/OracleDriver.html)
|
```
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY);
ResultSet rs = stmt.executeQuery(sql);
```
This should set it but apparently *some* drivers ignore it.
You could always try and set it again at ResultSet level.
```
rs.setFetchDirection(ResultSet.TYPE_FORWARD_ONLY);
```
Hope that helps.
|
How to set Cursor type in JDBC?
|
[
"",
"java",
"oracle",
"jdbc",
"cursors",
""
] |
Is it possible to do a "C like" fork in java, using an new independent jvm process ?
How?
|
Funnily, I am just working on this: a Java process running other Java processes. I used the article [From Runtime.exec() to ProcessBuilder](https://www.java-tips.org/java-se-tips-100019/88888889-java-util/426-from-runtimeexec-to-processbuilder.html) as a solid base, and [When Runtime.exec() won't](https://www.infoworld.com/article/2071275/when-runtime-exec---won-t.html?page=2) as a good advice how to gobble the output streams.
PS.: For those wondering, I had to do that (instead of spawning new threads) because yet another Java process is checking the presence of these processes which are, normally, ran separately with shell commands.
|
This answer is probably a little late but:
<http://akuma.kohsuke.org/>
seems to be exactly what your looking for
|
Java - C-Like Fork?
|
[
"",
"java",
"c",
"fork",
""
] |
Almost every new Java-web-project is using a modern MVC-framework such as Struts or Spring MVC for the web tier, Spring for the "Service"/business-logic-layer and an ORM mapper such as Hibernate for persistence. What is the equivalent in .NET?
I guess ASP.NET is used for the web tier and ADO.NET for persistence but what is the equivalent to Spring, i.e. what is used to wire transactions and components and such.
I am aware of Spring.NET but I'm more interested in the de facto way of building applications in .NET.
|
The default approach is ADO.NET/Linq-to-Sql, ASP.NET and custom service layer that reinvents the wheel. Microsoft has Unity for autowiring, but I do not feel dependency injection is mainstream in .NET world yet.
But if you go for the best practices, it is ASP.NET MVC for UI, any DI framework (Castle,Unity,Autofac,...) for wiring, and NHibernate for persistence.
|
Something like this?
<http://www.asp.net/mvc/>
|
.NET equivalent of modern Java web architecture
|
[
"",
"java",
".net",
"spring",
"ado.net",
"transactions",
""
] |
Is there a native c++ variable type that's "bigger" than a double?
float is 7
double is 15 (of course depending on the compiler)
Is there anything bigger that's native, or even non-native?
|
C++ has `long double`, but there is no guarantee that it's any more precise than a plain `double`. On an x86 platform, usually `double` is 64 bits, and `long double` is either 64 or 80 bits (which gives you 19 significant figures, if I remember right).
Your mileage may vary, especially if you're not on x86.
|
A long double typically only uses 10 bytes, but due to alignment may actually take up 12 or 16 (depending on the compiler and options) bytes in a structure.
The 10 byte long double provides a 64-bit mantissa; this is very convenient for when you want to store 64 bit integers in floating point without loss of precision.
|
What's bigger than a double?
|
[
"",
"c++",
"types",
"variables",
""
] |
I'm building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code below:
```
class BaseModel {
/*
* Return an instance of a Model from the database.
*/
static public function get (/* varargs */) {
// 1. Notice we want an instance of User
$class = get_class(parent); // value: bool(false)
$class = get_class(self); // value: bool(false)
$class = get_class(); // value: string(9) "BaseModel"
$class = __CLASS__; // value: string(9) "BaseModel"
// 2. Query the database with id
$row = get_row_from_db_as_array(func_get_args());
// 3. Return the filled instance
$obj = new $class();
$obj->data = $row;
return $obj;
}
}
class User extends BaseModel {
protected $table = 'users';
protected $fields = array('id', 'name');
protected $primary_keys = array('id');
}
class Section extends BaseModel {
// [...]
}
$my_user = User::get(3);
$my_user->name = 'Jean';
$other_user = User::get(24);
$other_user->name = 'Paul';
$my_user->save();
$other_user->save();
$my_section = Section::get('apropos');
$my_section->delete();
```
Obviously, this is not the behavior I was expecting (although the actual behavior also makes sense).. So my question is if you guys know of a mean to get, in the parent class, the name of child class.
|
in short. this is not possible. in php4 you could implement a terrible hack (examine the `debug_backtrace()`) but that method does not work in PHP5. references:
* # [30423](http://bugs.php.net/bug.php?id=30423)
* # [37684](http://bugs.php.net/bug.php?id=37684)
* # [34421](http://bugs.php.net/bug.php?id=34421)
**edit**: an example of late static binding in PHP 5.3 (mentioned in comments). note there are potential problems in it's current implementation ([src](https://web.archive.org/web/20120209224705/http://www.digitalsandwich.com/archives/65-Late-static-binding....sorta.html)).
```
class Base {
public static function whoAmI() {
return get_called_class();
}
}
class User extends Base {}
print Base::whoAmI(); // prints "Base"
print User::whoAmI(); // prints "User"
```
|
You don't need to wait for PHP 5.3 if you're able to conceive of a way to do this outside of a static context. In php 5.2.9, in a non-static method of the parent class, you can do:
```
get_class($this);
```
and it will return the name of the child class as a string.
i.e.
```
class Parent() {
function __construct() {
echo 'Parent class: ' . get_class() . "\n" . 'Child class: ' . get_class($this);
}
}
class Child() {
function __construct() {
parent::construct();
}
}
$x = new Child();
```
this will output:
```
Parent class: Parent
Child class: Child
```
sweet huh?
|
Getting the name of a child class in the parent class (static context)
|
[
"",
"php",
"inheritance",
"static-methods",
""
] |
I want to discover at run-time ONLY the static Methods of a class, how can I do this?
Or, how to differentiate between static and non-static methods.
|
Use `Modifier.isStatic(method.getModifiers())`.
```
/**
* Returns the public static methods of a class or interface,
* including those declared in super classes and interfaces.
*/
public static List<Method> getStaticMethods(Class<?> clazz) {
List<Method> methods = new ArrayList<Method>();
for (Method method : clazz.getMethods()) {
if (Modifier.isStatic(method.getModifiers())) {
methods.add(method);
}
}
return Collections.unmodifiableList(methods);
}
```
Note: This method is actually dangerous from a security standpoint. Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (see section 6 of the Java secure coding guidelines).
Disclaimer: Not tested or even compiled.
Note `Modifier` should be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.
|
You can get the static methods like this:
```
for (Method m : MyClass.class.getMethods()) {
if (Modifier.isStatic(m.getModifiers()))
System.out.println("Static Method: " + m.getName());
}
```
|
How can I check if a method is static using reflection?
|
[
"",
"java",
"reflection",
""
] |
I am writing some new code that will throw a custom exception - I want to include an error string and a status code. Which class should be exception derive from? `std::exception`? `std::runtime_error`? Any other 'gotchas' to worry about? I'm thinking of something like the following:
```
class MyException : public std::exception(?)
{
public:
enum Status
{
ERROR_FOO,
ERROR_BAR,
...
};
MyException(const std::string& error, Status code) :
error_(error), code_(code)
{
...
}
virtual const char* what() const
{
return error_.c_str();
}
Status code() const
{
return code_;
}
private:
std::string error_;
Status code_;
};
```
Then in the code:
```
throw MyException("Ooops!", MyException::ERROR_BAR);
```
|
Boost has a great document on [error and exception](http://www.boost.org/community/error_handling.html) handling which talks about common gotchas and how to properly inherit from std::exception(s).
|
Consider whether the status code is really appropriate. It's usually superior to create a hierarchy of exception classes. This way, the caller can better control which exceptions to treat and how and it makes the interface simpler.
Of course, sometimes status codes are still appropriate (compilers use them all the time).
|
Rolling my own exceptions
|
[
"",
"c++",
"exception",
""
] |
I have 2 handlers using the same form. How do I remove the handlers before adding the new one (C#)?
|
If you are working in the form itself, you should be able to do something like:
PseudoCode:
```
Delegate[] events = Form1.SomeEvent.GetInvokationList();
foreach (Delegate d in events)
{
Form1.SomeEvent -= d;
}
```
From outside of the form, your SOL.
|
If you know what those handlers are, just remove them in the same way that you subscribed to them, except with -= instead of +=.
If you don't know what the handlers are, you can't remove them - the idea being that the event encapsulation prevents one interested party from clobbering the interests of another class in observing an event.
EDIT: I've been assuming that you're talking about an event implemented by a different class, e.g. a control. If your class "owns" the event, then just set the relevant variable to null.
|
How do I unregister all handlers for a form event?
|
[
"",
"c#",
"handler",
""
] |
I have an enumeration value marked with the following attribute. The second parameter instructs the compiler to error whenever the value is used. I want this behavior for anyone that implements my library, but I need to use this enumeration value within my library. How do I tell the compiler to ignore the Obsolete error for the couple of uses in my library.
```
public enum Choices
{
One,
Two,
[ObsoleteAttribute("don't use me", true)]
Three,
Four
}
```
---
Solution (Thanks everyone)
```
public class EnumHack
{
static EnumHack()
{
// Safety check
if (Choices!= (Choices)Enum.Parse(typeof(Choices), "Three"))
throw new Exception("Choices.Three != 3; Who changed my Enum!");
}
[Obsolete("Backwards compatible Choices.Three", false)]
public const Choices ChoicesThree = (Choices)3;
}
```
|
Private a separate constant somewhere like this:
```
private const Choices BackwardsCompatibleThree = (Choices) 3;
```
Note that anyone else will be able to do the same thing.
|
What about using #pragma to disable the warning around the specfic code?
```
#pragma warning disable 0612
// Call obsolete type/enum member here
#pragma warning restore 0612
```
A note to visitors, this only works with types and enum members. As far as I am aware, this will not work with other type members (e.g. methods, properties, etc).
|
Ignore ObsoleteAttribute Compiler Error
|
[
"",
"c#",
""
] |
I'm playing around at the start of a personal project in C# and MySQL.
I am familiar with the use of the Gentle Framework (using MyGeneration to generate the classes, based on the data model). Here's what I like about Gentle;
* Simple-to-use [class].Retrieve(id) / [object].Persist() semantics with strong-typing of fields;
* I start with the DB data model, and choose when to generate new code files;
* MyGeneration allows for some 'manual code sections' which are kept across generations...
* ...and partial classes allow me to add permanent code in parallel files, e.g. simple read-only properties (like 'FullName' from FirstName and Surname members for a Person object) - or I could use inheritance;
* I find it a tolerable and quick way to create a DAL, and add certain Business-Object-Layer-like facilities to it.
Unfortunately, to query efficiently, I end up using queries / SqlCommands a fair bit, and relies on weakly typed references to column names etc., and appears to risk sidestepping the object broker and therefore caching advantages. In any event, Gentle is no longer being developed, and it seems like a good time to consider alternatives.
So, what should I consider?
* Generation of strongly-typed ADO Datasets is possible, but it seems like it will be difficult to add to it (e.g. that 'FullName' virtual column) in a way that will persist after updates to the table structure with regeneration of the dataset.
* NHibernate seems to have lots of fans... but my first looks into it seem to suggest that the XML data definition is king, not the existing data-model in the DB. It also looks quite heavy on dependencies;
* The SubSonic demo appears to suggest it generates files, and in the demo of WebAppProjects, looks like it might generate files in a way that I could add to, or inherit from;
* The MySql Connector.Net tools appear not to support the dataset generation for Linq (e.g. via drag-and-drop), and I suspect that this is a key need for strongly-typed data access.
Your thoughts will be gratefully appreciated! Thank you in advance...
|
[link text](http://weblogs.asp.net/zowens/archive/2007/09/18/subsonic-of-the-day-collections.aspx)I would go for Subsonic, mature DAL generator and improves productivity by great margin.
We have used it with both MySQL and SQL Server - no headaches. Generates classes for Tables, Stored procedures, column names. So every time we find ourselves doing Somthing Dot Intellisense Move Arrow keys and semicolon.
Any time your schema changes, you can regenerate those classes and you are home. Also, you can extend them by creating partial classes.
It supports almost all of the SQL Semantics - Joins, loading Collection by primary key, adding WHERE clause, Order by, Count, Top, Calling stored procedures, views and so on and Intuitive syntax is big plus.
To give you some glimpse- For Books table[BookID-PK, title, AuthorID], It generates several types of methods.
* Insert method which takes Title, AuthorID
* Nullable columns are optional
parameters a.k.a C# Nullable type ?
* Update method wich takes BookID, AuthorID, Title
* Load Book by Primary key (Useful when displaying detail page)
* BookCollection and Book Entities, Just call BookCollection.Load and you have list of books ready to bind to any databound control
Here's quick link.
Thanks,
Maulik Modi
|
I had some experience with Gentle and I do have to admit that it was pretty inefficient with queries. I would suggest looking into NHibernate, since it has a rich community. It is true that XML definitions are preferred, but there are ways of doing the mappings using class-level attributes.
SubSonic (especially the [3.0 version](http://blog.wekeroad.com/tags/subsonic/)) looks very promising with its use of [T4 templates](http://blog.wekeroad.com/blog/make-visual-studio-generate-your-repository/). That should give you more control over code generation. It can do LINQ too.
Don't invest in LINQ-to-SQL, since the rumors are that is going to be discontinued.
|
C# and MySQL - Gentle Framework alternatives
|
[
"",
"c#",
"orm",
""
] |
can you set SO\_RCVTIMEO and SO\_SNDTIMEO socket options in boost asio?
If so how?
Note I know you can use timers instead, but I'd like to know about these socket options in particular.
|
Absolutely! Boost ASIO allows you to access the native/underlying data, which in this case is the SOCKET itself. So, let's say you have:
```
boost::asio::ip::tcp::socket my_socket;
```
And let's say you've already called `open` or `bind` or some member function that actually makes `my_socket` usable. Then, to get the underlying SOCKET value, call:
```
SOCKET native_sock = my_socket.native();
int result = SOCKET_ERROR;
if (INVALID_SOCKET != native_sock)
{
result = setsockopt(native_sock, SOL_SOCKET, <the pertinent params you want to use>);
}
```
So there you have it! Boost's ASIO lets you do many things more quickly than you otherwise might be able to, but there are a lot of things you still need the normal socket library calls for. This happens to be one of them.
|
It doesn't appear to be built into Boost.Asio (as of current Boost SVN), but, if you're willing to write your own classes to simulate the `boost::asio::detail::socket_option` ones, you can always follow the examples in `boost/asio/socket_base.hpp` and do the following:
```
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_SNDTIMEO>
send_timeout;
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_RCVTIMEO>
receive_timeout;
```
(Obviously, I'm not suggesting you inject the `timeval` class into the `boost::asio::detail::socket_option` namespace, but I can't think of a good one to use at the moment. :-P)
Edit: My sample implementation of `socket_option::timeval`, based on `socket_option::integer`:
```
// Helper template for implementing timeval options.
template <int Level, int Name>
class timeval
{
public:
// Default constructor.
timeval()
: value_(zero_timeval())
{
}
// Construct with a specific option value.
explicit timeval(::timeval v)
: value_(v)
{
}
// Set the value of the timeval option.
timeval& operator=(::timeval v)
{
value_ = v;
return *this;
}
// Get the current value of the timeval option.
::timeval value() const
{
return value_;
}
// Get the level of the socket option.
template <typename Protocol>
int level(const Protocol&) const
{
return Level;
}
// Get the name of the socket option.
template <typename Protocol>
int name(const Protocol&) const
{
return Name;
}
// Get the address of the timeval data.
template <typename Protocol>
::timeval* data(const Protocol&)
{
return &value_;
}
// Get the address of the timeval data.
template <typename Protocol>
const ::timeval* data(const Protocol&) const
{
return &value_;
}
// Get the size of the timeval data.
template <typename Protocol>
std::size_t size(const Protocol&) const
{
return sizeof(value_);
}
// Set the size of the timeval data.
template <typename Protocol>
void resize(const Protocol&, std::size_t s)
{
if (s != sizeof(value_))
throw std::length_error("timeval socket option resize");
}
private:
static ::timeval zero_timeval()
{
::timeval result = {};
return result;
}
::timeval value_;
};
```
|
can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?
|
[
"",
"c++",
"boost",
"boost-asio",
""
] |
I'm trying to add a pojo to a collection in another pojo. I'm sure I'm making a really stupid mistake somewhere along the lines but I can't figure out how to solve it.
I have a pojo LookupTable which contains a list of Columns:
```
public class LookupTable {
private long id;
// More properties go here...
private List<Column> columns;
public void addColumn(Column column) {
this.columns.add(column);
}
// More methods go here...
}
```
In my hibernate configuration I have:
```
<class name="LookupTable" table="ARR_LOOKUP_TABLE">
<id name="id" column="ID">
<generator class="native"/>
</id>
<!-- Some properties here -->
<bag name="columns" cascade="all,delete-orphan" access="field">
<key column="LOOKUP_TABLE" not-null="true"/>
<one-to-many class="Column"/>
</bag>
</class>
<class name="Column" table="ARR_LOOKUP_COLUMN">
<id name="id" column="ID">
<generator class="native"/>
</id>
<!-- Some properties here -->
</class>
```
In my Spring config file I have:
```
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="managers" expression="execution(public * com.foo.*Manager.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="managers"/>
</aop:config>
```
And finally the code where it all fails within my manager class (com.foo.LookupTableManager):
```
public void addColumnToTable(Column column, long tableId) {
LookupTable lookupTable = this.lookupTableDao.findById(tableId);
lookupTable.addColumn(column);
this.lookupTableDao.saveOrUpdate(lookupTable);
}
```
The variable lookupTableDao here refers to a simple DAO class which extends HibernateDaoSupport.
The error I get is:
```
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:43)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:293)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.foo.AbstractDao.saveOrUpdate(AbstractDao.java:29)
at com.foo.LookupTableManager.addColumnToTable(LookupTableManager.java:338)
... etc ...
```
OK, I understand the basic message I'm getting. But what I don't understand is where I get the second session.... Can anyone help me with this?
I'm using Hibernate 3.2.6.ga, Spring 2.5.5 and Tomcat 6.0
|
Turns out I didn't have a transaction at all. I used almost the same transaction configuration in one of my other config files.
The pointcut over there was also called "managers", so my advisor here was referencing the pointcut in the other file.
*Renaming the pointcut solved my problem.*
|
My guess is that the `lookupTableDao.findById` call is getting your object in one session, but the `lookupTableDao.saveOrUpdate` is a different one - how do you get the `Session` object, via Spring?
Where is the `Column` object coming from - is that already on the DB or new?
|
Illegal attempt to associate a collection with two open sessions
|
[
"",
"java",
"hibernate",
"spring",
"transactions",
""
] |
If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?
For example:
I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so
```
import MyLib
ReallyBigLib = MyLib.SomeModule.ReallyBigLib
```
or just
```
import MyLib
import ReallyBigLib
```
|
Python modules could be considered as singletons... no matter how many times you import them they get initialized only once, so it's better to do:
```
import MyLib
import ReallyBigLib
```
Relevant documentation on the import statement:
<https://docs.python.org/2/reference/simple_stmts.html#the-import-statement>
> Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.
The imported modules are cached in [sys.modules](https://docs.python.org/2/library/sys.html#sys.modules):
> This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.
|
As others have pointed out, Python maintains an internal list of all modules that have been imported. When you import a module for the first time, the module (a script) is executed in its own namespace until the end, the internal list is updated, and execution of continues after the import statement.
Try this code:
```
# module/file a.py
print "Hello from a.py!"
import b
# module/file b.py
print "Hello from b.py!"
import a
```
There is no loop: there is only a cache lookup.
```
>>> import b
Hello from b.py!
Hello from a.py!
>>> import a
>>>
```
One of the beauties of Python is how everything devolves to executing a script in a namespace.
|
Does python optimize modules when they are imported multiple times?
|
[
"",
"python",
"python-import",
""
] |
I know that most people recommend using HttpRuntime.Cache because it has more flexibility... etc. But what if you want the object to persist in the cache for the life of the application? Is there any big downside to using the Application[] object to cache things?
|
As long as you don't abuse the application state, then I don't see a problem in using it for items that you don't want to expire.
Alternatively I would probably use a static variable near the code that uses it. That way you avoid to go through `HttpApplicationState` and then be forced to have a reference to System.Web if i want to access my data.
But be sure to think through how you use the object(s) that you store in `HttpApplicationState`. If it's a `DataSet` which you keep adding stuff to for each request, then at some point you end up eating up too much memory on the web-server. The same could happen if you keep adding items to `HttpApplicationState` when you process requests, at some point you will force the application to restart.
That's probably the advantage of using Cache in your situation. Consuming larger amounts memory isn't as fatal because you allow ASP.NET to release the items in your cache when memory becomes scarce.
|
Application is deprecated by Cache. If you need something with application scope, then you should either create it as a static member of a class or use the Cache. If you want to go the Cache route but don't ever want it to expire, you should use the CacheItemPriority.NotRemovable option when you Insert the value into the cache. Note that it is possible to use this priority and still use cache dependencies, for instance if your data depended on something in the file system. All the CacheItemPriority does is prevent the HttpRuntime.Cache from intelligently clearing the item when it feels memory pressure and uses its Least-Recently-Used algorithm to purge items that aren't seeing much use.
|
HttpRuntime.Cache[] vs Application[]
|
[
"",
"c#",
"asp.net",
"caching",
"httpruntime.cache",
""
] |
Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out.
Where can one find a good list of swear words in various languages and dialects?
Are there APIs available to sources that contain good lists? Or maybe an API that simply says "yes this is clean" or "no this is dirty" with some parameters?
What are some good methods for catching folks trying to trick the system, like a$$, azz, or a55?
Bonus points if you offer solutions for PHP. :)
## *Edit: Response to answers that say simply avoid the programmatic issue:*
I think there is a place for this kind of filter when, for instance, a user can use public image search to find pictures that get added to a sensitive community pool. If they can search for "penis", then they will likely get many pictures of, yep. If we don't want pictures of that, then preventing the word as a search term is a good gatekeeper, though admittedly not a foolproof method. Getting the list of words in the first place is the real question.
So I'm really referring to a way to figure out of a single token is dirty or not and then simply disallow it. I'd not bother preventing a sentiment like the totally hilarious "long necked giraffe" reference. Nothing you can do there. :)
|
[Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?](http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/)
Also, one can't forget [The Untold History of Toontown's SpeedChat](http://habitatchronicles.com/2007/03/the-untold-history-of-toontowns-speedchat-or-blockchattm-from-disney-finally-arrives/), where even using a "safe-word whitelist" resulted in a 14-year-old quickly circumventing it with:
*"I want to stick my long-necked Giraffe up your fluffy white bunny."*
Bottom line: Ultimately, for any system that you implement, there is absolutely no substitute for human review (whether peer or otherwise). Feel free to implement a rudimentary tool to get rid of the drive-by's, but for the determined troll, you absolutely must have a non-algorithm-based approach.
A system that removes anonymity and introduces accountability (something that Stack Overflow does well) is helpful also, particularly in order to help combat [John Gabriel's G.I.F.T.](http://www.penny-arcade.com/comic/2004/03/19/)
You also asked where you can get profanity lists to get you started -- one open-source project to check out is [Dansguardian](http://dansguardian.org) -- check out the source code for their default profanity lists. There is also an additional third party [Phrase List](http://contentfilter.futuragts.com/phraselists/) that you can download for the proxy that may be a helpful gleaning point for you.
**Edit in response to the question edit:** Thanks for the clarification on what you're trying to do. In that case, if you're just trying to do a simple word filter, there are two ways you can do it. One is to create a single long regexp with all of the banned phrases that you want to censor, and merely do a regex find/replace with it. A regex like:
```
$filterRegex = "(boogers|snot|poop|shucks|argh)"
```
and run it on your input string using [preg\_match()](http://us.php.net/preg_match) to wholesale test for a hit,
or [preg\_replace()](http://us.php.net/preg_replace) to blank them out.
You can also load those functions up with arrays rather than a single long regex, and for long word lists, it may be more manageable. See the [preg\_replace()](http://us.php.net/preg_replace) for some good examples as to how arrays can be used flexibly.
For additional PHP programming examples, see this page for a [somewhat advanced generic class](http://www.bitrepository.com/advanced-word-filter.html) for word filtering that \*'s out the center letters from censored words, and this [previous Stack Overflow question](https://stackoverflow.com/questions/24515/bad-words-filter) that also has a PHP example (the main valuable part in there is the SQL-based filtered word approach -- the leet-speak compensator can be dispensed with if you find it unnecessary).
You also added: "*Getting the list of words in the first place is the real question.*" -- in addition to some of the previous Dansgaurdian links, you may find [this handy .zip](http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/) of 458 words to be helpful.
|
Whilst I know that this question is fairly old, but it's a commonly occurring question...
There is both a reason and a distinct need for profanity filters (see [Wikipedia entry here](http://en.wikipedia.org/wiki/Profanity_filter)), but they often fall short of being 100% accurate for very distinct reasons; **Context** and **accuracy**.
It depends (wholly) on what you're trying to achieve - at it's most basic, you're probably trying to cover the "[seven dirty words](http://en.wikipedia.org/wiki/Seven_dirty_words)" and then some... Some businesses need to filter the most basic of profanity: basic swear words, URLs or even personal information and so on, but others need to prevent illicit account naming (Xbox live is an example) or far more...
User generated content doesn't just contain potential swear words, it can also contain offensive references to:
* Sexual acts
* Sexual orientation
* Religion
* Ethnicity
* Etc...
And potentially, in multiple languages. Shutterstock has developed [basic dirty-words lists](https://github.com/shutterstock/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words) in 10 languages to date, but it's still basic and very much oriented towards their 'tagging' needs. There are a number of other lists available on the web.
I agree with the accepted answer that it's not a defined science and *as* language is a continually evolving *challenge* but one where a 90% catch rate is better than 0%. It depends purely on your goals - what you're trying to achieve, the level of support you have and how important it is to remove profanities of different types.
In building a filter, you need to consider the following elements and how they relate to your project:
* Words/phrases
* Acronyms (FOAD/LMFAO etc)
* [False positives](http://en.wikipedia.org/wiki/False_positive#Type_I_error) (words, places and names like 'mishit', 'scunthorpe' and 'titsworth')
* URLs (porn sites are an obvious target)
* Personal information (email, address, phone etc - if applicable)
* Language choice (usually English by default)
* Moderation (how, if at all, you can interact with user generated content and what you can do with it)
You can easily build a profanity filter that captures 90%+ of profanities, but you'll never hit 100%. It's just not possible. The closer you want to get to 100%, the harder it becomes... Having built a complex profanity engine in the past that dealt with more than 500K realtime messages per day, I'd offer the following advice:
**A basic filter would involve:**
* Building a list of applicable profanities
* Developing a method of dealing with derivations of profanities
**A moderately complex filer would involve, (In addition to a basic filter):**
* Using complex pattern matching to deal with extended derivations (using advanced regex)
* Dealing with [Leetspeak](http://en.wikipedia.org/wiki/Leet) (l33t)
* Dealing with [false positives](http://en.wikipedia.org/wiki/False_positive#Type_I_error)
**A complex filter would involve a number of the following (In addition to a moderate filter):**
* [Whitelists](http://en.wikipedia.org/wiki/White_list) and blacklists
* [Naive bayesian inference](http://en.wikipedia.org/wiki/Bayesian_inference) filtering of phrases/terms
* [Soundex](http://en.wikipedia.org/wiki/Soundex) functions (where a word sounds like another)
* [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance)
* [Stemming](http://en.wikipedia.org/wiki/Porter_Stemmer)
* Human moderators to help guide a filtering engine to learn by example or where matches aren't accurate enough without guidance (a self/continually-improving system)
* Perhaps some form of AI engine
|
How do you implement a good profanity filter?
|
[
"",
"php",
"regex",
"user-input",
""
] |
I want do something like this:
```
Button btn1 = new Button();
btn1.Click += new EventHandler(btn1_Click);
Button btn2 = new Button();
// Take whatever event got assigned to btn1 and assign it to btn2.
btn2.Click += btn1.Click; // The compiler says no...
```
Where btn1\_Click is already defined in the class:
```
void btn1_Click(object sender, EventArgs e)
{
//
}
```
This won't compile, of course ("The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -="). Is there a way to take the event handler from one control and assign it to another at runtime? If that's not possible, is duplicating the event handler and assigning it to another control at runtime doable?
A couple of points: I have googled the heck out of this one for awhile and found no way of doing it yet. Most of the attempted approaches involve reflection, so if you read my question and think the answer is incredibly obvious, please try to compile the code in Visual Studio first. Or if the answer really is incredibly obvious, please feel free to slap me with it. Thanks, I'm really looking forward to seeing if this is possible.
I know I could just do this:
```
btn2.Click += new EventHandler(btn1_Click);
```
That's not what I'm looking for here.
This is also not what I'm looking for:
```
EventHandler handy = new EventHandler(btn1_Click);
Button btn1 = new Button();
btn1.Click += handy;
Button btn2 = new Button();
btn2.Click += handy;
```
|
Yeah, it's technically possible. Reflection is required because many of the members are private and internal. Start a new [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) project and add two buttons. Then:
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
button1.Click += new EventHandler(button1_Click);
// Get secret click event key
FieldInfo eventClick = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static);
object secret = eventClick.GetValue(null);
// Retrieve the click event
PropertyInfo eventsProp = typeof(Component).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList events = (EventHandlerList)eventsProp.GetValue(button1, null);
Delegate click = events[secret];
// Remove it from button1, add it to button2
events.RemoveHandler(secret, click);
events = (EventHandlerList)eventsProp.GetValue(button2, null);
events.AddHandler(secret, click);
}
void button1_Click(object sender, EventArgs e) {
MessageBox.Show("Yada");
}
}
}
```
If this convinces you that Microsoft tried really hard to prevent your from doing this, you understood the code.
|
No, you can't do this. The reason is encapsulation - events are *just* subscribe/unsubscribe, i.e. they don't let you "peek inside" to see what handlers are already subscribed.
What you *could* do is derive from Button, and create a public method which calls `OnClick`. Then you just need to make `btn1` an instance of that class, and subscribe a handler to `btn2` which calls `btn1.RaiseClickEvent()` or whatever you call the method.
I'm not sure I'd really recommend it though. What are you actually trying to do? What's the bigger picture?
EDIT: I see you've accepted the version which fetches the current set of events with reflection, but in case you're interested in the alternative which calls the OnXXX handler in the original control, I've got a sample here. I originally copied *all* events, but that leads to some very odd effects indeed. Note that this version means that if anyone subscribes to an event in the original button *after* calling CopyEvents, it's still "hooked up" - i.e. it doesn't really matter when you associate the two.
```
using System;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
class Test
{
static void Main()
{
TextBox output = new TextBox
{
Multiline = true,
Height = 350,
Width = 200,
Location = new Point (5, 15)
};
Button original = new Button
{
Text = "Original",
Location = new Point (210, 15)
};
original.Click += Log(output, "Click!");
original.MouseEnter += Log(output, "MouseEnter");
original.MouseLeave += Log(output, "MouseLeave");
Button copyCat = new Button
{
Text = "CopyCat",
Location = new Point (210, 50)
};
CopyEvents(original, copyCat, "Click", "MouseEnter", "MouseLeave");
Form form = new Form
{
Width = 400,
Height = 420,
Controls = { output, original, copyCat }
};
Application.Run(form);
}
private static void CopyEvents(object source, object target, params string[] events)
{
Type sourceType = source.GetType();
Type targetType = target.GetType();
MethodInfo invoker = typeof(MethodAndSource).GetMethod("Invoke");
foreach (String eventName in events)
{
EventInfo sourceEvent = sourceType.GetEvent(eventName);
if (sourceEvent == null)
{
Console.WriteLine("Can't find {0}.{1}", sourceType.Name, eventName);
continue;
}
// Note: we currently assume that all events are compatible with
// EventHandler. This method could do with more error checks...
MethodInfo raiseMethod = sourceType.GetMethod("On"+sourceEvent.Name,
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic);
if (raiseMethod == null)
{
Console.WriteLine("Can't find {0}.On{1}", sourceType.Name, sourceEvent.Name);
continue;
}
EventInfo targetEvent = targetType.GetEvent(sourceEvent.Name);
if (targetEvent == null)
{
Console.WriteLine("Can't find {0}.{1}", targetType.Name, sourceEvent.Name);
continue;
}
MethodAndSource methodAndSource = new MethodAndSource(raiseMethod, source);
Delegate handler = Delegate.CreateDelegate(sourceEvent.EventHandlerType,
methodAndSource,
invoker);
targetEvent.AddEventHandler(target, handler);
}
}
private static EventHandler Log(TextBox output, string text)
{
return (sender, args) => output.Text += text + "\r\n";
}
private class MethodAndSource
{
private readonly MethodInfo method;
private readonly object source;
internal MethodAndSource(MethodInfo method, object source)
{
this.method = method;
this.source = source;
}
public void Invoke(object sender, EventArgs args)
{
method.Invoke(source, new object[] { args });
}
}
}
```
|
Is it possible to "steal" an event handler from one control and give it to another?
|
[
"",
"c#",
".net",
""
] |
I have a XML Structure that looks like this.
```
<sales>
<item name="Games" sku="MIC28306200" iCat="28"
sTime="11/26/2008 8:41:12 AM"
price="1.00" desc="Item Name" />
<item name="Games" sku="MIC28307100" iCat="28"
sTime="11/26/2008 8:42:12 AM"
price="1.00" desc="Item Name" />
...
</sales>
```
I am trying to find a way to SORT the nodes based on the sTime attribute which is a DateTime.ToString() value. The trick is I need to keep the Nodes in tact and for some reason I can't find a way to do that. I'm fairly certain that LINQ and XPath have a way to do it, but I'm stuck because I can't seem to sort based on DateTime.ToString() value.
```
XPathDocument saleResults = new XPathDocument(@"temp/salesData.xml");
XPathNavigator navigator = saleResults.CreateNavigator();
XPathExpression selectExpression = navigator.Compile("sales/item/@sTime");
selectExpression.AddSort("@sTime",
XmlSortOrder.Descending,
XmlCaseOrder.None,
"",
XmlDataType.Number);
XPathNodeIterator nodeIterator = navigator.Select(selectExpression);
while( nodeIterator.MoveNext() )
{
string checkMe = nodeIterator.Current.Value;
}
```
I also need to maintain a pointer to the NODE to retrieve the values of the other attributes.
Perhaps this isn't a simple as I thought it would be.
Thanks.
**Solution**: Here's what I ended up using. Taking the selected answer and the IComparable class this is how I get the XML nodes sorted based on the sTime attribute and then get the all the attributes into the appropriate Arrays to be used later.
```
XPathDocument saleResults = new XPathDocument(@"temp/salesData.xml");
XPathNavigator navigator = saleResults.CreateNavigator();
XPathExpression selectExpression = navigator.Compile("sales/item");
XPathExpression sortExpr = navigator.Compile("@sTime");
selectExpression.AddSort(sortExpr, new DateTimeComparer());
XPathNodeIterator nodeIterator = navigator.Select(selectExpression);
int i = 0;
while (nodeIterator.MoveNext())
{
if (nodeIterator.Current.MoveToFirstAttribute())
{
_iNameList.SetValue(nodeIterator.Current.Value, i);
}
if (nodeIterator.Current.MoveToNextAttribute())
{
_iSkuList.SetValue(nodeIterator.Current.Value, i);
}
...
nodeIterator.Current.MoveToParent();
i++;
}
```
|
There's an overload of XPathExpression.Addsort which takes an IComparer interface. If you implement the comparison yourself as IComparer, you could use this mechanism.
```
class Program
{
static void Main(string[] args)
{
XPathDocument saleResults = new XPathDocument( @"salesData.xml" );
XPathNavigator navigator = saleResults.CreateNavigator( );
XPathExpression selectExpression = navigator.Compile( "sales/item" );
XPathExpression sortExpr = navigator.Compile("@sTime");
selectExpression.AddSort(sortExpr, new DateTimeComparer());
XPathNodeIterator nodeIterator = navigator.Select( selectExpression );
while ( nodeIterator.MoveNext( ) )
{
string checkMe = nodeIterator.Current.Value;
}
}
public class DateTimeComparer : IComparer
{
public int Compare(object x, object y)
{
DateTime dt1 = DateTime.Parse( x.ToString( ) );
DateTime dt2 = DateTime.Parse( y.ToString( ) );
return dt1.CompareTo( dt2 );
}
}
}
```
|
Here you go:
```
XmlDocument myDoc = new XmlDocument();
myDoc.LoadXml(@"
<sales>
<item name=""Games""
sku=""MIC28306200""
iCat=""28""
sTime=""11/26/2008 8:41:12 AM""
price=""1.00""
desc=""Item Name"" />
<item name=""Games""
sku=""MIC28307100""
iCat=""28""
sTime=""11/26/2008 8:42:12 AM""
price=""1.00""
desc=""Item Name"" />
</sales>
");
var sortedItems = myDoc.GetElementsByTagName("item").OfType<XmlElement>()
.OrderBy(item => DateTime.ParseExact(item.GetAttribute("sTime"), "MM/dd/yyyy h:mm:ss tt", null));
foreach (var item in sortedItems)
{
Console.WriteLine(item.OuterXml);
}
```
That's a Console app that works perfectly.
|
Sorting XML nodes based on DateTime attribute C#, XPath
|
[
"",
"c#",
"xml",
"sorting",
"xpath",
""
] |
First off, I apologize if this doesn't make sense. I'm new to XHTML, CSS and JavaScript.
I gather that in XHTML, the correct way to have a nested page is as follows (instead of an iframe):
```
<object name="nestedPage" data="http://abc.com/page.html" type="text/html"
width="500" height="400" />
```
If I have a nested page like that - is it possible to change the stylesheet used by the nested page at runtime using JavaScript in the parent page? Ideally this would happen immediately so that the nested page would never be visible with its original stylesheet.
Please assume that you do not have control of the original source code of the nested page, yet it is **on the same domain** (don't ask)
|
```
d = document.getElementsByTagName('object').namedItem('nestedPage').getContentDocument();
d.styleSheets[d.styleSheets.length].href = 'whereever';
```
WARNING: hasn't been tested in all browsers.
|
I'd suggest using an iframe for this, I don't know if the object-way of doing this is supported as well.
Anyway, after the page from the same domain has loaded, you can access all its properties via javascript.
For example, in jQuery, you'd use to change the css-file.
```
$("link [rel=stylesheet]", myFrame).attr('href', <new-url>);
```
with myFrame a reference to your iframe object.
|
Changing the stylesheet of a nested page at runtime
|
[
"",
"javascript",
"css",
"xhtml",
""
] |
I have several aspx pages that can be opened either normally (full screen in browser), or called from another page as a popup (I am using Greybox, fwiw)
If the page is opened as a popup in Greybox, I would like to NOT display the master page content (which displays common top and left menus, etc).
As far as I know, there is no way of knowing server side if the page is a popup, this must be detected in client side javascript (in the case of Greybox, by checking window.parent.parent), and therefore the master page content must be hidden via javascript as well.
Any ideas on how to approach this?
|
Create a simplified master page for the popup. Override the OnPreInit method (of the actual page) and switch out the masterpage based on a querystring argument:
```
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if(Request["PopUp"] == "Y")
{
MasterPageFile = "~/MyPopUp.master";
}
}
```
|
Well you could conditionally render the navigation controls etc. based on a querystring, pass the string in when it's a popup and if it exists don't render the controls. There are a few different ways to do it, but I think you should have the server not render the controls rather than client side hiding them.
P.S. Haven't heard of Greybox so I can't offer any specific insight there.
|
Is it possible to hide the content of an asp.net master page, if page is opened as a popup?
|
[
"",
"asp.net",
"javascript",
""
] |
I'm trying to do something like
```
URL clientks = com.messaging.SubscriptionManager.class.getResource( "client.ks" );
String path = clientks.toURI().getPath();
System.setProperty( "javax.net.ssl.keyStore", path);
```
Where client.ks is a file stored in com/messaging in the jar file that I'm running.
The thing that reads the javax.net.ssl.keyStore is expecting a path to the client.ks file which is in the jar. I'd rather not extract the file and put in on the client's machine if possible. So is it possible to reference a file in a jar?
This doesn't work as getPath() returns null. Is there another way to do this?
|
Still working on implementation, but I believe it is possible to load the keystore from the jar via InputStream and explicitly set the TrustStore programatically (vs setting the System properties). See the article: [Setting multiple truststore on the same JVM](https://stackoverflow.com/questions/7591281/setting-multiple-truststore-on-the-same-jvm)
Got it working!
```
InputStream keystoreInput = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(<path in jar>/client.ks");
InputStream truststoreInput = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(<path in jar>/client.ts");
setSSLFactories(keystoreInput, "password", truststoreInput);
keystoreInput.close();
truststoreInput.close();
private static void setSSLFactories(InputStream keyStream, String keyStorePassword,
InputStream trustStream) throws Exception
{
// Get keyStore
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// if your store is password protected then declare it (it can be null however)
char[] keyPassword = keyStorePassword.toCharArray();
// load the stream to your store
keyStore.load(keyStream, keyPassword);
// initialize a key manager factory with the key store
KeyManagerFactory keyFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFactory.init(keyStore, keyPassword);
// get the key managers from the factory
KeyManager[] keyManagers = keyFactory.getKeyManagers();
// Now get trustStore
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// if your store is password protected then declare it (it can be null however)
//char[] trustPassword = password.toCharArray();
// load the stream to your store
trustStore.load(trustStream, null);
// initialize a trust manager factory with the trusted store
TrustManagerFactory trustFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustFactory.init(trustStore);
// get the trust managers from the factory
TrustManager[] trustManagers = trustFactory.getTrustManagers();
// initialize an ssl context to use these managers and set as default
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, trustManagers, null);
SSLContext.setDefault(sslContext);
}
```
|
Here's a cleaned-up version of [user2529737's answer](https://stackoverflow.com/a/17352927/365237), in case it helps. It has removed unneeded trust store setup and added required imports, parameters for keystore type and key password.
```
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyStore;
public class PlainJavaHTTPS2Test {
public void setUp() throws Exception {
final String KEYSTOREPATH = "clientkeystore.p12"; // or .jks
// store password can be null if there is no password
final char[] KEYSTOREPASS = "keystorepass".toCharArray();
// key password can be null if there is no password
final char[] KEYPASS = "keypass".toCharArray();
try (InputStream storeStream = this.getClass().getResourceAsStream(KEYSTOREPATH)) {
setSSLFactories(storeStream, "PKCS12", KEYSTOREPASS, KEYPASS);
}
}
private static void setSSLFactories(InputStream keyStream, String keystoreType, char[] keyStorePassword, char[] keyPassword) throws Exception
{
KeyStore keyStore = KeyStore.getInstance(keystoreType);
keyStore.load(keyStream, keyStorePassword);
KeyManagerFactory keyFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFactory.init(keyStore, keyPassword);
KeyManager[] keyManagers = keyFactory.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagers, null, null);
SSLContext.setDefault(sslContext);
}
}
```
|
How to use a file in a jar as javax.net.ssl.keystore?
|
[
"",
"java",
"jar",
"executable-jar",
""
] |
Some days ago I realized that [PrintWriter](http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html) (as well as [PrintStream](http://java.sun.com/javase/6/docs/api/java/io/PrintStream.html)) **never throw an IOException** when writing, flushing or closing.
Instead it sets an internal flag (`trouble=true`) when an error occurs.
It's not possible to get the exact exception, but only **if** there was some exception ([checkError()](http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html#checkError())).
My question is: why would one want to have such behavior? Isn't that bad API design?
|
I think that since `System.out` and `System.err` are instances of `PrintStream`, some more relaxed error handling was provided. This was probably, as other posters have mentioned, to smooth the way for those transitioning from C/C++ circa 1995. When the Reader/Writer API was added, `PrintWriter` was created to parallel the existing `PrintStream`.
One application where this behavior is extremely desirable is logging. Logging is ancillary to a larger application. Typically, if logging fails, one doesn't want that the entire application to fail. Thus, it makes sense for `System.err`, at least, to ignore exceptions.
|
I wonder if its because IOExceptions are checked, this would require you placing a try catch block around every System.out. call.
update: Or a throws in your method signature.
That would get annoying very quickly.
|
PrintWriter and PrintStream never throw IOExceptions
|
[
"",
"java",
"api",
"exception",
""
] |
[This](https://stackoverflow.com/questions/116090/how-do-i-kill-a-process-using-vbnet-or-c) only helps kills processes on the local machine. How do I kill processes on remote machines?
|
You can use [wmi](http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept04/hey0927.mspx). Or, if you don't mind using external executable, use [pskill](http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx)
|
I like this (similar to answer from Mubashar):
```
ManagementScope managementScope = new ManagementScope("\\\\servername\\root\\cimv2");
managementScope.Connect();
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_Process Where Name = 'processname'");
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery);
ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
foreach (ManagementObject managementObject in managementObjectCollection)
{
managementObject.InvokeMethod("Terminate", null);
}
```
|
Kill a process on a remote machine in C#
|
[
"",
"c#",
".net",
"process",
"kill",
""
] |
My crappy web host did some upgrades the other day and some settings have gone awry, because looking at our company's wiki (MediaWiki), every quote is being escaped with a backslashes. It's not even just data which is being posted (i.e.: the articles) which are affected, but also the standard MediaWiki text. For example,
> You\'ve followed a link to a page that doesn\'t exist yet. To create the page, start typing in the box below (see the help page for more info). If you are here by mistake, just click your browser\'s \'\'\'back\'\'\' button.
The first thing I did was disable `magic_quotes_gpc` AND `magic_quotes_runtime` using a `.htaccess` file, but this is still occurring. My `php_info()` reports this:
```
Setting Local Value Master Value
magic_quotes_gpc Off On
magic_quotes_runtime Off On
magic_quotes_sybase Off Off
```
Any ideas?
|
If PHP flags are set with `php_admin_flag`/`php_admin_value`, you can't change it from a `.htaccess` file. This has caused me some headache before. Either disable it in `php.ini` or undo magic quotes in runtime:
<http://talks.php.net/show/php-best-practices/26>
|
You may want to confirm that the data in your DB hasn't been corrupted. If you were addslash()ing your data when, unbeknownst to you, magic\_quotes had been turned on, then you'd be double-slashifying data going into your DB.
|
Extra backslashes being added in PHP
|
[
"",
"php",
"apache",
"escaping",
"mediawiki",
""
] |
I've created a .Net library at work that is used by all of our developers. The security part of it uses Microsoft AzMan for the security backend. In order to create a security (AzMan) ClientContext I have to pass it a token value (as a uint). This is all fine an dandy until I needed to make a COM wrapper for our common library so some of our legacy pages could take advantage of it without being rewritten for now.
I cannot figure out how to get the token value to pass to AzMan from legacy ASP. The COM wrapper is setup to run as a COM Server and runs as a specific user that we use here for all COM objects, therefor the common library can't just pull the identity using .Net.
Any ideas?
|
If your not able to get to token, you could always use the **IAzApplication.InitializeClientContextFromName** while retrieving the user name from the request in your asp page and passing it to your com+ component.
<http://msdn.microsoft.com/en-us/library/aa377363(VS.85).aspx>
|
Are you using anonymous logons in the IIS configuration? If you use Windows Authentication and do the following in classic ASP you should get the logged on user:
```
Request.ServerVariables("LOGON_USER")
```
|
WindowsIdentity Token in Legacy ASP
|
[
"",
"c#",
".net",
"security",
"com",
"interop",
""
] |
Is there a UI library to create a message box or input box in python?
|
Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter).
If you can restrict yourself to a specific operating system, better choices might be available.
|
Simple message boxes and input boxes can be created using EasyGui, a small library using Tkinter, which Python comes with.
You can get EasyGui here: <http://easygui.sourceforge.net/>
|
Message Box in Python
|
[
"",
"python",
"user-controls",
"user-interface",
""
] |
I'm using a `java.util.concurrent.ExecutorService` that I obtained by calling `Executors.newSingleThreadExecutor()`. This `ExecutorService` can sometimes stop processing tasks, even though it has not been shutdown and continues to accept new tasks without throwing exceptions. Eventually, it builds up enough of a queue that my app shuts down with `OutOfMemoryError` exceptions.
The documentation seem to indicate that this single thread executor should survive task processing errors by firing up a new worker thread if necessary to replace one that has died. Am I missing something?
|
It sounds like you have two different issues:
1) You're over-feeding the work queue. You can't just keep stuffing new tasks into the queue, with no regard for the consumption rate of the task executors. You need to figure out some logic for knowing when you to block new additions to the work queue.
2) Any uncaught exception in a task's thread can completely kill the thread. When that happens, the ExecutorService spins up a new thread to replace it. But that doesn't mean you can ignore whatever problem is causing the thread to die in the first place! Find those uncaught exceptions and catch them!
This is just a hunch (cuz there's not enough info in your post to know otherwise), but I don't think your problem is that the task executor stops processing tasks. My guess is that it just doesn't process tasks as fast as you're creating them. (And the fact that your tasks sometimes die prematurely is probably orthogonal to the problem.)
At least, that's been my experience working with thread pools and task executors.
---
Okay, here's another possibility that sounds feasible based on your comment (that everything will run smoothly for hours until suddenly coming to a crashing halt)...
You might have a rare deadlock between your task threads. Most of the time, you get lucky, and the deadlock doesn't manifest itself. But occasionally, two or more of your task threads get into a state where they're waiting for the release of a lock held by the other thread. At that point, no more task processing can take place, and your work queue will pile up until you get the OutOfMemoryError.
Here's how I'd diagnose that problem:
Eliminate ALL shared state between your task threads. At first, this might require each task thread making a defensive copy of all shared data structures it requires. Once you've done that, it should be completely impossible to experience a deadlock.
At this point, gradually reintroduced the shared data structures, one at a time (with appropriate synchronization). Re-run your application after each tiny modification to test for the deadlock. When you get that crashing situation again, take a close look at the access patterns for the shared resource and determine whether you really need to share it.
As for me, whenever I write code that processes parallel tasks with thread pools and executors, I always try to eliminate **ALL** shared state between those tasks. As far as the application is concerned, they may as well be completely autonomous applications. Hunting down deadlocks is a drag, and in my experience, the best way to eliminate deadlocks is for each thread to have its own local state rather than sharing any state with other task threads.
Good luck!
|
My guess would be that your tasks are blocking indefinitely, rather than dying. Do you have evidence, such as a log statement at the end of your task, suggest that your tasks are successfully completing?
This could be a deadlock, or an interaction with some external process that is blocking.
|
what would make a single task executor stop processing tasks?
|
[
"",
"java",
"multithreading",
"concurrency",
"executorservice",
""
] |
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. All the images are part of the HTML page.
|
Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs.
```
"""
dumpimages.py
Downloads all the images on the supplied URL, and saves them to the
specified output file ("/test/" by default)
Usage:
python dumpimages.py http://example.com/ [output]
"""
from bs4 import BeautifulSoup as bs
from urllib.request import (
urlopen, urlparse, urlunparse, urlretrieve)
import os
import sys
def main(url, out_folder="/test/"):
"""Downloads all the images at 'url' to /test/"""
soup = bs(urlopen(url))
parsed = list(urlparse(url))
for image in soup.findAll("img"):
print("Image: %(src)s" % image)
filename = image["src"].split("/")[-1]
parsed[2] = image["src"]
outpath = os.path.join(out_folder, filename)
if image["src"].lower().startswith("http"):
urlretrieve(image["src"], outpath)
else:
urlretrieve(urlunparse(parsed), outpath)
def _usage():
print("usage: python dumpimages.py http://example.com [outpath]")
if __name__ == "__main__":
url = sys.argv[-1]
out_folder = "/test/"
if not url.lower().startswith("http"):
out_folder = sys.argv[-1]
url = sys.argv[-2]
if not url.lower().startswith("http"):
_usage()
sys.exit(-1)
main(url, out_folder)
```
**Edit:** You can specify the output folder now.
|
Ryan's solution is good, but fails if the image source URLs are absolute URLs or anything that doesn't give a good result when simply concatenated to the main page URL. urljoin recognizes absolute vs. relative URLs, so replace the loop in the middle with:
```
for image in soup.findAll("img"):
print "Image: %(src)s" % image
image_url = urlparse.urljoin(url, image['src'])
filename = image["src"].split("/")[-1]
outpath = os.path.join(out_folder, filename)
urlretrieve(image_url, outpath)
```
|
Download image file from the HTML page source
|
[
"",
"python",
"screen-scraping",
""
] |
My requirement is just to display a set of values retrieved from database on a spread. I am using jquery.
|
Favor XML over JSON when any of these is true:
* You need message validation
* You're using XSLT
* Your messages include a lot of marked-up text
* You need to interoperate with environments that don't support JSON
Favor JSON over XML when all of these are true:
* Messages don't need to be validated, or validating their deserialization is simple
* You're not transforming messages, or transforming their deserialization is simple
* Your messages are mostly data, not marked-up text
* The messaging endpoints have good JSON tools
|
I use JSON unless I'm required to use XML. It's simpler to understand, and (because it requires less configuration overhead) it's easier to program for reading and writing if the libraries are available in your context, and they're pretty ubiquitous now.
When Amazon first exposed their catalogs as a web service, they offered both JSON and XML. Something like 90% of the implementers chose JSON.
|
When to prefer JSON over XML?
|
[
"",
"javascript",
"jquery",
"xml",
"json",
""
] |
I'm developing a C++ command-line application in Visual Studio and need to debug it with command-line arguments. At the moment I just run the generated EXE file with the arguments I need (like this `program.exe -file.txt`) , but this way I can't debug. Is there somewhere I can specify the arguments for debugging?
|
Yes, it's in the *Debug* section of the properties page of the project.
In Visual Studio since 2008: right-click on the project node, choose *Properties*, go to the *Debugging* section -- there is a box for "Command Arguments".
|
The [Mozilla.org FAQ on debugging Mozilla on Windows](https://developer.mozilla.org/en/Debugging_Mozilla_on_Windows_FAQ) is of interest here.
In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, directly on the command line.
This looks like the following for Visual Studio 8 or 9 (Visual Studio 2005 or Visual Studio 2008, respectively)
```
devenv /debugexe 'program name' 'program arguments'
```
It is also possible to have an [explorer action](https://web.archive.org/web/20160606182914/http://www.olegsych.com:80/2007/08/debugexe-command-line-switch-in-visual-studio/) to start a program in the Visual Studio debugger.
|
Debugging with command-line parameters in Visual Studio
|
[
"",
"c++",
"visual-studio",
"debugging",
"command-line",
""
] |
OK so that title sucks a little but I could not think of anything better (maybe someone else can?).
So I have a few questions around a subject here. What I want to do is create a program that can take an object and use reflection to list all its properties, methods, constructors etc. I can then manipulate these objects at runtime to test, debug and figure out exactly what some of my classes / programs are doing whilst they are running, (some of them will be windows services and maybe installed on the machine rather than running in debug from VS).
So I would provide a hook to the program that from the local machine (only) this program could get an instance of the main object and therefore see all the sub objects running in it. (for security the program may need to be started with an arg to expose that hook).
The "reflection machine" would allow for runtime manipulation and interrogation.
Does this sound possible?
Would the program have to provide a hook or could the "reflection machine" take an EXE and (if it knew all the classes it was using), create an object to use?
I know you can import DLL's at runtime so that it knows about all sorts of classes, but can you import individual classes? I.E. Say I have project 'Y' that is not compiled to a DLL but I want to use the "reflection machine" on it, can I point at that directory and grab the files to be able to reference those classes?
EDIT: I would love to try and develop it my self but I already have a long list of projects I would like to do and have already started. Why reinvent the wheel when there is already a great selection to choose from.
|
Try looking at [Crack.NET](http://www.codeplex.com/cracknetproject/Release/ProjectReleases.aspx?ReleaseId=19002). It is used to do runtime manipulation and interrogation on WPF/WinForms but the source is available and might be a good start if it already doesn't meet your needs.
|
It sound as if Corneliu Tusnea's [Hawkeye](http://www.acorns.com.au/Projects/Hawkeye/) might be close to what you're looking for runtime interrogation of objects/properties/etc. He calls it the .NET Runtime Object Editor. I'm not sure if the homepage I linked to above or the [CodePlex project](http://www.codeplex.com/hawkeye) is the best place to start.
It's a bit out of date now, I think, but there's an [earlier version of it on CodeProject](http://www.codeproject.com/KB/cs/RuntimeObjectEditor.aspx) where you can see the source code for how and what he did.
|
How to use reflection to create a "reflection machine"
|
[
"",
"c#",
"reflection",
""
] |
I've got some code that will generically get all Controls in a form and put them in a list. Here's some of the code:
```
private List<Control> GetControlList(Form parentForm)
{
List<Control> controlList = new List<Control>();
AddControlsToList(parentForm.Controls, controlList);
return controlList;
}
private void AddControlsToList(Control.ControlCollection rootControls, List<Control> controlList)
{
foreach (Control c in rootControls)
{
controlList.Add(c);
if (c.HasChildren)
AddControlsToList(c.Controls, controlList);
//
}
}
```
So I'm only able to use c.HasChildren to check and see if there's any more child controls from this root control.
**What about a menuStrip, toolStrip, and statusStrip? How do I get all of the controls that are in these controls generically? Ex: MenuStripItem**
I know that I could try testing the c.GetType() == typeof(MenuStrip) but I was hoping to not have to do specific type tests.
If I need to give more info, please ask.
Thanks a bunch
|
I believe the VS designer does it by getting an instance of the control's designer (see the [`Designer` attribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.designerattribute.aspx)), and, if the designer is a [`ComponentDesigner`](http://msdn.microsoft.com/en-us/library/system.componentmodel.design.componentdesigner.aspx), getting the [`AssociatedComponents`](http://msdn.microsoft.com/en-us/library/system.componentmodel.design.componentdesigner.associatedcomponents.aspx) property.
**EDIT**:
Okay, I guess that's a little vague. A warning, though: what follows is a little complicated, and might not be worth the effort.
A note on nomenclature:
Below, I will be referring to both the designer within Visual Studio—which is the name used to refer to the functionality within Visual Studio by which the layout and content of forms and controls are edited visually—and to designer classes—which will be explained below. To prevent confusion as to which I am referring to at any given time, I will always refer to the designer functionality within Visual Studio as "the designer", and I will always refer to a designer class as an "IDesigner", which is the interface each must implement.
When the Visual Studio designer loads a component (usually a control, but also things like `Timer` and such), it looks for a custom attribute on the class of type `DesignerAttribute`. (Those unfamiliar with attributes might want [read up on them](http://msdn.microsoft.com/en-us/library/aa288059(VS.71).aspx) before continuing.)
This attribute, if present, provides the name of a class—an IDesigner—the designer can use to interface with the component. In effect, this class controls certain aspects of the designer and of the design-time behavior of the component. There's indeed quite a lot you can do with an IDesigner, but right now we're only interested in one thing.
Most controls that use a custom IDesigner use one that derives from `ControlDesigner`, which itself derives from `ComponentDesigner`. The `ComponentDesigner` class has a public virtual property called `AssociatedComponents`, which is meant to be overridden in derived classes to return a collection of references to all "child" components of this one.
To be more specific, the `ToolStrip` control (and by inheritance, the `MenuStrip` control) has a `DesignerAttribute` that references a class called `ToolStripDesigner`. It looks sort of like:
```
/*
* note that in C#, I can refer to the "DesignerAttribute" class within the [ brackets ]
* by simply "Designer". The compiler adds the "Attribute" to the end for us (assuming
* there's no attribute class named simply "Designer").
*/
[Designer("System.Windows.Forms.Design.ToolStripDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), ...(other attributes)]
public class ToolStrip : ScrollableControl, IArrangedElement, ...(other interfaces){
...
}
```
The `ToolStripDesigner` class is not public. It's internal to System.Design.dll. But since it's specified here by it's fully qualified name, the VS designer can use `Activator.CreateInstance` to create an instance of it anyway.
This `ToolStripDesigner` class, because it inherits [indirectly] from `ComponentDesigner` has an `AssociatedComponents` property. When you call it you get a new `ArrayList` that contains references to all the items that have been added to the `ToolStrip`.
So what would *your* code have to look like to do the same thing? Rather convoluted, but I think I have a working example:
```
/*
* Some controls will require that we set their "Site" property before
* we associate a IDesigner with them. This "site" is used by the
* IDesigner to get services from the designer. Because we're not
* implementing a real designer, we'll create a dummy site that
* provides bare minimum services and which relies on the framework
* for as much of its functionality as possible.
*/
class DummySite : ISite, IDisposable{
DesignSurface designSurface;
IComponent component;
string name;
public IComponent Component {get{return component;}}
public IContainer Container {get{return designSurface.ComponentContainer;}}
public bool DesignMode{get{return false;}}
public string Name {get{return name;}set{name = value;}}
public DummySite(IComponent component){
this.component = component;
designSurface = new DesignSurface();
}
~DummySite(){Dispose(false);}
protected virtual void Dispose(bool isDisposing){
if(isDisposing)
designSurface.Dispose();
}
public void Dispose(){
Dispose(true);
GC.SuppressFinalize(this);
}
public object GetService(Type serviceType){return designSurface.GetService(serviceType);}
}
static void GetComponents(IComponent component, int level, Action<IComponent, int> action){
action(component, level);
bool visible, enabled;
Control control = component as Control;
if(control != null){
/*
* Attaching the IDesigner sets the Visible and Enabled properties to true.
* This is useful when you're designing your form in Visual Studio, but at
* runtime, we'd rather the controls maintain their state, so we'll save the
* values of these properties and restore them after we detach the IDesigner.
*/
visible = control.Visible;
enabled = control.Enabled;
foreach(Control child in control.Controls)
GetComponents(child, level + 1, action);
}else visible = enabled = false;
/*
* The TypeDescriptor class has a handy static method that gets
* the DesignerAttribute of the type of the component we pass it
* and creates an instance of the IDesigner class for us. This
* saves us a lot of trouble.
*/
ComponentDesigner des = TypeDescriptor.CreateDesigner(component, typeof(IDesigner)) as ComponentDesigner;
if(des != null)
try{
DummySite site;
if(component.Site == null)
component.Site = site = new DummySite(component);
else site = null;
try{
des.Initialize(component);
foreach(IComponent child in des.AssociatedComponents)
GetComponents(child, level + 1, action);
}finally{
if(site != null){
component.Site = null;
site.Dispose();
}
}
}finally{des.Dispose();}
if(control != null){
control.Visible = visible;
control.Enabled = enabled;
}
}
/* We'll use this in the ListComponents call */
[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
const int WM_SETREDRAW = 11;
void ListComponents(){
/*
* Invisible controls and disabled controls will be temporarily shown and enabled
* during the GetComponents call (see the comment within that call), so to keep
* them from showing up and then disappearing again (or appearing to temporarily
* change enabled state), we'll disable redrawing of our window and re-enable it
* afterwards.
*/
SendMessage(Handle, WM_SETREDRAW, 0, 0);
GetComponents(this, 0,
/* You'll want to do something more useful here */
(component, level)=>System.Diagnostics.Debug.WriteLine(new string('\t', level) + component));
SendMessage(Handle, WM_SETREDRAW, 1, 0);
}
```
|
The items such as ToolStripItem etc aren't actually controls, they are simply components that make up a ToolStrip or MenuStrip.
Which means, that if you want to include those components in your flattened list of controls then you will need to do the specific checks.
|
Enumerate .Net control's items generically (MenuStrip, ToolStrip, StatusStrip)
|
[
"",
"c#",
".net-2.0",
""
] |
I'm trying to update a hashtable in a loop but getting an error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
```
private Hashtable htSettings_m = new Hashtable();
htSettings_m.Add("SizeWidth", "728");
htSettings_m.Add("SizeHeight", "450");
string sKey = "";
string sValue = "";
foreach (DictionaryEntry deEntry in htSettings_m)
{
// Get value from Registry and assign to sValue.
// ...
// Change value in hashtable.
sKey = deEntry.Key.ToString();
htSettings_m[sKey] = sValue;
}
```
Is there way around it or maybe there is a better data structure for such purpose?
|
you could read the collection of keys into another IEnumerable instance first, then foreach over that list
```
System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("test1", "test2");
ht.Add("test3", "test4");
List<string> keys = new List<string>();
foreach (System.Collections.DictionaryEntry de in ht)
keys.Add(de.Key.ToString());
foreach(string key in keys)
{
ht[key] = DateTime.Now;
Console.WriteLine(ht[key]);
}
```
|
In concept I would do:
```
Hashtable table = new Hashtable(); // ps, I would prefer the generic dictionary..
Hashtable updates = new Hashtable();
foreach (DictionaryEntry entry in table)
{
// logic if something needs to change or nog
if (needsUpdate)
{
updates.Add(key, newValue);
}
}
// now do the actual update
foreach (DictionaryEntry upd in updates)
{
table[upd.Key] = upd.Value;
}
```
|
How to update C# hashtable in a loop?
|
[
"",
"c#",
"data-structures",
"loops",
"hashtable",
""
] |
We have a Hibernate/Spring application that have the following Spring beans:
```
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" />
```
When wiring the application together we get the following error when using private constructors in our hibernate entities:
```
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No visible constructors in class 'ourclass'
```
The entities are typical domain objects such as an Employee or the like.
When changing the constructor's visibility modifier to package (or public) the application runs fine and the entities gets stored/loaded in the database. How do we/can we use private constructors/static factory methods with Spring/Hibernate transaction management?
We use Hibernate annotations to map the entities/relationships. No bean definitions are declared in the applicationContext.xml for the domain class that is related to the problem. It is a pojo that should have a static factory method and a private constructor.
How can we make Hibernate (org.springframework.spring-orm.hibernate3 classes i guess) make use of the static factory method instead of the constructor? Or possibly make it call a private constructor if necessary?
Using the spring factory-method configuration would make sense but the entities are not mapped as beans in our applicationContext.xml. They are only annotated with the @Entity annotation for Hibernate persistence.
Hope this edit clearifies (rather than mystifies) the question. :)
|
While I haven't used Spring, I have used Hibernate in a project which has classes which must either be instantiated by factory methods or through multiple argument constructors.
You can do this through an Interceptor, which is a class which listens in to several key hibernate events, such as when an object needs to be instantiated or when an object is loaded.
To make Hibernate use your own means of instantiating the object, do something like this:
```
public class MyInterceptor extends EmptyInterceptor {
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) {
if(entityName.equals(Foo.class.getName())
return Foo.create();
return null;
}
}
```
I'm a little suprised that you are having issues with Hibernate not instantiating objects with a non visible constructor, considering that it can be worked around with reflection and I haven't had that issue in my project (non of the classes actually have visible constructors). It may be something with Spring. Check which version of hibernate you are using as well.
|
Do you know about the property "factory-method" ? You can make spring call that method instead of the constructor to instantiate a bean.
|
Hibernate and Spring transactions - using private constructors/static factory methods
|
[
"",
"java",
"hibernate",
"spring",
"transactions",
""
] |
I have a python module that defines a number of classes:
```
class A(object):
def __call__(self):
print "ran a"
class B(object):
def __call__(self):
print "ran b"
class C(object):
def __call__(self):
print "ran c"
```
From within the module, how might I add an attribute that gives me all of the classes?
dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from *within* the module.
From outside of the module, I can simply use `getattr(mod, 'A')`, but I don't have a `self` kind of module from within the module itself.
This seems pretty obvious. Can someone tell me what I'm missing?
|
```
import sys
getattr(sys.modules[__name__], 'A')
```
|
You can smash this into one for statement, but that'd have messy code duplication.
```
import sys
import types
this_module = sys.modules[__name__]
[x for x in
[getattr(this_module, x) for x in dir(this_module)]
if type(x) == types.ClassType]
```
|
How can I dynamically get the set of classes from the current python module?
|
[
"",
"python",
"reflection",
"metaprogramming",
""
] |
I know the rule-of-thumb to read declarations right-to-left and I was fairly sure I knew what was going on until a colleague told me that:
```
const MyStructure** ppMyStruct;
```
means "ppMyStruct is **a pointer to a const pointer to a (mutable) MyStructure**" (in C++).
I would have thought it meant "ppMyStruct is **a pointer to a pointer to a const MyStructure**".
I looked for an answer in the C++ spec, but apparently I'm not very good at that...
What does in mean in C++, and does it mean the same thing in C?
|
Your colleague is wrong. That is a (non-const) pointer to a (non-const) pointer to a const MyStructure. In both C and C++.
|
In such cases the tool cdecl (or c++decl) can be helpfull:
```
[flolo@titan ~]$ cdecl explain "const struct s** ppMyStruct"
declare ppMyStruct as pointer to pointer to const struct s
```
|
What does a const pointer-to-pointer mean in C and in C++?
|
[
"",
"c++",
"c",
"pointers",
"constants",
""
] |
I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back.
Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported?
By zip file, I mean zip file. As supported in the Python zipfile package.
|
The only solution is to rewrite the method it uses for zipping files to read from a buffer. It would be trivial to add this to the standard libraries; I'm kind of amazed it hasn't been done yet. I gather there's a lot of agreement the entire interface needs to be overhauled, and that seems to be blocking any incremental improvements.
```
import zipfile, zlib, binascii, struct
class BufferedZipFile(zipfile.ZipFile):
def writebuffered(self, zipinfo, buffer):
zinfo = zipinfo
zinfo.file_size = file_size = 0
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell()
self._writecheck(zinfo)
self._didModify = True
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
self.fp.write(zinfo.FileHeader())
if zinfo.compress_type == zipfile.ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
else:
cmpr = None
while True:
buf = buffer.read(1024 * 8)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC) & 0xffffffff
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
position = self.fp.tell()
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
```
|
Changed in **Python 3.5** (from official docs): Added [support](https://docs.python.org/3/library/zipfile.html#zipfile-objects) for writing to **unseekable** streams.
This means that now for `zipfile.ZipFile` we can use streams which do not store the entire file in memory. Such streams [do not support](https://docs.python.org/3/library/io.html?highlight=io#io.IOBase.seekable) movement over the entire data volume.
So this is simple generator:
```
from zipfile import ZipFile, ZipInfo
def zipfile_generator(path, stream):
with ZipFile(stream, mode='w') as zf:
z_info = ZipInfo.from_file(path)
with open(path, 'rb') as entry, zf.open(z_info, mode='w') as dest:
for chunk in iter(lambda: entry.read(16384), b''):
dest.write(chunk)
# Yield chunk of the zip file stream in bytes.
yield stream.get()
# ZipFile was closed.
yield stream.get()
```
`path` is a string path of the large file or directory or `pathlike` object.
`stream` is the **unseekable** stream instance of the class like this (designed according to [official docs](https://docs.python.org/3/library/io.html?highlight=io)):
```
from io import RawIOBase
class UnseekableStream(RawIOBase):
def __init__(self):
self._buffer = b''
def writable(self):
return True
def write(self, b):
if self.closed:
raise ValueError('Stream was closed!')
self._buffer += b
return len(b)
def get(self):
chunk = self._buffer
self._buffer = b''
return chunk
```
You can try this code online: <https://repl.it/@IvanErgunov/zipfilegenerator>
---
There is also another way to create a generator without `ZipInfo` and manually reading and dividing your large file. You can pass the `queue.Queue()` object to your `UnseekableStream()` object and write to this queue in another thread. Then in current thread you can simply read chunks from this queue in iterable way. See [docs](https://docs.python.org/3/library/queue.html#queue-objects)
**P.S.**
[Python Zipstream by allanlei](https://github.com/allanlei/python-zipstream) is outdated and unreliable way. It was an attempt to add support for unseekable streams before it was done officially.
|
Create a zip file from a generator in Python?
|
[
"",
"python",
"zip",
""
] |
OK,
Here is my problem, I have a master page with a HEAD section that contains my JS includes. I have one JS include
```
<script src="Includes/js/browser.js" language="javascript" type="text/javascript"></script>
```
In my page i consume it like this:
```
<body>
<form id="form1" runat="server">
<div>
....
<script type="text/javascript">registerBookmarkButton();</script>
....
</div>
</form>
</body>
```
And i get this error:
```
Line: 216
Error: Object expected
```
Please tell me i just missed something and it's a stupid mistake
|
If you can use Firefox, I would highly recommend installing and enabling the Firebug addon.
Otherwise, see some of the following for tools that might help:
* [Javascript troubleshooting tools in IE](https://stackoverflow.com/questions/3404/javascript-troubleshooting-tools-in-ie)
* [Is there any good or reliable way to figure out where a JavaScript error is using only an Internet Explorer error message?](https://stackoverflow.com/questions/179054/is-there-any-good-or-reliable-way-to-figure-out-where-a-javascript-error-is-usi)
* [What is the Best Development “add on” for Browsers [closed]](https://stackoverflow.com/questions/313186/what-is-the-best-development-add-on-for-browsers-closed)
* [Debugging javascript in IE?](https://stackoverflow.com/questions/170164/debugging-javascript-in-ie)
|
As you wish.
> You just missed something and it's a stupid mistake.
:)
That being said, I'd try to find out which file it is that has the faulty line 216. Perhaps it's the browser.js file? Other possibilities include:
* You messed up the URL and the file isn't loaded;
* The function depends on the DOM to be completely loaded, but it's called before the relevant elements are created (most JS should be done after the onload event under normal circumstances).
|
How do I debug this weird IE JavaScript Problem
|
[
"",
"javascript",
"internet-explorer",
""
] |
Is there a fast algorithm for finding the Largest Common Substring in two `strings` or is it an NPComplete problem?
In PHP I can find a needle in a haystack:
```
<?php
if (strstr("there is a needle in a haystack", "needle")) {
echo "found<br>\n";
}
?>
```
I guess I could do this in a loop over one of the `strings` but that would be very expensive! Especially since my application of this is to search a database of email and look for spam (i.e. similar emails sent by the same person).
Does anyone have any PHP code they can throw out there?
|
I have since found [a relevant wikipedia article](http://en.wikipedia.org/wiki/Longest_common_substring_problem). It is not a NP complete problem, it can be done in O(mn) time using a dynamic programming algorithm.
In PHP I found the [similar\_text](https://www.php.net/manual/en/function.similar-text.php) function very useful. Here's a code sample to retrieve a series of text emails and loop through them and find ones that are 90% similar to each other. **Note: Something like this is NOT scalable**:
```
<?php
// Gather all messages by a user into two identical associative arrays
$getMsgsRes = mysql_query(SELECT * FROM email_messages WHERE from = '$someUserID');
while($msgInfo = mysql_fetch_assoc($getMsgsRes))
{
$msgsInfo1[] = $msgInfo;
$msgsInfo2[] = $msgInfo;
}
// Loop over msgs and compare each one to every other
foreach ($msgsInfo1 as $msg1)
foreach ($msgsInfo2 as $msg2)
similar_text($msg1['msgTxt'],$msg2['msgTxt'],$similarity_pst);
if ($similarity_pst > 90)
echo "{$msg1['msgID']} is ${similarity_pst}% to {$msg2['msgID']}\n";
?>
```
|
The [similar\_text](https://www.php.net/manual/en/function.similar-text.php) function may be what you want.
This calculates the similarity between two strings. Returns the number of matching chars in both strings
You may also want to look at [levenshtein](https://www.php.net/manual/en/function.levenshtein.php)
|
How can I find the Largest Common Substring between two strings in PHP?
|
[
"",
"php",
"algorithm",
"string",
"performance",
"spam-prevention",
""
] |
One thing that annoys me when debugging programs in Visual Studio (2005 in my case) is that when I use "step over" (by pressing `F10`) to execute to the next line of code, I often end up reaching that particular line of code in a totally different thread than the one I was looking at. This means that all the context of what I was doing was lost.
How do I work around this?
If this is possible to do in later versions of Visual Studio, I'd like to hear about it as well.
Setting a breakpoint on the next line of code which has a conditional to only break for this thread is not the answer I'm looking for since it is way too much work to be useful for me :)
|
I think there is only one answer to your question, which you have discounted as being 'way too much work.' However, I believe that is because you are going about it the wrong way. Let me present steps for adding a conditional breakpoint on Thread ID, which are extremely easy, but not obvious until you know them.
1. Stop the debugger at a point where you are in the correct thread you want to continue debugging in (*which I would guess is usually the first thread that gets there*).
2. Enter `$TID` into the watch window.
3. Add a break point with the condition `$TID == <`*value of $TID from Watch Window*`>`,
**Example**: `$TID == 0x000016a0`
4. Continue Execution.
`$TID` is a magic variable for Microsoft compilers (since at least Visual Studio 2003) that has the value of the current Thread ID. It makes it much easier than looking at (FS+0x18)[0x24]. =D
That being said, you can get the same behavior as the debugger's One-Shot breakpoints with some simple macros. When you step over, the debugger, behind the scenes, sets a breakpoint, runs to that breakpoint and then removes it. The key to a consistent user interface is removing those breakpoints if **ANY** breakpoint is hit.
The following two macros provide *Step Over* and *Run To Cursor* for the current thread. This is accomplished in the same manner as the debugger, with the breakpoints being removed after execution, regardless of which breakpoint is hit.
You will want to assign a key combination to run them.
> ***NOTE***: One caveat -- The *Step Over* macro only works correctly if the cursor is on the line you want to step over. This is because it determines the current location by the cursor location, and simply adds one to the line number. You may be able to replace the location calculation with information on the current execution point, though I was unable to locate that information from the Macro IDE.
Here they are and good luck bug hunting!!
> **To use these macros in Visual Studio:**
> 1. Open the Macro IDE ( from the Menu, select: *Tools->Macros->Macro IDE...* )
> 2. Add a new Code File ( from the Menu: select: *Project->Add New Item...*, choose *Code File*, and click *Add* )
> 3. Paste in this code.
> 4. Save the file.
>
> **To add key combinations for running these macros in Visual Studio:**
> 1. Open Options (from the Menu, select: *Tools->Options* )
> 2. Expand to *Environment->Keyboard*
> 3. In *Show commands containing:*, type ***Macros.*** to see all your macros.
> 4. Select a macro, then click in *Press shortcut keys:*
> 5. Type the combo you want to use (*backspace deletes typed combos*)
> 6. click *Assign* to set your shortcut to run the selected macro.
```
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module DebugHelperFunctions
Sub RunToCursorInMyThread()
Dim textSelection As EnvDTE.TextSelection
Dim myThread As EnvDTE.Thread
Dim bp As EnvDTE.Breakpoint
Dim bps As EnvDTE.Breakpoints
' For Breakpoints.Add()
Dim FileName As String
Dim LineNumber As Integer
Dim ThreadID As String
' Get local references for ease of use
myThread = DTE.Debugger.CurrentThread
textSelection = DTE.ActiveDocument.Selection
LineNumber = textSelection.ActivePoint.Line
FileName = textSelection.DTE.ActiveDocument.FullName
ThreadID = myThread.ID
' Add a "One-Shot" Breakpoint in current file on current line for current thread
bps = DTE.Debugger.Breakpoints.Add("", FileName, LineNumber, 1, "$TID == " & ThreadID)
' Run to the next stop
DTE.Debugger.Go(True)
' Remove our "One-Shot" Breakpoint
For Each bp In bps
bp.Delete()
Next
End Sub
Sub StepOverInMyThread()
Dim textSelection As EnvDTE.TextSelection
Dim myThread As EnvDTE.Thread
Dim bp As EnvDTE.Breakpoint
Dim bps As EnvDTE.Breakpoints
' For Breakpoints.Add()
Dim FileName As String
Dim LineNumber As Integer
Dim ThreadID As String
' Get local references for ease of use
myThread = DTE.Debugger.CurrentThread
textSelection = DTE.ActiveDocument.Selection
LineNumber = textSelection.ActivePoint.Line
FileName = textSelection.DTE.ActiveDocument.FullName
ThreadID = myThread.ID
LineNumber = LineNumber + 1
' Add a "One-Shot" Breakpoint in current file on current line for current thread
bps = DTE.Debugger.Breakpoints.Add("", FileName, LineNumber, 1, "$TID == " & ThreadID)
' Run to the next stop
DTE.Debugger.Go(True)
' Remove our "One-Shot" Breakpoint
For Each bp In bps
bp.Delete()
Next
End Sub
End Module
```
> **Disclaimer**: I wrote these macros in *Visual Studio 2005*. You can probably use them fine in *Visual Studio 2008*. They may require modification for *Visual Studio 2003* and before.
|
You can freeze a different thread or switch to another thread using the Threads debug window (`Ctrl` + `Alt` + `H`).
|
"Step over" when debugging multithreaded programs in Visual Studio
|
[
"",
"c++",
"visual-studio",
"multithreading",
"debugging",
"visual-studio-2005",
""
] |
In a [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 2.0 C# application I use the following code to detect the operating system platform:
```
string os_platform = System.Environment.OSVersion.Platform.ToString();
```
This returns "Win32NT". The problem is that it returns "Win32NT" even when running on Windows Vista 64-bit.
Is there any other method to know the correct platform (32 or 64 bit)?
Note that it should also detect 64 bit when run as a 32 bit application on Windows 64 bit.
|
**UPDATE:** As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check `Environment.Is64BitOperatingSystem`.
---
IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit).
As Microsoft's Raymond Chen describes, you have to first check if running in a 64-bit process (I think in .NET you can do so by checking IntPtr.Size), and if you are running in a 32-bit process, you still have to call the Win API function IsWow64Process. If this returns true, you are running in a 32-bit process on 64-bit Windows.
Microsoft's Raymond Chen:
[How to detect programmatically whether you are running on 64-bit Windows](http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx)
My solution:
```
static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool wow64Process
);
public static bool InternalCheckIsWow64()
{
if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
Environment.OSVersion.Version.Major >= 6)
{
using (Process p = Process.GetCurrentProcess())
{
bool retVal;
if (!IsWow64Process(p.Handle, out retVal))
{
return false;
}
return retVal;
}
}
else
{
return false;
}
}
```
|
.NET 4 has two new properties in the Environment class, [Is64BitProcess](http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess(VS.100).aspx) and [Is64BitOperatingSystem](http://msdn.microsoft.com/en-us/library/system.environment.is64bitoperatingsystem%28VS.100%29.aspx). Interestingly, if you use Reflector you can see they are implemented differently in the 32-bit & 64-bit versions of mscorlib. The 32-bit version returns false for Is64BitProcess and calls IsWow64Process via P/Invoke for Is64BitOperatingSystem. The 64-bit version just returns true for both.
|
How to detect Windows 64-bit platform with .NET?
|
[
"",
"c#",
"windows",
"64-bit",
".net-2.0",
"platform-detection",
""
] |
I'm looking for a way to display multiple colors in a single C#/.NET label. E.g the label is displaying a series of csv separated values that each take on a color depending on a bucket they fall into. I would prefer not to use multiple labels, as the values are variable length and I don't want to play with dynamic layouts. Is there a native support for this?
|
There is no native control in .NET that does this. Your best bet is to write your own UserControl (call it RainbowLabel or something). Normally you would have a custom label control inherit directly from Label, but since you can't get multi-colored text in one label, you would just inherit from UserControl.
For rendering the text, your UserControl could split the text on commas and then dynamically load a differently-colored Label for each chunk. A better way, however, would be to render the text directly onto your UserControl using the DrawString and MeasureString methods in the Graphics namespace.
Writing UserControls in .NET is really not difficult, and this kind of unusual problem is exactly what custom UserControls are for.
**Update**: here's a simple method you can use for rendering the multi-colored text on a PictureBox:
```
public void RenderRainbowText(string Text, PictureBox pb)
{
// PictureBox needs an image to draw on
pb.Image = new Bitmap(pb.Width, pb.Height);
using (Graphics g = Graphics.FromImage(pb.Image))
{
// create all-white background for drawing
SolidBrush brush = new SolidBrush(Color.White);
g.FillRectangle(brush, 0, 0,
pb.Image.Width, pb.Image.Height);
// draw comma-delimited elements in multiple colors
string[] chunks = Text.Split(',');
brush = new SolidBrush(Color.Black);
SolidBrush[] brushes = new SolidBrush[] {
new SolidBrush(Color.Red),
new SolidBrush(Color.Green),
new SolidBrush(Color.Blue),
new SolidBrush(Color.Purple) };
float x = 0;
for (int i = 0; i < chunks.Length; i++)
{
// draw text in whatever color
g.DrawString(chunks[i], pb.Font, brushes[i], x, 0);
// measure text and advance x
x += (g.MeasureString(chunks[i], pb.Font)).Width;
// draw the comma back in, in black
if (i < (chunks.Length - 1))
{
g.DrawString(",", pb.Font, brush, x, 0);
x += (g.MeasureString(",", pb.Font)).Width;
}
}
}
}
```
Obviously this will break if you have more than 4 comma-delimited elements in your text, but you get the idea. Also, there appears to be a small glitch in MeasureString that makes it return a width that is a couple pixels wider than necessary, so the multi-colored string appears stretched out - you might want to tweak that part.
It should be straightforward to modify this code for a UserControl.
**Note**: TextRenderer is a better class to use for drawing and measuring strings, since it uses ints. Graphics.DrawString and .MeasureString use floats, so you'll get off-by-a-pixel errors here and there.
**Update**: *Forget* about using TextRenderer. It is dog slow.
|
You could try using a RichTextBox so that you can get multiple colors for the string and then make it read only and remove the border. Change the background color to the same as the Form it is on and you might get away with it.
|
Multiple colors in a C# .NET label
|
[
"",
"c#",
".net",
"user-interface",
"colors",
"label",
""
] |
I have a bunch of controls (textbox and combobox) on a form with toolstripcontainer and toolstripbuttons for save, cancel etc for edits. We are using .Net 3.5 SP1
There is bunch of logic written in control.lostfocus and control.leave events. These events are not being called when clicked on the toolstrip buttons. Is there a way to call these events manually when any of these buttons are pressed.
Thanks.
Kishore
[Edit]
This is how I solved the problem. Thanks *[Chris Marasti-Georg](https://stackoverflow.com/questions/287685/raise-lostfocus-event-on-a-control-manually-c#287740)* for the pointer. In the button click event I calling focus on the toolstrip instead of the button as the toolstripbutton does not have a focus event. We can access the toolstrip on which the button is placed using
((ToolStripButton)sender).Owner.Focus()
-Kishore
|
You could listen to the click events on the buttons, and in the handler call their focus method. That would (hopefully) cause the previously focused control to respond correctly. Add the following handler to each button's click event:
```
private void ButtonClick(object sender, EventArgs e) {
if(sender != null) {
sender.Focus();
}
}
```
|
You can extend those controls and then call the OnLostFocus and OnLeave protected methods of the base class...
|
Raise LostFocus event on a control manually
|
[
"",
"c#",
".net",
""
] |
Have a use case wherein need to maintain a connection open to a database open to execute queries periodically.
Is it advisable to close connection after executing the query and then reopen it after the period interval (10 minutes). I would guess no since opening a connection to database is expensive.
Is connection pooling the alternative and keep using the connections?
|
You should use connection pooling. Write your application code to request a connection from the pool, use the connection, then return the connection back to the pool. This keeps your code clean. Then you rely on the pool implementation to determine the most efficient way to manage the connections (for example, keeping them open vs closing them).
Generally it is "expensive" to open a connection, typically due to the overhead of setting up a TCP/IP connection, authentication, etc. However, it can also be expensive to keep a connection open "too long", because the database (probably) has reserved resources (like memory) for use by the connection. So keeping a connection open can tie-up those resources.
You don't want to pollute your application code managing these types of efficiency trade-offs, so use a connection pool.
|
Yes, connection pooling is the alternative. Open the connection each time (as far as your code is concerned) and close it as quickly as you can. The connection pool will handle the physical connection in an appropriately efficient manner (including any keepalives required, occasional "liveness" tests etc).
I don't know what the current state of the art is, but I used [c3p0](http://sourceforge.net/projects/c3p0) very successfully for my last Java project involving JDBC (quite a while ago).
|
Reusing a connection while polling a database in JDBC?
|
[
"",
"java",
""
] |
I have the following situation:
I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop.
I want to be able to check whether the loop is still running or not.
For this, i'm doing, for each loop run:
```
LastTimeIDidTheLoop = new Date();
```
And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:
```
if (LastTimeIDidTheLoop is more than 30 seconds ago) {
alert("oops");
}
```
How do I do this?
Thanks!
|
what about:
```
newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
alert("oops");
}
```
|
JS date objects store milliseconds internally, subtracting them from each other works as expected:
```
var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000;
if (diffSeconds > 30)
{
// ...
}
```
|
How do I compare dates in Javascript?
|
[
"",
"javascript",
"date",
""
] |
I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.
I have an application that is pulling email via POP3. I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email. I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc. I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.
Hope this makes some amount of sense and that someone can shed some light on this. In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.
|
Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead.
This great Codeproject article by Peter Huber SG, entitled ['POP3 Email Client with full MIME Support (.NET 2.0)'](http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx) will give you an understanding of how MIME processing can be implemented, and the related RFC specification articles.
You can use the Codeproject article as a start for writing your own parser, or appraise a library like [SharpMimeTools](http://anmar.eu.org/projects/sharpmimetools/), which is an open source library for parsing and decoding MIME emails.
<http://anmar.eu.org/projects/sharpmimetools/>
Hope this helps!
|
Mightytighty is leading you down the right path, but you shouldn't presume the type of encoding. This should do the trick:
```
var dataStream = view.ContentStream;
dataStream.Position = 0;
byte[] byteBuffer = new byte[dataStream.Length];
var encoding = Encoding.GetEncoding(view.ContentType.CharSet);
string body = encoding.GetString(byteBuffer, 0,
dataStream.Read(byteBuffer, 0, byteBuffer.Length));
```
|
Retrieving AlternateView's of email
|
[
"",
"c#",
"html",
"email",
"pop3",
"plaintext",
""
] |
On various pages throughout my PHP web site and in various nested directories I want to include a specific file at a path relative to the root.
What single command can I put on both of these pages...
```
http://www.example.com/pageone.php
```
```
http://www.example.com/somedirectory/pagetwo.php
```
...to include this page:
```
http://www.example.com/includes/analytics.php
```
This does not work:
```
<?php include('/includes/analytics.php'); ?>
```
Does it matter that this is hosted in IIS on Windows?
|
If you give include() or require() (or the \*\_once versions) an absolute pathname, that file will be included. An absolute pathname starts with a "/" on unix, and with a drive letter and colon on Windows.
If you give a relative path (any other path), PHP will search the directories in the configuration value "include\_path" in order, until a match is found or there are no more directories to search.
So, in short, to include an absolute filename, give an absolute filename. See also the function [realpath()](http://www.php.net/realpath).
If you want to set your own include "root", have a look at [this question](https://stackoverflow.com/questions/344419/how-do-i-set-an-absolute-include-path-in-php) (specifically my answer of course :-)
|
You can just use `include $_SERVER['DOCUMENT_ROOT'] . "/includes/analytics.php";`
|
How do I format a PHP include() absolute (rather than relative) path?
|
[
"",
"php",
"path",
"include",
""
] |
I seemed to get the following exception when trying to deploy my application:
```
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
java.util.List is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at java.util.List
at private java.util.List foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse._return
at foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse
java.util.List does not have a no-arg default constructor.
this problem is related to the following location:
at java.util.List
at private java.util.List foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse._return
at foobar.alkohol.register.webservice.jaxws.GetRelationsFromPersonResponse
```
**My code worked just well until I changed the return type from List to List<List<RelationCanonical>>**
Here is the partial webservice:
```
@Name("relationService")
@Stateless
@WebService(name = "RelationService", serviceName = "RelationService")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public class RelationService implements RelationServiceLocal {
private boolean login(String username, String password) {
Identity.instance().setUsername(username);
Identity.instance().setPassword(password);
Identity.instance().login();
return Identity.instance().isLoggedIn();
}
private boolean logout() {
Identity.instance().logout();
return !Identity.instance().isLoggedIn();
}
@WebMethod
public List<List<RelationCanonical>> getRelationsFromPerson(@WebParam(name = "username")
String username, @WebParam(name = "password")
String password, @WebParam(name = "foedselsnummer")
String... foedselsnummer) {
......
......
......
}
```
**I have also tried by removing the @SOAPBinding and trying default, but the same result occurs.
Appreciate any help**
**UPDATE**
I want to note out something. I changed all List to ArrayList, and then it compiled. The reason why I say compiled and not worked is because it behaves strange. I get an Object of type:
RelationServiceStub.ArrayList
but the object has no get methods or does not behave as a List either. I also tried to cast it to a List but that didnt work.
Note that this is after I have used Axis 2 and wsdl2java So yes, now it compiles, but I dont know how to get the data out.
|
In my understanding, you will not be able to process a plain `List` via JAXB, as JAXB has no idea how to transform that into XML.
Instead, you will need to define a JAXB type which holds a `List<RelationCanonical>` (I'll call it `Type1`), and another one to hold a list of those types, in turn (as you're dealing with a `List<List<...>>`; I'll call this type `Type2`).
The result could then be an XML ouput like this:
```
<Type2 ...>
<Type1 ...>
<RelationCanonical ...> ... </RelationCanonical>
<RelationCanonical ...> ... </RelationCanonical>
...
</Type1>
<Type1>
<RelationCanonical ...> ... </RelationCanonical>
<RelationCanonical ...> ... </RelationCanonical>
...
</Type1>
...
</Type2>
```
Without the two enclosing JAXB-annotated types, the JAXB processor has no idea what markup to generate, and thus fails.
--Edit:
What I mean should look somewhat like this:
```
@XmlType
public class Type1{
private List<RelationCanonical> relations;
@XmlElement
public List<RelationCanonical> getRelations(){
return this.relations;
}
public void setRelations(List<RelationCanonical> relations){
this.relations = relations;
}
}
```
and
```
@XmlRootElement
public class Type2{
private List<Type1> type1s;
@XmlElement
public List<Type1> getType1s(){
return this.type1s;
}
public void setType1s(List<Type1> type1s){
this.type1s= type1s;
}
}
```
You should also check out the [JAXB section in the J5EE tutorial](http://java.sun.com/javaee/5/docs/tutorial/doc/bnazf.html) and the [Unofficial JAXB Guide](http://jaxb.java.net/guide/Mapping_interfaces.html).
|
If that suits your purpose you can always define an array like this:
```
YourType[]
```
JAXB can certainly figure out what that is and you should be able to immediatly use it client side. I would also recommend you to do it that way, since you should not be able to modify the array retrieved from a server via a List but via methods provided by the web service
|
java.util.List is an interface, and JAXB can't handle interfaces
|
[
"",
"java",
"web-services",
"jakarta-ee",
"jaxb",
"jbossws",
""
] |
I have a table User which has an identity column `UserID`, now what is the correct Linq to Entity line of code that would return me the max `UserID`?
I've tried:
```
using (MyDBEntities db = new MyDBEntities())
{
var User = db.Users.Last();
// or
var User = db.Users.Max();
return user.UserID;
}
```
but `Last` and `Max` don't seem to be supported.
Any ideas?
|
Do that like this
```
db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();
```
|
try this
```
int intIdt = db.Users.Max(u => u.UserId);
```
**Update:**
If no record then generate exception using above code try this
```
int? intIdt = db.Users.Max(u => (int?)u.UserId);
```
|
How do I get the max ID with Linq to Entity?
|
[
"",
"c#",
"linq",
"entity-framework",
"linq-to-entities",
""
] |
I've found the following code from here "[<http://www.boyet.com/Articles/CodeFromInternet.html>](http://www.boyet.com/Articles/CodeFromInternet.html)".
It returns the speed of the CPU in GHz but works only on 32bit Windows.
```
using System;
using System.Management;
namespace CpuSpeed
{
class Program
{
static double? GetCpuSpeedInGHz()
{
double? GHz = null;
using (ManagementClass mc = new ManagementClass("Win32_Processor"))
{
foreach (ManagementObject mo in mc.GetInstances())
{
GHz = 0.001 * (UInt32) mo.Properties["CurrentClockSpeed"].Value;
break;
}
}
return GHz;
}
static void Main(string[] args)
{
Console.WriteLine("The current CPU speed is {0}", (GetCpuSpeedInGHz() ?? -1.0).ToString());
Console.ReadLine();
}
}
}
```
I've searched for 64bit management classes, but without success.
Is there any other method to get the CPU speed under 64bit Windows?
|
I've used the following code based on the answer by Binoj Antony which returns the speed for each CPU/core, not only the first one:
```
Microsoft.Win32.RegistryKey registrykeyHKLM = Microsoft.Win32.Registry.LocalMachine;
string cpuPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor";
Microsoft.Win32.RegistryKey registrykeyCPUs = registrykeyHKLM.OpenSubKey(cpuPath, false);
StringBuilder sbCPUDetails = new StringBuilder();
int iCPUCount;
for (iCPUCount = 0; iCPUCount < registrykeyCPUs.SubKeyCount; iCPUCount++)
{
Microsoft.Win32.RegistryKey registrykeyCPUDetail = registrykeyHKLM.OpenSubKey(cpuPath + "\\" + iCPUCount, false);
string sMHz = registrykeyCPUDetail.GetValue("~MHz").ToString();
string sProcessorNameString = registrykeyCPUDetail.GetValue("ProcessorNameString").ToString();
sbCPUDetails.Append(Environment.NewLine + "\t" + string.Format("CPU{0}: {1} MHz for {2}", new object[] { iCPUCount, sMHz, sProcessorNameString }));
registrykeyCPUDetail.Close();
}
registrykeyCPUs.Close();
registrykeyHKLM.Close();
sCPUSpeed = iCPUCount++ + " core(s) found:" + sbCPUDetails.ToString();
```
Fell free to customize it for your needs.
|
Code below should do the trick
```
RegistryKey registrykeyHKLM = Registry.LocalMachine;
string keyPath = @"HARDWARE\DESCRIPTION\System\CentralProcessor\0";
RegistryKey registrykeyCPU = registrykeyHKLM.OpenSubKey(keyPath, false);
string MHz = registrykeyCPU.GetValue("~MHz").ToString();
string ProcessorNameString = (string)registrykeyCPU.GetValue("ProcessorNameString");
registrykeyCPU.Close();
registrykeyHKLM.Close();
Console.WriteLine("{0} MHz for {1}", MHz, ProcessorNameString);
```
|
How to detect CPU speed on Windows 64bit?
|
[
"",
"c#",
".net",
"windows",
"64-bit",
"cpu-speed",
""
] |
Having recently gotten into test driven development I am using the Nunit test runner shipped as part of resharper. It has some downsides in terms of there is no shortcut to run tests and I have to go looking for the Nunit test runner to invoke it using the mouse. It has a nice GUI and shows the results as part of the IDE well.
What do other people use for running unit tests against .net projects?
I have googled other apps including MBUnit and the Unit test App from Nunit.org and wondered what comes out on top for people.
|
Resharper does have some shortcomings...but it is possible to configure it to do what you want...
You can configure keyboard options in Visual Studio. Also, you can use the Unit Test Explorer in Resharper to find the tests you want and add them to the current session. I usually configure a shortcut (Alt+U) that runs all the tests in my current session...that way as I'm developing I can run all of the unit tests I need in seconds.
Also check out:
* [ReSharper run all unit tests in a project or solution at once](https://stackoverflow.com/questions/334933/resharper-run-all-unit-tests-in-a-project-or-solution-at-once)
* [Are there shortcut keys for ReSharper's Unit Test Runner?](https://stackoverflow.com/questions/175116/are-there-shortcut-keys-for-resharpers-unit-test-runner)
However, it would be nice if this didn't have to be manually configured! (Yes! I'm looking at you Resharper Dev team! LOL)
|
I've always been a fan of TestDriven.NET, I much prefer it over using ReSharper.
|
What is the best Nunit test runner out there?
|
[
"",
"c#",
"unit-testing",
"nunit",
"test-runner",
""
] |
I got a core that looks very different from the ones I usually get - most of the threads are in \_\_kernel\_vsyscall() :
```
9 process 11334 0xffffe410 in __kernel_vsyscall ()
8 process 11453 0xffffe410 in __kernel_vsyscall ()
7 process 11454 0xffffe410 in __kernel_vsyscall ()
6 process 11455 0xffffe410 in __kernel_vsyscall ()
5 process 11474 0xffffe410 in __kernel_vsyscall ()
4 process 11475 0xffffe410 in __kernel_vsyscall ()
3 process 11476 0xffffe410 in __kernel_vsyscall ()
2 process 11477 0xffffe410 in __kernel_vsyscall ()
1 process 11323 0x08220782 in MyClass::myfunc ()
```
What does that mean?
EDIT:
In particular, I usually see a lot of threads in "pthread\_cond\_wait" and "\_\_\_newselect\_nocancel" and now those are on the second frame in each thread - why is this core different?
|
`__kernel_vsyscal` is the method used by linux-gate.so (a part of the Linux kernel) to make a system call using the fastest available method, preferably the `sysenter` instruction. The thing is properly explained by [Johan Petersson](http://www.trilithium.com/johan/2005/08/linux-gate).
|
When you make a system call (like reading from a file, talking to hardware, writing to sockets) you're actually creating an interrupt. The system then handles the interrupt in kernel mode and your call returns with the result. Most of the time it's unusual for you to have a lot of threads in syscall unless you're making blocking calls, in which case it's expected.
More specifically, it means the thread is waiting on a kernel level system call. But that's (unfortunately for my points) already in the name :)
|
What is __kernel_vsyscall?
|
[
"",
"c++",
"gdb",
""
] |
I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As such, the launcher project is set as the "Startup Project" and, as a result, it's the only one I can set break points in and debug due to my limited knowledge of VS2005.
Is there a way to set multiple breakpoints across my five c++ projects in my single VS solution and debug them at the same time if the launcher project is the only project executed from VS?
***Note:*** *Manually starting new instances of each project via Visual Studio is not an option since their execution needs to be synchronized by the launcher.exe.*
I apologize if this is convoluted, it's the best I can explain it. Thanks in advance for your help!
|
What you need is in the Tools menu: Attach to Process. This gives you a list of running processes and allows you to attach your debugger to those processes.
For local debugging, Transport and Qualifier should keep their default values. The Attach To value just above the list determines which type of debugging you'll be doing (native or managed are the most common types), and normally the debugger can figure out a good default here as well.
The main interesting part is the list of processes - look in this list for the sub-processes you want to debug. Once you've found and selected the process, click Attach in the lower right corner (or just double-click the process), and the debugger will attach to that process and start debugging it.
You'll probably also want to enable the Debug Location toolbar, which provides a way to change the focus of the debugger to the various processes and threads you're attached to. Multi-process debugging within one Visual Studio instance can be tricky, so you can always consider starting separate instances to debug each different process.
Another tricky aspect of this can be debugging the initial startup of the sub-processes. Often the thing you want to debug happens before you can get the debugger attached, so you need some way to cause the process to wait for you to be ready. An easy way to do this in C++ is to use the IsDebuggerPresent function. Try adding this code to the very beginning of your main() function (or equivalent):
```
while( !IsDebuggerPresent() )
Sleep( 500 );
```
Or try this code for C#:
```
while( !System.Diagnostics.Debugger.IsAttached )
System.Threading.Thread.Sleep( 500 );
```
|
You can pick one at a time by running launcher manually (outside of visual studio, or with <ctrl-f5>) and then attaching to the process you want to debug once it's started. If it's one of the projects in your solution, you can set breakpoints and they'll get picked up when you attach the debugger.
|
Debugging Multi-Project (C++) Solutions in Visual Studio 2005
|
[
"",
"c++",
"visual-studio-2005",
"visual-c++-2005",
""
] |
I have a Windows application (VS2005/C#) which comes in two versions, Enterprise and Pro. In the Pro version, some of the features and menus are disabled. Currently, I'm doing this by commenting out the disabling code to create the Enterprise version, then I copy each executable file to another location. Obviously this process is fraught with peril... :)
I would like to have two folders for my two executable files, and visual studio should put the code to disable the features in the pro version, and put each in their correct folders. I have installer projects that would pick up the files from there and make the installers for the two versions. That part is already working, but I'm manually copying the two executables into the right folders before I build the installers. So it sucks...
What I'd like to do is something like this:
```
#ifdef PROVERSION
part1.disable();
part2.disable();
#endif
```
Is this possible with Visual studio???
Note, my overall goal is to automate the process of creating the two installers.
|
from the BUILD menu, select configuration manager option
on the active solution configuration dropdown select "new"
create two new 'configurations' one for PRO and one for ENTERPRISE
close the configuration manager.
open the project properties (from the project context menu)
select the build tab
select the PRO configuration (from the CONFIGURATION dropdown)
enter your compilation constant "PROVERSION" into the conditional compilation symbols textbox.
now all you have to do is select the config you want to build from the config dropdown on the main toolbar and then do your build.
when you build the PRO using the PRO configuration the compiler pragmas (#IF PROVERSION) scattered throughout your code will include the code limiting your feature set.
you may also consider setting a ENTERPRISE constant for the ENTERPRISE configuration if you want to specifically include ENTERPRISE features in an ENTERPRISE build (versus disabling enterprise features in a PRO build)
|
Yes, thats certainly possible. A visual studio solution comes with two configuration by default. (Release and Debug). You can create additional ones like "EnterpriseDebug" and "EnterpriseRelease" Just go to the Configuration Manager under (Build | Configuration Manager ) and then select <New...>
The configuration manager will by default create a folder named after the configuration and place the compiled binary files into it. You will have to manually set the conditional compilation symbols and use (#if) statement to add/remove your features.
|
Configurations and Program features in Visual Studio/C# Windows App
|
[
"",
"c#",
"configuration",
"visual-studio-2005",
"versioning",
""
] |
I have a PHP application and a need to generate a PDF with the result of query. The easiest way a found to do this was to use the DOMPDF to generate the PDF for me. So a made a function that generates the HTML for me then a pass this to DOMPDF. In the development and testing enviroment everything was fine but on production enviroment I had some problems with memory usage.
So I would like to know if my strategy was the best one or if there's a better and easy way to do this.
How would you do that?
|
I once did a PHP project generating PDF. I used [FPdf](http://www.fpdf.org/).
I never had any memory problems. It's free, it's pure PHP code. You don't have to load any extensions.
I don't know if there's some helpers to auto-generate document from a query, but in the website, you have some scripts that shows how to use it with MySql.
HTH
|
I'm amazed nobody uses FOP:) <http://xmlgraphics.apache.org/fop/> ... you basically feed it an XML flie and it generates a PDF file... very quick, and dosent kill your server.
|
Generating PDFs with PHP
|
[
"",
"php",
"pdf",
"dompdf",
""
] |
Always when I run java application it will display in Windows Task Manager is java.exe or javaw.exe. How to rename java.exe or javaw.exe process without wrapper by other programming languages.
|
If you are confused by looking at process names that are all the same (*java.exe*), try to
use [*Process Explorer*](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) instead of *Task Manager*, and display the *command line* field. This way, you can see the *class* or *jar* arguments that differentiate one process from another.
|
You could use [jSmooth](http://jsmooth.sourceforge.net/):
> JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications.
|
How to rename java.exe/javaw.exe process?
|
[
"",
"java",
""
] |
Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties.
```
foreach(UserControl uc in plhMediaBuys.Controls)
{
uc.PulblicPropertyIWantAccessTo;
}
```
|
```
foreach(UserControl uc in plhMediaBuys.Controls) {
MyControl c = uc as MyControl;
if (c != null) {
c.PublicPropertyIWantAccessTo;
}
}
```
|
```
foreach(UserControl uc in plhMediaBuys.Controls)
{
if (uc is MySpecificType)
{
return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
}
}
```
|
Casting a UserControl as a specific type of user control
|
[
"",
"c#",
"asp.net",
"user-controls",
""
] |
Is it ever OK to use [Environment.TickCount](https://learn.microsoft.com/en-us/dotnet/api/system.environment.tickcount) to calculate time spans?
```
int start = Environment.TickCount;
// Do stuff
int duration = Environment.TickCount - start;
Console.WriteLine("That took " + duration " ms");
```
Because `TickCount` is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful.
I'm using `DateTime.Now` instead. Is this the best way to do this?
```
DateTime start = DateTime.Now;
// Do stuff
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("That took " + duration.TotalMilliseconds + " ms");
```
|
Use the Stopwatch class. There is a decent example on [MSDN](https://en.wikipedia.org/wiki/Microsoft_Developer_Network): *[Stopwatch Class](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx)*
```
Stopwatch stopWatch = Stopwatch.StartNew();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
```
|
**Environment.TickCount** is based on [GetTickCount()](http://msdn.microsoft.com/en-us/library/ms724408.aspx) WinAPI function. It's in milliseconds.
But the actual precision of it is about 15.6 ms. So you can't measure shorter time intervals (or you'll get 0).
*Note:* The returned value is Int32, so this counter rolls over each ~49.7 days. You shouldn't use it to measure such long intervals.
**DateTime.Ticks** is based on [GetSystemTimeAsFileTime](http://msdn.microsoft.com/en-us/library/ms724397.aspx)() WinAPI function. It's in 100s nanoseconds (tenths of microsoconds).
The actual precision of DateTime.Ticks depends on the system. On Windows XP, the increment of system clock is about 15.6 ms, the same as in Environment.TickCount.
On Windows 7 its precision is 1 ms (while Environemnt.TickCount's is still 15.6 ms). However, if a power saving scheme is used (usually on laptops) it can go down to 15.6 ms as well.
**Stopwatch** is based on [QueryPerformanceCounter()](http://msdn.microsoft.com/en-us/library/ms644904.aspx) WinAPI function (but if high-resolution performance counter is not supported by your system, DateTime.Ticks is used)
Before using StopWatch notice two problems:
* it can be unreliable on multiprocessor systems (see MS [kb895980](http://support.microsoft.com/?scid=kb;en-us;895980), [kb896256](http://support.microsoft.com/?scid=kb;en-us;896256))
* it can be unreliable if CPU frequency varies (read [this](http://www.virtualdub.org/blog/pivot/entry.php?id=106) article)
You can evaluate the precision on your system with simple test:
```
static void Main(string[] args)
{
int xcnt = 0;
long xdelta, xstart;
xstart = DateTime.UtcNow.Ticks;
do {
xdelta = DateTime.UtcNow.Ticks - xstart;
xcnt++;
} while (xdelta == 0);
Console.WriteLine("DateTime:\t{0} ms, in {1} cycles", xdelta / (10000.0), xcnt);
int ycnt = 0, ystart;
long ydelta;
ystart = Environment.TickCount;
do {
ydelta = Environment.TickCount - ystart;
ycnt++;
} while (ydelta == 0);
Console.WriteLine("Environment:\t{0} ms, in {1} cycles ", ydelta, ycnt);
Stopwatch sw = new Stopwatch();
int zcnt = 0;
long zstart, zdelta;
sw.Start();
zstart = sw.ElapsedTicks; // This minimizes the difference (opposed to just using 0)
do {
zdelta = sw.ElapsedTicks - zstart;
zcnt++;
} while (zdelta == 0);
sw.Stop();
Console.WriteLine("StopWatch:\t{0} ms, in {1} cycles", (zdelta * 1000.0) / Stopwatch.Frequency, zcnt);
Console.ReadKey();
}
```
|
Environment.TickCount vs DateTime.Now
|
[
"",
"c#",
".net",
"datetime",
"timespan",
""
] |
Here I am faced with an issue that I believe(or at least hope) was solved 1 million times already.
What I got as the input is a string that represents a length of an object in imperial units. It can go like this:
```
$length = "3' 2 1/2\"";
```
or like this:
```
$length = "1/2\"";
```
or in fact in any other way we normally would write it.
In effort to reduce global wheel invention, I wonder if there is some function, class, or regexp-ish thing that will allow me to convert Imperial length into Metric length?
|
Here is my solution. It uses [eval()](http://php.net/eval) to evaluate the expression, but don't worry, the regex check at the end makes it completely safe.
```
function imperial2metric($number) {
// Get rid of whitespace on both ends of the string.
$number = trim($number);
// This results in the number of feet getting multiplied by 12 when eval'd
// which converts them to inches.
$number = str_replace("'", '*12', $number);
// We don't need the double quote.
$number = str_replace('"', '', $number);
// Convert other whitespace into a plus sign.
$number = preg_replace('/\s+/', '+', $number);
// Make sure they aren't making us eval() evil PHP code.
if (preg_match('/[^0-9\/\.\+\*\-]/', $number)) {
return false;
} else {
// Evaluate the expression we've built to get the number of inches.
$inches = eval("return ($number);");
// This is how you convert inches to meters according to Google calculator.
$meters = $inches * 0.0254;
// Returns it in meters. You may then convert to centimeters by
// multiplying by 100, kilometers by dividing by 1000, etc.
return $meters;
}
}
```
So for example, the string
```
3' 2 1/2"
```
gets converted to the expression
```
3*12+2+1/2
```
which gets evaluated to
```
38.5
```
which finally gets converted to 0.9779 meters.
|
The Zend Framework has a measurement component for just that purpose. I suggest you check it out - [here](http://framework.zend.com/manual/en/zend.measure.html).
```
$unit = new Zend_Measure_Length($length,Zend_Measure_Length::YARD);
$unit -> convertTo(Zend_Measure_Length::METER);
```
|
How to convert imperial units of length into metric?
|
[
"",
"php",
"regex",
"code-snippets",
""
] |
For those who like a good WPF binding challenge:
I have a nearly functional example of two-way binding a `CheckBox` to an individual bit of a flags enumeration (thanks Ian Oakes, [original MSDN post](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c05b7e7e-25cd-4a41-8bf5-e35d2caff797/)). The problem though is that the binding behaves as if it is one way (UI to `DataContext`, not vice versa). So effectively the `CheckBox` does not initialize, but if it is toggled the data source is correctly updated. Attached is the class defining some attached dependency properties to enable the bit-based binding. What I've noticed is that ValueChanged is never called, even when I force the `DataContext` to change.
**What I've tried:** Changing the order of property definitions, Using a label and text box to confirm the `DataContext` is bubbling out updates, Any plausible `FrameworkMetadataPropertyOptions` (`AffectsRender`, `BindsTwoWayByDefault`), Explicitly setting `Binding Mode=TwoWay`, Beating head on wall, Changing `ValueProperty` to `EnumValueProperty` in case of conflict.
Any suggestions or ideas would be extremely appreciated, thanks for anything you can offer!
The enumeration:
```
[Flags]
public enum Department : byte
{
None = 0x00,
A = 0x01,
B = 0x02,
C = 0x04,
D = 0x08
} // end enum Department
```
The XAML usage:
```
CheckBox Name="studentIsInDeptACheckBox"
ctrl:CheckBoxFlagsBehaviour.Mask="{x:Static c:Department.A}"
ctrl:CheckBoxFlagsBehaviour.IsChecked="{Binding Path=IsChecked, RelativeSource={RelativeSource Self}}"
ctrl:CheckBoxFlagsBehaviour.Value="{Binding Department}"
```
The class:
```
/// <summary>
/// A helper class for providing bit-wise binding.
/// </summary>
public class CheckBoxFlagsBehaviour
{
private static bool isValueChanging;
public static Enum GetMask(DependencyObject obj)
{
return (Enum)obj.GetValue(MaskProperty);
} // end GetMask
public static void SetMask(DependencyObject obj, Enum value)
{
obj.SetValue(MaskProperty, value);
} // end SetMask
public static readonly DependencyProperty MaskProperty =
DependencyProperty.RegisterAttached("Mask", typeof(Enum),
typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null));
public static Enum GetValue(DependencyObject obj)
{
return (Enum)obj.GetValue(ValueProperty);
} // end GetValue
public static void SetValue(DependencyObject obj, Enum value)
{
obj.SetValue(ValueProperty, value);
} // end SetValue
public static readonly DependencyProperty ValueProperty =
DependencyProperty.RegisterAttached("Value", typeof(Enum),
typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null, ValueChanged));
private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
isValueChanging = true;
byte mask = Convert.ToByte(GetMask(d));
byte value = Convert.ToByte(e.NewValue);
BindingExpression exp = BindingOperations.GetBindingExpression(d, IsCheckedProperty);
object dataItem = GetUnderlyingDataItem(exp.DataItem);
PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path);
pi.SetValue(dataItem, (value & mask) != 0, null);
((CheckBox)d).IsChecked = (value & mask) != 0;
isValueChanging = false;
} // end ValueChanged
public static bool? GetIsChecked(DependencyObject obj)
{
return (bool?)obj.GetValue(IsCheckedProperty);
} // end GetIsChecked
public static void SetIsChecked(DependencyObject obj, bool? value)
{
obj.SetValue(IsCheckedProperty, value);
} // end SetIsChecked
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.RegisterAttached("IsChecked", typeof(bool?),
typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(false, IsCheckedChanged));
private static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (isValueChanging) return;
bool? isChecked = (bool?)e.NewValue;
if (isChecked != null)
{
BindingExpression exp = BindingOperations.GetBindingExpression(d, ValueProperty);
object dataItem = GetUnderlyingDataItem(exp.DataItem);
PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path);
byte mask = Convert.ToByte(GetMask(d));
byte value = Convert.ToByte(pi.GetValue(dataItem, null));
if (isChecked.Value)
{
if ((value & mask) == 0)
{
value = (byte)(value + mask);
}
}
else
{
if ((value & mask) != 0)
{
value = (byte)(value - mask);
}
}
pi.SetValue(dataItem, value, null);
}
} // end IsCheckedChanged
/// <summary>
/// Gets the underlying data item from an object.
/// </summary>
/// <param name="o">The object to examine.</param>
/// <returns>The underlying data item if appropriate, or the object passed in.</returns>
private static object GetUnderlyingDataItem(object o)
{
return o is DataRowView ? ((DataRowView)o).Row : o;
} // end GetUnderlyingDataItem
} // end class CheckBoxFlagsBehaviour
```
|
You could use a value converter. Here's a very specific implementation for the target `Enum`, but would not be hard to see how to make the converter more generic:
```
[Flags]
public enum Department
{
None = 0,
A = 1,
B = 2,
C = 4,
D = 8
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DepartmentsPanel.DataContext = new DataObject
{
Department = Department.A | Department.C
};
}
}
public class DataObject
{
public DataObject()
{
}
public Department Department { get; set; }
}
public class DepartmentValueConverter : IValueConverter
{
private Department target;
public DepartmentValueConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Department mask = (Department)parameter;
this.target = (Department)value;
return ((mask & this.target) != 0);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
this.target ^= (Department)parameter;
return this.target;
}
}
```
And then use the converter in the XAML:
```
<Window.Resources>
<l:DepartmentValueConverter x:Key="DeptConverter" />
</Window.Resources>
<StackPanel x:Name="DepartmentsPanel">
<CheckBox Content="A"
IsChecked="{Binding
Path=Department,
Converter={StaticResource DeptConverter},
ConverterParameter={x:Static l:Department.A}}"/>
<!-- more -->
</StackPanel>
```
**EDIT:** I don't have enough "rep" (yet!) to comment below so I have to update my own post :(
In the last comment [Steve Cadwallader](https://stackoverflow.com/users/41693/steve-cadwallader) says: *"but when it comes to two-way binding the ConvertBack falls apart"*, well I've updated my sample code above to handle the ConvertBack scenario; I've also posted a sample working application [***here***](http://www.box.net/shared/8xp0qqsc47) (**edit:** note that the sample code download also includes a generic version of the converter).
Personally I think this is a lot simpler, I hope this helps.
|
Here's something I came up with that leaves the View nice and clean (no static resources necessary, no new attached properties to fill out, no converters or converter parameters required in the binding), and leaves the ViewModel clean (no extra properties to bind to)
The View looks like this:
```
<CheckBox Content="A" IsChecked="{Binding Department[A]}"/>
<CheckBox Content="B" IsChecked="{Binding Department[B]}"/>
<CheckBox Content="C" IsChecked="{Binding Department[C]}"/>
<CheckBox Content="D" IsChecked="{Binding Department[D]}"/>
```
The ViewModel looks like this:
```
public class ViewModel : ViewModelBase
{
private Department department;
public ViewModel()
{
Department = new EnumFlags<Department>(department);
}
public Department Department { get; private set; }
}
```
If you're ever going to assign a new value to the Department property, don't. Leave Department alone. Write the new value to Department.Value instead.
This is where the magic happens (this generic class can be reused for any flag enum)
```
public class EnumFlags<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible
{
private T value;
public EnumFlags(T t)
{
if (!typeof(T).IsEnum) throw new ArgumentException($"{nameof(T)} must be an enum type"); // I really wish they would just let me add Enum to the generic type constraints
value = t;
}
public T Value
{
get { return value; }
set
{
if (this.value.Equals(value)) return;
this.value = value;
OnPropertyChanged("Item[]");
}
}
[IndexerName("Item")]
public bool this[T key]
{
get
{
// .net does not allow us to specify that T is an enum, so it thinks we can't cast T to int.
// to get around this, cast it to object then cast that to int.
return (((int)(object)value & (int)(object)key) == (int)(object)key);
}
set
{
if ((((int)(object)this.value & (int)(object)key) == (int)(object)key) == value) return;
this.value = (T)(object)((int)(object)this.value ^ (int)(object)key);
OnPropertyChanged("Item[]");
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string memberName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName));
}
#endregion
}
```
|
How can you two-way bind a checkbox to an individual bit of a flags enumeration?
|
[
"",
"c#",
"wpf",
"data-binding",
"enums",
"bit-manipulation",
""
] |
I have an IQueryable and an object of type T.
I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName))
so ...
```
public IQueryable<T> DoWork<T>(string fieldName)
where T : EntityObject
{
...
T objectOfTypeT = ...;
....
return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}
```
Fyi, GetProperty isn't a valid function. I need something which performs this function.
Am I having a Friday afternoon brain melt or is this a complex thing to do?
---
objectOfTypeT I can do the following ...
```
var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();
```
Which works perfectly,now I just need the second part:
return SomeIQueryable().Where(o => **o.GetProperty(fieldName)** == matchValue);
|
Like so:
```
var param = Expression.Parameter(typeof(T), "o");
var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));
var body = Expression.Equal(
Expression.PropertyOrField(param, fieldName),
Expression.PropertyOrField(fixedItem, fieldName));
var lambda = Expression.Lambda<Func<T,bool>>(body,param);
return source.Where(lambda);
```
I have started a blog which will cover a number of expression topics, [here](http://marcgravell.blogspot.com/).
If you get any problems, another option is to extract the value from `objectOfTypeT` first (using reflection) and then use that value in the `Expression.Constant`, but I suspect it'll be fine "as is".
|
From what I can see so far it's going to have to be something like ...
```
IQueryable<T>().Where(t =>
MemberExpression.Property(MemberExpression.Constant(t), fieldName) ==
ParameterExpression.Property(ParameterExpression.Constant(item), fieldName));
```
While I can get this to compile it's not quite executing the way it is required.
|
How do I build a Linq Expression Tree that compares against a generic object?
|
[
"",
"c#",
"linq",
"entity-framework",
"generics",
"expression-trees",
""
] |
I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.
```
def run():
owd = os.getcwd()
#first change dir to build_dir path
os.chdir(testDir)
#run jar from test directory
os.system(cmd)
#change dir back to original working directory (owd)
```
note: I think my code formatting is off - not sure why. My apologies in advance
|
You simply need to add the line:
```
os.chdir(owd)
```
Just a note this was also answered in your other [question](http://stackoverflow.com/questions/299249/how-can-i-get-my-python-version-25-script-to-run-a-jar-file-inside-a-folder-ins).
|
A context manager is a very appropriate tool for this job:
```
from contextlib import contextmanager
import os
@contextmanager
def cwd(path):
oldpwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
```
...used as:
```
os.chdir('/tmp') # for testing purposes, be in a known directory
print(f'before context manager: {os.getcwd()}')
with cwd('/'):
# code inside this block, and only inside this block, is in the new directory
print(f'inside context manager: {os.getcwd()}')
print(f'after context manager: {os.getcwd()}')
```
...which will yield something like:
```
before context manager: /tmp
inside context manager: /
after context manager: /tmp
```
This is actually **superior** to the `cd -` shell builtin, inasmuch as it also takes care of changing directories back when a block is exited due to an exception being thrown.
---
For your specific use case, this would instead be:
```
with cwd(testDir):
os.system(cmd)
```
---
Another option to consider is using `subprocess.call()` instead of `os.system()`, which will let you specify a working directory for the command to run:
```
# note: better to modify this to not need shell=True if possible
subprocess.call(cmd, cwd=testDir, shell=True)
```
... which would prevent you from needing to change the interpreter's directory at all.
Note that now it is recommended to use `subprocess.run` (instead of `call`) but the same arguments are available, and in particular `cwd`: <https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module>.
|
How do I change directory back to my original working directory with Python?
|
[
"",
"python",
""
] |
I am working on a big C++ project. It is building using single Ant script which makes possible to compile the same source targeting more than one platform and compiler.
But, I have to work only for Windows platform and Visual Studio 2005 C++ compiler. It would be really nice if I could write code and compile in Visual Studio, instead of using Notepad++ and Ant scripts, as I do now.
I tried to install Nant and Nant addin for Visual Studio 2005, and to use existing Ant script, but it seems that Ant script cannot be used as a Nant script.
Is there any way to convert Ant script to Nant? Is any other approach to the problem at all, or I must create Visual Studio solution and projects manually?
I would try to avoid such solution because I have a bunch of tests that I don't know how to use in that case.
|
To my knowledge, there is no *automatic* way of converting Ant script to NAnt. However, since NAnt is based off of the Ant the conversion process would not be too far from the original, as long as the tasks are the "core" ones. Possibly an XSLT translation could be made on the Ant scripts to convert to NAnt as both are XML. If one were to go down this path the conversion should be done *dynamically* based of the original Ant scripts, so that only one set of scripts would have to be maintained.
If you would like to write and compile your C++ code inside of Visual Studio it's tough to beat the functionality that is built in with the IDE. However, this requires creating project files though. Otherwise, it seems that one would risk fighting an uphill battle with the tool.
One option for the tests would be to call out through a [custom build step](http://msdn.microsoft.com/en-us/library/e85wte0k(VS.80).aspx) to run them.
|
In my experience, the best way to integrate VS with ant is on the IDE side to call ant as a custom build step (as Scott Saad suggests), and from ant, to call msbuild.exe as the executable to build the project from the command line.
I know that this question is already answered -- I just wanted to suggest the possibility of using msbuild, as it's by far the easiest way to build VS projects from within ant itself.
|
Ant -> Nant -> Visual Studio 2005 Build
|
[
"",
"c++",
"visual-studio-2005",
"ant",
"nant",
"visual-c++-2005",
""
] |
I've got this date time string:
```
post["date"] = "2007-07-18 10:03:19"
```
I'd like to extract just "2007-07-18" as a date. I've seen some reference to `strptime` but I'm not sure how to use it. How can I extract the date from this string?
|
The other two answers are fine, but if you actually want the date for something else, you can use the `datetime` module:
```
from datetime import datetime
d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
day_string = d.strftime('%Y-%m-%d')
```
It might be overkill for now, but it'll come in useful. You can see all of the format specifiers [here](http://docs.python.org/library/time.html#time.strftime).
|
In your case, just use split:
```
>>> d1="2007-07-18 10:03:19"
>>> d1.split()[0]
'2007-07-18'
>>>
```
(The 1st part after splitting with whitespace)
If you insist on using `strptime`, the format is `"%Y-%m-%d %H:%M:%S"` :
```
>>> import time
>>> time.strptime(d1,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2007, tm_mon=7, tm_mday=18, tm_hour=10, tm_min=3, tm_sec=19, tm_wday=2, tm_yday=199, tm_isdst=-1)
>>> time.strftime("%Y-%m-%d", _)
'2007-07-18'
>>>
```
|
Convert a string with date and time to a date
|
[
"",
"python",
"datetime",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.