Re: override toString

2009-12-03 Thread Qian Xu
Max Samukha wrote:

> 
> this.classinfo can be seen as a virtual function returning the
> classinfo for the actual class instance and typeof(this).classinfo -
> as a static function returning the classinfo of the compile-time type
> of this (that is the class where it is called). So, your example
> should be rewritten (D2):
> 

Thanks. You made my day



Re: override toString

2009-12-03 Thread Qian Xu
Michal Minich wrote:
> 
> btw. I noticed that you are using "+" for string concatenation, how is
> possible that your program even comiples??? "~" should be used for string
> concatenation.

sorry, it was my type error. the code is not real ^^)



override toString

2009-12-03 Thread Qian Xu
Hi All,

I want to print some object information for debugging. But the name of class 
is incorrect. I do not know why.


module test;

class A {
  char[] data;
  public char[] toString() {
return "<" + this.classinfo.name + ": " + data + ">";
  }
}

class B: A {
  char[] data2;
  public override char[] toString() {
return "<" + this.classinfo.name + ": " + super.toString + ", " + data2 
+ ">";
  }
}

auto b = new B;
b.data = "hello";
b.data2 = "world";
Cout(b.toString); // , world>


The expected result should be:
, world>

But the actual result is:
, world>







Re: Potential memory leak?

2009-11-30 Thread Qian Xu
Eldar Insafutdinov wrote:
> 
> You only have to use scope for top-level QObject subclasses. For anything
> else you should use auto. Nevertheless, it would be useful if you submit a
> bug report.

Even when my application is multi-thread? I am not sure, if I can declare  
QPixmap also as "auto"



Potential memory leak?

2009-11-27 Thread Qian Xu
Hi All,

I am using QtD to do some gui stuff. As the QtD documentation described, Qt-
data types should be declared with keyword "scope", so that all variables 
can be deallocated in a right order.

I found a memory leak problem accidentally, when I executed the following 
code very frequently:

// public QRegion united(QRegion region) {...}
 
  scope regionA = new QRegion;
  scope regionB = regionA.united(anotherRegion); // Good Example
  scope regionA = regionA.united(anotherRegion); // Bad Example

I create a variable regionA and unite it with another region. The result of 
the function united is assigned to variable regionB. Everything is fine.

The third line sounds be correct as well. A new instance will be created and 
then the variable regionA will be assigned to this new instance, the old 
instance will be deallocated as soon as the code exits its scope. 

However the old instance, where the variable regionA previously was pointed 
to, still exists. 

I cannot reproceduce this problem with simple D data types.
But do you think this is a bug of dmd 1.051?

Qian Xu




Re: Linking problem with QtD

2009-10-30 Thread Qian Xu
Eldar Insafutdinov wrote:
> 
> All Qt versions keep forward binary compatibility and a full compatibility
> within a major version, 4.5.3 contains only bug fixes compared to 4.5.2.
> Version from code.google.com is a way to old, so I would not even
> consider it. Have you tried to turn on BUILD_EXAMPLES option in cmake? It
> will build all examples bundled with qtd.

The problem has been solve.

The linker "ld" searches first in "/usr/lib" (Qt 4.4.3) and then
my "/my-qt-sdk/lib", even when the path "/usr/lib" is not specified. 

I checked the man page of "ld". There is an argument "-rpath-link". If it is
not specified, the "/usr/lib" will be assumed.

So my problem is solve. Thanks for you all. Have a nice day.


Re: Linking problem with QtD

2009-10-30 Thread Qian Xu
Eldar Insafutdinov wrote:
> 
> I saw you made the reference to this link
> (http://www.dsource.org/projects/qtd/wiki/MacCaseStudy which contains this
> command line option, but still I don't understand why you get undefined
> symbols like QPrintDialog::options() const which belongs to libQtGui.

Because the demo project uses QApplication and QMainWindow, which belong to
libQtGui.


Re: Linking problem with QtD

2009-10-29 Thread Qian Xu
albatroz Wrote:

> Eldar Insafutdinov wrote:
> 
> > Qian Xu Wrote:
> > 
> >> Hi All,
> >> 
> >> I have almost built the first demo, but ...
> >> The components I have are as follows:
> >> 1. QtK SDK (LGPL edition) 4.5.3
> >> 2. the latest svn version of QtD (trunk-r309.zip)
> >> 3. DMD 1.050
> >> 4. Tango (current from trunk)
> >> 5. Platform: openSUSE 11.1.
> >> 6. cmake 2.6
> >> 
> >> After QtD was built successfully, I try to compile the demo
> >> (http://www.dsource.org/projects/qtd/wiki/MacCaseStudy)
> >> 
> >> I got many linking errors:
> >> 
> [code]../../../../build_dir/build/lib/libqtdgui.a(QPrintDialog_shell.cpp.o):
> >> In function `qtd_QPrintDialog_setOption_PrintDialogOption_bool':
> >> QPrintDialog_shell.cpp:(.text+0x20b): undefined reference to
> >> `QPrintDialog::setOption(QAbstractPrintDialog::PrintDialogOption, bool)'
> >> ../../../../build_dir/build/lib/libqtdgui.a(QPrintDialog_shell.cpp.o): In
> >> function `qtd_QPrintDialog_options':
> >> QPrintDialog_shell.cpp:(.text+0x22b): undefined reference to
> >> `QPrintDialog::options() const'[/code]
> >> 
> >> There are many undefined references. I checked the source and the '.a'
> >> files. These functions are defined correctly.
> >> 
> >> Have I still forget something by linking the demo or building the
> >> library?
> >> 
> >> Any hint is welcome
> > 
> > Hi!
> > 
> > Undefined symbols that are missing are from Qt libs. I'd recommend to do
> > 'make install' after you build QtD (don't forget to specify
> > CMAKE_INSTALL_PREFIX option in cmake prior to build to point to the
> > directory where you have your dmd toolchain) and then look into the build
> > scripts of the examples which typically have a name build.sh. They contain
> > the command line with all necessary libraries to link, typically:
> > 
> > -L-lqtdgui -L-lqtdcore -L-lQtCore -L-lQtGui
> > 
> > I saw you made the reference to this link
> > (http://www.dsource.org/projects/qtd/wiki/MacCaseStudy which contains this
> > command line option, but still I don't understand why you get undefined
> > symbols like QPrintDialog::options() const which belongs to libQtGui.
> 
> Hello,
> 
> I decided not to install it globally, first export to ldd the path to your 
> QT lib folder
> 
> export LIBRARY_PATH=/usr/lib64/qt4/
> 
> and build the examples using the complete path of libQtGui
> 
> -L/usr/lib64/qt4/libQtGui.so -L-lqtdgui -L-lqtdcore -L-lQtCore -L-lQtGui 
> 
> This allows me to have several folders with different versions.

I am considering two possible reasons:
1. I linked to a wrong Qt-library
2. The QtD is not compatible with Qt 4.5.3 (I Saw the build package uses Qt 
4.5.2, maybe those undefined references comes from Qt 4.5.3)

I have also downloaded a pre-compiled QtD library from code.google.com, it 
works. I can compile Hello world programs. However, this version does not 
contain all classes as the library I was trying to build. If later I find that 
some important classes are missing, it will be a big problem for choosing QtD.


Linking problem with QtD

2009-10-29 Thread Qian Xu
Hi All,

I have almost built the first demo, but ...
The components I have are as follows:
1. QtK SDK (LGPL edition) 4.5.3
2. the latest svn version of QtD (trunk-r309.zip)
3. DMD 1.050
4. Tango (current from trunk)
5. Platform: openSUSE 11.1. 
6. cmake 2.6

After QtD was built successfully, I try to compile the demo
(http://www.dsource.org/projects/qtd/wiki/MacCaseStudy)

I got many linking errors:
[code]../../../../build_dir/build/lib/libqtdgui.a(QPrintDialog_shell.cpp.o):
In function `qtd_QPrintDialog_setOption_PrintDialogOption_bool':
QPrintDialog_shell.cpp:(.text+0x20b): undefined reference to
`QPrintDialog::setOption(QAbstractPrintDialog::PrintDialogOption, bool)'
../../../../build_dir/build/lib/libqtdgui.a(QPrintDialog_shell.cpp.o): In
function `qtd_QPrintDialog_options':
QPrintDialog_shell.cpp:(.text+0x22b): undefined reference to
`QPrintDialog::options() const'[/code]

There are many undefined references. I checked the source and the '.a'
files. These functions are defined correctly.

Have I still forget something by linking the demo or building the library?

Any hint is welcome


Re: convert ... to array

2009-10-20 Thread Qian Xu
Chris Nicholson-Sauls wrote:

> Qian Xu wrote:
>> Hi All,
>> 
>> a function is declared as follows:
>> 
>>   class Foo
>>   {
>> final Value array(...)
>> {
>>   ...
>> }
>>   }
>> 
>> 
>> I can pass any number of parameters to this method array() like:
>> 
>>   auto foo = new Foo;
>>   foo.array(1, 2, 3);
>> 
>> 
>> But if I have only an array in hand, how to pass it to this method? Is it
>> possible?
>> 
>>   int[] myarray = [1, 2, 3];
>>   // how to pass "myarray" to foo.array(...)
>> 
>> 
>> Best regards
> 
> If you only intend Foo.array() to accept params of a particular type, just
> an arbitrary number of them, there's a syntax that marries variadic
> arguments and arrays together:
> 
> class Foo {
>  final Value array (int[] args ...) {
>  ...
>  }
> }
> 
> This will allow any number of int's to be passed, which are quietly
> packaged as an int[],
> and also transparently accepts int[] as-is.  Obviously, though, it isn't
> any help if you need to accept various types, and I'm not sure how well
> std.variant plays with this.
> 
> -- Chris Nicholson-Sauls

I have forgotten to say, that the class Foo comes from an external d-library
(tango), which means that I am not able to change the function interface.

I can only use the method foo.array(...)




convert ... to array

2009-10-20 Thread Qian Xu
Hi All,

a function is declared as follows:

  class Foo
  {
final Value array(...)
{
  ...
}
  }


I can pass any number of parameters to this method array() like:

  auto foo = new Foo;
  foo.array(1, 2, 3);


But if I have only an array in hand, how to pass it to this method? Is it
possible?

  int[] myarray = [1, 2, 3];
  // how to pass "myarray" to foo.array(...)


Best regards


Re: dmd does not show warnings by casting int to uint

2009-07-22 Thread Qian Xu
Stewart Gordon wrote:

> Qian Xu wrote:
>> Hi All,
>> 
>> I found out that dmd does not show warnings by casting int to uint.
> 
> 
> Known bug.
> 
> http://d.puremagic.com/issues/show_bug.cgi?id=259
> 
> Stewart.

thanks, good to know that. i thought i have not configured dmd correctly ^^)


dmd does not show warnings by casting int to uint

2009-07-21 Thread Qian Xu
Hi All,

I found out that dmd does not show warnings by casting int to uint.

demo code looks as follows:
---
module main;
void main()
{
  uint positive = 10;
  int  negative = -1;
  assert(negative < positive); // did not pass
}
---

The problem is that the integer "negative" is casted as uint (MAX_UINT)
However, I just wondered, why dmd does not show warnings?


Best regards
Qian


Re: "".dup is null

2009-05-04 Thread Qian Xu
Steven Schveighoffer wrote:

> On Mon, 04 May 2009 09:46:57 -0400, Qian Xu 
> wrote:
> 
>> Hi All,
>>
>> The following code will throw an exception:
>>   char[] s;
>>   assert( s.dup  is null); // OK
>>   assert("".dup !is null); // FAILED
>>
>> "".dup is expectly also an empty string.
>> Is this a compiler bug?
>>
> 
> I think you might have a bug?
> 
> "".dup is the same as s.dup, not sure why you would expect it to be
> not-null.
> 
> -Steve

They are not the same. s is null. "" is an empty string. empty string and
null are definitely two thing.


Re: "".dup is null

2009-05-04 Thread Qian Xu
Steven Schveighoffer wrote:

> I think you might have a bug?
> 
> "".dup is the same as s.dup, not sure why you would expect it to be
> not-null.
> 
> -Steve

If I have not explained clearly. 
Here is the full code:

  char[] s;
  assert(s is null);
  assert(s.dup is null);

  assert("" !is null); // OK
  assert("".dup !is null); // FAILED

At least the last two lines behave not consistent. 
Either both are failed, or both are passed. 



"".dup is null

2009-05-04 Thread Qian Xu
Hi All,

The following code will throw an exception: 
  char[] s;
  assert( s.dup  is null); // OK
  assert("".dup !is null); // FAILED

"".dup is expectly also an empty string. 
Is this a compiler bug?

--Qian




Re: clone method of Object

2009-04-15 Thread Qian Xu
grauzone wrote:

> 
> class A {
> B b;
> }
> 
> class B {
> A a;
> }
> 
> auto a = new A();
> auto b = new B();
> a.b = b;
> b.a = a;
> 
> Your recursive approach wouldn't quite work with that. Before cloning an
> object, you'll first have to check if the object was already cloned. If
> this is the case, use the previously created clone instead of making a
> new clone.

You are right. This case must be considered separately.


Re: clone method of Object

2009-04-15 Thread Qian Xu
grauzone wrote:

> ...
> cloned = clone(yourobject);

Hi again.

There are two things on my side:
1. Compiler refuses to clone private attributes. I have tried
gdc/gdmd/dmd_v1 in Linux.

2. I have implemented an example. But some part not implemented.

- code ---
T clone(T)(T oldobj)
{
  auto newobj = new T();
  if (oldobj is null)
  {
return newobj;
  }

  foreach (int i, _; oldobj.tupleof)
  {
auto elem = oldobj.tupleof[i];
static if (is(typeof(elem): char[]*))
{/*
  if (elem !is null)
  {
char[] tmp;
tmp = (*elem).dup;
newobj.tupleof[i] = &tmp;
  }
  else {
newobj.tupleof[i] = null;
  }*/
  NotImplemented_PleaseHelpMe;
}
else static if (is(typeof(elem) T2 : T2*))
{
  if (elem !is null)
  {
newobj.tupleof[i] = new T2;
   *newobj.tupleof[i] = *elem;
  }
  else {
newobj.tupleof[i] = null;
  }
}
else static if (is(typeof(elem) == class))
{
  if (elem !is null)
  {
newobj.tupleof[i] = clone(elem);
  }
  else {
newobj.tupleof[i] = null;
  }
}
else {
  newobj.tupleof[i] = elem;
}
  }
  return newobj;
}
- code ---



Re: clone method of Object

2009-04-15 Thread Qian Xu
grauzone wrote:
> newobject.tupleof[i] = old.tupleof[i];

If the current value of tupleof[i] is an object, the object will be
referenced, won't it?

Shall I write:

  auto elem = old.tupleof[i];
  static if (is(typeof(elem) == class))
  {
 newobject.tupleof[i] = clone(elem);
  }
  else
  {
 newobject.tupleof[i] = elem;
  }




--Qian


clone method of Object

2009-04-15 Thread Qian Xu
Hi All,

is there any (easy) way to clone an object or any other classes?


--Qian


Re: cast a LinkSeq

2009-04-06 Thread Qian Xu

Adam Burton wrote:
I wouldn't think so, cos LinkSeq!(Apple) does not inherit LinkSeq!(Fruit), 
they are 2 separate types. However your apples automatically downcast (or 
up, depending which way you like to draw your diagrams :-) ) so unless you  
intend to pass the LinkSeq!(Apple) into a function expecting LinkSeq!(Fruit)  
it shouldn't be a problem. If you are passing about LinqSeq!(Fruit) and want  
your LinkSeq!(Apple) to fit you might need to write some adapters and make 
use of the models available to you or something along them lines.


That's my understanding anyway.






yes. I can cast all Apple-object to Fruit-objects one by one. I hope 
there is an one-line-solution :-)


--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


cast a LinkSeq

2009-04-06 Thread Qian Xu
Hi All,

can I cast a LinkSeq from inherited type to base type?

 code --
   class Fruit {}
   class Apple: Fruit {}

   auto apples = new LinkSeq!(Apple);
   apples.append(new Apple);
   assert(apples !is null);
   assert(apples.length == 1);
   
   auto fruits = cast(LinkSeq!(Fruit))(apples);
   assert(fruits !is null); // <--- failed
   assert(fruits.length == 1);   
 code --


--Qian


Re: minimal evaluation

2009-04-06 Thread Qian Xu
torhu wrote:

> 
> If you mean short-circuit evalutation, I'm pretty sure that's always
> what the compiler does.

Thanks. Somebody posted this link:
http://digitalmars.com/d/1.0/expression.html#OrOrExpression



Re: Format.convert problme

2009-04-06 Thread Qian Xu
grauzone wrote:

> mport tango.io.Stdout;
> 
> void main() {
> 
> int v = 55;
> int *pv = &v;
> 
> //pv (an int pointer) can be exchanged with v (an int),
> //and it still works
> auto i = pv;
> 
> alias typeof(i) T;
> static if (is(T T2 : T2*)) {
> T2 i2 = *i;
> Stdout.formatln("{}", i2);
> } else {
> Stdout.formatln("{}", i);
> }
> 
> }


Thanks. Now I understood your code. ^^)


Re: minimal evaluation

2009-04-06 Thread Qian Xu
> 
> if (isNull(foo) ||
> isNull(foo.getBar) ||
> isNull(foo.getBar.getBar2)
> {
>   return false;
> }

Update: If minimal evaluation is not always enabled, and foo.getBar is NULL.
I will get a segfault when evaluating foo.getBar.getBar2.



minimal evaluation

2009-04-06 Thread Qian Xu
Hi All,

Is minimal evaluation always enabled in D?

I want to write a function IsNull(), so that I can check the precondition as
follows:

  if (isNull(foo) ||
  isNull(foo.getBar) ||
  isNull(foo.getBar.getBar2)
  {
return false;
  }
  // normal code goes here

If an argument is null, the IsNull() will return false. Internally it will
be logged to console as well.

But I am not sure, if dmd-compiler generates code without minimal evaluation
in some cases. If minimal evaluation is not always enabled. I cannot do
precodition check in my way. 

--Qian


Re: Format.convert problme

2009-04-06 Thread Qian Xu
grauzone wrote:

> 
> Check if the variable is a pointer, and if yes, dereference it:
> 
> alias typeof(i) T;
> static if (is(T T2 : T2*)) {
> T2 i2 = *i;
> Format.convert("{}", i2);
> } else {
> Format.convert("{}", i);
> }

Hi again,

I cannot compile this code 


Format.convert problme

2009-04-04 Thread Qian Xu

Hi All,

tango.text.convert.Format provides a nice function to convert anything 
to string.


It works perfect except the argument is a pointer type.
It will print the address of a pointer instead of its value

For instance: 
int* i = new int;
*i = 10;
Format.convert("{}", i); // <- the address of the pointer
--

How to let it print the value instead of the address?
Because I wanna write a dump function to dump the value of any data type 
(also void, null)





--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


No segfault -> null == ""

2009-03-31 Thread Qian Xu
Hi All,

When I was trying to learn how char-array works, I found something
unexpected.

-- code --
module string_test;

void main()
{
  // test 1
  assert(null == "", "null is empty"); // No segfault

  // test 2
  char[] test; // test = null;
  assert(test is null, "undefined_string is null");
  assert(test == "", "undefined_string (null) is empty");
  assert(test.length == 0, "undefined_string.length == 0");

  // test 3
  test = "";
  assert(test !is null, "empty_string is NOT null");
  assert(test == "", "empty_string is empty");
  assert(test.length == 0, "empty_string.length == 0");

  // test 4
  test = "hello";
  assert(test !is null, "non_empty_string is NOT empty");
  assert(test != "", "non_empty_string is NOT empty");
  assert(test.length > 0, "non_empty_string.length > 0");
}
-- code --

I just wondered, why the first test does not lead to a segfault. Is this an
undocumented compiler feature? I have tested it with gdc and gdmd. Both no
segfault.


--Qian


dump object

2009-03-30 Thread Qian Xu
Hi All,

previously I saw an article about how to dump an object with all properties.

-code---
void log(T)(T obj) {
  static if (is(T == struct) || is(T == class)){
     writef("{");
 foreach(i,_;obj.tupleof) {
   writefln("%s : %s,", obj.tupleof[i].stringof[4..$], obj.tupleof[i]);
 }
 writefln("}");
  }
  else {
 writefln(obj);
  }
}
-code---


But this function does not work with private attributes of an object.

How to print all public properties of an object?
It would be very useful for debug propose.


Best regards
--Qian


any framework or tips for multi-tier applications

2009-03-28 Thread Qian Xu
Hi All,

We are redesigning a system (previously was written in C) using D.
We use Boundary-Controll-Entity-Pattern.
To wrap db table to entities is a very time consuming work.
Is there any framework or tips for multi-tier applications in D?

--Qian


Re: I hate ".dup"

2009-03-24 Thread Qian Xu

Steven Schveighoffer wrote:

TimeStamp.iso8601(..) does not call the parse() function.


The bug was in parseInt.  Please try it.



It worth a try.
I have added too many ".dup" in my code.
I will confirm this ASAP.


Thanks for your information ^^)


--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: I hate ".dup"

2009-03-24 Thread Qian Xu
Steven Schveighoffer wrote:
> 
> Coincidentally, someone else discovered a buffer-overrun bug in
> tango.text.convert.TimeStamp, see
> http://www.dsource.org/projects/tango/forums/topic/704
> 
> Please try downloading the latest trunk code and see if your code still
> fails.
> 
> You should not have to .dup the string, if you do, that is a bug.
> 
> -Steve

TimeStamp.iso8601(..) does not call the parse() function. 




I hate ".dup"

2009-03-23 Thread Qian Xu
I have spent one day to find out an error.

-
class MyTime
{
  this(char[] timestring)
  {
 Time t;
 int p = tango.time.TimeStamp.iso8601(timestring, t);
 //...
  }
  // other methods
}
unittest
{
  MyTime mt = new MyTime("01:10:20,050");
  assert(MyTime.addMillis(mt, 1).toString() == "01:10:20,051"); // sometimes
failed
}
-

I ran this unit-test together with some other tests. Sometimes no error,
sometimes with errors. 

Finally I have added timestring.dup in constructor, the problem does not
appear any more. 

Oh god. I have to add ".dup" at the end of every string to avoid potential
program errors. This is so incredible


Best regards
Qian Xu


Re: How to reduce compile times?

2009-03-22 Thread Qian Xu

grauzone wrote:

Brian wrote:

On Sat, 21 Mar 2009 15:44:41 +0100, grauzone wrote:


I'm using dsss (with dmd under Linux) to compile my project, and
build/compile times are reaching unacceptable highs.


out of curiosity, how much code do you actually have? im using D for 
something with ~12,000 lines of code right now, spread among 40 files 
or so, with a somewhat excessive use of CTFE and templates all over. a 
full rebuild takes about 5 seconds with incremental builds taking 1 or 
2 seconds in most cases.


i just wanted to know what "excessively high" means

P.S. using dmd 1.036, rebuild 0.78, phobos, linux


65906 physical lines of code (+ some Tango .di imports + some small 
external libraries), maybe 200+ files, takes 1m10s to build when using 
normal dsss. With -full and oneatatime=no, compile time goes down to 6-7 
seconds. It's not that template- and CTFE-heavy.


Incremental builds can take relatively long (depending where the changed 
files are in the dependency tree), and it's really annoying.


I think it is normal. try to copy all files to a ram disk and then 
compile them again.


--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: How to reduce compile times?

2009-03-22 Thread Qian Xu

grauzone wrote:
In my case, this practically always causes linker errors. Of course I 
don't know why.


You could change the order of object files by linking.

if you have   -> gdmd bbb.o aaa.o ccc.o -o binrary (-L. -l)
change to -> gdmd aaa.o bbb.o ccc.o -o binrary (-L. -l)
or change to  -> gdmd aaa.o bbb.o ccc.o aaa.o bbb.o ccc.o -o binrary 
(-L. -l)



--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: Universel toString

2009-03-20 Thread Qian Xu
The problem has been solved.

There is a wonderfull function in Tango.


import tango.text.convert.Format;

class Foo {
  // attributes go here...
  public char[] toString() {
return Format.convert(" {} .. {} ..", attr1, attr2, attr3);
  }
}


This works perfect with all data types.



Re: Universel toString

2009-03-20 Thread Qian Xu
Daniel Keep wrote:
> 
> to!(char[]) should call toString.  to!(T) should support all atomic
> types, strings, structs and classes.
> 

There is one problem: I have to check, whether a pointer is NULL. 
If it is NULL, I should return "NULL", otherwise I should call to!(char[]
(*my_pointer_var)

I want to save this check.



Universel toString

2009-03-20 Thread Qian Xu
Hi All,

I want to write an universel toString() method for debugging propose.
However I cannot write in one version. The compiler says error all the time.
Could someone tell me, how to write an universel one?

What I want, is to convert primtive types (int, int*, bool, bool*, etc.) to
string using "tango.text.Convert.to()" and convert object to string by
calling obj.toString.


--- my current version -
public char[] toS(int* val)
{
if (val is null)
return "NULL";
return to!(char[])(*val);
}

public char[] toS(Object val)
{
if (val is null)
return "NULL";
return val.toString;
}

public char[] toS(char[] val)
{
if (val is null)
return "NULL";
return val;
}

public char[] toS(int val)
{
return to!(char[])(val);
}

public char[] toS(bool val)
{
return to!(char[])(val);
}
--- my current version -----



Best regards
--Qian Xu


Re: Segfault (NullPointerException) in Linux

2009-03-18 Thread Qian Xu

Frank Benoit wrote:

Qian Xu schrieb:
--- code 2 (current solution) --

public test(MyObj obj)
{
  if (obj !is null &&
  obj.getObj2 !is null &&
  obj.getObj2.getObj3 !is null)
  {
 obj.getObj2.getObj3.test();
  }
}

--


If you want to be able to return something like "nothing", you can use
NullObject. That is, return an object that lets you navigate the
references and lets you test for it being a "null" object.

auto o = obj.getObj2.getObj3;
if( !o.isNull() ){
o.test();
}


Hi, I have tried your code

But gdc said, "Error: no property 'isNull' for type 
'NullPointerExceptionTest.MyObj'


Did I miss something?


--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Segfault (NullPointerException) in Linux

2009-03-18 Thread Qian Xu
Hi All,

again to the topic "Segfault (NullPointerException) in Linux"

Is it really impossible to catch NullPointerException (segfault) using
try-catch-statement in Linux?

I can use signal handler to catch it at system level. But my program will
stop. If it can be captured inside the program. My program will be more
robust. And I can write my code more flexible.


- code 1 (ideal) -

public test(MyObj obj)
{
  try
  {
 obj.getObj2.getObj3.test();
  }
  except(E)
  {
 // NullPointerException was caught!
  }
}

- code 2 (current solution) --

public test(MyObj obj)
{
  if (obj !is null &&
  obj.getObj2 !is null &&
  obj.getObj2.getObj3 !is null)
  {
 obj.getObj2.getObj3.test();
  }
}

--


Best regards
--Qian


Re: statement is not reachable

2009-03-05 Thread Qian Xu
Jarrett Billingsley wrote:

> On Thu, Mar 5, 2009 at 3:17 AM, Qian Xu 
> wrote:
> 
>> this(char[] s, int flag) {
>> if (flag == 1)
>> {
>> this(1);
>> return;
>> }
>> else if (flag == 2)
>> {
>> this("hello");
>> return;
>> }
>> throw new Exception("unhandled case");
>> this(0); // fake
> 
> This line is unreachable.  The 'throw' before it makes it impossible
> for it to ever execute.  Just take out this line.


Hi Jarrett, 

but I need an exception here. This is an unexpected case. I want no instance
to be create in this case.

--Qian


statement is not reachable

2009-03-05 Thread Qian Xu
Hi All,

I have got a warning by compiling ("gdc file -Wall") the following code
--
module unreachable;
class Foo {
  this(int i) {}
  this(char[] s) {}
  this(char[] s, int flag) {
if (flag == 1)
{
  this(1);
  return;
}
else if (flag == 2)
{
  this("hello");
  return;
}
throw new Exception("unhandled case");
this(0); // fake
  }
}
void main()
{
  Foo foo = new Foo("world", 1);
  assert(false, "END");
}
---

The warning is: "statement is not reachable"

If I use switch-case-statment, I can see even an error message:
"constructor calls not allowed in loops or after labels"



So, is my design incorrect, or is the compiler too strict?

--Qian Xu




Re: Link Problem

2009-03-04 Thread Qian Xu
Steven Schveighoffer wrote:

> It appears that the SaxParser module is not defined in the library.  I
> would guess that your tango lib is not compiled from the .d files you are
> using for imports, one of those two is out of date.
> 
> -Steve


Thanks. The build system links with another SaxParser


--Qian Xu


Re: Access Vialotation

2009-03-03 Thread Qian Xu

BCS wrote:

Hello downs,


BCS:


you can have a posix signal handler throw an exception (I have done
it and had it work) but I have no idea if it is supported.


In my experience, that works exactly once.



That would match with what I needed: poor man's stack tracing

int EveryFunction()
{
scope(failure) writef("%s:%s\n",__FILE__,__LINE__);

...

}





it does not work with gdc.

d2.0 does not have problem with NullPointerException at all.


--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Link Problem

2009-03-03 Thread Qian Xu

Hi All (again),


I got the following error message when my program is going to be linked:

 error ---
default/common/configuration/Configuration_1.o:(.data+0x98): undefined 
reference to `_D5tango4text3xml9SaxParser12_ModuleInfoZ'

 error ---

Configuration_1.o is the output file of my source.
I compiled my program on two Linux machines. It works on one machine, 
but not the other.


I suppose:
1. the tango libraries are different. (I will verify it tomorrow in my 
office)
2. the SaxParser contains some template implementation. how this part is 
compiled? can this be a reason of my problem?


BTW: What is ModuleInfoZ?? I have not found it in SaxParser.d at all.



--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: Char[] confusing

2009-03-02 Thread Qian Xu

Lutger wrote:

s[4] means the fifth element of s[]
s[0..4] is a slice from the first to the fifth, but not including the fifth 
element. The last element in a slice is always one past the end of that 
slice. 



Thank you both.
I have to do math in mind in order to keep my code correct ;-)


IMO, it does not make any sense.
s[start..end]

  end - is neither the count of characters in the array slice,
   nor the end index of the slice.
it is just the index after the real end character.

--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: Reference counting

2009-03-02 Thread Qian Xu

BCS wrote:

Hello Qian,


Hi All,

is it possible to see the reference counting of a char[]?



Almost certainly no. D Uses a mark-and-sweep GC not a ref counting one, 
so there isn't a reference count.





sorry to have heard about that.
I am now suffering from debugging D programs in linux (opensuse).

--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Char[] confusing

2009-03-02 Thread Qian Xu

Hi,

I am confusing with getting sub-string of a char[].

- code -
module main;

import tango.io.Console;
import tango.text.convert.Integer;

void main()
{
  char[] s = "ABCDE"; // 5 chars
  int len = s.length;
  Cout("s='" ~ s ~ "', length=" ~ toString(len)).newline;
  Cout("s[" ~ toString(len-1) ~ "]= " ~ s[len-1]).newline;
  Cout("s[0 .. " ~ toString(len-1) ~ "]= " ~ s[0 .. len-1]).newline;
  Cout("s[0 .. " ~ toString(len) ~ "]= " ~ s[0 .. len]).newline;
  Cout("s[1 .. " ~ toString(len-1) ~ "]= " ~ s[1 .. len-1]).newline;
  Cout("s[1 .. " ~ toString(len) ~ "]= " ~ s[1 .. len]).newline;
}
- code -

The result is (dmd + windowsxp)

s='ABCDE', length=5
s[4]= E
s[0 .. 4]= ABCD
s[0 .. 5]= ABCDE
s[1 .. 4]= BCD
s[1 .. 5]= BCDE

---

My question is: why s[4]=E, but s[0..4]=ABCD (without E)







--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Reference counting

2009-03-02 Thread Qian Xu
Hi All,

is it possible to see the reference counting of a char[]?

I have some problems with PullParser (tango). 
I put an assertion here:
-
private XmlTokenType doAttributeName()
{
auto p = text.point;
auto q = p;
auto e = text.end;

assert (p < e, "No!!! text.point is after text.end!!");

char[] tmp = "";
while (*q > 63 || text.attributeName[*q])
-

The assert will be broken 1-2 times, when I run a same test 1000 times.

So I want to know about the inside world of D-Compiler.


Best regards
--Qian Xu


Re: Access Vialotation

2009-02-27 Thread Qian Xu
UPDATE: I am using gdc compiler in Linux


Access Vialotation

2009-02-27 Thread Qian Xu
Hi All,

Is there any way to keep program alive, when an AV takes place?

-- demo ---
module NullPointerExceptionTest;

class Foo {
  void bar() {}
}

void main() {
  Foo foo; // foo is still NULL
  try {
foo.bar(); // A NullPointerException will be thrown
  }
  catch (Exception E) {
// Can I catch this NullPointerException?
  }
}


The program will crash, when the line "foo.bar()" is executed, even when a
try-catch-block is added. So far as I know, Java and Delphi can prevent
such kind of crashes from happening with a try-catch-block. Is it possible
in D?

Best regards
--Qian


Dependency check

2009-02-14 Thread Qian Xu
Hi All,

Is there any tools to check dependency of d projects?
I want to remove all unnecessary imports, to make the build process more
faster :-)

Best regards
--Qian


Re: Compare two objects

2009-02-10 Thread Qian Xu
grauzone wrote:
> 
> Conclusion: == is absolutely useless in your case. Use something else.

But you have to write much more, just like my test(..) function does

--Qian Xu


Compare two objects

2009-02-10 Thread Qian Xu
Hi All,

I want to test, if two objects are equal. 
The rules are as follows: 
1. When both are null, it should return true. 
2. When one of them is null, it should return false.
3. When both not null, then compare their values (as two strings)

My test code
---
class Test {
  private int value;
  this(int value) {
this.value = value;
  }
  public int getValue() {
return this.value;
  }
  bool opEquals(Test obj) {
if (obj is null) {
  return this is null;
}
return this.getValue() == obj.getValue();
  }
}

procedure test(Test a, Test b) {
  if (a is null && b is null) return true;
  if (a !is null && a == b) return true;
  return false;
}

void main()
{
  Test a;
  Test b = new Test(100);
  assert(test(a, b)); // ok
  assert(a != b); // av error
}


If object at the left side of the != is null, I will get an AV error
immediately.
If I want to compare two objects safely, I have to write my own test(..)
function.
But this is not nice.

Can someone explain, is this a design shortcoming of D-Compiler, or I am
wrong.

Best regards
--Qian Xu





How to get the implementer of an interface?

2009-01-22 Thread Qian Xu
Hello All,

how to get the implementer of an interface?

Here is an example:
-
interface intf_1 {}
class c_1 : intf_1 {}
class c_2 : c_1 {}

c_1 aaa = new c_1;
c_2 bbb = new c_2;
auto list = [cast(intf_1)(bbb), cast(intf_1)(aaa)];
foreach (intf_1 i; list)
{
  print_intf_implementor(i);
  // bbb should return "c_2"
  // aaa should return "c_1"
}
-


--Qian


Re: query interface

2009-01-21 Thread Qian Xu
Frits van Bommel wrote:

> Qian Xu wrote:
>> Hi All,
>> 
>> can D check, whether a class A an Interface B supports?
>> 
>> like:
>> 
>>   if (supports(class_A, intf_B))
> 
>  if (is(class_A : intf_B))
> tests if 'class_A' is implicitly convertible to 'intf_B'. If the first
> is a class and the second an interface, that's equivalent to the class
> implementing the interface.

Thanks. Could you tell me, how to make a function for this? I do not know
how to pass an Interface as parameter.

like
  bool supports(T)(T obj, interface_type t)
  {
return (is(obj : t));
  }


Re: query interface

2009-01-21 Thread Qian Xu
Qian Xu wrote:

> Hi All,
> 
> can D check, whether a class A an Interface B supports?
> 
> like:
> 
>   if (supports(class_A, intf_B))
>   {
>  cast(intf_B) (class_A).hello();
>   }
> 
> --Qian

what I have found is:

  if (is(class_A == intf_B))
  {
cast(intf_B) (class_A).hello();
  }

Is there any better one?

--Qian


query interface

2009-01-21 Thread Qian Xu
Hi All,

can D check, whether a class A an Interface B supports?

like:

  if (supports(class_A, intf_B))
  {
 cast(intf_B) (class_A).hello();
  }

--Qian


Re: array initialization problem

2009-01-19 Thread Qian Xu
Denis Koroskin wrote:

> ...
> 
> For example, let's modify CSTR and see what happens:
> CSTR[0] = 'J'; // now it is "Jello"
> 
> printing e.str and e2.str gives us the following output:
> Jello
> Jello
> 
> ...

Hi again,

but there is one thing, I do not understand.
CSTR is a constant. But with "CSTR[0] = 'J'", you can modify a const anyway,
cannot you?

BTW: Do you know, why D do not use copy-on-write semantic instead of
referencing? IMO, copy-on-write is much performanter.

--Qian


Re: array initialization problem

2009-01-18 Thread Qian Xu

Denis Koroskin wrote:

7 - e2.str = "world";
State: CLIST : ["333", "444"];
  e : list = ["333", "444"]; str = "hello";
  e2: list = ["333", "444"]; str = "world";


Hope it helps.


Thanks for your nice answer. You made my day ;-)



--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


array initialization problem

2009-01-16 Thread Qian Xu

Hi All,

I have accidentally written a buggy class.

Briefly described as follows:
 1. The class contains a list of string
 2. The list of string is assigned to a constant in constructor
 3. Try to change the value of the list
 4. Create another class by repeating step 1-3 again
 5. Add both of them to a LinkSeq object
 6. Print their values again
Now you will find their lists have the same values now.

Can someone explain, why the values are different before they are 
inserted into a list?

And why this.str has no problem?


The console output and the source are included below.

# console output begin 

list: [111,222,]
 str: hello
-
list: [333,444,]
 str: world
-
--- after insert ---
-
list: [333,444,]
 str: hello
-
list: [333,444,]
 str: world
-

# console output end 

# code begin 

module test;

import tango.io.Console;
import tango.util.collection.LinkSeq;

const char[][] CLIST = [null, null];
const char[] CSTR = "hello";

class Entity
{
  char[][] list;
  char[] str;

  this()
  {
this.list = CLIST;
this.str = CSTR;
  }

  void print()
  {
Cout.opCall("list: [");
foreach (char[] s; list)
{
  Cout.opCall(s ~ ",");
}
Cout.opCall("]\n");
Cout.opCall(" str: "~this.str);
Cout.opCall("\n-\n");
  }
}

void main()
{
  Entity e = new Entity();
  e.list[0] = "111";
  e.list[1] = "222";
  e.str = "hello";
  e.print();

  Entity e2 = new Entity();
  e2.list[0] = "333";
  e2.list[1] = "444";
  e2.str = "world";
  e2.print();

  Cout.opCall("--- after insert ---\n-\n");
  LinkSeq!(Entity) l = new LinkSeq!(Entity)();
  l.append(e);
  l.append(e2);

  foreach (Entity entity; l)
  {
entity.print();
  }
}

# code end 


--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: confused with some_var.dup

2009-01-16 Thread Qian Xu
Denis Koroskin wrote:
> 
> The "Hello, World!" string is not allowed to be modified, because it could
> be shared throughot the project and will be most probably put in a
> read-only memory causing segfault at modification.
> 
> But it you need to have a modified version of this this, you create its
> copy (duplication, or 'dup' for short) and make whatever changes you want
> to it...

This confuses me very. 
Do you mean, there is no Copy-On-Write semantic in D?
IMO, D-Compiler should make decision about whether to allocate a new memory
block, not programmer.

--Qian


confused with some_var.dup

2009-01-15 Thread Qian Xu
When shall I use some_var.dup and when not?
Is there any guidlines?

--Qian


Re: timezone problem

2009-01-14 Thread Qian Xu
Stewart Gordon wrote:
> My library stores all times in UTC, but allows them to be manipulated in
> any time zone.  But it doesn't yet support daylight saving time
> adjustments.  I haven't quite worked out how best to do this.  (It
> initialises the working time zone to the user's current time zone under
> Windows, but that's it at the moment.)
> 

Thanks Stewart, this is a great library.
However the daylight saving problem is a big issue. I think it would be
easier to use an external library from other programming language (ie.
PHP), instead of implementing the own one for D. (But I do not know how)

--Qian


Re: timezone problem

2009-01-13 Thread Qian Xu
BTW: Is there any Date.Format("-mm-dd") function?


timezone problem

2009-01-13 Thread Qian Xu
Hi All,

I am fighting with date time conversion and have a problem right now:
I want to convert a local timestamp to UTC timestamp.
So I have to get the time zone information.
However in some countries (ie. German, US), the offset is not constant,
because of daylight saving issue.

Is there any "hidden" routine can tell the correct time zone information
(cross platform, esp. open suse)

Any hints are apprecated ^^)

--Qian


Re: Struct life time

2008-12-15 Thread Qian Xu

BCS wrote:

Reply to Qian,


Hi All,

I am new to D community. I have some problems with TimeOfDay struct.

I have defined a class:

class Test
{
TimeOfDay* getTime() {
return a_valid_timeofday_pointer;
}


Could you expand on this function? The rest looks good but if this 
function is returning a pointer to something that then goes out of scope 
(a local var for instance) than that would be the bug.



Hi, it was my fault.

My wrong code was:

  public TimeOfDay* getTime() {
char[] timestring = "10:00:00"; // for test
FullDate fd;
parseTime(timestring, fd);
return *fd.val.time();
  }


Today I have changed it to:


  public TimeOfDay* getTime() {
char[] timestring = "10:00:00"; // for test
FullDate fd;
parseTime(timestring, fd);
TimeOfDay* ret = new TimdOfDay();
*ret = fd.val.time();
return ret;
  }


Now it works properly.



--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Re: Struct life time

2008-12-14 Thread Qian Xu

BCS wrote:

Reply to Qian,


Hi All,

I am new to D community. I have some problems with TimeOfDay struct.

I have defined a class:

class Test
{
TimeOfDay* getTime() {
return a_valid_timeofday_pointer;
}


Could you expand on this function? The rest looks good but if this 
function is returning a pointer to something that then goes out of scope 
(a local var for instance) than that would be the bug.


Thanks BCS, I am not able to get my own code right now. I will post it 
tomorrow.



--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com


Struct life time

2008-12-14 Thread Qian Xu

Hi All,

I am new to D community. I have some problems with TimeOfDay struct.

I have defined a class:

  class Test
  {
TimeOfDay* getTime() {
  return a_valid_timeofday_pointer;
}
void setTime(TimeOfDay* value) {
  setValueAsTime(*value);
}
void setValueAsTime(TimeOfDay value) {
  Cout(TimeToChar(value)).newline;
}
/* the rest implementation of this class ... */
  }


I try to test if setTime() works properly.

If I call
  Cout(TimeToChar(*TestObj.getTime())).newline;
It works. The console will show "10:00:00" for example.

If I call
  TestObj.setTime(TestObj.getTime());
It does not work. The console will show "33140305:48698544:485947594" 
for example.


If I change the setTime() function to
  void setTime(TimeOfDay* value) {
Cout(TimeToChar(*value)).newline;
  }
or
  void setTime(TimeOfDay* value) {
TimeOfDay copy = *value;
setValueAsTime(copy);
  }
It works.

What's wrong with my code? (BTW: I do not want to change TimeOfDay* to 
TimeOfDay, otherwise null cannot be passed in.)


Thanks in advance.
--
Xu, Qian (stanleyxu)
 http://stanleyxu2005.blogspot.com