Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a `std::string` pointer?
Here's what I was looking forward to doing:
```
void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void Foo::Caller() {
try {
this->Bar(); // should throw
}
catch(std::string *caught) { // not quite sure the syntax is OK here...
std::cout << "Got " << caught << std::endl;
}
}
```
|
Yes. [`std::exception`](http://en.cppreference.com/w/cpp/error/exception) is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent [document](http://www.boost.org/community/error_handling.html) on good style for exceptions and error handling. It's worth a read.
|
A few principles:
1. you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
2. Don't throw pointers but object, that way memory is handled for you.
Example:
```
struct MyException : public std::exception
{
std::string s;
MyException(std::string ss) : s(ss) {}
~MyException() throw () {} // Updated
const char* what() const throw() { return s.c_str(); }
};
```
And then use it in your code:
```
void Foo::Bar(){
if(!QueryPerformanceTimer(&m_baz)){
throw MyException("it's the end of the world!");
}
}
void Foo::Caller(){
try{
this->Bar();// should throw
}catch(MyException& caught){
std::cout<<"Got "<<caught.what()<<std::endl;
}
}
```
|
c++ exception : throwing std::string
|
[
"",
"c++",
"exception",
"stl",
""
] |
I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?
|
The reference returned by `window.open()` is to the child window's `window` object. So you can do anything you would normally do, here's an example:
```
var myWindow = window.open('...')
myWindow.document.getElementById('foo').style.backgroundColor = 'red'
```
Bear in mind that this will only work if the parent and child windows **have the same domain**. Otherwise cross-site scripting security restrictions will stop you.
|
I think this will do the trick.
```
function popUp(){
var newWindow = window.open("","Test","width=300,height=300,scrollbars=1,resizable=1")
//read text from textbox placed in parent window
var text = document.form.input.value
var html = "<html><head></head><body>Hello, <b>"+ text +"</b>."
html += "How are you today?</body></html>"
newWindow .document.open()
newWindow .document.write(html)
newWindow .document.close()
}
```
|
How do I write content to another browser window using Javascript?
|
[
"",
"javascript",
"dom",
""
] |
I have a large collection of data in an excel file (and csv files). The data needs to be placed into a database (mysql). However, before it goes into the database it needs to be processed..for example if columns 1 is less than column 3 add 4 to column 2. There are quite a few rules that must be followed before the information is persisted.
What would be a good design to follow to accomplish this task? (using java)
**Additional notes**
The process needs to be automated. In the sense that I don't have to manually go in and alter the data. We're talking about thousands of lines of data with 15 columns of information per line.
Currently, I have a sort of chain of responsibility design set up. One class(Java) for each rule. When one rule is done, it calls the following rule.
**More Info**
Typically there are about 5000 rows per data sheet. Speed isn't a huge concern because
this large input doesn't happen often.
I've considered drools, however I wasn't sure the task was complicated enough for drols.
Example rules:
1. All currency (data in specific columns) must not contain currency symbols.
2. Category names must be uniform (e.g. book case = bookcase)
3. Entry dates can not be future dates
4. Text input can only contain [A-Z 0-9 \s]
etc..
Additionally if any column of information is invalid it needs to be reported when
processing is complete
(or maybe stop processing).
My current solution works. However I think there is room for improvement so I'm looking
for ideals as to how it can be improved and or how other people have handled similar
situations.
I've considered (very briefly) using drools but I wasn't sure the work was complicated enough to take advantage of drools.
|
If I didn't care to do this in 1 step (as Oli mentions), I'd probably use a [pipe and filters](http://www.eaipatterns.com/PipesAndFilters.html) design. Since your rules are relatively simple, I'd probably do a couple delegate based classes. For instance (C# code, but Java should be pretty similar...perhaps someone could translate?):
```
interface IFilter {
public IEnumerable<string> Filter(IEnumerable<string> file) {
}
}
class PredicateFilter : IFilter {
public PredicateFilter(Predicate<string> predicate) { }
public IEnumerable<string> Filter(IEnumerable<string> file) {
foreach (string s in file) {
if (this.Predicate(s)) {
yield return s;
}
}
}
}
class ActionFilter : IFilter {
public ActionFilter(Action<string> action) { }
public IEnumerable<string> Filter(IEnumerable<string> file) {
foreach (string s in file) {
this.Action(s);
yield return s;
}
}
}
class ReplaceFilter : IFilter {
public ReplaceFilter(Func<string, string> replace) { }
public IEnumerable<string> Filter(IEnumerable<string> file) {
foreach (string s in file) {
yield return this.Replace(s);
}
}
}
```
From there, you could either use the delegate filters directly, or subclass them for the specifics. Then, register them with a Pipeline that will pass them through each filter.
|
I think your method is OK. Especially if you use the same interface on every processor.
You could also look to somethink called Drules, currently Jboss-rules. I used that some time ago for a rule-heavy part of my app and what I liked about it is that the business logic can be expressed in for instance a spreadsheet or DSL which then get's compiled to java (run-time and I think there's also a compile-time option). It makes rules a bit more succint and thus readable. It's also very easy to learn (2 days or so).
Here's a link to the opensource [Jboss-rules](https://www.jboss.org/community/docs/DOC-10741). At jboss.com you can undoubtedly purchase an offically maintained version if that's more to your companies taste.
|
Application design for processing data prior to database
|
[
"",
"java",
"design-patterns",
"chain-of-responsibility",
""
] |
I've got the following JavaScript on my web page...
```
64 var description = new Array();
65 description[0] = "..."
66 description[1] = "..."
...
78 function init() {
79 document.getElementById('somedivid').innerHTML = description[0];
80 }
81
82 window.onload = init();
```
In Microsoft Internet Explorer it causes the following error...
> A Runtime Error has occurred.
> Do you wish to debug?
>
> Line: 81
> Error: Not implemented

Line 79 executes as expected.
If line 79 is commented out, it still throws the error.
If I comment out line 82, then the function does not execute and there is no error.
|
Shouldn't line 82 read:
```
window.onload = init;
```
When you do "init()" it's a call to a function that returns void. You end up calling that function before the page loads.
|
To preserve any previously set onload functions try this
```
var prevload = window.onload;
window.onload = function(){
prevload();
init();
}
```
|
Why am I getting this Javascript runtime error?
|
[
"",
"javascript",
"html",
"internet-explorer",
""
] |
While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead.
For an example, see [JBossCache 2.2](http://www.jboss.org/file-access/default/members/jbosscache/freezone/docs/2.2.0.GA/userguide_en/html_single/index.html#api.listener). The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses).
Here's a sample from the JBossCache docs:
```
@CacheListener
public class MyListener {
@CacheStarted
@CacheStopped
public void cacheStartStopEvent(Event e) {
switch (e.getType()) {
case Event.Type.CACHE_STARTED:
System.out.println("Cache has started");
break;
case Event.Type.CACHE_STOPPED:
System.out.println("Cache has stopped");
break;
}
}
@NodeCreated
@NodeRemoved
@NodeVisited
@NodeModified
@NodeMoved
public void logNodeEvent(NodeEvent ne) {
log("An event on node " + ne.getFqn() + " has occured");
}
```
}
The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it.
So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?
|
You can already do this today with [EventBus](http://eventbus.org "EventBus").
Following example is from [EventBus Getting Started guide](http://eventbus.org/confluence/display/EventBus/Getting+Started). Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of publisher(s). Without EventBus, statusbar will need to be added as listener to many classes. Statusbar can also be created and destroyed at any time.
```
public StatusBar extends JLabel {
public StatusBar() {
AnnotationProcessor.process(this);
}
@EventSubscriber(eventClass=StatusEvent.class)
public void updateStatus(StatusEvent statusEvent) {
this.setText(statusEvent.getStatusText();
}
}
```
A similar project is [ELF (Event Listener Framework)](https://elf.dev.java.net/) but it seems to be less mature.
I'm currently researching about event notification frameworks on [Publish-Subscribe Event Driven Programming | Kev's Spring vs Java EE Dev](http://spring-java-ee.blogspot.com/2009/12/publish-subscribe-event-driven.html) and the followup articles.
|
I've made <http://neoevents.googlecode.com> to handle this kind of annotation based event handler.
```
@actionPerformed
private void onClick() {
//do something
}
protected void initComponents() {
JButton button = new JButton("Click me!!!");
button.addActionListener(new ActionListener(this) );
}
```
It looks as simple as I was expecting it to be. Annotations are available for every single listener in J2SE.
|
Generic, annotation-driven event notification frameworks
|
[
"",
"java",
"events",
"annotations",
"notifications",
""
] |
I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the parent doesn't offer which is in its self not fundamentally sound. But is there some way to do this? Here is a code example to so I can better explain what I"m asking.
```
public class SomeBaseClass {
public string GetBaseClassName {get;set;}
public bool BooleanEvaluator {get;set;}
}
public class SomeDerivedClass : SomeBaseClass {
public void Insert(SqlConnection connection) {
//...random connection stuff
cmd.Parameters["IsItTrue"].Value = this.BooleanEvalutar;
//...
}
}
public static void Main(object[] args) {
SomeBaseClass baseClass = new SomeBaseClass();
SomeDerivedClass derClass = (SomeDerivedClass)baseClass;
derClass.Insert(new sqlConnection());
}
```
I know this seems goofy but is there any way to accomplish something of this sort?
|
Not soundly, in "managed" languages. This is *downcasting*, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes - where does this "more" come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for derived types that will take the base type as a prototype.
One could build something with reflection that handled the simple cases (more specific types that have no addition state). In general, just redesign to avoid the problem.
Edit: Woops, can't write conversion operators between base/derived types. An oddity of Microsoft trying to "protect you" against yourself. Ah well, at least they're no where near as bad as Sun.
|
Try composition instead of inheritance!
It seems to me like you'd be better off passing an instance of SomeBaseClass to the SomeDerivedClass (which will no longer derive base class, and should be renamed as such)
```
public class BooleanHolder{
public bool BooleanEvaluator {get;set;}
}
public class DatabaseInserter{
BooleanHolder holder;
public DatabaseInserter(BooleanHolder holder){
this.holder = holder;
}
public void Insert(SqlConnection connection) {
...random connection stuff
cmd.Parameters["IsItTrue"].Value = holder.BooleanEvalutar;
...
}
}
public static void Main(object[] args) {
BooleanHolder h = new BooleanHolder();
DatabaseInserter derClass = new DatabaseInserter(h);
derClass.Insert(new sqlConnection);
}
```
Check out <http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html> (page 3):
> Code reuse via composition Composition
> provides an alternative way for Apple
> to reuse Fruit's implementation of
> peel(). Instead of extending Fruit,
> Apple can hold a reference to a Fruit
> instance and define its own peel()
> method that simply invokes peel() on
> the Fruit.
|
A way of casting a base type to a derived type
|
[
"",
"c#",
"oop",
"inheritance",
"design-patterns",
""
] |
This seems like a pretty softball question, but I always have a hard time looking up this function because there seem there are so many variations regarding the referencing of char and tchar.
|
[MultiByteToWideChar](http://msdn.microsoft.com/en-us/library/dd319072(v=vs.85).aspx) but also see ["A few of the gotchas of MultiByteToWideChar"](http://archives.miloush.net/michkap/archive/2005/04/19/409566.html).
|
The simplest way is to use the conversion macros:
* CW2A
* CA2W
* etc...
[MSDN](http://msdn.microsoft.com/en-us/library/87zae4a3(VS.71).aspx)
|
What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?
|
[
"",
"c++",
"c",
"string",
"char",
"tchar",
""
] |
How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc?
What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)?
What is WCF *not* good for that you've seen people try to shoehorn it into?
-Adam
|
Comparing with .asmx: WCF is the next generation of Microsoft's Web service development platform, which addresses many of the issues with older versions, specifically:
* better interoperation, so you can interoperate with Web services that aren't from Microsoft or that are published on the Internet
* much more flexible, so it's easier and faster for developers to get their jobs done
* easier to configure without changing code, reducing the cost of maintenance significantly
It may be that they raise the question of how it relates to SOA, a "service-oriented architecture". WCF is the Microsoft solution for creating applications that participate in these distributed systems.
|
Tell them it'll let you do your job easier which translates into less time and less money.
|
How to promote WCF to a non-techie?
|
[
"",
"c#",
".net",
"wcf",
"web-services",
"soa",
""
] |
I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it.
(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).
Here is the function I've written:
```
CREATE FUNCTION dbo.GetFriendlyDateTimeValue
(
@CompareDate DateTime
)
RETURNS nvarchar(48)
AS
BEGIN
DECLARE @Now DateTime
DECLARE @Hours int
DECLARE @Suff nvarchar(256)
DECLARE @Found bit
SET @Found = 0
SET @Now = getDate()
SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60
IF @Hours <= 1
BEGIN
SET @Suff = 'Just Now'
SET @Found = 1
RETURN @Suff
END
IF @Hours < 24
BEGIN
SET @Suff = ' Hours Ago'
SET @Found = 1
END
IF @Hours >= 8760 AND @Found = 0
BEGIN
SET @Hours = @Hours / 8760
SET @Suff = ' Years Ago'
SET @Found = 1
END
IF @Hours >= 720 AND @Found = 0
BEGIN
SET @Hours = @Hours / 720
SET @Suff = ' Months Ago'
SET @Found = 1
END
IF @Hours >= 168 AND @Found = 0
BEGIN
SET @Hours = @Hours / 168
SET @Suff = ' Weeks Ago'
SET @Found = 1
END
IF @Hours >= 24 AND @Found = 0
BEGIN
SET @Hours = @Hours / 24
SET @Suff = ' Days Ago'
SET @Found = 1
END
RETURN Convert(nvarchar, @Hours) + @Suff
END
```
|
As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:
```
CASE
WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now()
THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
WHEN datediff(now(), compare_date) = 1
THEN 'Yesterday'
WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now()
THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')
ELSE concat(datediff(now(), compare_date),' days ago')
END
```
Based on a similar sample seen on the [MySQL Date and Time](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#c9500) manual pages
|
In Oracle:
```
select
CC.MOD_DATETIME,
'Last modified ' ||
case when (sysdate - cc.mod_datetime) < 1
then round((sysdate - CC.MOD_DATETIME)*24) || ' hours ago'
when (sysdate - CC.MOD_DATETIME) between 1 and 7
then round(sysdate-CC.MOD_DATETIME) || ' days ago'
when (sysdate - CC.MOD_DATETIME) between 8 and 365
then round((sysdate - CC.MOD_DATETIME) / 7) || ' weeks ago'
when (sysdate - CC.MOD_DATETIME) > 365
then round((sysdate - CC.MOD_DATETIME) / 365) || ' years ago'
end
from
customer_catalog CC
```
|
Best way to convert DateTime to "n Hours Ago" in SQL
|
[
"",
"sql",
"datetime",
"function",
""
] |
I've got a siluation where i need to access a SOAP web service with WSE 2.0 security. I've got all the generated c# proxies (which are derived from Microsoft.Web.Services2.WebServicesClientProtocol), i'm applying the certificate but when i call a method i get an error:
```
System.Net.WebException : The request failed with HTTP status 405: Method Not Allowed.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
```
I've done some googling and it appears that this is a server configuration issue.
However this web service is used many clients without any problem (the web service is provided by a Telecom New Zealand, so it's bound to be configured correctly. I believe it's written in Java)
Can anyone shed some light on this issue?
|
Ok, found what the problem was. I was trying to call a .wsdl url instead of .asmx url.
Doh!
|
I found this was due to WCF not being installed on IIS. The main thing is that the .svc extension has to be mapped in IIS [See MSDN here.](http://msdn.microsoft.com/en-us/library/ms752252%28v=vs.90%29.aspx) Use the ServiceModelReg tool to complete the installation. You'll always want to verify that WCF is installed and .svc is mapped in IIS anytime you get a new machine or reinstall IIS.
|
How to solve HTTP status 405 "Method Not Allowed" when calling Web Services
|
[
"",
"c#",
".net",
"web-services",
"wse2.0",
""
] |
I have a 2 dimensional array, like so:
```
char[,] str = new char[2,50];
```
Now, after I've stored contents in both str[0] and str[1], how do I store it in a
```
string[] s = new string[2];
```
?
I tried
```
s[0] = str[0].ToString();
```
but that seems to be an error: VC# expects 'two' indices within the braces, which means I can convert only a character from the array. Is there a way to convert the entire str[0] to a string? Or is changing it to a jagged array the only solution?
|
A jagged array is almost always the best solution for a variety of reasons, and this is one good example. There is so much more flexibility available with an array of arrays than with a multi-dimensional array. In this case, once you have the values in an array of chars, then a constructor on the string class can be used to create a string from it.
Also, the jagged array would be composed of "vectors" (i.e., a single-dimensional arrays with a zero-lower-bound index), which are much more preferment in .Net because they are given special treatment by the CLR.
So without knowing what the rest of your program is doing, that would be my recommendation.
If you do attempt to construct a string manually by looping through the array indexes, instead of using a jagged array, then I recommend using the StringBuilder class to do it.
I just banged this out, but it should be something like this:
```
// For the multi-dimentional array
StringBuilder sb = new StringBuilder();
for (int stringIndex = 0; stringIndex < s.Length; stringIndex++)
{
sb.Clear();
for (int charIndex = 0; charIndex < str.UpperBound(1); charIndex++)
sb.Append(str[stringIndex,charIndex]);
s[stringIndex] = sb.ToString();
}
// For the jagged array
for (int index = 0; index < s.Length; index++)
s[index] = new string(str[index]);
```
|
Assuming the dimensions are fixed as 2x50:
```
char[,] str = new char[2,50];
// populate str somehow
// chose which of the strings we want (the 'row' index)
int strIndex = 0;
// create a temporary array (faster and less wasteful than using a StringBuilder)
char[] chars = new chars[50];
for (int i = 0; i < 50; i++)
chars[i] = str[strIndex, i];
string s = new string[chars];
```
This would be easier and more performant if you used a jagged array:
```
char[][] str = new char[2][];
```
Then you could write:
```
string s = new string(characters[0]);
```
|
How do I create a string from one row of a two dimensional rectangular character array in C#?
|
[
"",
"c#",
"arrays",
"string",
"character",
"multidimensional-array",
""
] |
I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/finally clauses to be sure that, should something wrong happen, the Buffer Streams would be closed (and thus, my OS ressources freed) before quiting the function.
I trimmed down the function to show the pattern:
```
public static void copyFile(FileOutputStream oDStream, FileInputStream oSStream) throw etc...
{
BufferedInputStream oSBuffer = new BufferedInputStream(oSStream, 4096);
BufferedOutputStream oDBuffer = new BufferedOutputStream(oDStream, 4096);
try
{
try
{
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
}
finally
{
oDBuffer.close(); // could throw a IOException
}
}
finally
{
oSBuffer.close(); // could throw a IOException
}
}
```
As far as I understand it, I cannot put the two `close()` in the finally clause because the first `close()` could well throw, and then, the second would not be executed.
I know C# has the *Dispose* pattern that would have handled this with the `using` keyword.
I even know better a C++ code would have been something like (using a Java-like API):
```
void copyFile(FileOutputStream & oDStream, FileInputStream & oSStream)
{
BufferedInputStream oSBuffer(oSStream, 4096);
BufferedOutputStream oDBuffer(oDStream, 4096);
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
// I don't care about resources, as RAII handle them for me
}
```
I am missing something, or do I really have to produce ugly and bloated code in Java just to handle exceptions in the `close()` method of a Buffered Stream?
(Please, tell me I'm wrong somewhere...)
**EDIT: Is it me, or when updating this page, I saw both the question and all the answers decreased by one point in a couple of minutes? Is someone enjoying himself too much while remaning anonymous?**
EDIT 2: **McDowell** offered a very interesting link I felt I had to mention here:
<http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html>
EDIT 3: Following McDowell's link, I tumbled upon a proposal for Java 7 of a pattern similar to the C# using pattern: <http://tech.puredanger.com/java7/#resourceblock> . My problem is explicitly described. Apparently, even with the Java 7 `do`, the problems remain.
|
The try/finally pattern is the correct way to handle streams in most cases for Java 6 and lower.
*Some are advocating silently closing streams. Be careful doing this for these reasons: [Java: how not to make a mess of stream handling](http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html)*
---
Java 7 introduces *try-with-resources*:
```
/** transcodes text file from one encoding to another */
public static void transcode(File source, Charset srcEncoding,
File target, Charset tgtEncoding)
throws IOException {
try (InputStream in = new FileInputStream(source);
Reader reader = new InputStreamReader(in, srcEncoding);
OutputStream out = new FileOutputStream(target);
Writer writer = new OutputStreamWriter(out, tgtEncoding)) {
char[] buffer = new char[1024];
int r;
while ((r = reader.read(buffer)) != -1) {
writer.write(buffer, 0, r);
}
}
}
```
[`AutoCloseable`](http://download.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html) types will be automatically closed:
```
public class Foo {
public static void main(String[] args) {
class CloseTest implements AutoCloseable {
public void close() {
System.out.println("Close");
}
}
try (CloseTest closeable = new CloseTest()) {}
}
}
```
|
Unfortunately, this type of code tends to get a bit bloated in Java.
By the way, if one of the calls to oSBuffer.read or oDBuffer.write throws an exception, then you probably want to let that exception permeate up the call hierarchy.
Having an unguarded call to close() inside a finally-clause will cause the original exception to be replaced by one produced by the close()-call. In other words, a failing close()-method may hide the original exception produced by read() or write(). So, I think you want to ignore exceptions thrown by close() if *and only if* the other methods did not throw.
I usually solve this by including an explicit close-call, inside the inner try:
```
try {
while (...) {
read...
write...
}
oSBuffer.close(); // exception NOT ignored here
oDBuffer.close(); // exception NOT ignored here
} finally {
silentClose(oSBuffer); // exception ignored here
silentClose(oDBuffer); // exception ignored here
}
```
```
static void silentClose(Closeable c) {
try {
c.close();
} catch (IOException ie) {
// Ignored; caller must have this intention
}
}
```
Finally, for performance, the code should probably work with buffers (multiple bytes per read/write). Can't back that by numbers, but fewer calls should be more efficient than adding buffered streams on top.
|
RAII in Java... is resource disposal always so ugly?
|
[
"",
"java",
"design-patterns",
"raii",
"resource-management",
""
] |
Here is the directory layout that was installed with Leopard. What is the "A" directory and why the "Current" directory in addition to the "CurrentJDK"?
It seems like you can easily switch the current JDK by move the CurrentJDK link, but then the contents under Current and A will be out of sync.
```
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.3 -> 1.3.1
drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 1.4.1 -> 1.4
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.6 -> 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 A
lrwxr-xr-x 1 root wheel 1 Jun 14 15:49 Current -> A
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 CurrentJDK -> 1.5
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions $
```
and the contents of A
```
-rw-r--r-- 1 root wheel 1925 Feb 29 2008 CodeResources
drwxr-xr-x 34 root wheel 1156 Jun 14 15:49 Commands
drwxr-xr-x 3 root wheel 102 Mar 6 2008 Frameworks
drwxr-xr-x 16 root wheel 544 Jun 14 15:49 Headers
-rwxr-xr-x 1 root wheel 236080 Feb 29 2008 JavaVM
drwxr-xr-x 29 root wheel 986 Jun 14 15:49 Resources
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions/A $
```
|
The (`A`, `Current` symbolic-linked to `A`) is part of the structure of a Mac OS X framework, which `JavaVM.framework` is. This framework may have C or Objective-C code in it, in addition to the actual JVM installations. Thus it could potentially be linked against from some C or Objective-C code in addition to containing the JVM alongside that.
Note that you **should not** change the `CurrentJDK` link to point at anything but what it is set to by Mac OS X. Unlike on other platforms, the Java virtual machine is an operating system service on Mac OS X, and changing it in this way would put you in an unsupported (and potentially untested, unstable, etc.) configuration.
|
You should use the Java Preferences command to change the jvm version.
If you have spotlight on your Harddisk, you can just spotlight "Java Preferences"
|
Explain the JVM Directory Layout on Mac OSX Leopard
|
[
"",
"java",
"macos",
"jvm",
""
] |
I have a function pointer defined by:
```
typedef void (*EventFunction)(int nEvent);
```
Is there a way to handle that function with a specific instance of a C++ object?
```
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
class B
{
private:
A a;
public:
B() { a.SetEvent(EventFromA); } // What do I do here?
void EventFromA(int nEvent) { // do stuff }
};
```
**Edit:** Orion pointed out the options that Boost offers such as:
```
boost::function<int (int)> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
```
Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?
|
I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
<http://www.codeproject.com/KB/cpp/FastDelegate.aspx>
|
You can use function pointers to index into the vtable of a given object instance. This is called a [member function pointer](http://www.parashift.com/c++-faq-lite/pointers-to-members.html). Your syntax would need to change to use the ".\*" and the "&::" operators:
```
class A;
class B;
typedef void (B::*EventFunction)(int nEvent)
```
and then:
```
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne(B* delegate) { ((*delegate).*handler)(1); } // note: ".*"
};
class B
{
private:
A a;
public:
B() { a.SetEvent(&B::EventFromA); } // note: "&::"
void EventFromA(int nEvent) { /* do stuff */ }
};
```
|
Calling a C++ function pointer on a specific object instance
|
[
"",
"c++",
"pointers",
"function",
""
] |
What are some practical uses for the "[Curiously Recurring Template Pattern](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern)"? The "[counted class](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern#Object_counter)" example commonly shown just isn't a convincing example to me.
|
[Simulated dynamic binding](http://c2.com/cgi/wiki?SimulatedDynamicBinding).
Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on.
|
It's also especially useful for **mixins** (by which I mean classes you inherit from to provide functionality) which themselves need to know what type they are operating on (and hence need to be templates).
In *Effective C++*, Scott Meyers provides as an example a class template NewHandlerSupport<T>. This contains a static method to override the new handler for a particular class (in the same way that std::set\_new\_handler does for the default operator new), and an operator new which uses the handler. In order to provide a per-type handler, the parent class needs to know what type it is acting on, so it needs to be a class template. The template parameter is the child class.
You couldn't really do this without CRTP, since you need the NewHandlerSupport template to be instantiated separately, with a separate static data member to store the current new\_handler, per class that uses it.
Obviously the whole example is extremely non-thread-safe, but it illustrates the point.
Meyers suggests that CRTP might be thought of as "Do It For Me". I'd say this is generally the case for any mixin, and CRTP applies in the case where you need a mixin template rather than just a mixin class.
|
Practical Uses for the "Curiously Recurring Template Pattern"
|
[
"",
"c++",
"templates",
"design-patterns",
"crtp",
"f-bounded-polymorphism",
""
] |
I have to lock user accounts in Active Directory programmatically in C#.
Unfortunately it doesn't work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won't accept the value and resets it without further notice to 512 (=normal account).
Now I tried to lock the account by providing incorrect credentials (see below), but this doesn't work either.
```
int retries = 0;
while (!adsUser.IsAccountLocked && retries < MAX_LOCK_RETRIES)
{
retries++;
try
{
new DirectoryEntry(userPath, logonName, incorrectPassword).RefreshCache();
}
catch (Exception)
{
/* ... */
}
adsUser.GetInfo();
}
```
Any ideas?
|
Make sure the account you're using to disable the account has sufficient privileges to disable accounts. See [this example](http://msdn.microsoft.com/en-us/library/ms696026(VS.85).aspx) from Microsoft.
|
This code will work to lock a user in AD
```
/// <summary>
/// Locks a user account
/// </summary>
/// <param name="userName">The name of the user whose account you want to unlock</param>
/// <remarks>
/// This actually trys to log the user in with a wrong password.
/// This in turn will lock the user out
/// </remarks>
public void LockAccount(string userName)
{
DirectoryEntry user = GetUser(userName);
string path = user.Path;
string badPassword = "SomeBadPassword";
int maxLoginAttempts = 10;
for (int i = 0; i < maxLoginAttempts; i++)
{
try
{
new DirectoryEntry(path, userName, badPassword).RefreshCache();
}
catch (Exception e)
{
}
}
user.Close();
}
```
|
Lock Active Directory accounts programmatically
|
[
"",
"c#",
"active-directory",
""
] |
Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter.
Detais are following:
```
//exception overloads:
public FilterXmlParseException(string message, Exception innerException)
: base(message, innerException) { }
public FilterXmlParseException(string message, IXmlLineInfo lineInfo) {...}
//Usage:
XmlReader reader = ...
IXmlLineInfo lineinfo = (IXmlLineInfo)reader;
//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
//ok
throw new FilterXmlParseException("<Filter> element expected", lineinfo);
```
And it fails since it could not select correct overload.But why? We see that XmlReader supports an interface and it is not inherited from System.Exception
|
The line:
```
//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
```
because XmlReader doesn't implement IXmlLineInfo. I am not sure if your cast works, but the casts are not checked statically. If it actually works, it is because the concrete class (that inherits from XmlReader) implements this interface, but the compiler has no way to know it.
|
It couldn't choose an overload for the XmlReader call because *neither* overload is acceptable. XmlReader does not inherit from Exception, so the first call is invalid. XmlReader also does not Implement IXmlLineInfo.
The reason why it works in the second case is that you are forcing the cast. However, I believe that if you were to actually run that code, it would throw an InvalidCastException. Read the documentation on XmlReader, and you'll see that the only interface it implements is IDispoable.
<http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx>
|
Compiler could not choose an overload between interface and exception
|
[
"",
"c#",
".net",
"compiler-construction",
""
] |
I'm looking for books or online resources that go in detail over programming techniques for high performance computing using C++.
|
practically all HPC code I've heard of is either for solving sytems of linear equations or FFT's. Heres some links to start you off at least in the libraries used:
* [BLAS](http://en.wikipedia.org/wiki/Blas) - standard set of routines for linear algebra - stuff like matrix multiplication
* [LAPACK](http://en.wikipedia.org/wiki/Lapack) - standard set of higher level linear algebra routines - stuff like LU decomp.
* [ATLAS](http://en.wikipedia.org/wiki/Automatically_Tuned_Linear_Algebra_Software) - Optimized BLAS implementation
* [FFTW](http://en.wikipedia.org/wiki/FFTW) - Optimized FFT implementation
* [PBLAS](http://people.scs.fsu.edu/~burkardt/f_src/pblas/pblas.html) - BLAS for distributed processors
* [SCALAPACK](http://people.scs.fsu.edu/~burkardt/f_src/scalapack/scalapack.html) - distributed LAPACK implementation
* [MPI](http://en.wikipedia.org/wiki/Message_Passing_Interface) - Communications library for distributed systems.
* [PETSc](http://mcs.anl.gov/petsc) - Scalable nonlinear and linear solvers (user-extensible, interface to much above)
|
Even though not FOSS, the Intel [IPP](http://www.intel.com/cd/software/products/asmo-na/eng/302910.htm) and [MKL](http://www.intel.com/cd/software/products/asmo-na/eng/307757.htm) libraries can really save you a lot of time (both in development and at runtime) if you need to perform any of the operations supported by these libraries (e.g.: signal processing, image processing, matrix math). Of course, it depends on your platform whether you can take benefit from them.
(No: I don't work for Intel, but a happy customer of theirs I am.)
|
Resources for high performance computing in C++
|
[
"",
"c++",
"performance",
""
] |
I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range.
Here's an example:
```
IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
```
|
This is already in the framework: [Enumerable.Range](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx).
For other types, you might be interested in the range classes in my [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) library.
|
Alternately, a fluent interface from extension methods:
```
public static IEnumerable<int> To(this int start, int end)
{
return start.To(end, i => i + 1);
}
public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
{
int current = start;
while (current < end)
{
yield return current;
current = next(current);
}
}
```
used like:
```
1.To(100)
```
|
What's the best way to write [0..100] in C#?
|
[
"",
"c#",
"linq",
"optimization",
"sequences",
""
] |
What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.
|
Quick'n'dirty:
```
int value = 0x48454C4F;
Console.WriteLine(Encoding.ASCII.GetString(
BitConverter.GetBytes(value).Reverse().ToArray()
));
```
Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.
EDIT: The `Reverse` method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario.
|
Char? Maybe you are looking for this handy little helper function?
```
Byte[] b = BitConverter.GetBytes(i);
Char c = (Char)b[0];
[...]
```
|
Conversion from 32 bit integer to 4 chars
|
[
"",
"c#",
"encoding",
""
] |
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.
Example:
```
public interface ICut
{
void Cut();
}
public class Knife : ICut
{
void ICut.Cut()
{
//Cut Something
}
}
```
And to use the Knife object:
```
ICut obj = new Knife();
obj.Cut();
```
Would you recommend this method of interface implementation? Why or why not?
EDIT:
Also, given that I am using an explicit interface the following would NOT work.
```
Knife obj = new Knife();
obj.Cut();
```
|
To quote GoF chapter 1:
* "Program to an interface, not an implementation".
* "Favor object composition over class inheritance".
As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.
ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)
ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?
|
I've only used it in scenarios where I want to restrict access to certain methods.
```
public interface IWriter
{
void Write(string message);
}
public interface IReader
{
string Read();
}
public class MessageLog : IReader, IWriter
{
public string Read()
{
// Implementation
return "";
}
void IWriter.Write(string message)
{
// Implementation
}
}
public class Foo
{
readonly MessageLog _messageLog;
IWriter _messageWriter;
public Foo()
{
_messageLog = new MessageLog();
_messageWriter = _messageLog;
}
public IReader Messages
{
get { return _messageLog; }
}
}
```
Now Foo can write messages to it's message log using \_messageWriter, but clients can only read. This is especially beneficial in a scenario where your classes are ComVisible. Your client can't cast to the Writer type and alter the information inside the message log.
|
Using explicit interfaces to ensure programming against an interface
|
[
"",
"c#",
"design-patterns",
"interface",
""
] |
Where do you store *user-specific* and *machine-specific* **runtime** configuration data for J2SE application?
(For example, *C:\Users\USERNAME\AppData\Roaming</em> on Windows and /home/username* on Unix)
How do you get these locations in the filesystem in platform-independent way?
|
That depends on your kind of J2SE Application:
* J2SE executable JAR file (very simple): use [user.home System property](http://www.mindspring.com/~mgrand/java-system-properties.htm) to find home-dir. Then make a subdir accordingly (like e.g. PGP, SVN, ... do)
* Java Web Start provides very nice included methods to safe properties. Always user-specific
* Finally Eclipse RCP: There you have the notion of the workspace (also derived from user.home) for users and configuration (not totally sure how to access that tricky in Vista) for computer wide usage
All these approaches are, when used with care -- use correct [separatorChar](http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#separator) -- OS neutral.
|
First on the format:
1. Java [property files](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html#load(java.io.InputStream)) are good for key/value pairs (also automatically handle the newline chars). A degree of structure is possible by using 'dot notation'. Drawback is that the structure does not allow you to easily enumerate top-level configuration entities and work in drill-down manner. Best used for a small set of often tweakable environment-specific settings
2. XML files - quite often used for more complex configuration of various Java frameworks (notably J2EE and Spring). I would advice that you at least learn about [Spring](http://static.springframework.org/spring/docs/2.5.x/reference/index.html) - it contains many ideas worth knowing even if you decide not to use it. If you decide to roll your own XML configuration, I'd recommend using [XStream](http://xstream.codehaus.org/) with customized serialization options or if you just need to parse some XML, take a look at [XOM](http://www.xom.nu/). BTW Spring also allows you to plug your custom XML configuration language, but it's a [relatively complex task](http://static.springframework.org/spring/docs/2.5.x/reference/extensible-xml.html). XML configuration is best used for more complex 'internal' configuration that is not seen or tweaked by the end user.
3. Serialized Java objects - a quick and easy way to persist the state of an object and restore it later. Useful if you write a configuration GUI and you don't care if the configuration is human readable. Beware of [compatibility issues](http://www.ibm.com/developerworks/library/j-serialtest.html) when you evolve classes.
4. Preferences - introduced in [Java 1.4](http://java.sun.com/j2se/1.5.0/docs/api/java/util/prefs/Preferences.html), allow you to store typed text, numbers, byte arrays and other primitives in platform-specific storage. On Windows, that is the registry (you can choose between */Software/JavaSoft/Prefs* under *HKLM* or *HKCU*). Under Unix the same API creates files under the user home or */etc*. Each prefs hive can be exported and imported as XML file. You can specify custom implementation of the [PreferencesFactory](http://java.sun.com/j2se/1.4.2/docs/api/java/util/prefs/PreferencesFactory.html) interface by setting the "java.util.prefs.PreferencesFactory" JVM property to your implementation class name.
In general using the prefs API can be a good or a bad thing based on your app scenario.
1. If you plan to have multiple versions of the same code running on the same machine with different configuration, then using the Preferences API is a bad idea.
2. If you plan using the application in a restricted environment (Windows domain or tightly managed Unix box) you need to make sure that you have proper access to the necessary registry keys/directories. This has caught me by surprise more than once.
3. Beware from roaming profiles (replicated home dirs) they make up for some funny scenarios when more than one active machines are involved.
4. Preferences are not as obvious as a configuration file under the application's directory. most of the desktop support staff doesn't expect and doesn't like them.
Regarding the file layout of the prefs it again depends on your application. A generic suggestion is:
1. Package most of your XML files inside application's JAR either in the root or under /META-INF directory. These files will be read-only and are considered private for the application.
2. Put the user modifiable configuration under *$APP\_HOME/conf* . It should consist mainly of properties files and occasionally a simple XML file (XStream serialization). These files are tweaked as part of the installation process and are usually not user serviceable.
3. Under the user-home, in a dot-directory (i.e. '~/.myapplication') store any user configuration. The user configuration may override the one in the application *conf* directory. Any changes made from within the application go here (see also next point).
4. You can also use an *$APP\_HOME/var* directory to store any other mutable data which is specific to this application instance (as opposed to the user). Another advantage of this approach is that you can move and backup the whole application and it's configuration by simple copy of one directory.
This illustrates some standard techniques for managing configuration. You can implement them using different libraries and tools, starting from raw JRE, adding Spring/Guice or going for a full J2EE container (possibly with embedded Spring)
Other approaches for managing configuration are:
1. Using [multiple base directories](http://azeditech.com/tomcat/multiple-tomcat-instances.html) for running multiple instances of the application using different configurations.
2. Using [lightweight](http://www.mulesource.org/display/GALAXY/Home) [registries](http://wso2.org/projects/registry) for centralized configuration management
3. A centrally managed Configuration Management Database (CMDB) file, containing the host-specific values for each machine is rsync-ed every night to all production hosts. The application uses a templated configuration and selects from the CMDB during runtime based on the current hostname.
|
What is the proper way to store app's conf data in Java?
|
[
"",
"java",
"configuration",
""
] |
Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a .NET school...) and while I was doing my final year project, i found this definition for a model
> The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.
it doesn't say the model should represent one table as what activerecord does. And normally within a transaction, one may have to query a few unrelated tables and then manipulate data from different tables... so if activerecord is used as model, then either one would have to cram all the logic code into the controller (which is kinda popular in some php frameworks) that makes it difficult to test or hack the activerecord model so that it performs database operation on not only the table it maps to, but also other related tables as well...
so, what is so great about abusing (IMHO) activerecord as the model in a MVC architectural pattern?
|
Martin Fowler described this pattern in Patterns of Enterprise Application Architecture together with two other patterns or architectures. These patterns are good for different situations and different amounts of complexity.
If you want to so only simple stuff you can use Transaction Script. This is an architecture you saw in lot's of old ASP and PHP pages where a single script contained the business logic, data-access logic and presentation logic. This falls apart fast when things get more complicated.
The next thing you can do is add some separation between presentation and model. This is activerecord. The model is still tied to the database but you've a bit more flexibility because you can reuse your model/dataccess between views/pages/whatever. It's not as flexible as it could be but depending on your data-access solution it can be flexible enough. Frameworks like CSLA in .Net have a lot of aspects from this patterm (I think Entity Framework looks a bit too much like this too). It can still handle a lot of complexity without becoming unmaintainable.
The next step is separating your data-access layer and your model. This usually requires a good OR mapper or a lot of work. So not everyone wants to go this way. Lot's of methodologies like domain driven design perscribe this approach.
So it's all a matter of context. What do you need and what is the best solution. I even still use transaction-script sometimes for simple single use code.
|
I've said many times that using Active Record (or ORM which is almost the same) as Business Models is not a good idea. Let me explain:
The fact that PHP is Open Source, Free (and all that long story...) provides it with a vast community of developers pouring code into forums, sites like GitHub, Google code and so on. You might see this as a good thing, but sometimes it tends not to be "so good". For instance, suppose you are facing a project and you wish to use a ORM framework for facing your problem written in PHP, well... you'll have a lot of [options to choose for](http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software):
* Doctrine
* Propel
* QCodo
* Torpor
* RedBean
And the list goes on and on. New projects are created regularly. So imagine that you've built a full blown framework and even a source code generator based on that framework. But you didn't placed business classes because, after all, "why writing the same classes again?". Time goes by and a new ORM framework is released and you want to switch to the new ORM, but you'll have to modify almost every client application using direct reference to your data model.
Bottom line, Active Record and ORM are meant to be in the Data Layer of your application, if you mix them with your Presentation Layer, you can experience problems like this example I've just laid.
Hear @Mendelt's wise words: Read Martin Fowler. He's put many books and articles on OO design and published some good material on the subject. Also, you might want to look into [Anti-Patterns](http://www.antipatterns.com/), more specifically into [Vendor Lock In](http://www.antipatterns.com/vendorlockin.htm), which is what happens when we make our application dependent on 3rd party tools. Finally, I wrote [this](http://davidcondemarin.blogspot.com/2010/11/using-orm-classes-as-business-models.html) blog post speaking about the same issue, so if you want to, check it out.
Hope my answer has been of any use.
|
activerecord as model, is this a good idea?
|
[
"",
"php",
"model-view-controller",
"activerecord",
""
] |
Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)?
|
Go into 'Window' -> 'Preferences' then select 'Java' -> 'Installed JREs', clone the JRE used by Tomcat and add the following to the default VM Arguments
```
-Djava.security.manager -Djava.security.policy="XXXX\conf\catalina.policy"
```
With XXXX replaced by the appropriate path - Mine was `C:\Program Files\Apache Software Foundation\Tomcat 5.5`). Then change the JRE name (I added "security enabled" to the end) and click 'Finish'.
After that, open 'Server' -> 'Runtime Environments' in the preferences, and select your Apache Tomcat environment, then click the 'Edit...' button. In the resulting window, select the new security enabled JRE, then click 'Finish' and restart Tomcat.
|
Or you can just check "Enable Security" in Server Overview page.
(Server -> your server setting -> Overview )
then eclipse will add parameters below
> -Djava.security.manager -Djava.security.policy=X:XXX\XXX.metadata.plugins\org.eclipse.wst.server.core\tmp0\conf\catalina.policy
> -Dwtp.configured.security=true
|
Configuring tomcat security manager in Eclipse
|
[
"",
"java",
"eclipse",
"tomcat",
""
] |
Lately I've been taking a look at [Haxe](http://haxe.org), to build an application to be deployed to Apache running PHP. Well, while it looks like it might suit my needs (deploying to PHP, but not using an awful language), I haven't found anything to make the actual application development easier than building a traditional non-MVC PHP app. Are there any toolkits/frameworks that I'm missing, that would be worthwhile?
It'd be nice if it were MVC inspired, and I'd definitely want an easy way to use nice URLS, though I could settle for mod\_rewrite rules if necessary.
Edit: The idea is to **not** use something like CakePHP on the PHP end, but to instead use something like CakePHP on the Haxe end.
|
There is a port of PureMVC for Haxe: [https://github.com/PureMVC/puremvc-haxe-standard-framework/wiki](https://github.com/PureMVC/puremvc-haxe-standard-framework/wiki "PureMVC haXe")
As far as I know this the only thing for Haxe, but there are discussions on the mailing list about creating a own framework, but this could take a while.
|
I'm happy to say that haXigniter has been completely rewritten, to get away from the PHP-framework-style as mentioned by Marek. Now it adheres much more to better OO-principles and is also a standard haXe library, so upgrades are much simpler. Please check it out at <http://github.com/ciscoheat/haxigniter>.
|
Web "frameworks" for Haxe to deploy in a PHP environment?
|
[
"",
"php",
"web-frameworks",
"haxe",
""
] |
Structs seem like a useful way to parse a binary blob of data (ie a file or network packet). This is fine and dandy until you have variable size arrays in the blob. For instance:
```
struct nodeheader{
int flags;
int data_size;
char data[];
};
```
This allows me to find the last data character:
```
nodeheader b;
cout << b.data[b.data_size-1];
```
Problem being, I want to have multiple variable length arrays:
```
struct nodeheader{
int friend_size;
int data_size;
char data[];
char friend[];
};
```
I'm not manually allocating these structures. I have a file like so:
```
char file_data[1024];
nodeheader* node = &(file_data[10]);
```
As I'm trying to parse a binary file (more specifically a class file). I've written an implementation in Java (which was my class assignment), no I'm doing a personal version in C++ and was hoping to get away without having to write 100 lines of code. Any ideas?
Thanks,
Stefan
|
You cannot have multiple variable sized arrays. How should the compiler at compile time know where friend[] is located? The location of friend depends on the size of data[] and the size of data is unknown at compile time.
|
This is a very dangerous construct, and I'd advise against it. You can only include a variable-length array in a struct when it is the LAST element, and when you do so, you have to make sure you allocate enough memory, e.g.:
```
nodeheader *nh = (nodeheader *)malloc(sizeof(nodeheader) + max_data_size);
```
What you want to do is just use regular dynamically allocated arrays:
```
struct nodeheader
{
char *data;
size_t data_size;
char *friend;
size_t friend_size;
};
nodeheader AllocNodeHeader(size_t data_size, size_t friend_size)
{
nodeheader nh;
nh.data = (char *)malloc(data_size); // check for NULL return
nh.data_size = data_size;
nh.friend = (char *)malloc(friend_size); // check for NULL return
nh.friend_size = friend_size;
return nh;
}
void FreeNodeHeader(nodeheader *nh)
{
free(nh->data);
nh->data = NULL;
free(nh->friend);
nh->friend = NULL;
}
```
|
Dereferencing Variable Size Arrays in Structs
|
[
"",
"c++",
"struct",
""
] |
What is the difference between applying the visitor design pattern to your code and the following approach:
```
interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s) {
this.s = s;
}
public void setInterface(Dointerface d) {
this.d = d;
}
public void perform() {
d.perform(this);
}
public static void main(String[] args) {
T t = new T("Geonline");
t.setInterface(new Dointerface() {
public void perform(Object o) {
T a = (T)o;
System.out.println(a.getS());
}
});
t.perform();
}
}
```
I assume that by using interfaces, we're not really separating the algorithm.
|
Two things:
* In your example you need two methods. The `perfom` and the `setInterface`. With a visitor pattern you would only need one method, the `perfom`, usually called `accept`.
* If you need more than one 'performer', you will have to set the performer -via the `setInterface` method- for each. This makes it impossible to make your class immutable.
|
There is quite a big difference.
The visitor pattern uses interfaces, but its purpose is to be able to perform an operation to one or more classes (who implement an interface) without having to change the classes. Hence, the implementation actually "visits" the class and does its thing without the class being modified.
An interface is a basic concept used to provide a common API to a potentially diverse group of classes. The typical test for an interface is that classes that share it are alike in at least that one respect (is-like-a) and in those cases can be treated as such.
[Here is a simple example on wikipedia that shows a couple of visitors in java.](http://en.wikipedia.org/wiki/Visitor_pattern#Example_in_Java)
|
what is the difference between using the visitor pattern and an interface?
|
[
"",
"java",
"design-patterns",
"coding-style",
"visitor-pattern",
""
] |
I want to make a JavaScript application that's not open source, and thus I wish to learn how to can obfuscate my JS code? Is this possible?
|
**Obfuscation:**
Try [**YUI Compressor**](http://yuilibrary.com/). It's a very popular tool, built, enhanced and maintained by the Yahoo UI team.
You may also use:
* [Google Closure Compiler](http://closure-compiler.appspot.com/home)
* [UglifyJS](http://marijnhaverbeke.nl/uglifyjs)
`UPDATE: This question was originally asked on 2008, and The mentioned technologies are deprecated. you can use:`
* [terser](https://github.com/terser/terser) - more information in [web.dev](https://web.dev/unminified-javascript/).
**Private String Data:**
Keeping string values private is a different concern, and obfuscation won't really be of much benefit. Of course, by packaging up your source into a garbled, minified mess, you have a light version of **security** through **obscurity**. Most of the time, it's your user who is viewing the source, and the string values on the client are intended for their use, so that sort of private string value isn't often necessary.
If you really had a value that you never wanted a user to see, you would have a couple of options. First, you could do some kind of encryption, which is decrypted at page load. That would probably be one of the most secure options, but also a lot of work which may be unnecessary. You could probably base64 encode some string values, and that would be easier.. but someone who really wanted those string values could **easily decode them**. Encryption is the only way to truly prevent anyone from accessing your data, and most people find that to be more security than they need.
**Sidenote:**
Obfuscation in Javascript has been known to cause some bugs. The obfuscators are getting a little better about it, but many outfits decide that they see enough benefit from **minifying** and **gzipping**, and the added savings of obfuscation **isn't always worth the trouble**. If you're trying to protect your source, maybe you'll decide that it's worth your while, just to make your code harder to read. [**JSMin**](http://www.crockford.com/javascript/jsmin.html) is a good alternative.
|
I'm surprised no one has mentioned Google's [Closure Compiler](http://code.google.com/closure/compiler/). It doesn't just minify/compress, it analyzes to find and remove unused code, and rewrites for maximum minification. It can also do type checking and will warn about syntax errors.
JQuery recently switched from YUI Compresser to Closure Compiler, and saw a "[solid improvement](http://twitter.com/jeresig/status/5462879648)"
|
How can I obfuscate (protect) JavaScript?
|
[
"",
"javascript",
"obfuscation",
"source-code-protection",
""
] |
Does any one know how can I convert a BSTR to an int in VC++ 2008
Thanks in advance.
|
You can [pass a BSTR safely](https://stackoverflow.com/questions/71980/how-do-you-efficiently-copy-bstr-to-wchart) to any function expecting a `wchar_t *`. So you can use [\_wtoi](http://msdn.microsoft.com/en-us/library/yd5xkb5c(VS.80).aspx)().
|
Google suggests [`VarI4FromStr`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms221194%28v=vs.85%29.aspx):
```
HRESULT VarI4FromStr(
_In_ LPCOLESTR strIn,
_In_ LCID lcid,
_In_ ULONG dwFlags,
_Out_ LONG *plOut
);
```
|
Convert BSTR to int
|
[
"",
"c++",
"winapi",
""
] |
I notice that modern C and C++ code seems to use `size_t` instead of `int`/`unsigned int` pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.
|
The `size_t` type is the unsigned integer type that is the result of the `sizeof` operator (and the `offsetof` operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The `size_t` type may be bigger than, equal to, or smaller than an `unsigned int`, and your compiler might make assumptions about it for optimization.
You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in [pdf](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) format, or in the C11 standard, section 7.19, also available as a [pdf draft](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf).
|
Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide `size_t`. The C standards committee introduced `size_t` to eliminate a portability problem
[Explained in detail at embedded.com (with a very good example)](http://www.embedded.com/electronics-blogs/programming-pointers/4026076/Why-size-t-matters)
|
unsigned int vs. size_t
|
[
"",
"c++",
"c",
"size-t",
""
] |
What is the SQL command to copy a table from one database to another database?
I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database.
Sorry if the question is too novice.
Thanks.
|
If your two database are separated, the simplest thing to do would be to create a dump of your table and to load it into the second database. Refer to your database manual to see how a dump can be performed.
Otherwise you can use the following syntax (for MySQL)
```
INSERT INTO database_b.table (SELECT * FROM database_a.table)
```
|
If the target table doesn't exist....
```
CREATE TABLE dest_table AS (SELECT * FROM source_table);
```
If the target table does exist
```
INSERT INTO dest_table (SELECT * FROM source_table);
```
Caveat: Only tested in Oracle
|
SQL Command for copying table
|
[
"",
"sql",
"mysql",
""
] |
I've been writing some providers in c# that inherit from the providerbase class. I've found that it's hard to write tests that use the providers as most mocking frameworks will only allow you to mock an interface.
Is there any way to mock a call to a provider that inherits from providerbase?
If not, is there a pattern that I can use to implement mocking of providers?
|
Mocking frameworks should be able to create for you a mock object based on a class, as long as it's got virtual members.
You may also want to take a look at [Typemock](http://www.typemock.com/)
|
I know Rhino mocks can mock classes too, most other mocking frameworks should have no problems with this either.
Things too keep in mind: The class can't be sealed. You need to mark methods you want to mock virtual and the class needs a constructor with no arguments this can be protected, private won't work. (just tried this out)
Keep in mind that the mocking framework will just create a class that inherits from your class and creates an object of that type. So constructors will get called. This can cause unexpected behaviour in your tests.
|
Mocking classes that aren't interfaces
|
[
"",
"c#",
"unit-testing",
"mocking",
""
] |
I want to calculate the time span between 2 times which I saved in a database.
So literally I want to know the length of time between the 2 values.
14:10:20 - 10:05:15 = 02:05:05
So the result would be 02:05:05.
How would I be able to achieve this using C#?
14:10:20 is the format I saved it in in my database.
|
Read the two time values into TimeSpan variables, then perform a `.Subtract()` on the bigger TimeSpan variable to get the TimeSpan result.
E.g. `TimeSpan difference = t1.Subtract(t2);`.
|
Your first step will be to get the timevalues stored in your database into .NET `DateTime` structs.
If you stored them as SQL-DateTime values in the database you can get them directly as `DateTime`. It would look something like this:
```
SQLCommand getTimeCommand = new SQLCommand("SELECT time FROM table", dbConnection);
SQLDataReader myReader = getTimeCommand.ExecuteReader();
while (myReader.Read())
{
DateTime time = myReader.GetDateTime(0);
}
myReader.Close();
```
Your implementation might differ, refer to the ADO.NET documentation in the MSDN library.
If you already got a string representing the time you can parse the string into a `DateTime` using the static methods
```
DateTime.Parse
```
or
```
DateTime.ParseExact
```
In your case you might need to use `ParseExact`, which can pe provided with a format-string defining how to read the string. Examples should be found in the MSDN library.
Durations in .NET are stored inside a `TimeSpan` struct. Getting the elapsed time between to datetimes is easy:
```
DateTime time1, time2; //filled with your timevalues from the db
TimeSpan elapsed = d2 - d1;
```
`elapsed` now contains the timespan between the two `DateTimes`. There are several members for the struct to access the `TimeSpan`. Look into the MSDN-Library to find the ones you need.
|
How do you calculate accumulative time in C#?
|
[
"",
"c#",
"datetime",
"time",
""
] |
I'm experimenting with internationalization by making a Hello World program that uses properties files + ResourceBundle to get different strings.
Specifically, I have a file "messages\_en\_US.properties" that stores "hello.world=Hello World!", which works fine of course.
I then have a file "messages\_ja\_JP.properties" which I've tried all sorts of things with, but it always appears as some type of garbled string when printed to the console or in Swing. The problem is obviously with the reading of the content into a Java string, as a Java string in Japanese typed directly into the source can print fine.
Things I've tried:
* The .properties file in UTF-8 encoding with the Japanese string as-is for the value. Something I read indicates that Java expects a properties file to be in the native encoding of the system...? It didn't work either way.
* The file in default encoding (ISO-8859-1) and the value stored as escaped Unicode created by the native2ascii program included with Java. Tried with a source file in various Japanese encodings... SHIFT-JIS, EUC-JP, ISO-2022-JP.
**Edit:**
I actually figured this out while I was typing this, but I figured I'd post it anyway and answer it in case it helps anyone.
|
I realized that native2ascii was assuming (surprise) that it was converting from my operating system's default encoding each time, and as such not producing the correct escaped Unicode string.
Running native2ascii with the "-encoding *encoding\_name*" option where *encoding\_name* was the name of the source file's encoding (SHIFT-JIS in this case) produced the correct result and everything works fine.
Ant also has a native2ascii task that runs native2ascii on a set of input files and sends output files wherever you want, so I was able to add a builder that does that in Eclipse so that my source folder has the strings in their original encoding for easy editing and building automatically puts converted files of the same name in the output folder.
|
As of JDK 1.6, Properties has a [load()](http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)) method that accepts a Reader. That means you can save all the property files as UTF-8 and read them all directly by passing an InputStreamReader to load(). I think that's the most elegant solution, but it requires your app to run on a Java 6 runtime.
Historically, load() only accepted an InputStream, and the stream was decoded as ISO-8859-1. *Not* the system default encoding, always ISO-8859-1. That's important, because it makes a certain hack possible. Say your property file is stored as UTF-8. After you retrieve a property, you can re-encode it as ISO-8859-1 and decode it again as UTF-8, like this:
```
String realProp = new String(prop.getBytes("ISO-8859-1"), "UTF-8");
```
It's ugly and fragile, but it does work. But I think the best solution, at least for the next few years, is the one you found: bulk-convert the files with native2ascii using a build tool like Ant.
|
How do I properly store and retrieve internationalized Strings in properties files?
|
[
"",
"java",
"encoding",
"properties",
"internationalization",
""
] |
Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?
|
The libraries and frameworks mentioned here are good, but if all you want to do is fill in a form and flatten it, I recommend the command line tool called pdftk (PDF Toolkit).
See <https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/>
You can call the command line from php, and the command is
`pdftk` *formfile.pdf* `fill_form` *fieldinfo.fdf* `output` *outputfile.pdf* `flatten`
You will need to find the format of an FDF file in order to generate the info to fill in the fields. Here's a good link for that:
<http://www.tgreer.com/fdfServe.html>
[Edit: The above link seems to be out of commission. Here is some more info...]
The pdftk command can generate an FDF file from a PDF form file. You can then use the generated FDF file as a sample. The form fields are the portion of the FDF file that looks like
```
...
<< /T(f1-1) /V(text of field) >>
<< /T(f1-2) /V(text of another field) >>
...
```
You might also check out [php-pdftk](https://github.com/mikehaertl/php-pdftk), which is a library specific to PHP. I have not used it, but commenter Álvaro (below) recommends it.
|
A big +1 to the accepted answer, and a little tip if you run into encoding issues with the fdf file. If you generate the fields.fdf and upon running
```
file -bi fields.fdf
```
you get
```
application/octet-stream; charset=binary
```
then you've most likely run into a UTF-16 character set issue.
Try converting the ftf by means of
```
cat fields.fdf | sed -e's/\x00//g' | sed -e's/\xFE\xFF//g' > better.fdf
```
I was then able to edit and import the better.fdf file into my PDF form.
Hopefully this saves someone some Google-ing
|
Filling PDF Forms with PHP
|
[
"",
"php",
"pdf",
""
] |
I've never had to do IPC on Windows before. I'm developing a pair of programs, a standard GUI/CLI app, and a windows service. The app has to tell the service what to do. So, assuming the communication is local only, what would be the best communication method for these two processes?
By best I mean more robust and less error prone, not the best performance nor the easiest to code.
Note I'm asking about what to use, a standard TCP socket, named pipes, or some other means of communication only.
|
IPC in .Net can be achieved using:
# WCF
using named pipes **requires .Net 3.0** and above.
## Code example
* The WCF class **NetNamedPipeBinding** can be used for interprocess communication on the same machine. The MSDN documentaion for this class includes a code sample covering this scenario <http://msdn.microsoft.com/en-us/library/system.servicemodel.netnamedpipebinding.aspx>
---
# Remoting
The original IPC framework released with .Net 1.0. I believe remoting is no longer being actively developed, and you are encouraged to use WCF instead
## Code example
[Inter-process communication via Remoting](http://www.codeproject.com/KB/threads/process_communication.aspx/process_communication.aspx) - uses a tcp channel
## Resources
* GenuineChannels, sell a remoting toolkit that includes a Shared Memory Channel. <http://www.genuinechannels.com/Index.aspx>
* [Ingo Rammer](http://www.thinktecture.com/resourcearchive/tools-and-software/dotnetremotingprojects), wrote the definitive .Net remoting book, [Advanced .NET Remoting, Second Edition](https://rads.stackoverflow.com/amzn/click/com/1590594177)
---
# Win32 RPC using csharptest-net RpcLibrary
I came across a project recently that has wrapped the Win32 RPC library and created a .net class library that can be used for local and remote RPC
**Project home page**: <http://csharptest.net/projects/rpclibrary/>
**MSDN references:**
* How rpc works: <http://technet.microsoft.com/en-us/library/cc738291(v=ws.10).aspx>
* RPC functions: <http://msdn.microsoft.com/en-us/library/aa378623(v=VS.85).aspx>
Also has a google protocol buffers rpc client that runs on top of the library: <https://code.google.com/p/protobuf-csharp-rpc/>
---
# WM\_COPYDATA
For completeness it's also possible to use the WIN32 method with the [WM\_COPYDATA](http://msdn.microsoft.com/en-us/library/ms649011.aspx) message. I've used this method before in .Net 1.1 to create a single instance application opening multiple files from windows explorer.
## Resources
* [MSDN - WM\_COPYDATA](http://msdn.microsoft.com/en-us/library/ms649011.aspx)
* [Code example](http://www.codeproject.com/KB/cs/wm_copydata_use.aspx)
* [PInvoke.net declaration](http://www.pinvoke.net/search.aspx?search=wm_copyData)
# Sockets
Using a custom protocol (harder)
|
For local only, we have had success using Named Pipes. Avoids the overhead of TCP, and is pretty much (at least for .NET) as efficient as you can get while also having a decent API to work with.
|
Interprocess communication for Windows in C# (.NET 2.0)
|
[
"",
"c#",
".net",
"ipc",
""
] |
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.
I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.
I know one method of doing this is to use the `String.format` method:
```
String.format("%.5g%n", 0.912385);
```
returns:
```
0.91239
```
which is great, however it always displays numbers with 5 decimal places even if they are not significant:
```
String.format("%.5g%n", 0.912300);
```
returns:
```
0.91230
```
Another method is to use the `DecimalFormatter`:
```
DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
```
returns:
```
0.91238
```
However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this:
```
0.912385 -> 0.91239
0.912300 -> 0.9123
```
What is the best way to achieve this in Java?
|
Use [`setRoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)), set the [`RoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html) explicitly to handle your issue with the half-even round, then use the format pattern for your required output.
Example:
```
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}
```
gives the output:
```
12
123.1235
0.23
0.1
2341234.2125
```
---
**EDIT**: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:
```
Double d = n.doubleValue() + 1e-6;
```
To round down, subtract the accuracy.
|
Assuming `value` is a `double`, you can do:
```
(double)Math.round(value * 100000d) / 100000d
```
That's for 5 digits precision. The number of zeros indicate the number of decimals.
|
How to round a number to n decimal places in Java
|
[
"",
"java",
"decimal",
"rounding",
"digits",
""
] |
I want to programmatically create a new column in an MS Access table. I've tried many permutations of `ALTER TABLE MyTable Add MyField DECIMAL (9,4) NULL;` and got:
> Syntax Error in Field Definition
I can easily create a number field that goes to a `Double` type, but I want `decimal`. I would very strongly prefer to do this in a single `ALTER TABLE` statement and not have to create a field and then alter it.
I am using Access 2003.
|
If you want to create a new column in an acces table, it is easy to use the DAO.tableDef object:
```
Dim my_tableDef As DAO.TableDef
Dim my_field As DAO.Field
Set my_tableDef = currentDb.TableDefs(my_table)
Set my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize)
my_Field.decimalPlaces = myDecimalPlaces
my_Field.defaultValue = myDefaultValue
my_tableDef.Fields.Append my_Field
set my_Field = nothing
set my_tableDef = nothing
```
Of course you can further delete it.
You might have the posibility to do so with ADODB (or ADOX?) object, but as long as you are working on an mdb file, DAO is straight and efficient.
PS: after checking on some forums, it seems there is a bug with decimal fields and DAO. <http://allenbrowne.com/bug-08.html>. Advices are "go for double"(which is what I do usually to avoid any loosy issues related to decimal rounding) or use "implicite" ADO to modify your database
```
strSql = "ALTER TABLE MyTable ADD COLUMN MyField DECIMAL (28,3);"
CurrentProject.Connection.Execute strSql
```
|
The decimal data type isn't supported in the default Jet 4.0 mdb file. You have to use the SQL Server compatibility syntax (ANSI 92) setting to use the decimal data type in the SQL Window.
Click on the menu, Tools > Options. Click on the Tables/Query tab. Mark the check box for "This database" in the SQL Server compatibility syntax (ANSI 92) section. This mode will affect the entire db, including queries with wildcards, so you may want to try this on a copy of your db.
Paste this into the SQL window:
```
ALTER TABLE MyTable
Add COLUMN MyField DECIMAL (9,4) NULL;
```
If you don't want to alter the mode of your database, you must use vba code with the adodb library:
```
Dim conn As ADODB.Connection
Set conn = CurrentProject.Connection
conn.Execute "ALTER TABLE MyTable " _
& "ADD COLUMN MyField DECIMAL (9,4) NULL;"
conn.Close
```
|
How do I create a decimal field in Access with Alter Table?
|
[
"",
"sql",
"ms-access",
""
] |
I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.
Given this data:
```
var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");
```
And this code: \*\* Which is not correct and is what needs to be fixed!! \*\*
```
var shaped = data.Select(c =>
new { c = c }
).ToList();
serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();
```
I would like `desiredResult` to be:
```
{
"One": "One",
"Two": "Two",
"Three": "Three"
}
```
but it is currently:
`{ "c" : "One" },{ "c" : "Two" }`, etc.
One problem is that on the left side of the object initializer I want the value of `c`, not `c` itself...
|
Solution offered for correctness, not performance.
```
List<string> data = new List<string>()
{
"One",
"Two",
"Three"
};
string result =
"{ "
+
string.Join(", ", data
.Select(c => @"""" + c + @""": """ + c + @"""")
.ToArray()
) + " }";
```
|
In json, the "c" in "c" : "One" is the property name. And in the C# world, you can't create property names on the fly (ignoring System.ComponentModel).
Basically, I don't think you can do what you want.
|
Object Initializer syntax to produce correct Json
|
[
"",
"c#",
"linq",
"json",
""
] |
This is a minor bug (one I'm willing to live with in the interest of go-live, frankly), but I'm wondering if anyone else has ideas to fix it.
I have a C# WinForms application. When the app is launched via the executable (not via the debugger), the first thing the user sees is a console window, followed by the main window (after pre-loading is complete.)
I'd like to not display the console window. (Like I said, it's a minor bug.)
The project output is already set to Windows Application.
Here's (most of) the code for the Main() method. I've snipped out various proprietary/security related stuff, replacing it with comments where appropriate.
```
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// SNIP: Get username from Windows, associate with DB user
if (user == null || user.UID == 0 || (user.Active.HasValue && !(user.Active.Value)))
{
MessageBox.Show(ErrorStrings.UnknownUser, ErrorStrings.TitleBar, MessageBoxButtons.OK,
MessageBoxIcon.Error);
Application.Exit();
return;
}
// SNIP: Associate user with employee object
Application.Run(new MainForm());
}
catch (Exception ex)
{
if (ExceptionPolicy.HandleException(ex, UiStrings.ExceptionPolicy))
{
string message = ErrorStrings.UnhandledPreface + ex.ToString();
MessageBox.Show(message, ErrorStrings.TitleBar, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
}
```
Anyone have any ideas?
|
My first guess would be to double check your Project Property settings and make sure that the output type is Windows Application and not Console Application.
|
I found it.
When the project is built in Visual Studio, there are no problems -- no console window.
When the project is built from CruiseControl, that's when we get a console window.
The difference? Visual Studio (based on my election of a WinForms app) is appending /target:winexe to the csc line.
CruiseControl calls a series of NAnt scripts. In the source.build script, the compile step is misconfigured, and is targeting exe instead of winexe -- the equivalent of selecting "Console App" in VS. Thus, a console window on release builds vs. debug builds.
Relevant NAnt:
```
<csc output="${build.outputPath}\[myapp].exe" target="winexe" debug="Full" rebuild="true">
<!-- lots of references, sources and resources -->
</csc>
```
Yeah, now I feel dumb. :)
|
Console window displays at WinForm startup (C#)
|
[
"",
"c#",
".net",
"winforms",
""
] |
If I have a subclass that has yet to implement a function provided by the base class, I can override that function and have it throw a `NotSupportedException`. Is there a way to generate a compile-time error for this to avoid only hitting this at runtime?
Update: I can't make the base class abstract.
|
[Obsolete("This still needs implementing", true/false)] true if you don't want the build to succeed, false if you just want a warning
Slightly hackish ... but it does the job of warning at compile time.
|
You can make the base class abstract:
```
abstract class Foo
{
public abstract void Bar();
}
```
Now, any subclass must implement `Bar()`, or it won't compile.
|
Compile-time error for NotSupportedException in subclass function
|
[
"",
"c#",
"exception",
"inheritance",
""
] |
There's another post on SO relating to .NET -- not us. Pure PHP. Trying to find the best way/process to deploy stable version of our PHP app. I've seen an article on [Capistrano](http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/), but am curious what else is out there. Aside from the obvious reasons, I'm also looking to add some scripting so that the [SVN rev number gets added in there as well](https://stackoverflow.com/questions/111436/how-can-i-get-the-svn-revision-number-in-php).
Much thanks.
|
I've used a home-grown script for quite some time. It will (based on an application configuration file):
1. Run `svn export` on the repository based on a tag.
2. Package the export into a tar or zip file, which includes the tag in the name.
3. Use `scp` to copy the package to the appropriate server (QA or release).
4. Connect to the server with `ssh` to install the package and run post-install scripts.
The application configuration file is part of the project. It can tell the script (at step 2) to strip paths and otherwise process specified files. It also specifies server names and how to handle externals.
I've recently migrated the script to support Git as well as Subversion. I'm also probably going to migrate it to PHP since we're now running in a mixed (Linux and Windows) set up, with Linux now in the minority.
I have plans to automatically call the script with post-commit hooks, but haven't had the need to implement that just yet.
|
Coincidentally, I was just reading about an Apache Ant/gnu make like build tool called [Phing](http://phing.info). What I like about it is the ability to write [custom extensions](http://phing.info/docs/guide/current/chapters/ExtendingPhing.html#WritingTasks) in PHP!
|
What's the best process / app for automated deployment of PHP apps?
|
[
"",
"php",
"deployment",
""
] |
The [Flot API documentation](http://flot.googlecode.com/svn/trunk/API.txt) describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines without also removing the x-axis labels. I've tried changing the tickColor, ticks, and tickSize options with no success.
I want to create beautiful, Tufte-compatible graphs such as these:
[<http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif>](http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif)
[<http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg>](http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg)
I find the vertical ticks on my graphs to be chart junk. I am working with a time series that I am displaying as vertical bars so the vertical ticks often cut through the bars in a way that is visually noisy.
|
As Laurimann noted, Flot continues to evolve. The ability to control this has been added to the API (as noted in the flot issue Nelson linked to).
If you download the latest version (which is still labeled 0.6), you can disable lines on an axis with "tickLength", like so:
```
xaxis: {
tickLength: 0
}
```
Rather annoyingly, this addition hasn't been updated in the API documentation.
|
This post comes over two years later than OP and Flot (now version 0.6) might have evolved a lot during that time or maybe there's better options than it around but in either case here's my contribution.
I accidentally bumped into a workaround for this problem: set grid's tick color's alpha channel to fully transparent. For example:
```
var options = {
grid: {show: true,
color: "rgb(48, 48, 48)",
tickColor: "rgba(255, 255, 255, 0)",
backgroundColor: "rgb(255, 255, 255)"}
};
```
Works for me.
|
In Flot, is it possible to eliminate or hide grid ticks without eliminating the corresponding label?
|
[
"",
"javascript",
"jquery",
"graph",
"flot",
""
] |
I want to attach a click event to a button element and then later remove it, but I can't get `unclick()` or `unbind()` event(s) to work as expected. In the code below, the button is `tan` colour and the click event works.
```
window.onload = init;
function init() {
$("#startButton").css('background-color', 'beige').click(process_click);
$("#startButton").css('background-color', 'tan').unclick();
}
```
How can I remove events from my elements?
|
There's no such thing as `unclick()`. Where did you get that from?
You can remove individual event handlers from an element by calling unbind:
```
$("#startButton").unbind("click", process_click);
```
If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument to `unbind()`:
```
$("#startButton").unbind("click");
```
|
Or you could have a situation where you want to unbind the click function just after you use it, like I had to:
```
$('#selector').click(function(event){
alert(1);
$(this).unbind(event);
});
```
|
Event handling jQuery unclick() and unbind() events?
|
[
"",
"javascript",
"jquery",
"css",
"event-handling",
""
] |
Is there any way to redefine a class or some of its methods without using typical inheritance? For example:
```
class third_party_library {
function buggy_function() {
return 'bad result';
}
function other_functions(){
return 'blah';
}
}
```
What can I do to replace `buggy_function()`? Obviously this is what I would like to do
```
class third_party_library redefines third_party_library{
function buggy_function() {
return 'good result';
}
function other_functions(){
return 'blah';
}
}
```
This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.
I've found this [library](http://pecl.php.net/package/classkit) that says it can do it, but I'm wary as it's 4 years old.
EDIT:
I should have clarified that I cannot rename the class from `third_party_library` to `magical_third_party_library` or anything else because of framework limitations.
For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a "partial class."
|
It's called [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch). But, PHP doesn't have native support for it.
Though, as others have also pointed out, the [runkit library](http://docs.php.net/runkit) is available for adding support to the language and is the successor to [classkit](http://docs.php.net/manual/en/book.classkit.php). And, though it seemed to have been [abandoned](http://pecl.php.net/package/runkit) by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a [new home and maintainer](https://github.com/zenovich/runkit).
I still [can't say I'm a fan](https://stackoverflow.com/revisions/137028/3) of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug.
Still, [`runkit_method_redefine`](https://www.php.net/manual/en/function.runkit-method-redefine.php) appears to be what you're looking for, and an example of its use can be found in [`/tests/runkit_method_redefine.phpt`](https://github.com/zenovich/runkit/blob/master/tests/runkit_method_redefine.phpt) in the repository:
```
runkit_method_redefine('third_party_library', 'buggy_function', '',
'return \'good result\''
);
```
|
runkit seems like a good solution but its not enabled by default and parts of it are still experimental. So I hacked together a small class which replaces function definitions in a class file. Example usage:
```
class Patch {
private $_code;
public function __construct($include_file = null) {
if ( $include_file ) {
$this->includeCode($include_file);
}
}
public function setCode($code) {
$this->_code = $code;
}
public function includeCode($path) {
$fp = fopen($path,'r');
$contents = fread($fp, filesize($path));
$contents = str_replace('<?php','',$contents);
$contents = str_replace('?>','',$contents);
fclose($fp);
$this->setCode($contents);
}
function redefineFunction($new_function) {
preg_match('/function (.+)\(/', $new_function, $aryMatches);
$func_name = trim($aryMatches[1]);
if ( preg_match('/((private|protected|public) function '.$func_name.'[\w\W\n]+?)(private|protected|public)/s', $this->_code, $aryMatches) ) {
$search_code = $aryMatches[1];
$new_code = str_replace($search_code, $new_function."\n\n", $this->_code);
$this->setCode($new_code);
return true;
} else {
return false;
}
}
function getCode() {
return $this->_code;
}
}
```
Then include the class to be modified and redefine its methods:
```
$objPatch = new Patch('path_to_class_file.php');
$objPatch->redefineFunction("
protected function foo(\$arg1, \$arg2)
{
return \$arg1+\$arg2;
}");
```
Then eval the new code:
```
eval($objPatch->getCode());
```
A little crude but it works!
|
Redefine Class Methods or Class
|
[
"",
"php",
"class",
"methods",
"redefine",
""
] |
I have a collection of classes that I want to serialize out to an XML file. It looks something like this:
```
public class Foo
{
public List<Bar> BarList { get; set; }
}
```
Where a bar is just a wrapper for a collection of properties, like this:
```
public class Bar
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
```
I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form.
I want to get a nice XML representation like this:
```
<?xml version="1.0" encoding="utf-8"?>
<Foo>
<BarList>
<Bar>
<Property1>Value</Property1>
<Property2>Value</Property2>
</Bar>
<Bar>
<Property1>Value</Property1>
<Property2>Value</Property2>
</Bar>
</Barlist>
</Foo>
```
where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination.
I've marked Foo with the attribute
```
[XmlRoot("Foo")]
```
and the `list<Bar>` with the attribute
```
[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")]
```
in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this:
```
<?xml version="1.0" encoding="utf-8"?>
<Foo>
<Barlist />
</Foo>
```
I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me.
|
Just to check, have you marked Bar as [Serializable]?
Also, you need a parameter-less ctor on Bar, to deserialize
Hmm, I used:
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Foo f = new Foo();
f.BarList = new List<Bar>();
f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" });
XmlSerializer ser = new XmlSerializer(typeof(Foo));
using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create))
{
ser.Serialize(fs, f);
}
}
}
public class Foo
{
[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
public List<Bar> BarList { get; set; }
}
[XmlRoot("Foo")]
public class Bar
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
```
And that produced:
```
<?xml version="1.0"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BarList>
<Bar>
<Property1>abc</Property1>
<Property2>def</Property2>
</Bar>
</BarList>
</Foo>
```
|
Everything looks great. As @Carl said you need to add the **[Serializable]** attibute to your classes, but other than that your XML creation should work find.
**Foo**
```
[Serializable]
[XmlRoot("Foo")]
public class Foo
{
[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
public List<Bar> BarList { get; set; }
}
```
**Bar**
```
[Serializable]
public class Bar
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
```
**Code to test**
```
Foo f = new Foo();
f.BarList = new List<Bar>();
f.BarList.Add(new Bar() { Property1 = "s", Property2 = "2" });
f.BarList.Add(new Bar() { Property1 = "s", Property2 = "2" });
FileStream fs = new FileStream("c:\\test.xml", FileMode.OpenOrCreate);
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Foo));
s.Serialize(fs, f);
```
**Output**
```
<?xml version="1.0" ?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BarList>
<Bar>
<Property1>s</Property1>
<Property2>2</Property2>
</Bar>
<Bar>
<Property1>s</Property1>
<Property2>2</Property2>
</Bar>
</BarList>
</Foo>
```
|
Serializing Lists of Classes to XML
|
[
"",
"c#",
"xml",
"serialization",
""
] |
Consider:
```
var something = {
wtf: null,
omg: null
};
```
My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now. Except for this. I don't recall ever seeing this before. What is it? And where can I learn more about it?
|
It is an object literal with two properties. Usually this is how people create associative arrays or hashes because JS doesn't natively support that data structure. Though note that it is still a fully-fledged object, you can even add functions as properties:
```
var myobj = {
name: 'SO',
hello: function() {
alert(this.name);
}
};
```
And you can iterate through the properties using a for loop:
```
for (i in myobj) {
// myobj[i]
// Using the brackets (myobj['name']) is the same as using a dot (myobj.name)
}
```
|
It's object literal syntax. The 'wft' and 'omg' are property names while, null and null are the property values.
It is equivalent to:
```
var something = new Object();
something.wtf = null;
something.omg = null;
```
Check out Mozilla's documentation on object literals: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer>
|
What is this thing in JavaScript?
|
[
"",
"javascript",
"object-literal",
""
] |
Here's the jist of the problem: Given a list of sets, such as:
```
[ (1,2,3), (5,2,6), (7,8,9), (6,12,13), (21,8,34), (19,20) ]
```
Return a list of groups of the sets, such that sets that have a shared element are in the same group.
```
[ [ (1,2,3), (5,2,6), (6,12,13) ], [ (7,8,9), (21,8,34) ], [ (19,20) ] ]
```
Note the stickeyness - the set (6,12,13) doesn't have a shared element with (1,2,3), but they get put in the same group because of (5,2,6).
To complicate matters, I should mention that I don't really have these neat sets, but rather a DB table with several million rows that looks like:
```
element | set_id
----------------
1 | 1
2 | 1
3 | 1
5 | 2
2 | 2
6 | 2
```
and so on. So I would love a way to do it in SQL, but I would be happy with a general direction for the solution.
**EDIT**: Changed the table column names to (element, set\_id) instead of (key, group\_id), to make the terms more consistent. Note that Kev's answer uses the old column names.
|
The problem is exactly the computation of the connected components of an hypergraph: the integers are the vertices, and the sets are the hyperedges. A usual way of computing the connected components is by flooding them one after the other:
* for all i = 1 to N, do:
* if i has been tagged by some j < i, then continue (I mean skip to the next i)
* else flood\_from(i,i)
where flood\_from(i,j) would be defined as
* for each set S containing i, if it is not already tagged by j then:
* tag S by j and for each element k of S, if k is not already tagged by j, then tag it by j, and call flood\_from(k,j)
The tags of the sets then give you the connected components you are looking for.
---
In terms of databases, the algorithm can be expressed as follows: you add a TAG column to your database, and you compute the connected component of set i by doing
* S = select all rows where set\_id == i
* set TAG to i for the rows in S
* S' = select all rows where TAG is not set and where element is in element(S)
* while S' is not empty, do
* ---- set TAG to i for the rows in S'
* ---- S'' = select all rows where TAG is not set and where element is in element(S')
* ---- S = S union S'
* ---- S' = S''
* return set\_id(S)
---
Another (theoretical) way of presenting this algorithm would be to say that you are looking for the fixed points of a mapping:
* if A = {A1, ..., An} is a set of sets, define union(A) = A1 union ... union An
* if K = {k1, ..., kp} is a set of integers, define incidences(K) = the set of sets which intersect K
Then if S is a set, the connected component of S is obtained by iterating (incidences)o(union) on S until a fixed point is reached:
1. K = S
2. K' = incidences(union(K)).
3. if K == K', then return K, else K = K' and go to 2.
|
You could think of it as a graph problem where the set (1,2,3) is connected to the set (5,2,6) via the 2. And then use a standard algorithm to fine the connected sub-graphs.
Here's a quick python implementation:
```
nodes = [ [1,2,3], [2,4,5], [6,7,8], [10,11,12], [7,10,13], [12], [] ]
links = [ set() for x in nodes ]
#first find the links
for n in range(len(nodes)):
for item in nodes[n]:
for m in range(n+1, len(nodes)):
if (item in nodes[m]):
links[n].add(m)
links[m].add(n)
sets = []
nodes_not_in_a_set = range(len(nodes))
while len(nodes_not_in_a_set) > 0:
nodes_to_explore = [nodes_not_in_a_set.pop()]
current_set = set()
while len(nodes_to_explore) > 0:
current_node = nodes_to_explore.pop()
current_set.add(current_node)
if current_node in nodes_not_in_a_set:
nodes_not_in_a_set.remove(current_node)
for l in links[current_node]:
if l not in current_set and l not in nodes_to_explore:
nodes_to_explore.append(l)
if len(current_set) > 0:
sets.append(current_set)
for s in sets:
print [nodes[n] for n in s]
```
output:
```
[[]]
[[6, 7, 8], [10, 11, 12], [7, 10, 13], [12]]
[[1, 2, 3], [2, 4, 5]]
```
|
Partition a list of sets by shared elements
|
[
"",
"sql",
"algorithm",
"set",
""
] |
What's the C++ way of parsing a string (given as char \*) into an int? Robust and clear error handling is a plus (instead of [returning zero](http://en.cppreference.com/w/cpp/string/byte/atoi)).
|
In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.
```
int myNr = std::stoi(myString);
```
It will throw an exception on conversion error.
Even these new functions still have the **same issue** as noted by Dan: they will happily convert the string "11x" to integer "11".
See more: <http://en.cppreference.com/w/cpp/string/basic_string/stol>
|
## What not to do
Here is my first piece of advice: **do not use stringstream for this**. While at first it may seem simple to use, you'll find that you have to do a lot of extra work if you want robustness and good error handling.
Here is an approach that intuitively seems like it should work:
```
bool str2int (int &i, char const *s)
{
std::stringstream ss(s);
ss >> i;
if (ss.fail()) {
// not an integer
return false;
}
return true;
}
```
This has a major problem: `str2int(i, "1337h4x0r")` will happily return `true` and `i` will get the value `1337`. We can work around this problem by ensuring there are no more characters in the `stringstream` after the conversion:
```
bool str2int (int &i, char const *s)
{
char c;
std::stringstream ss(s);
ss >> i;
if (ss.fail() || ss.get(c)) {
// not an integer
return false;
}
return true;
}
```
We fixed one problem, but there are still a couple of other problems.
What if the number in the string is not base 10? We can try to accommodate other bases by setting the stream to the correct mode (e.g. `ss << std::hex`) before trying the conversion. But this means the caller must know *a priori* what base the number is -- and how can the caller possibly know that? The caller doesn't know what the number is yet. They don't even know that it *is* a number! How can they be expected to know what base it is? We could just mandate that all numbers input to our programs must be base 10 and reject hexadecimal or octal input as invalid. But that is not very flexible or robust. There is no simple solution to this problem. You can't simply try the conversion once for each base, because the decimal conversion will always succeed for octal numbers (with a leading zero) and the octal conversion may succeed for some decimal numbers. So now you have to check for a leading zero. But wait! Hexadecimal numbers can start with a leading zero too (0x...). Sigh.
Even if you succeed in dealing with the above problems, there is still another bigger problem: what if the caller needs to distinguish between bad input (e.g. "123foo") and a number that is out of the range of `int` (e.g. "4000000000" for 32-bit `int`)? With `stringstream`, there is no way to make this distinction. We only know whether the conversion succeeded or failed. If it fails, we have no way of knowing *why* it failed. As you can see, `stringstream` leaves much to be desired if you want robustness and clear error handling.
This leads me to my second piece of advice: **do no use Boost's `lexical_cast` for this**. Consider what the `lexical_cast` documentation has to say:
> Where a higher degree of control is
> required over conversions,
> std::stringstream and
> std::wstringstream offer a more
> appropriate path. Where
> non-stream-based conversions are
> required, lexical\_cast is the wrong
> tool for the job and is not
> special-cased for such scenarios.
What?? We've already seen that `stringstream` has a poor level of control, and yet it says `stringstream` should be used instead of `lexical_cast` if you need "a higher level of control". Also, because `lexical_cast` is just a wrapper around `stringstream`, it suffers from the same problems that `stringstream` does: poor support for multiple number bases and poor error handling.
## The best solution
Fortunately, somebody has already solved all of the above problems. The C standard library contains `strtol` and family which have none of these problems.
```
enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };
STR2INT_ERROR str2int (int &i, char const *s, int base = 0)
{
char *end;
long l;
errno = 0;
l = strtol(s, &end, base);
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) {
return OVERFLOW;
}
if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) {
return UNDERFLOW;
}
if (*s == '\0' || *end != '\0') {
return INCONVERTIBLE;
}
i = l;
return SUCCESS;
}
```
Pretty simple for something that handles all the error cases and also supports any number base from 2 to 36. If `base` is zero (the default) it will try to convert from any base. Or the caller can supply the third argument and specify that the conversion should only be attempted for a particular base. It is robust and handles all errors with a minimal amount of effort.
Other reasons to prefer `strtol` (and family):
* It exhibits much better [runtime performance](http://tinodidriksen.com/2010/02/16/cpp-convert-string-to-int-speed/)
* It introduces less compile-time overhead (the others pull in nearly 20 times more SLOC from headers)
* It results in the smallest code size
There is absolutely no good reason to use any other method.
|
How to parse a string to an int in C++?
|
[
"",
"c++",
"parsing",
""
] |
I'm trying to write a faster user switching app for Windows. Win+L and selecting users is very cumbersome. If I start Task Manager as administrator, it shows active users and I can select one and "Connect" (if I enter their password).
How do I get the list of all users (or all active users)?
I'm using C# (Visual Studio Express).
|
I'd try [WTSEnumerateSessions](http://msdn.microsoft.com/en-us/library/aa383833(VS.85).aspx) to get all available sessions.
|
If you'd rather not deal with the P/Invokes, you can use [Cassia](http://cassia.googlecode.com), which wraps the ugly for you:
```
using Cassia;
foreach (ITerminalServicesSession session in new TerminalServicesManager().GetSessions())
{
if (!string.IsNullOrEmpty(session.UserName))
{
Console.WriteLine("Session {0} (User {1})", session.SessionId, session.UserName);
}
}
```
|
How do I get a list of local Windows users who are logged in?
|
[
"",
"c#",
".net",
"windows",
""
] |
Is there a freely available Base64 decoding code snippet in C++?
|
See *[Encoding and decoding base 64 with C++](http://www.adp-gmbh.ch/cpp/common/base64.html)*.
Here is the implementation from that page:
```
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
```
|
Here's my modification of [the implementation that was originally written by *René Nyffenegger*](http://www.adp-gmbh.ch/cpp/common/base64.html). And why have I modified it? Well, because it didn't seem appropriate to me that I should work with binary data stored within `std::string` object ;)
**base64.h**:
```
#ifndef _BASE64_H_
#define _BASE64_H_
#include <vector>
#include <string>
typedef unsigned char BYTE;
std::string base64_encode(BYTE const* buf, unsigned int bufLen);
std::vector<BYTE> base64_decode(std::string const&);
#endif
```
**base64.cpp**:
```
#include "base64.h"
#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(BYTE c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(BYTE const* buf, unsigned int bufLen) {
std::string ret;
int i = 0;
int j = 0;
BYTE char_array_3[3];
BYTE char_array_4[4];
while (bufLen--) {
char_array_3[i++] = *(buf++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::vector<BYTE> base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
BYTE char_array_4[4], char_array_3[3];
std::vector<BYTE> ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret.push_back(char_array_3[i]);
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]);
}
return ret;
}
```
Here's the usage:
```
std::vector<BYTE> myData;
...
std::string encodedData = base64_encode(&myData[0], myData.size());
std::vector<BYTE> decodedData = base64_decode(encodedData);
```
|
Base64 decode snippet in C++
|
[
"",
"c++",
"base64",
""
] |
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.
Here are some trivial examples where they functionally do the same thing if either were found within another function:
**Lambda function**
```
>>> a = lambda x : 1 + x
>>> a(5)
6
```
**Nested function**
```
>>> def b(x): return 1 + x
>>> b(5)
6
```
Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)
Does it even matter? If it doesn't then does that violate the Pythonic principle:
> [There should be one-- and preferably only one --obvious way to do it.](https://www.python.org/dev/peps/pep-0020/).
|
If you need to assign the `lambda` to a name, use a `def` instead. `def`s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
`lambda`s can be used for *use once, throw away* functions which won't have a name.
However, this use case is very rare. You rarely need to pass around unnamed function objects.
The builtins `map()` and `filter()` need function objects, but **list comprehensions** and **generator expressions** are generally more readable than those functions and can cover all use cases, without the need of lambdas.
For the cases you really need a small function object, you should use the `operator` module functions, like `operator.add` instead of `lambda x, y: x + y`
If you still need some `lambda` not covered, you might consider writing a `def`, just to be more readable. If the function is more complex than the ones at `operator` module, a `def` is probably better.
So, real world good `lambda` use cases are very rare.
|
Practically speaking, to me there are two differences:
The first is about what they do and what they return:
* def is a keyword that doesn't return anything and creates a 'name' in the local namespace.
* lambda is a keyword that returns a function object and does not create a 'name' in the local namespace.
Hence, if you need to call a function that takes a function object, the only way to do that in one line of python code is with a lambda. There's no equivalent with def.
In some frameworks this is actually quite common; for example, I use [Twisted](http://twistedmatrix.com/) a lot, and so doing something like
```
d.addCallback(lambda result: setattr(self, _someVariable, result))
```
is quite common, and more concise with lambdas.
The second difference is about what the actual function is allowed to do.
* A function defined with 'def' can contain any python code
* A function defined with 'lambda' has to evaluate to an expression, and can thus not contain statements like print, import, raise, ...
For example,
```
def p(x): print x
```
works as expected, while
```
lambda x: print x
```
is a SyntaxError.
Of course, there are workarounds - substitute `print` with `sys.stdout.write`, or `import` with `__import__`. But usually you're better off going with a function in that case.
|
Which is more preferable to use: lambda functions or nested functions ('def')?
|
[
"",
"python",
"syntax",
"function",
"lambda",
""
] |
In my `urls.py` file, I have:
```
from myapp import views
...
(r'^categories/$', views.categories)
```
Where `categories` is a view function inside `myapp/views.py`. No other URLconf lines reference `views.categories`.
In a unit test file, I’m trying to grab this URL using `django.core.urlresolvers.reverse()`, instead of just copying '/categories/' (DRY and all that). So, I have:
```
from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
```
When I run my tests, I get a `NoReverseMatch` error:
```
NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
```
It matches just fine if I make the URL pattern a named pattern, like this:
```
url(r'^categories/$', views.categories, 'myapp-categories')
```
And use the pattern name to match it:
```
url = reverse('myapp-categories')
```
But as far as I can tell from [the `reverse` documentation](http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse), I shouldn’t need to make it a named URL pattern just to use `reverse`.
Any ideas what I’m doing wrong?
|
After futher investigation, turns out it was an issue with how I was importing the views module:
[How do I successfully pass a function reference to Django’s reverse() function?](https://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function)
Thanks for the help though, guys: you inspired me to look at it properly.
|
Jack M.'s example is nearly correct.
It needs to be a url function, not a tuple, if you want to use named urls.
```
url(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
```
|
How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern?
|
[
"",
"python",
"django",
""
] |
I collect a few corner cases and [brain teasers](http://www.yoda.arachsys.com/csharp/teasers.html) and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:
```
string x = new string(new char[0]);
string y = new string(new char[0]);
Console.WriteLine(object.ReferenceEquals(x, y));
```
I'd expect that to print False - after all, "new" (with a reference type) *always* creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should. Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)
Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.
Any other gems lurking out there?
|
I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)
```
static void Foo<T>() where T : new()
{
T t = new T();
Console.WriteLine(t.ToString()); // works fine
Console.WriteLine(t.GetHashCode()); // works fine
Console.WriteLine(t.Equals(t)); // works fine
// so it looks like an object and smells like an object...
// but this throws a NullReferenceException...
Console.WriteLine(t.GetType());
}
```
So what was T...
Answer: any `Nullable<T>` - such as `int?`. All the methods are overridden, except GetType() which can't be; so it is cast (boxed) to object (and hence to null) to call object.GetType()... which calls on null ;-p
---
Update: the plot thickens... Ayende Rahien threw down a [similar challenge on his blog](http://ayende.com/Blog/archive/2009/11/25/can-you-hack-this-out-hint-1.aspx), but with a `where T : class, new()`:
```
private static void Main() {
CanThisHappen<MyFunnyType>();
}
public static void CanThisHappen<T>() where T : class, new() {
var instance = new T(); // new() on a ref-type; should be non-null, then
Debug.Assert(instance != null, "How did we break the CLR?");
}
```
But it can be defeated! Using the same indirection used by things like remoting; warning - the following is **pure evil**:
```
class MyFunnyProxyAttribute : ProxyAttribute {
public override MarshalByRefObject CreateInstance(Type serverType) {
return null;
}
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }
```
With this in place, the `new()` call is redirected to the proxy (`MyFunnyProxyAttribute`), which returns `null`. Now go and wash your eyes!
|
Bankers' Rounding.
This one is not so much a compiler bug or malfunction, but certainly a strange corner case...
The .Net Framework employs a scheme or rounding known as Banker's Rounding.
In Bankers' Rounding the 0.5 numbers are rounded to the nearest even number, so
```
Math.Round(-0.5) == 0
Math.Round(0.5) == 0
Math.Round(1.5) == 2
Math.Round(2.5) == 2
etc...
```
This can lead to some unexpected bugs in financial calculations based on the more well known Round-Half-Up rounding.
This is also true of Visual Basic.
|
What's the strangest corner case you've seen in C# or .NET?
|
[
"",
"c#",
".net",
""
] |
In visual C++, I can do things like this:
```
template <class T>
class A{
protected:
T i;
};
template <class T>
class B : public A<T>{
T geti() {return i;}
};
```
If I try to compile this in g++, I get an error. I have to do this:
```
template <class T>
class B : public A<T>{
T geti() {return A<T>::i;}
};
```
Am I not supposed to do the former in standard C++? Or is something misconfigured with gcc that's giving me errors?
|
This used to be allowed, but changed in [gcc 3.4](http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus).
In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,
```
template <typename T> struct B {
int m;
int n;
int f ();
int g ();
};
int n;
int g ();
template <typename T> struct C : B<T> {
void h ()
{
m = 0; // error
f (); // error
n = 0; // ::n is modified
g (); // ::g is called
}
};
```
You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,
```
template <typename T> void C<T>::h ()
{
this->m = 0;
this->f ();
this->n = 0
this->g ();
}
```
|
I figured this one out:
* [C++ Super FAQ: "Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class?"](https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-types)
* [C++ Super FAQ: "Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?"](https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-members)
Apparently, the first example ISN'T valid C++ and it's bad that msvc takes this. There are solutions posted on the C++ faq lite.
|
Accessing protected members from subclasses: gcc vs msvc
|
[
"",
"c++",
"gcc",
"g++",
"visual-c++",
""
] |
I got a text file with a couple of lines and I am looking for a string in this file. I need to pass following command line parameters to the program:
- file path
- the string I am looking for
- maximum number of processes the program is allowed to "fork" in order to complete this task.
How to such a program should be constructed?
|
A couple of thoughts.
* You will have to open the file separately from each process, otherwise they will share a single file descriptor and thus have a shared position in the file (or not, see the comments, as this may be system specific...).
* You may not see the speed increase you are hoping for due to disk access and/or cache miss patterns.
You might be able to beat both issues by memory mapping the file (well you still risk an increased cache miss rate)...
---
How badly do you need this? It runs a real risk of being premature optimization. I would recommend against touching the problem without a compelling need. Really.
|
Consider why you think you need to parallelize this, and if you're going to see any actual performance benefit. You're likely to be limited by disk access time, and there's overhead to forking. Your best option might be to do a standard single-threaded search (probably with a regex).
|
How to paralleize search for a string in a file with a help of fork? (GNU Linux/g++)
|
[
"",
"c++",
"linux",
"file",
"search",
"parallel-processing",
""
] |
In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.
```
for ( int i=0; i < vecVector.size(); i++ )
{
..
}
```
Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?
|
Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings.
### Genericity
Iterators increase the genericity of your code.
For example:
```
typedef std::vector<int> Container ;
void doSomething(Container & p_aC)
{
for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it)
{
int & i = *it ; // i is now a reference to the value iterated
// do something with "i"
}
}
```
Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code.
Should you have used index-based code instead, it would have needed to be re-written.
### Access
The iterator should be viewed like a kind of super pointer.
It "points" to the value (or, in case of maps, to the pair of key/value).
But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque).
### Algorithms
Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here.
|
Using iterators allows your code to be agnostic about the implementation of your container. If random access for your container is cheap, there isn't much difference performance-wise.
But in lots of cases you won't know whether that is the case. If you try do use your method on a linked list, for example, with subscripting, the container is going to have to walk the list on every iteration to find your element.
So unless you know for sure that random access to your container is cheap, use an iterator.
|
Iterators.. why use them?
|
[
"",
"c++",
"stl",
"iterator",
""
] |
Basically what the title says. (Forgive me because I am a .NET newb)
In my department, we have a server running .net 3.5 and ever since I got into this section I have been using LINQ. However, I am starting a personal project on a different server (obviously), so 2 questions:
What do I need to get up and running with LINQ?
What does the server need to run LINQ?
Will .net 2.0 work on the server?
The code behind would be C# if that matters.
**Edit:**
Would I have to compile it in 3.5 or would 2.0 work?
|
To get up and running, I would definitely recommend checking out [LINQ in Action](https://rads.stackoverflow.com/amzn/click/com/1933988169 "LINQ in Action").

Your compiler needs to be [.NET 3.5 framework](http://www.microsoft.com/downloads/details.aspx?FamilyId=333325FD-AE52-4E35-B531-508D977D32A6&displaylang=en). If you are copying over only compiled code, then you will **not need 3.5** on your server, you only need it on your development machine. This can help if your server admin is unwilling to install the 3.5 framework on your server. However, if you are publishing source code, say to a development server to compile, then yes that server will need 3.5.
Once you have the 3.5 framework installed, you can run web apps either as 2.0 or 3.5. All you have to do is specify it in your [Web.Config](https://web.archive.org/web/20211020153237/https://www.4guysfromrolla.com/articles/121207-1.aspx) file.
If you are interested in working with LINQ to SQL and managing dbml files, you will need [Visual Studio 2008](http://msdn.microsoft.com/en-us/vstudio/products/cc533447.aspx "Visual Studio 2008 Express Edition"). However, Visual Studio 2005 will still compile dbml files properly, given that you have the 3.5 framework installed.
|
I would encourage you to check out [LinqPad](http://www.linqpad.net/) as a learning tool. It's a standalone application that lets you play with Linq queries without worrying about getting it to run on a server.
|
Getting started using Linq, what do I need?
|
[
"",
"c#",
".net",
"linq",
""
] |
The following code:
```
template <typename S, typename T>
struct foo {
void bar();
};
template <typename T>
void foo <int, T>::bar() {
}
```
gives me the error
```
invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'
```
(I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:
```
template <typename S>
struct foo {
void bar();
};
template <>
void foo <int>::bar() {
}
```
then it compiles correctly.
|
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. `template <typename U = T> struct Nested`) would work. Or else you can try deriving from another template that partially specializes (works if you use the `this->member` notation, otherwise you will encounter compiler errors).
|
Although coppro mentioned two solutions already and Anonymous explained the second one, it took me quite some time to understand the first one. Maybe the following code is helpful for someone stumbling across this site, which still ranks high in google, like me. The example (passing a vector/array/single element of numericalT as dataT and then accessing it via [] or directly) is of course somewhat contrived, but should illustrate how you actually can come very close to partially specializing a member function by wrapping it in a partially specialized class.
```
/* The following circumvents the impossible partial specialization of
a member function
actualClass<dataT,numericalT,1>::access
as well as the non-nonsensical full specialisation of the possibly
very big actualClass. */
//helper:
template <typename dataT, typename numericalT, unsigned int dataDim>
class specialised{
public:
numericalT& access(dataT& x, const unsigned int index){return x[index];}
};
//partial specialisation:
template <typename dataT, typename numericalT>
class specialised<dataT,numericalT,1>{
public:
numericalT& access(dataT& x, const unsigned int index){return x;}
};
//your actual class:
template <typename dataT, typename numericalT, unsigned int dataDim>
class actualClass{
private:
dataT x;
specialised<dataT,numericalT,dataDim> accessor;
public:
//... for(int i=0;i<dataDim;++i) ...accessor.access(x,i) ...
};
```
|
"invalid use of incomplete type" error with partial template specialization
|
[
"",
"c++",
"gcc",
"templates",
"partial-specialization",
""
] |
I've recently inherited C# console application that is in need of some pruning and clean up. Long story short, the app consists of a single class containing over 110,000 lines of code. Yup, over 110,000 lines in a single class. And, of course, the app is core to our business, running 'round the clock updating data used on a dynamic website. Although I'm told my predecessor was "a really good programmer", it obvious he was not at all into OOP (or version control).
Anyway... while familiarizing myself with the code I've found plenty of methods that are declared, but never referenced. It looks as if copy/paste was used to version the code, for example say I have a method called getSomethingImportant(), chances are there is another method called getSomethingImortant\_July2007() (the pattern is functionName\_[datestamp] in most cases). It looks like when the programmer was asked to make a change to getSomethingImportant() he would copy/paste then rename to getSomethingImortant\_Date, make changes to getSomethingImortant\_Date, then change any method calls in the code to the new method name, leaving the old method in the code but never referenced.
I'd like to write a simple console app that crawls through the one huge class and returns a list of all methods with the number of times each method was referenced. By my estimates there are well over 1000 methods, so doing this by hand would take a while.
Are there classes within the .NET framework that I can use to examine this code? Or any other usefull tools that may help identify methods that are declared but never referenced?
(Side question: Has anyone else ever seen a C# app like this, one reeeealy big class? It's more or less one huge procedural process, I know this is the first I've seen, at least of this size.)
|
You could try to use [NDepend](http://www.ndepend.com/) if you just need to extract some stats about your class. Note that this tool relies on Mono.Cecil internally to inspect assemblies.
|
To complete the *Romain Verdier* answer, lets dig a bit into what NDepend can bring to you here. (*Disclaimer: I am a developer of the NDepend team*)
NDepend lets query your .NET code with some LINQ queries. Knowing which methods call and is called by which others, is as simple as writing the following LINQ query:
```
from m in Application.Methods
select new { m, m.MethodsCalled, m.MethodsCallingMe }
```
The result of this query is presented in a way that makes easy to browse callers and callees (and its 100% integrated into Visual Studio).

---
There are many other NDepend capabilities that can help you. For example you can *right click a method in Visual Studio > NDepend > Select methods... > that are using me (directly or indirectly)* ...

The following code query is generated...
```
from m in Methods
let depth0 = m.DepthOfIsUsing("NUnit.Framework.Constraints.ConstraintExpression.Property(String)")
where depth0 >= 0 orderby depth0
select new { m, depth0 }
```
... which matches direct and indirect callers, with the depth of calls (1 means direct caller, 2 means caller of direct callers and so on).

And then by clicking the button **Export to Graph**, you get a call graph of your pivot method (of course it could be the other way around, i.e method called directly or indirectly by a particular pivot method).

|
How do you programmatically identify the number of references to a method with C#
|
[
"",
"c#",
"refactoring",
""
] |
I have many years of experience in Java including Swing, Servlet and JDBC, but have never programmed for a Java EE server.
Many job advertisements from large companies are specifically asking for Java EE experience. Are there specific skills or development environments that I should learn to qualify for these kinds of jobs?
|
Download JBoss and get to work on the sample applications in the documentation. If you've done java, you're 95% there. Java EE adds the container and naming aspect to the java you already know and love. With the advent of EJB3, beans got a lot simpler as you only need a couple of annotations to get rolling with EJB. Java EE can be a bit daunting with the acronym soup of technologies available, but concentrate on the basics: EJB3, JNDI, JMS, data access (like Hibernate/JDO), and container basics.
|
"Are there specific skills or development environments that I should learn to qualify for these kinds of jobs?"
If I were to interview someone for a typical Java EE shop, I would like to know how well you know the following
1) servlets
2) EJB (maybe)
3) JSP
4) ant
5) junit
6) subversion or other VCS
7) http and html
8) javascript
9) struts
10) hibernate
11) spring(maybe)
I'm not trying to scare you BUT 1/2 of what you need to know you can get by the "PROFESSIONAL J2EE" from WROX press. Rest of the skill, you should be able to get by with a spring book(most spring books also talk about stuts and hibernate) -- for example "The Spring Primer" -- <http://www.sourcebeat.com/books/springlive.html>.
Good Luck
|
Java EE Programming Skills
|
[
"",
"java",
"jakarta-ee",
""
] |
What is the difference between the `search()` and `match()` functions in the Python `re` module?
I've read the [Python 2 documentation](https://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match) ([Python 3 documentation](https://docs.python.org/3/library/re.html#search-vs-match)), but I never seem to remember it.
|
`re.match` is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using `^` in the pattern.
As the [re.match documentation](http://docs.python.org/2/library/re.html#re.match) says:
> If zero or more characters at the
> **beginning of string** match the regular expression pattern, return a
> corresponding `MatchObject` instance.
> Return `None` if the string does not
> match the pattern; note that this is
> different from a zero-length match.
>
> Note: If you want to locate a match
> anywhere in string, use `search()`
> instead.
`re.search` searches the entire string, as [the documentation says](http://docs.python.org/2/library/re.html#re.search):
> **Scan through string** looking for a
> location where the regular expression
> pattern produces a match, and return a
> corresponding `MatchObject` instance.
> Return `None` if no position in the
> string matches the pattern; note that
> this is different from finding a
> zero-length match at some point in the
> string.
So if you need to match at the beginning of the string, or to match the entire string use `match`. It is faster. Otherwise use `search`.
The documentation has a [specific section for `match` vs. `search`](http://docs.python.org/2/library/re.html#search-vs-match) that also covers multiline strings:
> Python offers two different primitive
> operations based on regular
> expressions: `match` checks for a match
> **only at the beginning** of the string,
> while `search` checks for a match
> **anywhere** in the string (this is what
> Perl does by default).
>
> Note that `match` may differ from `search`
> even when using a regular expression
> beginning with `'^'`: `'^'` matches only
> at the start of the string, or in
> `MULTILINE` mode also immediately
> following a newline. The “`match`”
> operation succeeds *only if the pattern
> matches at the **start** of the string*
> regardless of mode, or at the starting
> position given by the optional `pos`
> argument regardless of whether a
> newline precedes it.
Now, enough talk. Time to see some example code:
```
# example code:
string_with_newlines = """something
someotherthing"""
import re
print re.match('some', string_with_newlines) # matches
print re.match('someother',
string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
re.MULTILINE) # also won't match
print re.search('someother',
string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
re.MULTILINE) # also finds something
m = re.compile('thing$', re.MULTILINE)
print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
re.MULTILINE) # also matches
```
|
`search` ⇒ find something anywhere in the string and return a match object.
`match` ⇒ find something at the *beginning* of the string and return a match object.
|
What is the difference between re.search and re.match?
|
[
"",
"python",
"regex",
"search",
"match",
"string-matching",
""
] |
I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<list>
```
Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new elements, and a php page which will insert the data into the XML file. Here's the code for index.php:
```
<html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$activities = = $xmldoc->firstChild->firstChild;
if($activities!=null){
while(activities!=null){
echo $activities->textContent.'<br/>';
activities = activities->nextSibling.
}
}
?>
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text' name='activity'/>
<input type='submit' value='send'/>
</form>
</body>
</html
```
and here's the code for insert.php:
```
<?php
header('Location:index.php');
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$newAct = $_POST['activity'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
```
The user is to access index.php, where he would see a list of the current activities present in the XML file, and a text field below where he can insert new activities. Upon clicking the send button, the page would call insert.php, which contains a code that opens the XML file in a DOM tree, inserts a new node under the root node and calls back the index.php page, where the user should be able to see the list of activities, his new activity there under the others. It is not working. When i click on the button to submit a new entry, the pages refreshes and apparently nothing happens, the XML is the same as before. What did i do wrong? Also, i'd like to know if there's a better way of doing it.
|
is your code block copy and pasted from your existing files? if so i see two potential issues:
```
<form name='input' action'insert.php' method='post'> // should be:
<form name="input" action="insert.php" method="post">
```
note: you're missing `action`**=**`"insert.php"`, which would cause the form to just reload itself without submitting, which is the behaviour you describe.
secondly, make sure you have write permission to "sample.xml". you can confirm if you're actually writing anything:
```
print 'I wrote '.$xmldoc->save('sample.xml').' bytes of data';
```
|
Final Solution
**sample.XML**
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<activity>Jogging</activity>
<activity>Theatre</activity>
<activity>Programming</activity>
</list>
```
**index.php**
```
<html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load("sample.xml", LIBXML_NOBLANKS);
$activities = $xmldoc->firstChild->firstChild;
if($activities!=null){
while($activities!=null){
echo $activities->textContent."<br/>";
$activities = $activities->nextSibling;
}
}
?>
<form name="input" action="insert.php" method="post">
insert activity:
<input type="text" name="activity"/>
<input type="submit" value="send"/>
</form>
</body>
</html>
```
**insert.php**
```
<?php
header('Location:index.php');
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$newAct = $_POST['activity'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
```
|
Inserting data in XML file with PHP DOM
|
[
"",
"php",
"xml",
"dom",
""
] |
What is the best way to take a given PHP object and serialize it as XML? I am looking at simple\_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.
|
take a look at PEAR's [XML\_Serializer](http://pear.php.net/package/XML_Serializer) package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc.
Should do the trick
|
I'd agree with using PEAR's XML\_Serializer, but if you want something simple that supports objects/arrays that have properties nested, you can use this.
```
class XMLSerializer {
// functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
public static function generateValidXmlFromObj(stdClass $obj, $node_block='nodes', $node_name='node') {
$arr = get_object_vars($obj);
return self::generateValidXmlFromArray($arr, $node_block, $node_name);
}
public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generateXmlFromArray($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
}
private static function generateXmlFromArray($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
}
}
```
|
PHP Object as XML Document
|
[
"",
"php",
"xml",
"xml-serialization",
""
] |
I am working a standalone c# desktop application that sends out documents and then imports them from Outlook when they are sent back. The application picks up the emails from a specified folder processes them and then saves the senders name plus other stuff to a database.
This works well for Outlook 2003 and 2007 which has the SenderEmailAddress property. However Outlook 2000 and XP does not have this property and will not consistently return name@domain.com. I am providing support for these versions.
I have found that a library called Outlook Redemption will solve this but I am developing in .net and really want to avoid writing to customer registries. I also found MAPI33 a .Net wrapper around MAPI but it is unclear from the forums whether it is still being supported.
Would appreciate any pointers as to a .Net alternative to the Redemption dll or an approach to being able to consistently retrieve an email address across Outlook versions.
Many thanks
AbsFabs
**Epilogue:**
I ended up using a solution from this article <http://support.microsoft.com/kb/324530>. It comprised creating a reply and then extracting the reply to address of the created mailitem. It worked well for emails sent over the internet and is currently going through Exchange Server testing.
Also found this on my travels <http://anoriginalidea.wordpress.com/2008/01/11/getting-the-smtp-email-address-of-an-exchange-sender-of-a-mailitem-from-outlook-in-vbnet-vsto/> it appears to be a touch involved. This might comprise my plan B if my existing implementation does not survive testing.
Thanks for your feedback
AbsFabs
I ultimately wound up using Redemption. Excellent tool for the job. My issue was with having to register the dll when my app was installed. Since my app is written in dotnet it does not need to register anything. I was able to work around the dll registration issue using registry-free COM.
Many thanks for your inspiration.
|
I'm using the Outlook Redemption solution in a C# production code. It works beautifully.
With it, you can get the SenderID of a mail message (IRDOMail), and from there, you can use the GetAddressEntryFromID() method of the IRDOSession object.
|
While having a similar problem at work, we decided to go the netMAPI route, which has caused some problems.
The main problem with it is that MAPI managed its own memory, as does .NET meaning that occasionally (we have around 300 people using our in house software) it would cause our application to crash, generating the windows 'report error' dialog rather than our own bug tracking dialog. This was caused by the two overwriting each others memory heaps.
As we have to use an exchange server, we did some research, and discovered that if you wrote the MAPI code in a VB6 app, it would have its own memory space, and thus not overwrite the .NET heap.
It is a rather long winded way of doing things, but thus far we have had no problems, and hundreds (if not thousands) of emails are sent by our staff everyday.
|
Consistently retrieve "From" email addresses across Outlook versions
|
[
"",
"c#",
".net",
"outlook",
"ms-office",
""
] |
I am trying to convert an `int` into three `bytes` representing that `int` (big endian).
I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.
For example:
```
int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
```
\*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.
|
To get the least significant byte:
```
b3 = myInt & 0xFF;
```
The 2nd least significant byte:
```
b2 = (myInt >> 8) & 0xFF;
```
And the 3rd least significant byte:
```
b1 = (myInt >> 16) & 0xFF;
```
**Explanation:**
Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte.
|
```
byte b1 = (myint >> 16) & 0xff;
byte b2 = (myint >> 8) & 0xff;
byte b3 = myint & 0xff;
```
I am unsure how this holfds in java though, i aam not a java dev
|
How can I turn an int into three bytes in Java?
|
[
"",
"java",
"bit-manipulation",
"byte",
"bit-shift",
""
] |
Other than standard OO concepts, what are some other strategies that allow for producing good, clean PHP code when a framework is not being used?
|
Remember: MVC, OOP and tiers are design concepts, not language constructs, nor file-structuring.
For me, this means that when not using a framework, and when there's not different teams for programming and designing; there's no value in using *another* template system on top of PHP (which is a template language). Also, separating code from layout doesn't necessarily mean doing it on different files.
This is how i used to do for one-off, seldom expanded, PHP web apps:
1. write a 'general utilities' file, there i put some formatting/sanitising functions, as well as a few DB access functions:
1. getquery(): given a SQL, returns a result object
* getrecord(): given a SQL, returns a record object (and closes the query)
* getdatum(): given a SQL, returns a single field (and closes the query)
* put all configurations (DB access, some URL prefixes, etc) on a 'config.php' file
* write a model layer, either one file, or one for each object you store on DB. There, will be all the SQL constants, present a higher-level API, based on your conceptual objects, not on DB records.
that's your 'framework', then you write the 'presentation' layer:
4. one PHP file for each page, starts with some *simple* code to fetch the objects needed, followed by HTML with interspeced PHP code, just to 'fill in the holes'. with very few exceptions, the most complex code there should be for loops. I make a rule to use only one-liners, the `?>` should be in the same line as the opening `<?php`
* each data-entry form should point to a small PHP without any HTML, that simply get's the POST data, enters into the DB, and forwards to the calling page.
and that's it. If working alone, it has all the separation of intents you need, without drowning in a lot of files for a single user action. Each page as seen by the user is managed by a single PHP file.
It's even easy to maintain, after a few months without looking at the code, since it's easy to test the app, taking note of the filenames in the URL field of the browser. This guides you directly to the relevant code.
(nowadays, of course, i'm using Django for almost everything...)
|
I'd say pretty much the same as for any other language:
* Don't optimise prematurely
* Keep methods small
* Practise DRY
* Practise data-driven programming
* Use sensible shortcuts (e.g. ternary operator)
* Format your code well so that it can be understood by others
* Don't use OO blindly
* Always check return codes for errors
* Enable the highest warning level and ensure your code doesn't produce any warnings
* Be *very* careful when it comes to typing issues (this goes for all weakly-typed languages). The '===' operator is your friend.
|
How do you write good PHP code without the use of a framework?
|
[
"",
"php",
""
] |
What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?
I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.
```
Type type = typeof(FooBar)
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
type.GetConstructors(flags)
.Where(constructor => constructor.GetParameters().Length == 0)
.First();
```
|
```
type.GetConstructor(Type.EmptyTypes)
```
|
If you actually **need** the ConstructorInfo object, then see [Curt Hagenlocher's answer](https://stackoverflow.com/questions/142356/most-efficient-way-to-get-default-constructor-of-a-type#142362).
On the other hand, if you're really just trying to create an object at run-time from a `System.Type`, see [`System.Activator.CreateInstance`](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) -- it's not just future-proofed (Activator handles more details than `ConstructorInfo.Invoke`), it's also **much** less ugly.
|
Most efficient way to get default constructor of a Type
|
[
"",
"c#",
".net",
"reflection",
""
] |
I hope this is programmer-related question. I'm in the hobby business of C# programming. For my own purposes I need to parse html files and the best idea is..regular expression. As many found out, it's quite time consuming to learn them and thus I'm quite interested if you know about some application that would be able to take **input** (piece of any code), **understand what i need** (by Me selecting a piece of the code I need to "cut out"), and **give me the proper regular expression** for it or more options.
As I've heard, Regex is a little science of itself, so it might not be as easy as I'd imagine.
|
Yes there is Roy Osherove wrote exactly what you're looking for - [regulazy](http://files.osherove.com/Regulazy/Regulazy.103.zip)
|
You might also want to try txt2re : <http://txt2re.com/>, which tries to identify patterns in a user-supplied string and allows to build a regex out of them.
|
Is there an Application to Create Regular Expression Out of Text by Selecting Wanted Area?
|
[
"",
"c#",
"regex",
"automation",
""
] |
[JavaScript post request like a form submit](https://stackoverflow.com/q/133925) shows you how to submit a form that you create via POST in JavaScript. Below is my modified code.
```
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form); // Not entirely sure if this is necessary
form.submit();
```
What I would like to do is open the results in a new window. I am currently using something like this to open a page in a new window:
```
onclick = window.open(test.html, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
```
|
Add
```
<form target="_blank" ...></form>
```
or
```
form.setAttribute("target", "_blank");
```
to your form's definition.
|
If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):
```
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");
// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
```
|
After submitting a POST form open a new window showing the result
|
[
"",
"javascript",
"html",
"post",
""
] |
I am just checking out F#, so apologies if this is a silly question, but in the VS2008 F# CTP 1.9.6.2 'Tutorial' project, both // and /// are used for commenting code.
Is there a functional difference between the two slash vs three slash commenting, or is it convention (as it appears in the tutorial code) to comment a function with /// and use // for everything else?
|
Using three slashes (///) is a C# convention for [XML Documentation Comments](https://learn.microsoft.com/en-gb/dotnet/csharp/programming-guide/xmldoc/) that is adopted by F# as well.
|
/// is for documentation comments. VS will use it when generating intellisense information.
|
.NET // vs /// Comments convention
|
[
"",
"c#",
"f#",
"comments",
""
] |
I am looking for a method to compare and sort UTF-8 strings in C++ in a case-insensitive manner to use it in a [custom collation function in SQLite](http://www.sqlite.org/c3ref/create_collation.html).
1. The method should *ideally* be locale-independent. However I won't be holding my breath, as far as I know, collation is very language-dependent, so anything that works on languages other than English will do, even if it means switching locales.
2. Options include using standard C or C++ library or a *small* (suitable for embedded system) and *non-GPL* (suitable for a proprietary system) third-party library.
What I have so far:
1. `strcoll` with C locales and `std::collate`/`std::collate_byname` are case-sensitive. (Are there case-insensitive versions of these?)
2. I tried to use a POSIX strcasecmp, but it seems to be [not defined](http://www.opengroup.org/onlinepubs/007908775/xsh/strcasecmp.html) for locales other than `"POSIX"`
> *In the POSIX locale, strcasecmp() and strncasecmp() do upper to lower conversions, then a byte comparison. The results are unspecified in other locales.*
And, indeed, the result of `strcasecmp` does not change between locales on Linux with GLIBC.
```
#include <clocale>
#include <cstdio>
#include <cassert>
#include <cstring>
const static char *s1 = "Äaa";
const static char *s2 = "äaa";
int main() {
printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2));
printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2));
assert(setlocale(LC_ALL, "en_AU.UTF-8"));
printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2));
printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2));
assert(setlocale(LC_ALL, "fi_FI.UTF-8"));
printf("strcasecmp('%s', '%s') == %d\n", s1, s2, strcasecmp(s1, s2));
printf("strcoll('%s', '%s') == %d\n", s1, s2, strcoll(s1, s2));
}
```
This is printed:
```
strcasecmp('Äaa', 'äaa') == -32
strcoll('Äaa', 'äaa') == -32
strcasecmp('Äaa', 'äaa') == -32
strcoll('Äaa', 'äaa') == 7
strcasecmp('Äaa', 'äaa') == -32
strcoll('Äaa', 'äaa') == 7
```
P. S.
And yes, I am aware about [ICU](http://icu-project.org/), but we can't use it on the embedded platform due to its [enormous size](http://www.icu-project.org/charts/icu4c_footprint.html).
|
What you really want is logically impossible. There is no locale-independent, case-insensitive way of sorting strings. The simple counter-example is "i" <> "I" ? The naive answer is no, but in Turkish these strings are unequal. "i" is uppercased to "İ" (U+130 Latin Capital I with dot above)
UTF-8 strings add extra complexity to the question. They're perfectly valid multi-byte char\* strings, if you have an appropriate locale. But neither the C nor the C++ standard defines such a locale; check with your vendor (too many embedded vendors, sorry, no genearl answer here). So you HAVE to pick a locale whose multi-byte encoding is UTF-8, for the mbscmp function to work. This of course influences the sort order, which is locale dependent. And if you have NO locale in which const char\* is UTF-8, you can't use this trick at all. (As I understand it, Microsoft's CRT suffers from this. Their multi-byte code only handles characters up to 2 bytes; UTF-8 needs 3)
wchar\_t is not the standard solution either. It supposedly is so wide that you don't have to deal with multi-byte encodings, but your collation will still depend on locale (LC\_COLLATE) . However, using wchar\_t means you now choose locales that do not use UTF-8 for const char\*.
With this done, you can basically write your own ordering by converting strings to lowercase and comparing them. It's not perfect. Do you expect L"ß" == L"ss" ? They're not even the same length. Yet, for a German you have to consider them equal. Can you live with that?
|
I have no definitive answer in the form of example code, but I should point out that an UTF-8 bytestream contains, in fact, Unicode characters and you have to use the wchar\_t versions of the C/C++ runtime library.
You have to convert those UTF-8 bytes into wchar\_t strings first, though. This is not very hard, as the UTF-8 encoding standard is [very well documented](http://en.wikipedia.org/wiki/UTF-8). I know this, because I've done it, but I can't share that code with you.
|
Case-insensitive UTF-8 string collation for SQLite (C/C++)
|
[
"",
"c++",
"sqlite",
"unicode",
"utf-8",
"internationalization",
""
] |
How do you perform a CROSS JOIN with LINQ to SQL?
|
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
```
var combo = from p in people
from c in cars
select new
{
p.Name,
c.Make,
c.Model,
c.Colour
};
```
|
The same thing with the Linq extension method `SelectMany` (lambda syntax):
```
var names = new string[] { "Ana", "Raz", "John" };
var numbers = new int[] { 1, 2, 3 };
var newList=names.SelectMany(
x => numbers,
(y, z) => { return y + z + " test "; });
foreach (var item in newList)
{
Console.WriteLine(item);
}
```
|
How do you perform a CROSS JOIN with LINQ to SQL?
|
[
"",
"c#",
"linq",
"linq-to-sql",
"cross-join",
""
] |
With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them?
Why???
I'm working on processing some openstreetmap xml data and these files are huge. I'm currently streaming them in since I can't load them all in one chunk but I just got curious about the upper limits on malloc or new.
|
Short answer: Not likely
In order for this to work, you absolutely would **have** to use a 64-bit processor.
Secondly, it would depend on the Operating System support for allocating more than 4G of RAM to a single process.
In theory, it would be possible, but you would have to read the documentation for the memory allocator. You would also be more susceptible to memory fragmentation issues.
There is good information on [Windows memory management](http://www.microsoft.com/whdc/system/kernel/wmm.mspx).
|
**A Primer on physcal and virtual memory layouts**
You would need a 64-bit CPU and O/S build and almost certainly enough memory to avoid thrashing your working set. A bit of background:
A 32 bit machine (by and large) has registers that can store one of 2^32 (4,294,967,296) unique values. This means that a 32-bit pointer can address any one of 2^32 unique memory locations, which is where the magic 4GB limit comes from.
Some 32 bit systems such as the SPARCV8 or Xeon have MMU's that pull a trick to allow more physical memory. This allows multiple processes to take up memory totalling more than 4GB in aggregate, but each process is limited to its own 32 bit virtual address space. For a single process looking at a virtual address space, only 2^32 distinct physical locations can be mapped by a 32 bit pointer.
I won't go into the details but [This presentation](http://pages.cs.wisc.edu/~remzi/Classes/537/Fall2005/Lectures/lecture14.ppt) (warning: powerpoint) describes how this works. Some operating systems have facilities (such as those described [Here](http://msdn.microsoft.com/en-us/library/aa366796(VS.85).aspx) - thanks to FP above) to manipulate the MMU and swap different physical locations into the virtual address space under user level control.
The operating system and memory mapped I/O will take up some of the virtual address space, so not all of that 4GB is necessarily available to the process. As an example, Windows defaults to taking 2GB of this, but can be set to only take 1GB if the /3G switch is invoked on boot. This means that a single process on a 32 bit architecture of this sort can only build a contiguous data structure of somewhat less than 4GB in memory.
This means you would have to explicitly use the [PAE](http://msdn.microsoft.com/en-us/library/aa366527(VS.85).aspx) facilities on Windows or [Equivalent facilities on Linux](http://www.ibm.com/developerworks/linux/library/l-memmod/#extend) to manually swap in the overlays. This is not necessarily that hard, but it will take some time to get working.
Alternatively you can get a 64-bit box with lots of memory and these problems more or less go away. A 64 bit architecture with 64 bit pointers can build a contiguous data structure with as many as 2^64 (18,446,744,073,709,551,616) unique addresses, at least in theory. This allows larger contiguous data structures to be built and managed.
|
Can you allocate a very large single chunk of memory ( > 4GB ) in c or c++?
|
[
"",
"c++",
"c",
"memory",
"malloc",
""
] |
I'm using a lot of JQuery in a web application that I am building for a client and I want to find an javascript implementation of a modal dialog that is reasonably stable across the following browser set.
IE 7+
FF 2+
Chrome and Safari
I've tried a couple of jQuery plugins but there always seems to be artifacts in one of these browsers.
--- Edit
`jqModal` seems to be more stable but I have an issue in IE7 where the dialog immediately disappears after popping up. I suspect a js event isn't being canceled or something. I'll have a bit more of a play.
|
I used [jqModal](http://dev.iceburg.net/jquery/jqModal/) few times and I'm very satisfied. It is pretty configurable yet very light weight.
|
Have you tried [YUI](http://developer.yahoo.com/yui/container/dialog/)? I'm not sure what the support is for Chrome but I've had good luck with it for IE and Firefox and allegedly it works with Safari.
|
What is the most stable modal dialog implementation across browsers to use from javascript for a web app?
|
[
"",
"javascript",
"jquery",
"modal-dialog",
"cross-browser",
"jqmodal",
""
] |
For my current C++ project I need to detect a unique string for every monitor that is connected and active on a large number of computers.
Research has pointed to 2 options
1. Use WMI and query the Win32\_DesktopMonitor for all active monitors. Use the PNPDeviceID for unique identification of monitors.
2. Use the EnumDisplayDevices API, and dig down to get the device ID.
I'm interested in using the device id for unique model identification because monitors using the default plug and play driver will report a generic string as the monitor name "default plug and play monitor"
I have been experiencing issues with the WMI method, it seems to be only returning 1 monitor on my Vista machine, looking at the doco it turns out it does not work as expected on non WDDM devices.
The EnumDisplayDevices seems to be a little problematic to get going when it runs from a background service (especially on Vista), If it's in session 0 it will return no info.
* Has anyone else had to do something similar (find unique model string for all connected active monitors?)
* What approach worked best?
|
This is my current work-in-progress code for detecting the monitor device id, reliably.
```
CString DeviceID;
DISPLAY_DEVICE dd;
dd.cb = sizeof(dd);
DWORD dev = 0;
// device index
int id = 1;
// monitor number, as used by Display Properties > Settings
while (EnumDisplayDevices(0, dev, &dd, 0))
{
DISPLAY_DEVICE ddMon;
ZeroMemory(&ddMon, sizeof(ddMon));
ddMon.cb = sizeof(ddMon);
DWORD devMon = 0;
while (EnumDisplayDevices(dd.DeviceName, devMon, &ddMon, 0))
{
if (ddMon.StateFlags & DISPLAY_DEVICE_ACTIVE &&
!(ddMon.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
{
DeviceID.Format (L"%s", ddMon.DeviceID);
DeviceID = DeviceID.Mid (8, DeviceID.Find (L"\\", 9) - 8);
}
devMon++;
ZeroMemory(&ddMon, sizeof(ddMon));
ddMon.cb = sizeof(ddMon);
}
ZeroMemory(&dd, sizeof(dd));
dd.cb = sizeof(dd);
dev++;
}
```
|
I've just discovered you can query Win32\_PnPEntity for service="monitor", and it will return all monitors.
Results on my machine:
```
select * from Win32_PnPEntity where service="monitor"
Availability | Caption | ClassGuid | CompatibleID | ConfigManagerErrorCode | ConfigManagerUserConfig | CreationClassName | Description | DeviceID | ErrorCleared | ErrorDescription | HardwareID | InstallDate | LastErrorCode | Manufacturer | Name | PNPDeviceID | PowerManagementCapabilities | PowerManagementSupported | Service | Status | StatusInfo | SystemCreationClassName | SystemName
| Dell 2007FP (Digital) | {4d36e96e-e325-11ce-bfc1-08002be10318} | array[0..0] | 0 | False | Win32_PnPEntity | Dell 2007FP (Digital) | DISPLAY\DELA021\5&4F61016&0&UID257 | | | array[0..0] | | | Dell Inc. | Dell 2007FP (Digital) | DISPLAY\DELA021\5&4F61016&0&UID257 | | | monitor | OK | | Win32_ComputerSystem | 8HVS05J
| Dell ST2320L_Digital | {4d36e96e-e325-11ce-bfc1-08002be10318} | array[0..0] | 0 | False | Win32_PnPEntity | Dell ST2320L_Digital | DISPLAY\DELF023\5&4F61016&0&UID256 | | | array[0..0] | | | Dell Inc. | Dell ST2320L_Digital | DISPLAY\DELF023\5&4F61016&0&UID256 | | | monitor | OK | | Win32_ComputerSystem | 8HVS05J
```
|
EnumDisplayDevices vs WMI Win32_DesktopMonitor, how to detect active monitors?
|
[
"",
"c++",
"windows",
"winapi",
"wmi",
""
] |
I'm playing around with the [`<canvas>`](http://developer.mozilla.org/en/HTML/Canvas) element, drawing lines and such.
I've noticed that my diagonal lines are antialiased. I'd prefer the jaggy look for what I'm doing - is there any way of turning this feature off?
|
For images there's now [`context.imageSmoothingEnabled`](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled)`= false`.
However, there's nothing that explicitly controls line drawing. You may need to draw your own lines ([the hard way](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm)) using `getImageData` and `putImageData`.
|
Draw your `1-pixel` lines on coordinates like `ctx.lineTo(10.5, 10.5)`. Drawing a one-pixel line over the point `(10, 10)` means, that this `1` pixel at that position reaches from `9.5` to `10.5` which results in two lines that get drawn on the canvas.
A nice trick to not always need to add the `0.5` to the actual coordinate you want to draw over if you've got a lot of one-pixel lines, is to `ctx.translate(0.5, 0.5)` your whole canvas at the beginning.
|
Can I turn off antialiasing on an HTML <canvas> element?
|
[
"",
"javascript",
"html",
"canvas",
"antialiasing",
""
] |
I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?
|
Anonymous inner class
Say you want to have a function passed in with a `String` param that returns an `int`.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
```
interface StringFunction {
int func(String param);
}
```
A method that takes the pointer would just accept `StringFunction` instance like so:
```
public void takingMethod(StringFunction sf) {
int i = sf.func("my string");
// do whatever ...
}
```
And would be called like so:
```
ref.takingMethod(new StringFunction() {
public int func(String param) {
// body
}
});
```
*EDIT:* In Java 8, you could call it with a lambda expression:
```
ref.takingMethod(param -> bodyExpression);
```
|
For each "function pointer", I'd create a small [functor class](http://en.wikipedia.org/wiki/Function_object#In_Java) that implements your calculation.
Define an interface that all the classes will implement, and pass instances of those objects into your larger function. This is a combination of the "[command pattern](http://en.wikipedia.org/wiki/Command_pattern)", and "[strategy pattern](https://stackoverflow.com/questions/91932/how-does-the-strategy-pattern-work)".
@sblundy's example is good.
|
What's the nearest substitute for a function pointer in Java?
|
[
"",
"java",
"closures",
"function-pointers",
""
] |
I keep reading about how great this new Canvas element for HTML5 is and I see amazing demos done with just javascript and no flash. Where can I find some good information on how to some of these things myself?
|
[The specification](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element) defines the API and behaviour.
[This tutorial](http://developer.mozilla.org/en/Canvas_tutorial) should help you get started.
|
There's the original [Apple tutorial](http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/Canvas.html)
Also the [draft html5 spec](http://www.w3.org/html/wg/html5/#the-canvas-element)
And of course you can (as people have) ask questions about specific features, etc on SO :D
|
Where can I find some good information about how the new canvas HTML element works?
|
[
"",
"javascript",
"html",
"canvas",
""
] |
When is it a good idea to use [`PHP_EOL`](https://www.php.net/manual/en/reserved.constants.php)?
I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?
|
Yes, `PHP_EOL` is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Note that [PHP\_EOL](http://php.net/manual/en/reserved.constants.php) represents the endline character for the *current* system. For instance, it will not find a Windows endline when executed on a unix-like system.
|
From `main/php.h` of PHP version 7.1.1 and version 5.6.30:
```
#ifdef PHP_WIN32
# include "tsrm_win32.h"
# include "win95nt.h"
# ifdef PHP_EXPORTS
# define PHPAPI __declspec(dllexport)
# else
# define PHPAPI __declspec(dllimport)
# endif
# define PHP_DIR_SEPARATOR '\\'
# define PHP_EOL "\r\n"
#else
# if defined(__GNUC__) && __GNUC__ >= 4
# define PHPAPI __attribute__ ((visibility("default")))
# else
# define PHPAPI
# endif
# define THREAD_LS
# define PHP_DIR_SEPARATOR '/'
# define PHP_EOL "\n"
#endif
```
As you can see `PHP_EOL` can be `"\r\n"` (on Windows servers) or `"\n"` (on anything else). On PHP versions **prior** 5.4.0RC8, there were a third value possible for `PHP_EOL`: `"\r"` (on MacOSX servers). It was wrong and has been fixed on 2012-03-01 with [bug 61193](https://bugs.php.net/bug.php?id=61193).
As others already told you, you can use `PHP_EOL` in any kind of output (where **any** of these values are valid - like: HTML, XML, logs...) where you want unified [newlines](http://en.wikipedia.org/wiki/End_of_line). Keep in mind that it's the server that it's determining the value, not the client. Your Windows visitors will get the value from your Unix server which is inconvenient for them sometimes.
I just wanted to show the possibles values of `PHP_EOL` backed by the PHP sources since it hasn't been shown here yet...
|
When do I use the PHP constant "PHP_EOL"?
|
[
"",
"php",
"eol",
""
] |
I have a new application written in WPF that needs to support an old API that allows it to receive a message that has been posted to a hidden window. Typically another application uses FindWindow to identify the hidden window using the name of its custom window class.
**1) I assume to implement a custom window class I need to use old school win32 calls?**
My old c++ application used RegisterClass and CreateWindow to make the simplest possible invisible window.
I believe I should be able to do the same all within c#. I don't want my project to have to compile any unmanaged code.
I have tried inheriting from System.Windows.Interop.HwndHost and using System.Runtime.InteropServices.DllImport to pull in the above API methods.
Doing this I can successfully host a standard win32 window e.g. "listbox" inside WPF.
However when I call CreateWindowEx for my custom window it always returns null.
My call to RegisterClass succeeds but I am not sure what I should be setting the
WNDCLASS.lpfnWndProc member to.
**2) Does anyone know how to do this successfully?**
|
For the record I finally got this to work.
Turned out the difficulties I had were down to string marshalling problems.
I had to be more precise in my importing of win32 functions.
Below is the code that will create a custom window class in c# - useful for supporting old APIs you might have that rely on custom window classes.
It should work in either WPF or Winforms as long as a message pump is running on the thread.
EDIT:
Updated to fix the reported crash due to early collection of the delegate that wraps the callback. The delegate is now held as a member and the delegate explicitly marshaled as a function pointer. This fixes the issue and makes it easier to understand the behaviour.
```
class CustomWindow : IDisposable
{
delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[System.Runtime.InteropServices.StructLayout(
System.Runtime.InteropServices.LayoutKind.Sequential,
CharSet = System.Runtime.InteropServices.CharSet.Unicode
)]
struct WNDCLASS
{
public uint style;
public IntPtr lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public string lpszMenuName;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public string lpszClassName;
}
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern System.UInt16 RegisterClassW(
[System.Runtime.InteropServices.In] ref WNDCLASS lpWndClass
);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern IntPtr CreateWindowExW(
UInt32 dwExStyle,
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
string lpClassName,
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
string lpWindowName,
UInt32 dwStyle,
Int32 x,
Int32 y,
Int32 nWidth,
Int32 nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam
);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern System.IntPtr DefWindowProcW(
IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam
);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern bool DestroyWindow(
IntPtr hWnd
);
private const int ERROR_CLASS_ALREADY_EXISTS = 1410;
private bool m_disposed;
private IntPtr m_hwnd;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!m_disposed) {
if (disposing) {
// Dispose managed resources
}
// Dispose unmanaged resources
if (m_hwnd != IntPtr.Zero) {
DestroyWindow(m_hwnd);
m_hwnd = IntPtr.Zero;
}
}
}
public CustomWindow(string class_name){
if (class_name == null) throw new System.Exception("class_name is null");
if (class_name == String.Empty) throw new System.Exception("class_name is empty");
m_wnd_proc_delegate = CustomWndProc;
// Create WNDCLASS
WNDCLASS wind_class = new WNDCLASS();
wind_class.lpszClassName = class_name;
wind_class.lpfnWndProc = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate);
UInt16 class_atom = RegisterClassW(ref wind_class);
int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) {
throw new System.Exception("Could not register window class");
}
// Create window
m_hwnd = CreateWindowExW(
0,
class_name,
String.Empty,
0,
0,
0,
0,
0,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero
);
}
private static IntPtr CustomWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
private WndProc m_wnd_proc_delegate;
}
```
|
I'd like to comment the answer of morechilli:
```
public CustomWindow(string class_name){
if (class_name == null) throw new System.Exception("class_name is null");
if (class_name == String.Empty) throw new System.Exception("class_name is empty");
// Create WNDCLASS
WNDCLASS wind_class = new WNDCLASS();
wind_class.lpszClassName = class_name;
wind_class.lpfnWndProc = CustomWndProc;
UInt16 class_atom = RegisterClassW(ref wind_class);
int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) {
throw new System.Exception("Could not register window class");
}
// Create window
m_hwnd = CreateWindowExW(
0,
class_name,
String.Empty,
0,
0,
0,
0,
0,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero
);
}
```
In the constructor I copied above is slight error: The WNDCLASS instance is created, but not saved. It will eventually be garbage collected. But the WNDCLASS holds the WndProc delegate. This results in an error as soon as WNDCLASS is garbage collected. The instance of WNDCLASS should be hold in a member variable until the window is destroyed.
|
Registering a custom win32 window class from c#
|
[
"",
"c#",
"windows",
"winapi",
"interop",
""
] |
I am using PHP with Apache on Linux, with Sendmail. I use the PHP [`mail`](http://php.net/manual/en/function.mail.php) function. The email is sent, but the envelope has the `Apache_user@localhostname` in `MAIL FROM` (example nobody@conniptin.internal) and some remote mail servers reject this because the domain doesn't exist (obviously). Using `mail`, can I force it to change the envelope `MAIL FROM`?
EDIT: If I add a header in the fourth field of the `mail`() function, that changes the `From` field in the headers of the body of the message, and DOES NOT change the envelope `MAIL FROM`.
I can force it by spawning sendmail with `sendmail -t -odb -oi -frealname@realhost` and piping the email contents to it. Is this a better approach?
Is there a better, simpler, more PHP appropriate way of doing this?
EDIT: The bottom line is I should have RTM. Thanks for the answers folks, the fifth parameter works and all is well.
|
mail() has a 4th and 5th parameter (optional). The 5th argument is what should be passed as options directly to sendmail. I use the following:
```
mail('to@blah.com','subject!','body!','From: from@blah.com','-f from@blah.com');
```
|
I would also recommend checking into [PHPMailer](http://phpmailer.codeworxtech.com). It's great for creating and sending email, making the process a lot easier, along with support for SMTP.
|
How to change envelope from address using PHP mail?
|
[
"",
"php",
"email",
""
] |
I have followed all the instructions here: <http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/>
to install & config apache
get the PHP5 packages
and get the CURL packages.
I run the apache and run a PHP script. no problem.
but when I run the php script with curl, it fails.
It returns: `**Call to undefined function curl_version() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\testing.php on line 5**`
In which line 5 is a called to `curl_init()`
I output the php -i to see whether the right path to extension is called. It is correctly set:
```
extension_dir => C:\PHP\ext => C:\PHP\ext
cURL support => enabled
cURL Information => libcurl/7.16.0 OpenSSL/0.9.8g zlib/1.2.3
```
I even tried to run `curl_version()` but still, same kind of error comes up.
It looks like the PHP can't find the CURL extension, but the `php.ini` (and also php -i) shows that it is set.
any idea? :)
```
P.S> System I m running on:
Windows XP
Apache 2.2
PHP 5.2.6
CURL Win32 Generic Binaries: Win32 2000/XP metalink 7.19.0 binary SSL enabled Daniel Stenberg 249 KB
```
I didn't get this:
```
Win32 2000/XP 7.19.0 libcurl SSL enabled Günter Knauf 1.55 MB
Should I get this one instead?
```
---
The reason I need to use CURL is that it is the requirement from my project. So, I can only stick with that.
XAMPP... how does it work in Windows? Is there any site that you can recommend? Thanks.
I have tried a lot of things on installing cURL and check everything, but still, I'm stilling circling around the problem and have no idea what's going on.
The Apache server uses the right PHP.ini. and the PHP.ini has the correct extension\_dir and extension=php\_curl.dll
I have no idea why it doesn't work. even I follow every step for setting it up. :(
|
You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.
Write down the PHP ini directory path you see in the variables list now!
You will probably notice that it's different from your PHP-CLI ini file.
Enable the extension
You're done :-)
|
**Use the following steps to install curl:**
1. Open <https://curl.haxx.se/dlwiz?type=bin> in a browser.
2. Select your operating system in the dropdown box: either Windows /Win32 or Win 64. Click Select!
3. For Win 32, choose whether you will use curl in a Windows Command Prompt (Generic) or in a Cygwin terminal (cygwin). For Win 64, choose whether you will use curl in a Windows Command Prompt (Generic) or MinGW (MinGW64). Click Select!
4. If required, choose your Windows operating system. Finish.
5. Click Download for the version which has SSL enabled or disabled
6. Open the downloaded zip file. Extract the files to an easy-to-find place, such as C:\Program Files.
**Testing curl**
1. Open up the Windows Command Prompt terminal. (From the Start menu, click Run, then type cmd.)
2. Set the path to include the directory where you put curl.exe. For example, if you put it in C:\Program Files\curl, then you would type the following command:
set path=%path%;"c:\Program Files\curl"
NOTE: You can also directly copy the curl.exe file any existing path in your path
3. Type curl.
You should see the following message:
curl: try 'curl –help' or 'curl –message' for more information
This means that curl is installed and the path is correct.
|
How do I install cURL on Windows?
|
[
"",
"php",
"windows",
"curl",
"windows-xp",
"installation",
""
] |
How can I determine if I have write permission on a remote machine in my intranet using C# in .Net?
|
The simple answer would be to try it and see. The Windows security APIs are not for the faint of heart, and may be possible you have write permission without having permission to view the permissions!
|
Been there too, the best and most reliable solution I found was this:
```
bool hasWriteAccess = true;
string remoteFileName = "\\server\share\file.name"
try
{
createRemoteFile(remoteFileName);
}
catch (SystemSecurityException)
{
hasWriteAccess = false;
}
if (File.Exists(remoteFileName))
{
File.Delete(remoteFileName);
}
return hasWriteAccess;
```
|
How can I programmatically determine if I have write privileges using C# in .Net?
|
[
"",
"c#",
".net",
"networking",
"file-permissions",
""
] |
In Gmail, I have a bunch of labeled messages.
I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.
```
c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
```
I'm not finding many examples for this sort of thing.
|
`imaplib` is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the [IMAP specification](http://www.faqs.org/rfcs/rfc3501.html).
As you'll see in section "6.4.4. SEARCH Command", there are many things you can specify for search criterion. Note that you have to `SELECT` a mailbox (IMAP's name for a folder) before you can search for anything. (Searching multiple folders simultaneously requires multiple IMAP connections, as I understand it.) `IMAP4.list` will help you figure out what the mailbox identifiers are.
Also useful in formulating the strings you pass to `imaplib` is "9. Formal Syntax" from the RFC linked to above.
The `r'(\HasNoChildren) "/"'` is a mailbox flag on the root mailbox, `/`. See "7.2.6. FLAGS Response".
Good luck!
|
```
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('**label name**') # <-- the label in which u want to search message
obj.search(None, 'FROM', '"LDJ"')
```
|
How do I perform an IMAP search in Python (using Gmail and imaplib)?
|
[
"",
"python",
"gmail",
"imap",
""
] |
i have a library with some entities that share the same interface. clients and service share this assembly. now i wonder if there is a way to have this Interface-type as Parameter in my service contracts so that i can use the same method for all classes implementing the interface.
the entities themselve are all decorated with datacontract-attribute and its members with datamember attributes.
is it possible at all? probably with the *NetDataContractSerializer*?
i know that i can do it with a base class (some abstract class e.g.) and the *knowntype*-attribute but i´d definitely prefer the Interface as identificator of the objects cause it is used widely in the client app and would ease development.
thanks
|
I solved the problem using the ServiceKnownType attribute at the implementations of the OperationContracts.
When telling your classes that implement the interface as ServiceKnownType's, you can use the interface as parameter and therefore are able to use all classes implementing your interface as long as they are serializable. (look at "Programming WCF Services" from Juval Löwy, page 100)
|
It certainly isn't possible under regular "mex". It *might* be possible with assembly sharing, but I really wouldn't recommend it - you are fighting WCF: it will be brittle, etc. Of course, you can always mask this in your object model - i.e. rather than calling the [OperationContract] method directly, abstract this away into a wrapper method that hides the WCF details (perhaps using different objects for the data transfer than it actually returns).
|
Wcf and Interfaces as Parameters
|
[
"",
"c#",
".net",
"wcf",
"web-services",
""
] |
I am converting an excel sheet formula to java but I can't understand how excel manages to take the following: 0.22
Applies a formula: =TEXT(R5/14, "h:mm")
and somehow arrives at: 0.22
Again if I provide: 2.8
it arrives at 4.48
Can someone please explain to me how it does this. I have read a little regarding decimal and I understand the conversion but this hasn't yet helped to explain the above.
|
Excel stores datetime values as:
* The number to the left of the decimal represents the number of days since January 1, 1900
* The number to the right of the decimal represents the fractional portion of a 24-hour day
In your example, you are converting a decimal to a textual representation of the hour and minute portions of the datetime value.
Working through your first formula, 0.22 divided by 14 (why are you doing this?) equals 0.015714286. If you then apply this fraction against a 24-hour day (multiply by 1440 minutes), it equals 22 minutes and some change (i.e. "0:22").
Working through your second formula, 2.8 divided by 14 equals 0.2. Multiplied by 1440, it equals 288 minutes, which is 4 hours and 48 minutes (i.e. "4:48").
|
Or the Abacus Formula Compiler for Java, which allows you to compile the formulas in Excel sheets right down to Java byte code for fast and easy calling from your Java apps (can compile at run-time without the JDK).
<http://www.formulacompiler.org/>
|
Expressing Excel formula in Java (decimal to time interpretation)
|
[
"",
"java",
"excel",
"datetime",
"decimal",
""
] |
I'm writing an app which for various reasons involves Internet Explorer (IE7, for the record), ActiveX controls, and a heroic amount of JavaScript, which is spread across multiple .js includes.
One of our remote testers is experiencing an error message and IE's error message says something to the effect of:
```
Line: 719
Char: 5
Error: Unspecified Error
Code: 0
URL: (the URL of the machine)
```
There's only one JavaScript file which has over 719 lines and line 719 is a blank line (in this case).
None of the HTML or other files involved in the project have 719 or more lines, but the resulting HTML (it's sort of a server-side-include thing), at least as IE shows from "View Source" does have 719 or more lines - but line 719 (in this case) is a closing table row tag (no JavaScript, in other words).
The results of "View Generated Source" is only 310 lines in this case.
I would imagine that it could possibly be that the entire page, with the contents of the JavaScript files represented inline with the rest of the HTML could be where the error is referring to but I don't know any good way to view what that would be,
So, given a JavaScript error from Internet Explorer **where the line number is the only hint** but the page is actually spread across multiple files?
**UPDATE:** The issue is exacerbated by the fact that the user experiencing this is remote and for various network reasons, debugging it using something like Visual Studio 2008 (which has awesome JavaScript debugging, by the way) is impossible. I'm limited to having one of us look at the source to try and figure out what line of code it's crapping out on.
**UPDATE 2:** The real answer (as accepted below) seems to be "no, not really". For what it's worth though, Robert J. Walker's bit about it being off by one did get me pointed in the right direction as I think it was the offending line. But since that's not really what I'd call good or reliable (IE's fault, not Robert J. Walker's fault) I'm going to accept the "no, not really" answer. I'm not sure if this is proper SO etiquette. Please let me know if it's not via the comments.
|
In short. Not really. Try finding the error in FF first, and if that fails, you can get an almost as good debugger with [Visual Web Developer](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/). Debugging IE just sucks for the most part.
|
The best way I found to debug javascript was to add several Response.Write() or alert message near the place i believed the code broke. The write or alert that doesn't show is closest to the problematic area of the code.
I did it this way because I haven't found an easier way.
Update: If you use this method of debugging you can use the writes/alerts to the contents of variables as well.
|
Is there any good or reliable way to figure out where a JavaScript error is using only an Internet Explorer error message?
|
[
"",
"javascript",
"debugging",
"internet-explorer",
""
] |
Simply put, is there a way to create a 2D javascript array using similar syntax to this?
```
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
```
|
You can create any n-dimensional arrays using *exactly* the format you suggest as in the following sample:
```
<script>
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
var newArray3d =
[[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],
[[10, 11, 12],[13, 14, 15],[16, 17, 18]],
[[20, 21, 22],[23, 24, 25],[26, 27, 28]]]
alert(newArray[0]);
alert(newArray[0][2]);
alert(newArray3d[0]);
alert(newArray3d[1][0]);
alert(newArray3d[1][0][2]);
</script>
```
The alert boxes return, in sequence:
```
0,1,2
2
0,1,2,3,4,5,6,7,8
10,11,12
12
```
|
Yes. This works fine:
```
<script>
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
alert(newArray[0][2]);
</script>
```
|
2D Javascript array
|
[
"",
"javascript",
"arrays",
"multidimensional-array",
""
] |
How can dynamic Key-value pairs of objects be stored in app.config in using the application settings api, at runtime?
I've been trying to get my head around, and I can't find any meaningful example or documentation.
I seems that .Net dictionary classes can't be serialized in XML to store them in app.config
Is the only way to do it by using custom XML serialized classes, or are there any other ways?
|
After some more searching net, I've found a very good (albeit very long) article which describes in dept the .Net configuration model:
[Unraveling the Mysteries of .NET 2.0 Configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx)
I also found something very usefull:
[Configuration Section Designer](http://www.codeplex.com/csd)
A visual studio adding for visually designing config sections and generating the coresponging XSD files. I hope someone finds this useful.
|
You ought to be able to do something like this:
```
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting with a name Key and a Value stored in variable called Value
config.AppSettings.Settings.Add("Key", Value );
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
```
|
How to store key-value pairs in application settings at runtime?
|
[
"",
"c#",
".net",
"settings",
"app-config",
""
] |
How does one do this?
If I want to analyze how something is getting compiled, how would I get the emitted assembly code?
|
Use the [-S](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S) option to `gcc` (or `g++`), optionally with [-fverbose-asm](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm) which works well at the default [-O0](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0) to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at.
```
gcc -S helloworld.c
```
This will run the preprocessor (cpp) over *helloworld.c*, perform the initial compilation and then stop before the assembler is run. For useful compiler options to use in that case, see *[How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output)* (or just **look at your code on [Matt Godbolt's online Compiler Explorer](https://godbolt.org/)** which filters out directives and stuff, and has highlighting to match up source lines with asm using debug information.)
By default, this will output the file `helloworld.s`. The output file can be still be set by using the [-o](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-o) option, including `-o -` to write to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) for pipe into [less](https://en.wikipedia.org/wiki/Less_(Unix)).
```
gcc -S -o my_asm_output.s helloworld.c
```
Of course, this only works if you have the original source.
An alternative if you only have the resultant object file is to use [objdump](https://linux.die.net/man/1/objdump), by setting the `--disassemble` option (or `-d` for the abbreviated form).
```
objdump -S --disassemble helloworld > helloworld.dump
```
`-S` interleaves source lines with normal disassembly output, so this option works best if debugging option is enabled for the object file ([-g](https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g) at compilation time) and the file hasn't been stripped.
Running `file helloworld` will give you some indication as to the level of detail that you will get by using *objdump*.
Other useful `objdump` options include `-rwC` (to show symbol relocations, disable line-wrapping of long machine code, and demangle C++ names). And if you don't like AT&T syntax for x86, `-Mintel`. See [the man page](https://man7.org/linux/man-pages/man1/objdump.1.html).
So for example, `objdump -drwC -Mintel -S foo.o | less`.
`-r` is very important with a `.o` that only has `00 00 00 00` placeholders for symbol references, as opposed to a linked executable.
|
This will generate assembly code with the C code + line numbers interwoven, to more easily see which lines generate what code ([-S](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S) [-fverbose-asm](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm) [-g](https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g) [-O2](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O2)):
```
# Create assembler code:
g++ -S -fverbose-asm -g -O2 test.cc -o test.s
# Create asm interlaced with source lines:
as -alhnd test.s > test.lst
```
It was found in [Algorithms for programmers](http://www.jjj.de/fxt/fxtbook.pdf), page 3 (which is the overall 15th page of the PDF).
|
How do you get assembler output from C/C++ source in GCC?
|
[
"",
"c++",
"c",
"assembly",
"gcc",
"disassembly",
""
] |
I have a problem which requires me to parse several log files from a remote machine.
There are a few complications:
1) The file may be in use
2) The files can be quite large (100mb+)
3) Each entry may be multi-line
To solve the in-use issue, I need to copy it first. I'm currently copying it directly from the remote machine to the local machine, and parsing it there. That leads to issue 2. Since the files are quite large copying it locally can take quite a while.
To enhance parsing time, I'd like to make the parser multi-threaded, but that makes dealing with multi-lined entries a bit trickier.
The two main issues are:
1) How do i speed up the file transfer (Compression?, Is transferring locally even neccessary?, Can I read an in use file some other way?)
2) How do i deal with multi-line entries when splitting up the lines among threads?
UPDATE: The reason I didnt do the obvious parse on the server reason is that I want to have as little cpu impact as possible. I don't want to affect the performance of the system im testing.
|
If you are reading a sequential file you want to read it in line by line over the network. You need a transfer method capable of streaming. You'll need to review your IO streaming technology to figure this out.
Large IO operations like this won't benefit much by multithreading since you can probably process the items as fast as you can read them over the network.
Your other great option is to put the log parser on the server, and download the results.
|
The better option, from the perspective of performance, is going to be to perform your parsing at the remote server. Apart from exceptional circumstances the speed of your network is always going to be the bottleneck, so limiting the amount of data that you send over your network is going to greatly improve performance.
This is one of the reasons that so many databases use stored procedures that are run at the server end.
Improvements in parsing speed (if any) through the use of multithreading are going to be swamped by the comparative speed of your network transfer.
If you're committed to transferring your files before parsing them, an option that you could consider is the use of on-the-fly compression while doing your file transfer.
There are, for example, sftp servers available that will perform compression on the fly.
At the local end you could use something like [libcurl](http://curl.haxx.se/libcurl/) to do the client side of the transfer, which also supports on-the-fly decompression.
|
What's the best way to read and parse a large text file over the network?
|
[
"",
"c#",
".net",
"multithreading",
"parsing",
"networking",
""
] |
I'm developing non-interactive cpu-bound application which does only computations, almost no IO. Currently it works too long and while I'm working on improving the algorithm, I also think if it can give any benefit to change language or platform. Currently it is C++ (no OOP so it is almost C) on windows compiled with Intel C++ compiler. Can switching to ASM help and how much? Can switching to Linux and GCC help?
|
Just to be thorough: the first thing to do is to gather profile data and the second thing to do is consider your algorithms. I'm sure you know that, but they've got to be #included into any performance-programming discussion.
To be direct about your question "Can switching to ASM help?" the answer is "If you don't know the answer to that, then probably not." Unless you're very familiar with the CPU architecture and its ins and outs, it's unlikely that you'll do a significantly better job than a good optimizing C/C++ compiler on your code.
The next point to make is that significant speed-ups in your code (aside from algorithmic improvements) will almost certainly come from parallelism, not linear increases. Desktop machines can now throw 4 or 8 cores at a task, which has much more performance potential than a slightly better code generator. Since you're comfortable with C/C++, OpenMP is pretty much a no-brainer; it's very easy to use to parallelize your loops (obviously, you have to watch loop-carried dependencies, but it's definitely "the simplest parallelism that could possibly work").
Having said all that, code generation quality does vary between C/C++ compilers. The Intel C++ compiler is well-regarded for its optimization quality and has full support not just for OpenMP but for other technologies such as the Threading Building Blocks.
Moving into the question of what programming languages might be even better than C++, the answer would be "programming languages that actively promote / facilitate concepts of parallelism and concurrent programming." Erlang is the belle of the ball in that regard, and is a "hot" language right now and most people interested in performance programming are paying at least some attention to it, so if you want to improve your skills in that area, you might want to check it out.
|
It's always algorithm, rarely language. Here's my clue: "while I'm working on improving the algorithm".
Tweaking may not be enough.
Consider radical changes to the algorithm. You've got to eliminate processing, not make the processing go faster. The culprit is often "search" -- looping through data looking for something. Find ways to eliminate search. If you can't eliminate it, replace linear search with some kind of tree search or a hash map of some kind.
|
What language/platform would you recommend for CPU-bound application?
|
[
"",
"c++",
"performance",
"algorithm",
""
] |
I was asked to build a java system that will have the ability to load new code (expansions) while running.
How do I re-load a jar file while my code is running? or how do I load a new jar?
Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does not complicate things too much).
What are the things I should look out for?
(think of it as two different questions - one regarding reloading classes at runtime, the other regarding adding new classes).
|
Reloading existing classes with existing data is likely to break things.
You can load new code into new class loaders relatively easily:
```
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();
```
Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, `java.beans`, etc).
If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.
Of course debugging systems can do fancier things, but are more hacky and less reliable.
It is possible to add new classes into a class loader. For instance, using `URLClassLoader.addURL`. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.
|
This works for me:
```
File file = new File("c:\\myjar.jar");
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");
```
|
How to load a jar file at runtime
|
[
"",
"java",
"jar",
"runtime",
"classloader",
""
] |
Suppose you have a collection of `Foo` classes:
```
class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
```
And you want to check this collection to see if another entry has a matching `Bar`.
```
bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
isDuplicate = true;
break;
}
}
```
`Contains()` doesn't work because it compares the classes as whole.
Does anyone have a better way to do this that works for .NET 2.0?
|
```
fooList.Exists(item => item.Bar == SomeBar)
```
That's not LINQ, but a Lambda expression, but nevertheless, it uses a v3.5 feature. No problem:
```
fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
```
That should work in 2.0.
|
Implement the [IEqualityComparer<T>](http://msdn.microsoft.com/en-us/library/ms132151.aspx) interface, and use the matching [Contains](http://msdn.microsoft.com/en-us/library/bb339118.aspx) method.
```
public class MyFooComparer: IEqualityComparer<Foo> {
public bool Equals(Foo foo1, Foo foo2) {
return Equals(foo1.Bar, foo2.Bar);
}
public int GetHashCode(Foo foo) {
return foo.Bar.GetHashCode();
}
}
Foo exampleFoo = new Foo();
exampleFoo.Bar = "someBar";
if(myList.Contains(exampleFoo, new MyFooComparer())) {
...
}
```
|
Checking for duplicates in a collection
|
[
"",
"c#",
".net",
".net-2.0",
""
] |
**Summary:** C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...
**The problem**
Today, on a training session on C#, the teacher showed us some code which contained a bug only when run on multiprocessors.
I'll summarize to say that sometimes, the compiler or the JIT screws up by calling the finalizer of a C# class object before returning from its called method.
The full code, given in Visual C++ 2005 documentation, will be posted as an "answer" to avoid making a very very large questions, but the essential are below:
The following class has a "Hash" property which will return a cloned copy of an internal array. At is construction, the first item of the array has a value of 2. In the destructor, its value is set to zero.
The point is: If you try to get the "Hash" property of "Example", you'll get a clean copy of the array, whose first item is still 2, as the object is being used (and as such, not being garbage collected/finalized):
```
public class Example
{
private int nValue;
public int N { get { return nValue; } }
// The Hash property is slower because it clones an array. When
// KeepAlive is not used, the finalizer sometimes runs before
// the Hash property value is read.
private byte[] hashValue;
public byte[] Hash { get { return (byte[])hashValue.Clone(); } }
public Example()
{
nValue = 2;
hashValue = new byte[20];
hashValue[0] = 2;
}
~Example()
{
nValue = 0;
if (hashValue != null)
{
Array.Clear(hashValue, 0, hashValue.Length);
}
}
}
```
But nothing is so simple...
The code using this class is wokring inside a thread, and of course, for the test, the app is heavily multithreaded:
```
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
t.Join();
}
private static void ThreadProc()
{
// running is a boolean which is always true until
// the user press ENTER
while (running) DoWork();
}
```
The DoWork static method is the code where the problem happens:
```
private static void DoWork()
{
Example ex = new Example();
byte[] res = ex.Hash; // [1]
// If the finalizer runs before the call to the Hash
// property completes, the hashValue array might be
// cleared before the property value is read. The
// following test detects that.
if (res[0] != 2)
{
// Oops... The finalizer of ex was launched before
// the Hash method/property completed
}
}
```
Once every 1,000,000 excutions of DoWork, apparently, the Garbage Collector does its magic, and tries to reclaim "ex", as it is not anymore referenced in the remaning code of the function, and this time, it is faster than the "Hash" get method. So what we have in the end is a clone of a zero-ed byte array, instead of having the right one (with the 1st item at 2).
My guess is that there is inlining of the code, which essentially replaces the line marked [1] in the DoWork function by something like:
```
// Supposed inlined processing
byte[] res2 = ex.Hash2;
// note that after this line, "ex" could be garbage collected,
// but not res2
byte[] res = (byte[])res2.Clone();
```
If we supposed Hash2 is a simple accessor coded like:
```
// Hash2 code:
public byte[] Hash2 { get { return (byte[])hashValue; } }
```
So, the question is: **Is this supposed to work that way in C#/.NET, or could this be considered as a bug of either the compiler of the JIT?**
# edit
See Chris Brumme's and Chris Lyons' blogs for an explanation.
<http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx>
<http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx>
Everyone's answer was interesting, but I couldn't choose one better than the other. So I gave you all a +1...
Sorry
:-)
# Edit 2
I was unable to reproduce the problem on Linux/Ubuntu/Mono, despite using the same code on the same conditions (multiple same executable running simultaneously, release mode, etc.)
|
It's simply a bug in your code: finalizers should not be accessing managed objects.
The only reason to implement a finalizer is to release unmanaged resources. And in this case, you should carefully implement [the standard IDisposable pattern](http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx).
With this pattern, you implement a protected method "protected Dispose(bool disposing)". When this method is called from the finalizer, it cleans up unmanaged resources, but does not attempt to clean up managed resources.
In your example, you don't have any unmanaged resources, so should not be implementing a finalizer.
|
What you're seeing is perfectly natural.
You don't keep a reference to the object that owns the byte array, so that object (not the byte array) is actually free for the garbage collector to collect.
The garbage collector really can be that aggressive.
So if you call a method on your object, which returns a reference to an internal data structure, and the finalizer for your object mess up that data structure, you need to keep a live reference to the object as well.
The garbage collector sees that the ex variable isn't used in that method any more, so it can, and as you notice, will garbage collect it under the right circumstances (ie. timing and need).
The correct way to do this is to call GC.KeepAlive on ex, so add this line of code to the bottom of your method, and all should be well:
```
GC.KeepAlive(ex);
```
I learned about this aggressive behavior by reading the book [Applied .NET Framework Programming](http://www.microsoft.com/mspress/books/5353.aspx) by Jeffrey Richter.
|
Finalizer launched while its object was still being used
|
[
"",
"c#",
".net",
"garbage-collection",
"finalization",
""
] |
I want to log to the console when I'm using un-minimized JavaScript files.
Comments are taken out already when I minimize JavaScript. I'm wondering if there's a way I can write a command that isn't commented out but will still be taken out when I minimize the JavaScript file.
|
If your goal is just to reduce the js size you can separate you logging functions into a separate file.
In your "main" js add a function `function doLogging(object){}` then in your separate logging functions file replace the function with `function doLogging(object){/*your logging code*/};`
Just remember to include your main js before the logging js. When you minify just comment out the logging script tags from the html. This way you will only have one (or a couple of) empty function definitions in the minified js and one line of code calling those functions per loggingn action.
|
I think I'd be pretty upset if a Javascript minimizer changed the behaviour of my code based on some funny/clever/odd code construct. How could you ever be sure that code construct isn't there intentionally?
As has been suggested, have a variable that disables logging. Then as part of your minimize script or batch job, you can swap that variable to its non-logging state using sed (for example) before minimizing.
|
Javascript Commands Only Executed When Unminimized
|
[
"",
"javascript",
"minimize",
""
] |
I have a legacy application that is written in C# and it displays a very complex treeview with 10 to 20 thousand elements.
In the past I encountered a similar problem (but in C++) that i solved with the OWNERDATA capability offered by the Win32 API.
Is there a similar mechanism in C#?
EDIT: The plan is to optimize the creation time as well as browsing time. The method available through Win32 API is excellent in both of these cases as it reduce initialization time to nothing and the number of requests for elements are limited to only the ones visible at any one time.
Joshl: We are actually doing exactly what you suggest already, but we still need more efficiency.
|
I don't believe the .NET TreeView supports what you want, although this type of model is supported by .NET's DataGridView (see DataGridView's [VirtualMode](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode.aspx) property). The TreeView will let you draw your own nodes but it won't let you populate them from some virtual store.
If possible, you might want to consider the use of a DataGridView for your application. If not, managing the nodes manually (like joshl mentions above) might work if you can get around some issues with refreshing the screen properly when nodes are expanded. Outside of that, you might want to check out some of the third party vendors, like [this one (Divelements SandGrid)](http://www.divelements.co.uk/net/controls/sandgrid/), that might (emphasis on might) support your desired mode of operation.
NOTE: The SandGrid is not supported by Divelements as of the end of July 2013.
|
One technique for improving performance is to load TreeNodes as the user expands the treeview. Normally a user will not require 20,000 nodes to be open on their screen at once. Only load the level that the user needs to see, along with whatever child information you need to properly display affordances to the user (expand icon if children exist, counts, icons, etc). As the user expands nodes, load children just in time.
Helpful hint from Keith: With the winforms TreeView you need to have at least one child node or it won't show the expand [+], but then you handle the TreeNodeExpanded event to remove that dummy node and populate the children.
|
Slow treeview in C#
|
[
"",
"c#",
"winforms",
"user-interface",
"optimization",
""
] |
How can I validate that my ASPNET AJAX installation is correct.
I have Visual Studio 2008 and had never previously installed any AJAX version.
My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior.
I tried installing AJAX from [MSDN](http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en) followed by an IISRESET yet still it is still not working properly.
What can I check to diagnose the problem?
**Update:** When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler:
```
http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&t=633564733834698722
http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&t=ffffffff867086f6
http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&t=ffffffff867086f6
```
but when I run within IIS i only get this single request :
```
http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&t=ffffffff867086f6
```
Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests.
|
Check for any JavaScript errors. Sometimes the JavaScript required for the UpdatePanel to work fails to load.
|
Another option would be to check your web.config. You could for example create an new Ajax enabled ASP.NET website from Visual Studio. This will generate a correct web.config. Copy over all non-ajax sections from your existing web.config and you're set. This worked for me.
-Edoode
|
How to validate ASPNET AJAX installation
|
[
"",
"c#",
"asp.net",
"ajax",
""
] |
I am trying to write a web service to spec and it requires a different response body depending on whether the method completes successfully or not. I have tried creating two different DataContract classes, but how can I return them and have them serialized correctly?
|
The answer is **yes** but it is tricky and you lose strong typing on your interface. If you return a **Stream** then the data could be xml, text, or even a binary image. For DataContract classes, you'd then serialize the data using the **DataContractSerializer**.
See the [BlogSvc](http://codeplex.com/blogsvc) and more specifically the [**RestAtomPubService.cs** WCF service](http://blogsvc.codeplex.com/SourceControl/changeset/22604#Main/Source/Services/AtomPub/RestAtomPubService.cs) for more details. Note, that source code will also show you how to accept different types of data into a WCF rest method which requires a content type mapper.
|
The best way to indicate that your WCF web service has failed would be to throw a FaultException. There are settings in your service web.config files that allow the entire fault message to be passed to the client as part of the error.
Another approach may be to inherit both of your results from the same base class or interface. The service would return an instance of the base type. You can then use the KnownType attribute to inform the client that multiple types may be returned. Come to think of it, it might be possible to use Object as the base type, but I haven't tried it.
Failing either of those approaches, you can create a custom result object that contains both a result and error properties and your client can then decide which course of action to take. I had to use this approach for Silverlight 2 because Beta 2 does not yet fully support fault contracts. It's not pretty, I wouldn't normally recommend it, but if it's the only way that works or you feel it is the best approach for your situation...
If you are having troubles with ADO.NET Data Services, I have less experience there.
[Here's some information](http://bloggingabout.net/blogs/jpsmit/archive/2007/03/21/wcf-fault-contracts.aspx) on implementing FaultContracts
|
Is there a way to return different types from a WCF REST method?
|
[
"",
"c#",
".net",
"wcf",
"rest",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.