Constructor is not callable using argument types

2017-08-08 Thread Nrgyzer via Digitalmars-d-learn

Hi guys,

I've the following code:

abstract class a {}
class b : a { this(a* myAttr = null) {} }
class c : a { this(a* myAttr = null) {} }

void main()
{
auto myb = new b();
auto myc = new c();
}

DMD says "Constructor c.this(a* myAttr = null) is not callable 
using argument types (b*)". I'm confused why it fails because 
class b and c are both derived from class a and the constructor 
of class b accepts a pointer of class a.


When I replace "auto myb = new b();" by "a myb = new b();", it 
works as expected. But then I cannot class-specific functions of 
class b because I've the instance of the base-class a. So, what's 
the correct way?


Convert hex to binary

2015-04-24 Thread nrgyzer via Digitalmars-d-learn

Hi,

I'm looking for a function that converts my hex-string to a 
binary representation. In Python I write the following:


myHex = 123456789ABCDEF
myBin = myHex.decode('hex')

But how to do the same in D? Is there any function?

Thanks for suggestions!


Re: Convert hex to binary

2015-04-24 Thread nrgyzer via Digitalmars-d-learn

On Friday, 24 April 2015 at 18:45:55 UTC, Jesse Phillips wrote:

On Friday, 24 April 2015 at 18:14:07 UTC, nrgyzer wrote:

Hi,

I'm looking for a function that converts my hex-string to a 
binary representation. In Python I write the following:


myHex = 123456789ABCDEF
myBin = myHex.decode('hex')

But how to do the same in D? Is there any function?

Thanks for suggestions!


import std.stdio;
void main(){
import std.conv;
import std.format;

auto i = to!ulong(123456789ABCDEF, 16);

writeln(format(%b, i));
}


Thanks to all of you for the solutions, but what if the 
hex-string exceeds the limit of ulong, for instance 
123456789ABCDEF0123456789ABCDEF1234. How to convert them to a 
ulong-array?


Re: std.array.split - Template instantiating error

2015-04-18 Thread nrgyzer via Digitalmars-d-learn
On Saturday, 18 April 2015 at 13:00:59 UTC, Steven Schveighoffer 
wrote:

On 4/18/15 4:18 AM, nrgyzer wrote:



array.d(1510): Error not a property splitter(range, sep).array
sample.d(6): Error template instance std.array.split!(string, 
char)

error instantiating


Are you using -property switch? Looks like std.array does not 
obey property switch requirements. I confirm that compiling 
with -property fails, while compiling without -property works. 
We really need to fix this, and by fix, I mean fix -property so 
it allows calling 0-arg functions without parentheses that 
aren't marked with @property.


-Steve


Yees... Removing the -property switch solved the problem, 
thanks :)


std.array.split - Template instantiating error

2015-04-18 Thread nrgyzer via Digitalmars-d-learn

Hi,

I've the following source:

import std.array : split;
import std.stdio : writeln;

void main()
{
   string myString = Hello World;
   string[] splitted = myString.split( );
}

But when I compile the code above, I'm getting the following 
error:


Error: template instance std.array.split!(string, string) error 
instantiating.


I'm using the latest version of dmd (2.067.0), but I cannot 
figure out what I'm doing wrong :(. How to solve the problem?


Thanks in advance!


Re: std.array.split - Template instantiating error

2015-04-18 Thread nrgyzer via Digitalmars-d-learn
On Saturday, 18 April 2015 at 08:13:00 UTC, Rikki Cattermole 
wrote:

On 18/04/2015 8:08 p.m., nrgyzer wrote:

Hi,

I've the following source:

import std.array : split;
import std.stdio : writeln;

void main()
{
   string myString = Hello World;
   string[] splitted = myString.split( );
}

But when I compile the code above, I'm getting the following 
error:


Error: template instance std.array.split!(string, string) error
instantiating.

I'm using the latest version of dmd (2.067.0), but I cannot 
figure out

what I'm doing wrong :(. How to solve the problem?

Thanks in advance!


alias immutable(char)[] string;

T[] split(T, U=typeof(T.init[0]))(T from, U sep)

Aka try changing   to ' '.


I already tried to change the separator from string ( ) to char 
(' ') . I'm getting the same result:


array.d(1510): Error not a property splitter(range, sep).array
sample.d(6): Error template instance std.array.split!(string, 
char) error instantiating


Re: Error: Undefined identifier when moving import to another module

2014-10-20 Thread nrgyzer via Digitalmars-d-learn

On Sunday, 19 October 2014 at 22:22:05 UTC, Joakim wrote:

On Sunday, 19 October 2014 at 09:39:05 UTC, nrgyzer wrote:

Hi guys,

when I do the following:

module myMain;

import example;
import std.traits;
import my.static.library.binding;

static this()
{
  foreach ( m; __traits(allMembers, example) )
  {
 static if ( isCallable!(mixing(m) )
 {
// ... do something here
 }
  }
}

void main() { /* do something here */ }

And my example-module looks like:

module example;

void exmapleFunction()
{
  // do something here
}

I can compile my application without any error, BUT when I 
move the import of my.static.library.binding to the 
example-module:


module example;

import my.static.library.binding;

void exmapleFunction()
{
  // do something here
}

... I'm getting many error messages like these:

myMain.d-mixin-11(11): Error: undefined identifier 
_D12TypeInfo_xAa6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D49TypeInfo_xAS3std8typecons16__T5TupleTkTkTkZ5Tuple6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D75TypeInfo_xAS3std3uni38__T13InversionListTS3std3uni8GcPolicyZ13InversionList6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D55TypeInfo_xAE3std5regex15__T6ParserTAyaZ6Parser8Operator6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D31TypeInfo_xAS3std5regex8Bytecode6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D110TypeInfo_xAS3std3uni152__T4TrieTS3std3uni20__T9BitPackedTbVmi1Z9BitPackedTwVmi1114112TS3std3uni23__T9sliceBitsVmi8Vmi21Z9sliceBitsTS3std3uni22__T9sliceBitsVmi0Vmi8Z9sliceBitsZ4Trie6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D45TypeInfo_xS3std5regex14__T7ShiftOrTaZ7ShiftOr6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D11TypeInfo_xw6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D11TypeInfo_xb6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D13TypeInfo_xAya6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D41TypeInfo_xS3std5regex12__T5StackTkZ5Stack6__initZ


I'm having no idea what's going wrong here. I'm simply moving 
the import from the file where my main() is located in to the 
example-module. When removing the import of 
my.static.library.binding in the example-module allows me to 
successfully compile everything. But I need the import in the 
example-module. Any suggestions what's going wrong here/how I 
can solve the error?


An import is private by default:

http://dlang.org/module.html

When you move the import of my.static.library.binding to the 
example module, its declarations are no longer available in 
the myMain module.  You'd have to make it a public import 
my.static.library.binding to make it available to other 
modules.


Hm, I made it public and I'm getting the same error. I also 
imported the same module in my main which also gives me the same 
error.


Re: Error: Undefined identifier when moving import to another module

2014-10-20 Thread nrgyzer via Digitalmars-d-learn

On Monday, 20 October 2014 at 16:05:14 UTC, nrgyzer wrote:

On Sunday, 19 October 2014 at 22:22:05 UTC, Joakim wrote:

On Sunday, 19 October 2014 at 09:39:05 UTC, nrgyzer wrote:

Hi guys,

when I do the following:

module myMain;

import example;
import std.traits;
import my.static.library.binding;

static this()
{
 foreach ( m; __traits(allMembers, example) )
 {
static if ( isCallable!(mixing(m) )
{
   // ... do something here
}
 }
}

void main() { /* do something here */ }

And my example-module looks like:

module example;

void exmapleFunction()
{
 // do something here
}

I can compile my application without any error, BUT when I 
move the import of my.static.library.binding to the 
example-module:


module example;

import my.static.library.binding;

void exmapleFunction()
{
 // do something here
}

... I'm getting many error messages like these:

myMain.d-mixin-11(11): Error: undefined identifier 
_D12TypeInfo_xAa6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D49TypeInfo_xAS3std8typecons16__T5TupleTkTkTkZ5Tuple6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D75TypeInfo_xAS3std3uni38__T13InversionListTS3std3uni8GcPolicyZ13InversionList6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D55TypeInfo_xAE3std5regex15__T6ParserTAyaZ6Parser8Operator6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D31TypeInfo_xAS3std5regex8Bytecode6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D110TypeInfo_xAS3std3uni152__T4TrieTS3std3uni20__T9BitPackedTbVmi1Z9BitPackedTwVmi1114112TS3std3uni23__T9sliceBitsVmi8Vmi21Z9sliceBitsTS3std3uni22__T9sliceBitsVmi0Vmi8Z9sliceBitsZ4Trie6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D45TypeInfo_xS3std5regex14__T7ShiftOrTaZ7ShiftOr6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D11TypeInfo_xw6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D11TypeInfo_xb6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D13TypeInfo_xAya6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D41TypeInfo_xS3std5regex12__T5StackTkZ5Stack6__initZ


I'm having no idea what's going wrong here. I'm simply moving 
the import from the file where my main() is located in to the 
example-module. When removing the import of 
my.static.library.binding in the example-module allows me 
to successfully compile everything. But I need the import in 
the example-module. Any suggestions what's going wrong 
here/how I can solve the error?


An import is private by default:

http://dlang.org/module.html

When you move the import of my.static.library.binding to the 
example module, its declarations are no longer available in 
the myMain module.  You'd have to make it a public import 
my.static.library.binding to make it available to other 
modules.


Hm, I made it public and I'm getting the same error. I also 
imported the same module in my main which also gives me the 
same error.


I temporarely solved the error by making the import in the module 
where the main()-function is located in public and importing this 
file into the other module. This solved the error but is not a 
perfect solution...


Re: Error: Undefined identifier when moving import to another module

2014-10-20 Thread nrgyzer via Digitalmars-d-learn
This solved the problem for the first time, BUT - I don't know if 
it's a bug or a feature - I ran into another problem. I'm having 
the following few lines:


module example;

private
{
   string[string] myPrivateArray;
}

static this()
{
   foreach ( m; __traits(allMembers, example) )
   {

  writefln(%s :: %s, m, __traits(getProtection, m));
   }
}

void main() { /* empty */ }

Compiling and running the application say's that myPrivateArray 
is public:


myPrivateArray :: public

I declared myPrivateArray using the private keyword, but the 
dmd-trait `getProtection` says public. Why?


Re: Error: Undefined identifier when moving import to another module

2014-10-20 Thread nrgyzer via Digitalmars-d-learn

On Monday, 20 October 2014 at 17:37:34 UTC, nrgyzer wrote:
This solved the problem for the first time, BUT - I don't know 
if it's a bug or a feature - I ran into another problem. I'm 
having the following few lines:


module example;

private
{
   string[string] myPrivateArray;
}

static this()
{
   foreach ( m; __traits(allMembers, example) )
   {

  writefln(%s :: %s, m, __traits(getProtection, m));
   }
}

void main() { /* empty */ }

Compiling and running the application say's that myPrivateArray 
is public:


myPrivateArray :: public

I declared myPrivateArray using the private keyword, but the 
dmd-trait `getProtection` says public. Why?


Ah, okay, I also need to use mixin(m) to get the protection. But 
in this case, getProtection only works if I want retrieve the 
protection for a variable, contained in the same module. I simply 
can't use getProtection if I'm using the allMembers-trait for 
another module where the variable is private...


Error: Undefined identifier when moving import to another module

2014-10-19 Thread nrgyzer via Digitalmars-d-learn

Hi guys,

when I do the following:

module myMain;

import example;
import std.traits;
import my.static.library.binding;

static this()
{
   foreach ( m; __traits(allMembers, example) )
   {
  static if ( isCallable!(mixing(m) )
  {
 // ... do something here
  }
   }
}

void main() { /* do something here */ }

And my example-module looks like:

module example;

void exmapleFunction()
{
   // do something here
}

I can compile my application without any error, BUT when I move 
the import of my.static.library.binding to the example-module:


module example;

import my.static.library.binding;

void exmapleFunction()
{
   // do something here
}

... I'm getting many error messages like these:

myMain.d-mixin-11(11): Error: undefined identifier 
_D12TypeInfo_xAa6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D49TypeInfo_xAS3std8typecons16__T5TupleTkTkTkZ5Tuple6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D75TypeInfo_xAS3std3uni38__T13InversionListTS3std3uni8GcPolicyZ13InversionList6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D55TypeInfo_xAE3std5regex15__T6ParserTAyaZ6Parser8Operator6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D31TypeInfo_xAS3std5regex8Bytecode6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D110TypeInfo_xAS3std3uni152__T4TrieTS3std3uni20__T9BitPackedTbVmi1Z9BitPackedTwVmi1114112TS3std3uni23__T9sliceBitsVmi8Vmi21Z9sliceBitsTS3std3uni22__T9sliceBitsVmi0Vmi8Z9sliceBitsZ4Trie6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D45TypeInfo_xS3std5regex14__T7ShiftOrTaZ7ShiftOr6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D11TypeInfo_xw6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D11TypeInfo_xb6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D13TypeInfo_xAya6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D41TypeInfo_xS3std5regex12__T5StackTkZ5Stack6__initZ


I'm having no idea what's going wrong here. I'm simply moving the 
import from the file where my main() is located in to the 
example-module. When removing the import of 
my.static.library.binding in the example-module allows me to 
successfully compile everything. But I need the import in the 
example-module. Any suggestions what's going wrong here/how I can 
solve the error?


Re: Error: Undefined identifier when moving import to another module

2014-10-19 Thread nrgyzer via Digitalmars-d-learn

On Sunday, 19 October 2014 at 14:48:18 UTC, monarch_dodra wrote:

On Sunday, 19 October 2014 at 09:39:05 UTC, nrgyzer wrote:

Hi guys,

when I do the following:
 static if ( isCallable!(mixing(m) )


mixing ?


void main() { /* do something here */ }


What exactly are you doing here?


... I'm getting many error messages like these:

myMain.d-mixin-11(11): Error: undefined identifier 
_D12TypeInfo_xAa6__initZ
myMain.d-mixin-11(11): Error: undefined identifier 
_D49TypeInfo_xAS3std8typecons16__T5TupleTkTkTkZ5Tuple6__initZ

myMain.d-mixin-11(11): Error: undefined identifier


Sounds like your import was also import std.typecons which 
appears to have been required in your main.


mixing should be replaced with mixin: static if ( 
isCallable!(mixin(m) )


My main is empty in both cases. So nothing done in my main 
(currently).


Re: Error: Undefined identifier when moving import to another module

2014-10-19 Thread nrgyzer via Digitalmars-d-learn

On Sunday, 19 October 2014 at 17:14:14 UTC, monarch_dodra wrote:

On Sunday, 19 October 2014 at 16:09:41 UTC, nrgyzer wrote:
mixing should be replaced with mixin: static if ( 
isCallable!(mixin(m) )


My main is empty in both cases. So nothing done in my main 
(currently).


Posting full code that actually compiles and reproduces the 
issue helps.


I posted the full code - except the library. But the library 
contains over hundred thousand lines of code, so I think that's a 
bit too much to post here...


Re: Using __traits to find functions in sub-modules

2014-10-17 Thread nrgyzer via Digitalmars-d-learn

On Thursday, 16 October 2014 at 19:19:21 UTC, John Colvin wrote:

On Thursday, 16 October 2014 at 18:39:50 UTC, nrgyzer wrote:

Hi,
I'm using structs to describe my functions:

struct example
{
  string name;
  uint someValue;
}

module mod.example1;

@example(example1, 1)
void myFunction()
{
// do something
}

module mod.example2;

@example(example2, 2)
void myFunction()
{
// do something
}

I'm using the struct to describe functions in different 
modules. Now, I want add all functions which are described 
using the example-struct to an array during compile time. But 
how can I do this? I know, I can use __trait(allMembers, 
mod.example1) and __trait(allMembers, mod.example2), but I 
only want specify the parent module (mod), for instance:


void main()
{
  foreach (member, __traits(allMembers, mod))
  {
 writeln(member);
  }
}

But this only shows object - nothing else. No sub-modules 
like mod.example1 or mod.example2. So, how can I find all 
functions that are described using my structure during compile 
time and add them to an array?


I already tried this:

void main()
{
  foreach (cmodule; ModuleInfo)
  {
 foreach (submodule; __traits(allMembers, cmodule))
 {
 // ... also tried: foreach (submodule; 
__traits(allMembers, mixin(cmodule.name))), cmodule.name is 
not available during compile time...

 }
  }
}

But it always stats that 'cmodule' has no members. Does anyone 
know how to solve the problem?


perhaps you could get somewhere by using a package.d in every 
package?


If it needs to work on packages you don't control then I don't 
really know :/


Hm, importing the package doesn't help :(
Okay, I see... I've to solve the problem using another idea...


Using __traits to find functions in sub-modules

2014-10-16 Thread nrgyzer via Digitalmars-d-learn

Hi,
I'm using structs to describe my functions:

struct example
{
   string name;
   uint someValue;
}

module mod.example1;

@example(example1, 1)
void myFunction()
{
// do something
}

module mod.example2;

@example(example2, 2)
void myFunction()
{
// do something
}

I'm using the struct to describe functions in different modules. 
Now, I want add all functions which are described using the 
example-struct to an array during compile time. But how can I do 
this? I know, I can use __trait(allMembers, mod.example1) and 
__trait(allMembers, mod.example2), but I only want specify the 
parent module (mod), for instance:


void main()
{
   foreach (member, __traits(allMembers, mod))
   {
  writeln(member);
   }
}

But this only shows object - nothing else. No sub-modules like 
mod.example1 or mod.example2. So, how can I find all functions 
that are described using my structure during compile time and add 
them to an array?


I already tried this:

void main()
{
   foreach (cmodule; ModuleInfo)
   {
  foreach (submodule; __traits(allMembers, cmodule))
  {
  // ... also tried: foreach (submodule; __traits(allMembers, 
mixin(cmodule.name))), cmodule.name is not available during 
compile time...

  }
   }
}

But it always stats that 'cmodule' has no members. Does anyone 
know how to solve the problem?


Using TreeSet and __gshared values

2014-09-03 Thread nrgyzer via Digitalmars-d-learn

Hi guys,

I'm having some trouble using the treeset implementation of
Steven (dcollections) in conjunction with __gshared. When I do
the following:

class Entry
{
int value;
this(int v)
{
value = v;
}
int opCmp(Object o)
{
return -1;
}
}

void main()
{

auto tree = new TreeSet!Entry();
tree.add(new Entry(10));
tree.add(new Entry(20));
tree.add(new Entry(30));

foreach (ref entry; tree)
{
writeln(entry.value);
}
}

I'm getting the following output:

10
20
30

But when I replace the class as follows:

class Entry
{
__gshared int value;
this(int v)
{
value = v;
}
int opCmp(Object o)
{
return -1;
}
}

I'm getting the following output:

30
30
30

Do anyone have any ideas what can cause the problem?


Re: Value of floating in JSONValue

2014-08-22 Thread nrgyzer via Digitalmars-d-learn

On Thursday, 21 August 2014 at 23:29:56 UTC, Idan Arye wrote:

On Thursday, 21 August 2014 at 23:05:48 UTC, Ali Çehreli wrote:
I don't think it is a concern as JSON does not encode types. 
It is up to the receiver how to interpret the data. Here is 
the output of the program above:


{value:1.234567889998901}

Ali


JSON may not encode the very specific type the language that 
created it was using, but it does differ between strings and 
numbers. {value:1.234567889998901} is different from 
{value:1.234567889998901}, virtually any JSON 
implementation for any language(there might be exceptions - 
maybe TCL) will parse them to different language constructs, 
and code that expect one may fail, crash or misbehave when 
given the other.


That's exactly my problem. The remote PC expects a numeric value
with a precision of up to 6 floating points. So using a string
instead of float would cause an error.


Re: goto skips declaration of variable

2014-08-21 Thread nrgyzer via Digitalmars-d-learn

On Tuesday, 19 August 2014 at 20:33:00 UTC, monarch_dodra wrote:

On Monday, 18 August 2014 at 13:51:14 UTC, nrgyzer wrote:

Hi all,

I've the following code snipped:

import std.bigint;
void main(string[] args)
{
BigInt i = 12345;
if (args.length  1)
{
goto Exit;
}
i = BigInt(67890);
Exit:
return;
}


For what it's worth, whenever you have goto-end style code, 
place all your code in a proper block, in such a way that all 
your variable declarations are in that block, and all your 
gotos break out of this block. This way, a goto will *never* 
cross a declaration, so coding is easy. The only variables you 
place at the top or the ones that could need cleanup.


void main(string[] args)
{
//Declarations that need cleanup:
void* p;

//Code
{
BigInt i = 12345; //Local variable
if (args.length  1)
{
goto Exit; //Breaks out of block
}
i = BigInt(67890);
BigInt j = 54321; //Local variable
}

//End
Exit:
CleanUp(p);
return;
}


Yes, that works. I'm using the goto-command to exit my function
if an error (not necessarily an exception) occured. Sure, I can
simply do a return, but I personally prefer a fixed endpoint of
my functions. This also simplifies debugging my application
because I don't need 10 or 20 breakpoints (one before each
return-point).


Re: goto skips declaration of variable

2014-08-21 Thread nrgyzer via Digitalmars-d-learn

On Thursday, 21 August 2014 at 17:39:16 UTC, Ali Çehreli wrote:

On 08/21/2014 04:12 AM, nrgyzer wrote:

 I'm using the goto-command to exit my function
 if an error (not necessarily an exception) occured.

Sorry to repeat myself but if an exception occurs in code 
before the goto, the exit code will not be executed. Of course, 
it may be that the function is defined 'nothrow' so my concern 
does not apply.


 Sure, I can
 simply do a return, but I personally prefer a fixed endpoint
of
 my functions.

Again, that is not possible in a language that has exceptions.

Ali


Sure, but what about the following pretty simple source:

bool testa(int a)
{
bool fIsValid = (a  0);

if (a  0)
   goto Exit;

throw new Exception(int = 0);
Exit:
return fIsValid;
}

int main(string[] args)
{
testa(10); // Use goto
testa(-1); // Throws an exception
}

I'm absolutely aware that gotos are useless if an exception
occured before the goto appears. But in some cases they are very
useful, especially when I want prevent 10 ident-steps or
something else...

Okay, my question was answered - compiler bug. Thanks in advance!


Value of floating in JSONValue

2014-08-21 Thread nrgyzer via Digitalmars-d-learn

Hi everyone,

I'm facing a problem with the JSON functions. I've to communicate
with another PC using JSON. Here's a simple snipped which shows
my problem:

import std.json;
import std.stdio;
void main()
{
double d = 1.23456789;
JSONValue j = d;
sendToRemote(toJSON(j));
}

My problem is that the remote PC receives 1.23457 instead of
1.23456789. But when I add the following:

import std.json;
import std.stdio;
void main()
{
double d = 1.23456789;
JSONValue j = d;
sendToRemote(toJSON(j));
writefln(%.8f, j.floating);
}

writefln() shows me 1.23456789. So, the value is correct. I think
the problem is the default representation of any floating point
number to string. Is there any chance I can send 1.23456789
instead of 1.23457 to my remote PC?

Note: I cannot use strings because the other PC expects a numeric
data type.


Re: goto skips declaration of variable

2014-08-19 Thread nrgyzer via Digitalmars-d-learn
On Monday, 18 August 2014 at 17:47:21 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Mon, 18 Aug 2014 13:51:12 +
nrgyzer via Digitalmars-d-learn 
digitalmars-d-learn@puremagic.com

wrote:

When I try to compile this sample application I'm getting the 
following error:


sample.d(7): Error: goto skips declaration of variable 
sample.main.__ctmp1344 at sample.d(9)

it's compiler bug i believe.

but why do you need gotos at the first place? i'm not saying 
that you
must avoid gotos at all costs!, but D has some nice features 
like
scope(exit), scope(success), scope(failure) and nested 
functions, which
can render gotos unnecessary in many cases (and make code 
cleaner).


I know, gotos are having a negative connotation. Sure, I can also 
use nested functions, but in my opinion it results in dirty and 
complex code. It's totally overkilled compared to a simple if and 
goto-instruction. The same regards the scoping... it's simply to 
much overhead.


goto skips declaration of variable

2014-08-18 Thread nrgyzer via Digitalmars-d-learn

Hi all,

I've the following code snipped:

import std.bigint;
void main(string[] args)
{
BigInt i = 12345;
if (args.length  1)
{
goto Exit;
}
i = BigInt(67890);
Exit:
return;
}

When I try to compile this sample application I'm getting the 
following error:


sample.d(7): Error: goto skips declaration of variable 
sample.main.__ctmp1344 at sample.d(9)


I know that the error is caused by the line 'i = 
BigInt(67890)'. I also know that I can simply replace the 
goto-condition with something like this:


if (args.length == 0)
{
i = BigInt(67890);
}

But that's not what I want because I've many BigInt-assignments 
in my real application. That would result in a very very deep, 
nested source structure and that really hurts. So, is there any 
solution how I can realize the BigInt-assignment after the 
goto-Command (or better: without skipping the declaration)?


Re: How to set JSON_TYPE in 2.0.65

2014-04-03 Thread nrgyzer

On Monday, 31 March 2014 at 19:05:11 UTC, Matt Soucy wrote:

On 03/31/2014 02:59 PM, nrgyzer wrote:

Hi guys,

I updated my dmd version from 2.0.63 to 2.0.65 and having some 
trouble
with my JSON-definitions. The code below worked in 2.0.63 but 
not in

2.0.65:

JSONValue oJson = JSONValue();
oJson.type = JSON_TYPE.OBJECT; // FAILS
oJson.object[myEntry] = JSONValue();
oJson.object[myEntry].type = JSON_TYPE.STRING; // FAILS
oJSon.object[myEntry].str = MyText;

Since the type property is a constant in 2.0.65, I've no idea 
how I can
set the type for my JSON entries. I already tried the 
following:


JSONValue oJson = JSONValue(JSON_TYPE.OBJECT);
oJson.object[myEntry] = JSONValue(JSON_TYPE.STRING);
oJSon.object[myEntry].str = MyText;

But this gives me something like: JSONValue is not an object.

Any idea how I can set the corresponding value type?
I believe that this was simplified in recent releases, so one 
only needs

to do the following:

JSONValue oJson;
oJson.object[myEntry] = MyText;

(Untested but I believe this is how it's supposed to be now)


Thanks Matt, but this doesn't work because the object-property 
checks the type of the JSONValue and throws the corresponding 
exception. But the following works:


JSONValue oJson = [myEntry : MyText];
oJson.object[myEntry_2] = MyText_2;
...

Thanks to all!


How to set JSON_TYPE in 2.0.65

2014-03-31 Thread nrgyzer

Hi guys,

I updated my dmd version from 2.0.63 to 2.0.65 and having some 
trouble with my JSON-definitions. The code below worked in 2.0.63 
but not in 2.0.65:


JSONValue oJson = JSONValue();
oJson.type = JSON_TYPE.OBJECT; // FAILS
oJson.object[myEntry] = JSONValue();
oJson.object[myEntry].type = JSON_TYPE.STRING; // FAILS
oJSon.object[myEntry].str = MyText;

Since the type property is a constant in 2.0.65, I've no idea how 
I can set the type for my JSON entries. I already tried the 
following:


JSONValue oJson = JSONValue(JSON_TYPE.OBJECT);
oJson.object[myEntry] = JSONValue(JSON_TYPE.STRING);
oJSon.object[myEntry].str = MyText;

But this gives me something like: JSONValue is not an object.

Any idea how I can set the corresponding value type?


Re: Socket: Detect connection close

2014-03-24 Thread nrgyzer
On Monday, 24 March 2014 at 05:32:30 UTC, Vladimir Panteleev 
wrote:

On Sunday, 23 March 2014 at 20:12:38 UTC, nrgyzer wrote:

Hi guys,

I'm experimenting with sockets and having trouble to detect 
when the remote side closes the connection. Here's my code:


// Client:
module client;

import std.socket;

void main()
{
TcpSocket s = new TcpSocket();
s.connect(new InternetAddress(localhost, 8080));
SocketStream ss = new SocketStream(s);

for (int i= 0; i  10; i++)
{
ss.write(1);
ss.flush();
}
ss.socket.shutdown(SocketShutdown.BOTH);
ss.close();
}

// Server:
module server;

import std.sdio;
import std.socket;

void main()
{

TcpSocket s = new TcpSocket(AddressFamily.INET);
s.bind(new InternetAddress(localhost, 8080));
s.blocking(false);
s.listen(0);

while(1)
{
try {
Socket requestSocket = oSocket.accept();
RequestThread rt = new RequestThread(requestSocket);
rt.start();
}
catch (SocketAcceptException e)
{
Thread.yield();
}
}

s.socket.shutdown(SocketShutdown.BOTH);
s.close();

}

class RequestThread : Thread
{
private {
__gshared Socket s;

void run()
{
ubyte[1] buffer;
while(s.isAlive)
{
s.receive(buffer);
writeln(receiving);
}
writeln(client closed connection);
}

}

public this(Socket socket)
{
super(run);
s = socket;
}
}

I know... dirty (really) dirty code, but it works , except 
that I'm in an endless loop and my server always prints 
receiving. I never see client closed connection although 
the client sends only 10 int values. It seems that s.isAlive 
is always true. How can I detect when the client closes the 
connection (or how can I detect if the connection is broken)?


You can determine when the connection was closed on the remote 
side by checking if s.receive returns an empty array.


Alright, that world work. But what about sending 10 Bytes, 
waiting some minutes (probably some hours) and sending 10 Bytes 
again. Is it possible to do this on the same Socket?


My scenario is: I've one central server and multiple clients. The 
clients are connecting to the server and send (or request) some 
information. After that the clients are simply sleeping for an 
unknown time. For instance client 1 for 1 seconds, client 2 for 1 
minute, client 3 for 1 hours and client 4 for 1 day. After that 
time they resend/request some more information from the server... 
my questions regarding this are:


- When I client connects, the server creates a thread. How can I 
determine that I can terminate the thread because the connection 
is inactive (for instance because the client closed the 
connection or some connecting issues)?
- How can the client check if the connection is alive? (If the 
connection isn't alive, I need to reconnect)


Socket: Detect connection close

2014-03-23 Thread nrgyzer

Hi guys,

I'm experimenting with sockets and having trouble to detect when 
the remote side closes the connection. Here's my code:


// Client:
module client;

import std.socket;

void main()
{
TcpSocket s = new TcpSocket();
s.connect(new InternetAddress(localhost, 8080));
SocketStream ss = new SocketStream(s);

for (int i= 0; i  10; i++)
{
ss.write(1);
ss.flush();
}
ss.socket.shutdown(SocketShutdown.BOTH);
ss.close();
}

// Server:
module server;

import std.sdio;
import std.socket;

void main()
{

TcpSocket s = new TcpSocket(AddressFamily.INET);
s.bind(new InternetAddress(localhost, 8080));
s.blocking(false);
s.listen(0);

while(1)
{
try {
Socket requestSocket = oSocket.accept();
RequestThread rt = new RequestThread(requestSocket);
rt.start();
}
catch (SocketAcceptException e)
{
Thread.yield();
}
}

s.socket.shutdown(SocketShutdown.BOTH);
s.close();

}

class RequestThread : Thread
{
private {
__gshared Socket s;

void run()
{
ubyte[1] buffer;
while(s.isAlive)
{
s.receive(buffer);
writeln(receiving);
}
writeln(client closed connection);
}

}

public this(Socket socket)
{
super(run);
s = socket;
}
}

I know... dirty (really) dirty code, but it works , except that 
I'm in an endless loop and my server always prints receiving. I 
never see client closed connection although the client sends 
only 10 int values. It seems that s.isAlive is always true. How 
can I detect when the client closes the connection (or how can I 
detect if the connection is broken)?


Thanks for any suggestions or ideas!


Rang violation using AA's

2013-02-08 Thread Nrgyzer

Hi guys,

I'm updated from DMD 2.060 to 2.061 and I just run into some 
trouble by using associative arrays. Let's say I've the following 
few lines:


string[string] myValues;

ref string getValue(string v) {
   return myValues[v];
}

void main() {
   getValue(myValue) = myString;
}

I get a range violation in getValue() because the entry does not 
exist. But as far as I know, this worked in 2.060 (no range 
violation). One idea was to initialize the value in getValue() if 
it does not exist, but my associative array looks like:


string[string][][string] myValues;

... how to initialize this? So, is this a bug or is it my mistake?


Re: Rang violation using AA's

2013-02-08 Thread Nrgyzer

On Friday, 8 February 2013 at 19:24:55 UTC, simendsjo wrote:

On Friday, 8 February 2013 at 17:16:15 UTC, Nrgyzer wrote:

Hi guys,

I'm updated from DMD 2.060 to 2.061 and I just run into some 
trouble by using associative arrays. Let's say I've the 
following few lines:


string[string] myValues;

ref string getValue(string v) {
  return myValues[v];
}

void main() {
  getValue(myValue) = myString;
}

I get a range violation in getValue() because the entry does 
not exist. But as far as I know, this worked in 2.060 (no 
range violation). One idea was to initialize the value in 
getValue() if it does not exist, but my associative array 
looks like:


string[string][][string] myValues;

... how to initialize this? So, is this a bug or is it my 
mistake?


Did that really work before? Looks like a bug as you are 
accessing an element that doesn't exist.


The following works:

import std.stdio;
void main() {
string[string][][string] myValues;
assert(myValues.length == 0);

myValues[a] = new string[string][100]; // Doesn't have to 
create 100 elements of course

assert(myValues[a].length == 100);
assert(myValues[a][0].length == 0);

myValues[a][0][b] = aoeu;
assert(myValues[a][0][b] == aoeu);
}


I downloaded 2.060, tried my example above and it works in 2.060 
without any range exceptions. Using 2.061 throws me the range 
exception (using the same code). I also tried the following (as 
described in the documentation of AA's):


void main() {
   int[string] b;
   b[hello] = 3;
}

This works for both versions... but I don't know why using a 
method with ref-return value doesn't work anymore.


Thanks for your suggestion.


Re: Rang violation using AA's

2013-02-08 Thread Nrgyzer

On Friday, 8 February 2013 at 20:30:00 UTC, Maxim Fomin wrote:

On Friday, 8 February 2013 at 20:10:32 UTC, Nrgyzer wrote:

void main() {
  int[string] b;
  b[hello] = 3;
}

This works for both versions... but I don't know why using a 
method with ref-return value doesn't work anymore.


Thanks for your suggestion.


This works because an element is assigned if absent (expression 
is treated as lvalue). In case of return an element is not 
assigned (rvalue), so exception is thrown. I do not now why it 
worked in 2.060.


It worked in version 2.060 and lower... but as already mentioned 
not in 2.061. I don't know if it's intended or not.


Error 168 64K Global Types

2013-01-06 Thread nrgyzer

Hi guys,

after some hours I successfully compiled wxD without errors. When 
I try to compile a simple example like the hello example I get 
the following message:


dmd -c -version=wx28 -version=__WXMSW__ -version=ANSI -I..\.. 
Hello.d


dmd -g -of..\..\bin\Hello.exe Hello.obj ..\..\wxd.lib 
..\..\wxc.lib C:\wxWidgets-2.8.10\lib\dmc_lib\wxbase28d.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxbase28d_xml.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxmsw28d_core.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxmsw28d_adv.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxmsw28d_html.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxmsw28d_xrc.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxtiffd.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxjpegd.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxpngd.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxzlibd.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxregexd.lib  
C:\wxWidgets-2.8.10\lib\dmc_lib\wxexpatd.lib   kernel32.lib 
user32.lib gdi32.lib comdlg32.lib winspool.lib winmm.lib 
shell32.lib comctl32.lib ole32.lib oleaut32.lib uuid.lib 
rpcrt4.lib advapi32.lib wsock32.lib odbc32.lib-L/EXETYPE:NT 
-L/SU:WINDOWS:4.0


OPTLINK (R) for Win32  Release 8.00.12
Copyright (C) Digital Mars 1989-2010  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
OPTLINK : Error 168: 64K Global Types
--- errorlevel 1

--- errorlevel 1

I already found a thread regarding wx/wxd where this error was 
also discussed, but no concrete solution was shown (or I 
overlooked the answer...). But is there any solution to fix this 
error? (I'm using DMD 2.061)


Thanks in advance!


Re: Reflection: Get all inherited classes of a base class

2012-12-25 Thread nrgyzer
On Saturday, 22 December 2012 at 22:28:57 UTC, Adam D. Ruppe 
wrote:

On Saturday, 22 December 2012 at 22:14:28 UTC, nrgyzer wrote:
is it possible to get a list of all inherited classes from a 
base class like this:


Yes, though it isn't compile time - gotta be runtime.

ClassInfo[] getChildClasses(ClassInfo c) {
ClassInfo[] info;

// MoudleInfo is a magical thing in object.d,
// implicitly imported, that can loop over all
// modules in the program: user and library
foreach(mod; ModuleInfo) {
// the localClasses member gives back
// ClassInfo things that we can compare
foreach(cla; mod.localClasses) {
// note: we could also check this
// recursively and check
// cla.interfaces as well as base
if(cla.base is c)
info ~= cla;
}
}

return info;
}


So this should be enough for your example assert, but remember 
you can't do things like templates on this, since it is all 
runtime.


Thanks Adam, that's exactly what I need... is it possible to call 
a static method only using TypeInfo_Class or do I need to call 
the constructor using create-method? I think using annotation 
would be very helpful for my idea:


abstract class A {
   static abstract string myName(); // this surely doesn't work
   string[] getChildClassNames() {
  string[] retArray;
  foreach(mod; ModuleInfo) {
 foreach(cla; mod.localClasses) {
if (cla is this.classinfo)
   retArray ~= cla.myName; // adds Class B and 
Class C

 }
  return retArray;
   }
}

class B : A {
   override static string myName() { return Class B; }
}

class C : A {
   override static string myName() { return Class C; }
}

But as in the most other languages it's impossible to declare 
abstract static methods and I also have no direct access from 
TypeInfo_Class to my static attributes and/or methods (or is 
there any chance without creating an instance of the class?).


Hence, annotations would be very useful at this point, but is 
there any other possibility to do something like shown above...?


CURL: Save response to string

2012-06-30 Thread Nrgyzer
Hi guys,

I know... there's a lib for curl but I'm using an old CURL-binding for D... 
I've the following problem: I'm sending my login data to
a web page and I want store the response of curl_easy_perform() in a string. So 
I'm using the following few lines to do that:

string temp;

size_t callback(char* ptr, size_t size, size_t, nmemb, string* stream) {
   temp ~= *ptr;
   // or: How can I append ptr to my stream?
   // When I use '*stream ~= cast(char) ptr;' I get an memory violation...
}

void main() {
CURL* curl = curl_easy_init();

curl_httppost* post;

curl_formadd(post, last, CURLFORM_COPYNAME, toStringz(username), 
CURLFORM_COPYCONTENTS, toStringz(username),
CURLFORM_END);
curl_formadd(post, last, CURLFORM_COPYNAME, toStringz(password), 
CURLFORM_COPYCONTENTS, toStringz(password),
CURLFORM_END);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, temp);
curl_easy_setopt(curl, CURLOPT_URL, 
toStringz(https://myURL.tld/login.php;));
curl_easy_perform(curl);
writeln(temp);
}

But when I run the code, temp is completely empty... does anyone know how to 
fix that or what I'm doing wrong?

Thanks for all suggestions!


std.path.buildPath() and string enumeration

2012-05-30 Thread nrgyzer
Hi,

I've the following enumeration:

enum path : string {

  log1 = /var/log1,
  log2 = /var/log2

}

Now... when I try to do the following:

string subDirectory = example;

string newPath = buildPath(path.log1, subDirectory);

I get the following errors:

Error: template std.path.buildPath does not match any function template
declaration
Error: template std.path.buildPath(C) if (isSomeChar!(C)) cannot deduce
template function from argument types !()(path,string)
Error: template std.path.buildPath does not match any function template
declaration
Error: template std.path.buildPath(C) if (isSomeChar!(C)) cannot deduce
template function from argument types !()(path,string)

Is this a bug in std.path.buildPath() or is there anything I'm doing wrong?


Re: std.path.buildPath() and string enumeration

2012-05-30 Thread nrgyzer
== Auszug aus bearophile (bearophileh...@lycos.com)'s Artikel
 nrgyzer:
  Is this a bug in std.path.buildPath() or is there anything I'm
  doing wrong?
 The signature of buildPath is:
 immutable(C)[] buildPath(C)(const(C[])[] paths...);
 But your inputs aren't of the same type. Named enum create their
 own type. You give buildPath a type string and a type path, that
 is not a string.
 There are various solutions, this compiles, but it's not very
 safe:
 buildPath(cast(string)path.log1, subDirectory);
 Another solution is to not use a named enum:
 enum : string {
  path_log1 = /var/log1,
  path_log2 = /var/log2
 }
 buildPath(path_log1, subDirectory)
 In bugzilla I have asked for an enum property that returns the
 raw valuetype of an enum.
 Bye,
 bearophile

Alright, thanks... but I want to do the following:

foreach(c; __traits(allMembers, path))
 if (!exists(mixin(path. ~ c))) mkdirRecurse(mixin(path. ~ c));

When I use a named enum, I can't use the source above... so I've to cast in the
buildPath()-method to my path enumeration or is there any other chance to
realize the foreach-loop?


Method-call based on template argument

2012-05-09 Thread nrgyzer
I'm trying to do the following:

module myModule;

int calculate(T)(int a, int b) if(T == add) {
   return a + b;
}

int calculate(T)(int a, int b) if(T == subtract) {
   return a - b;
}

But when I try to run the following code, I get template myModule.calculate
does not match any function template declaration:

void main() {

   int a = 10;
   int b = 20;
   std.stdio.writeln(calculate!(add)(a, b));
   std.stdio.writeln(calculate!(subtract)(a, b));

}

Is there any way to check if the given template argument is add or
subtract? I also tried:

int calculate(string T)(int a, int b) if(T == add) {
   return a + b;
}

int calculate(string T)(int a, int b) if(T == subtract) {
   return a - b;
}

... without any success (I'll get an instantiation error).


Re: Method-call based on template argument

2012-05-09 Thread nrgyzer
Hm... yes - works. I simply rewrote my method-header and it just works, too...
but thanks :)


Re: Nested RegEx

2012-04-24 Thread nrgyzer
== Auszug aus Dmitry Olshansky (dmitry.o...@gmail.com)'s Artikel
 On 21.04.2012 22:46, H. S. Teoh wrote:
  On Sat, Apr 21, 2012 at 09:41:18PM +0400, Dmitry Olshansky wrote:
  On 21.04.2012 21:24, nrgyzer wrote:
  Hi guys,
 
  I'm trying to use std.regex to parse a string like the following:
 
  string myString = preOuter {if condition1} content1 {if condition2}
content2
  {elseif condition3} content3 {else}any other content{/if}{/if} postOuter;
 
 
  Simply put pure regex is incapable of arbitrary-nested if-else
  statements. In a sense if... /if is a case of balanced parens
  problem and it's widely know to form non-regular language.
 
  This is of theoretical interest to me. Very often I find myself wanting
  a concise way to express patterns with nested matching delimiters, but
  regexes can't do it. But to jump to a full-blown stack-based language
  seems like an overkill to me: stack languages can express *much* more
  than just nested delimiters, most of which is difficult to encapsulate
  in a nice, concise syntax like regexes. All I want is a simple way to
  express the kind of simple nesting that matching delimiters give.
 
 Recursive descent is not particularly bad unless minimal grammar
 descent depth is high. Example:
 a+b-c
 uses a quite a lot of recursive calls for grammar with e.g. 10+ operator
 precedence levels.
 I'm thinking of merging operator precedence parser with regex might be a
 happy marriage you know.
 Back to OP topic something along the lines of this will do it (beware of
 stack overflow):
 void parseIf(){
   static int ifNest;
   if(input.startWith({if)){
   ifNest++;
   scope(exit) ifNest--;
   enforce(ifNest  1, conservative stack overflow);
   parseCond(input[2..$-1]);//regex that does condition
   enforce(input[$-1] == '}', close that if);
   parseIf();//parse body or another nested if
   //parseElse();//goes here, as does elif
   }
   else
   parseBody();// the regex you used before
 }
 
  [...]
  One day I may add push-pop stack extensions (that allow this kind of
  thing) into regex but I'd have to think hard to make it efficient.
  [...]
 
  Plus, have a nice concise syntax for it (otherwise I might as well just
  write a recursive descent parser for it in the first place).
 
 Concise syntax  lots of power is a priority actually, because I can
 detect if push-pop stuff is used or not and pick the right engine for
 the job. So different big-oh complexity is not important.

Thanks guys... I just solved the problem by using indexOf() from std.string for
parsing my if-statements. So... in principle, I can have unlimited nested if-
statements, but I think it's much more difficult (and slower) than using any
regex-expression.


Nested RegEx

2012-04-21 Thread nrgyzer
Hi guys,

I'm trying to use std.regex to parse a string like the following:

string myString = preOuter {if condition1} content1 {if condition2} content2
{elseif condition3} content3 {else}any other content{/if}{/if} postOuter;

Is there any chance to use std.regex to parse the string above? I currently
used the following expression:

auto r = regex(`(.*?)\{if:(?Pcondition(.+?))\}(?Pcontent(.*))(\{/if\})
(.*)`, g);

but it doesn't fit my nested if- and else-statements correctly.

Thanks in advance for any suggestions!


IPC: Pipes std.process

2012-02-23 Thread nrgyzer
I'm working on IPC's. I already figured out that the implementation depends on
the operation system. Is there any solution to support both - windows  posix
systems? I'm developing on a win-machine and don't want to re-write my app on
linux. As I saw on dlang.org, std.process of Phobos (prerelease) seems to
support creating pipes for both system types. So I downloaded the latest
version from https://github.com/kyllingstad/phobos/blob/new-std-process. When I
run win32.mak using make -f win32.mak, I got the following error:

Error: don't know how to make '..\druntime\lib\druntime.lib

So, I first try to build druntime.lib using win32.make and I got:

masm386 -DM_I386=1 -D_WIN32 -Mx src\rt\minit.asm;
Can't run 'masm386', check PATH

I also downloaded masm386 and I just get the following error:

dmc -c  src\rt\minit.asm
masm386 -DM_I386=1 -D_WIN32 -Mx src\rt\minit.asm;
 Assembling: src\rt\minit.asm;
MASM : fatal error A1000: cannot open file : src\rt\minit.asm;

Does anyone know how to solve this error (minit.asm exists in src\rt\) or is
there any other solution (for e.g. based on the stable version of phobos)?

Thx in advance!


Re: Socket: The connection was reset

2012-02-10 Thread nrgyzer
Works perfectly, thanks :)
But... how can I read the complete HTTP-header? When I try the following:

string header;
ubyte[1024] buffer;
while (cs.receive(buffer)) header ~= buffer;

... it works as long as the header doesn't have a length like 1024, 2048,
3072... Otherwise cs.receive() blocks forever and the server doesn't respond
anything. Is there any solution how to prevent/solve this problem?


== Auszug aus DNewbie (r...@myopera.com)'s Artikel
 Try this
   while(true) {
   Socket cs = s.accept();
   cs.receive(new byte[1024]);
   cs.sendTo(HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nHello
World);
   cs.close();
   }
 On Thu, Feb 9, 2012, at 07:31 PM, Nrgyzer wrote:
  Hi guys,
 
  I wrote the following few lines:
 
  private {
 
  import std.socket;
 
  }
 
  void main() {
 
  Socket s = new TcpSocket();
  s.bind(new InternetAddress(80));
  s.listen(0);
 
  while(true) {
 
  Socket cs = s.accept();
  cs.sendTo(HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nHello
World);
  cs.close();
 
  }
 
  s.close();
 
  }
 
  The code compiles successfully and I also the server also responses with
  Hello World, but when I reload the page I sometimes get the following
  error (Firefox): The
  connection was reset - I also often get the same error in other
  browsers. Is there anything wrong with the code?
 
  Thanks in advance!
 



Re: Socket: The connection was reset

2012-02-10 Thread nrgyzer
Yep, thanks... but I already checked out the return value and the problem is 
If the socket is blocking, receive waits until there is data to be received.. 
The following
socket blocks and the server doesn't respond:

while(true) {

Socket cs = s.accept();
ubyte[] header;
ubyte[1] buffer;
while (cs.receive(buffer)) header ~= buffer;

cs.sendTo(HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nHello World);
cs.close();

}

cs.receive() blocks (because no more data is available) - cs.sendTo() and 
cs.close() isn't called, because cs.receive() waits for more data. I can solve 
the problem by using
non-blocking sockets:

while(true) {

Socket cs = s.accept();
cs.blocking(false);
ubyte[] header;
ubyte[1] buffer;
while (cs.receive(buffer)) header ~= buffer;

cs.sendTo(HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nHello World);
cs.close();

}

But... how can I make sure that I got all data sent by the client/browser?

== Auszug aus DNewbie (r...@myopera.com)'s Artikel
 nrgyzer,
 please check the return value of 'receive'.
 http://dlang.org/phobos/std_socket.html#receive
 On Fri, Feb 10, 2012, at 02:06 PM, nrgyzer wrote:
  Works perfectly, thanks :)
  But... how can I read the complete HTTP-header? When I try the following:
 
  string header;
  ubyte[1024] buffer;
  while (cs.receive(buffer)) header ~= buffer;
 
  ... it works as long as the header doesn't have a length like 1024, 2048,
  3072... Otherwise cs.receive() blocks forever and the server doesn't
  respond
  anything. Is there any solution how to prevent/solve this problem?
 
 
  == Auszug aus DNewbie (r...@myopera.com)'s Artikel
   Try this
 while(true) {
 Socket cs = s.accept();
 cs.receive(new byte[1024]);
 cs.sendTo(HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nHello
  World);
 cs.close();
 }
   On Thu, Feb 9, 2012, at 07:31 PM, Nrgyzer wrote:
Hi guys,
   
I wrote the following few lines:
   
private {
   
import std.socket;
   
}
   
void main() {
   
Socket s = new TcpSocket();
s.bind(new InternetAddress(80));
s.listen(0);
   
while(true) {
   
Socket cs = s.accept();
cs.sendTo(HTTP/1.1 200 OK\r\nContent-Length: 
11\r\n\r\nHello
  World);
cs.close();
   
}
   
s.close();
   
}
   
The code compiles successfully and I also the server also responses with
Hello World, but when I reload the page I sometimes get the following
error (Firefox): The
connection was reset - I also often get the same error in other
browsers. Is there anything wrong with the code?
   
Thanks in advance!
   
 
 



std.stream.Stream.read([...]) matches both

2012-01-16 Thread Nrgyzer
Hi,

I used Stream.read(out float) to read bytes of my stream. It worked for 2.056,
but when I try to compile my code using 2.057 I get the following message:

((shared(float)))
matches both:
std.stream.Stream.read(out float x)
and:
std.stream.Stream.read(out real x)

Because of threading the value must be shared... but how can I solve the double
matching of the methods?

Thanks in advance!


Internal error: ..\ztc\cgcs.c 352

2011-11-22 Thread Nrgyzer
Hi guys,

I get an internal error in \ztc\cgcs.c 352 when I try to do the following:

HashMap!(uint, float[2]) example;

void main() {
   example = new HashMap!(uint, float[2])();
   example.set(0, [10.f, 20.f]);
   example.set(10, [100.f, 200.f]);

   foreach (ref c; example.keys) std.stdio.writeln(example[c][0]);
   // same result by using foreach (ref c; example.keys) std.stdio.writeln
(example.elemAt(c).front()[0]);

}

I know that dcollection is a third party library, but it seems to be an error/
bug in the latest dmd compiler (2.056). Btw... the following code works:

HashMap!(uint, float[2]) example;

void main() {
   example = new HashMap!(uint, float[2])();
   example.set(0, [10.f, 20.f]);
   example.set(10, [100.f, 200.f]);

   foreach (ref c; example.keys) {
  float[2] f = example.elemAt(c).front();
  std.stdio.writeln(f[0]);
   }

}

Can anyone confirm the error? Thanks!


shared members and castings

2011-11-12 Thread nrgyzer
Hi guys,

is there any way to use shared members without casting them? Fox example:

class Example {

private shared HashSet!(string) ex;

...

this() {
ex = cast(shared) new HashSet!(string)();
}

void write() {
foreach (ref c; cast(HashSet!(string)) ex) {
std.stdio.writeln(c);
}
}
}

Without casting, I always get some errors. My classes contains many different
collections and values, so I've many casts which makes the code at some points
a bit unclear. Is there any way to prevent the casting from/to shared objects?


Re: Insert array into an AA

2011-08-19 Thread nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Thu, 18 Aug 2011 06:47:32 -0400, nrgyzer nrgy...@gmail.com
wrote:
  == Auszug aus Robert Clipsham (rob...@octarineparrot.com)'s
Artikel
  On 16/08/2011 20:17, nrgyzer wrote:
   Hi everyone,
  
   I've the following:
  
   private static ubyte[][2][hash_t] classInstances;
  
   this() {
  
   classInstances[toHash()] = new ubyte[2]; // does not work
  
   }
  
   I want insert every class instance into the hashmap. Every
class
   instance should be contained in the map after the constructor
was
   called. When I compile my code, I get Error: cannot implicitly
   convert expression (new ubyte[](2u)) of type ubyte[] to ubyte[]
[]
   which is logical. But is there any way to insert every
instance into
   the array and define the array/map for this entry?
  
   Thanks in advance!
  Is there any particular reason you're using ubyte[][2][hash_t]
there? To
  keep a reference to each instance simply use:
  
  class MyClass {
   static MyClass[] classInstances;
   this() {
   classInstances ~= this;
   }
  }
  
  If you in fact want to have a hashmap indexed by the instances
with
  values of type ubyte[][2], you can do this:
  
  class MyClass {
   static ubyte[][2][MyClass] classInstances;
   this() {
   classInstances[this] = new ubyte[][2];
   }
  }
  
  The problem in your original code is that you were using = new
ubyte[2]
  rather than = new ubyte[][2]. Hope this helps.
 
  Ok, that works - thx.
 
  @Steve: I'll delete the entries from the map, but what's about
  overriding the toHash()-function and return a simply int value?
 If two instances return the same hash value (as is easily possible,
but
 maybe not for your context), then a collision occurs.  Then opCmp
is used
 to determine if they are actually identical.
 If you use hash_t as your key, then only one object is stored in
the map,
 the other is simply overwritten.
  I also need this map-structure for further steps in my
application. I's
  possible to change it to
 
  ubyte[][hash_t] classInstancesOne; // or ubyte[][MyClass]
  ubyte[][hash_t] classInstancesTwo; // or ubyte[][MyClass]
 
  but I thought one map for the same sense is better.
 ubyte[][Object] should work for all class types.
  Btw: I've two classes where one inherits:
 
  class MyClassOne {
 
 protected {
static __gshared {
   uint counter;
   uint[MyClassOne] fixedData;
}
uint otherData;
 
this(uint d) {
   otherData = d;
}
 }
 
 this() {
fixedData[this] = ++counter;
 }
 
 @property ref {
uint myPropOne() { return fixedData[this]; }
uint myPropTwo() { return otherData; }
 }
 
  }
 
  class MyClassTwo : MyClassOne {
 
 shared(MyClassOne) supInstance;
 
 this(uint d, MyClassOne mco) {
super(d);
supInstance = mco;
 }
 
 override ref alias supInstance.myPropOne myPropOne;
 
  }
 
  When I create an instance of MyClassOne and call myPropOne on it,
I get
  1. When I'm using this instance to create an instance of
  MyClassTwo and call myPropOne, I get 0. Is there anything I'm
doing
  wrong?
 That crazy override ref alias line, I have no idea what you're doing
 there.  For sure, override ref is not needed.
 I'm surprised all of this compiles.
  What I'm trying to do is: One super-class which contains some
fixed data
  (not inheritable) and some data which are different for each
  class.
 Note that protected does not prevent MyClassTwo from changing it.
 Also note that even though you've only created one instance of
MyClassOne,
 every MyClassTwo instance is a MyClassOne (and calls MyClassOne's
 constructor).  I think you have applied the wrong techniques to
solving
 your design.  Without knowing further your design/context, I can't
really
 help.
 -Steve

I'm working on a game where the player can build different buildings.
There are some general building-structures which defines the costs to
build it and some other things, but the name of each building can be
modified by the player. So, each building can have it's own name, but
the costs to build are always the same for each building.
To prevent the redefinition of all the property-methods, I want
redirect the properties of a simple building-property to it's
building structure. For example:

class BuildingShell {

   private float[BuildingShell] pCostsToBuild;

   protected {
  string pName;
  this(string name) {
 pName = name;
  }
   }

   this(string name, float costs) {
  pName = name;
  pCostsToBuild[this] = costs;
   }

   @property {
  ref float costsToBuild() { return pCostsToBuild[this]; }
  string name() { return pName; }
   }

}

class Building : BuildingShell {

   shared(BuildingShell) pShell;

   this(BuldingShell bs, string name) {
  super(name);
  pShell = cast(shared) bs;
   }

   override @property

Re: Insert array into an AA

2011-08-18 Thread nrgyzer
== Auszug aus Robert Clipsham (rob...@octarineparrot.com)'s Artikel
 On 16/08/2011 20:17, nrgyzer wrote:
  Hi everyone,
 
  I've the following:
 
  private static ubyte[][2][hash_t] classInstances;
 
  this() {
 
  classInstances[toHash()] = new ubyte[2]; // does not work
 
  }
 
  I want insert every class instance into the hashmap. Every class
  instance should be contained in the map after the constructor was
  called. When I compile my code, I get Error: cannot implicitly
  convert expression (new ubyte[](2u)) of type ubyte[] to ubyte[][]
  which is logical. But is there any way to insert every instance into
  the array and define the array/map for this entry?
 
  Thanks in advance!
 Is there any particular reason you're using ubyte[][2][hash_t] there? To
 keep a reference to each instance simply use:
 
 class MyClass {
  static MyClass[] classInstances;
  this() {
  classInstances ~= this;
  }
 }
 
 If you in fact want to have a hashmap indexed by the instances with
 values of type ubyte[][2], you can do this:
 
 class MyClass {
  static ubyte[][2][MyClass] classInstances;
  this() {
  classInstances[this] = new ubyte[][2];
  }
 }
 
 The problem in your original code is that you were using = new ubyte[2]
 rather than = new ubyte[][2]. Hope this helps.

Ok, that works - thx.

@Steve: I'll delete the entries from the map, but what's about overriding the 
toHash()-function and return a simply int value?
I also need this map-structure for further steps in my application. I's 
possible to change it to

ubyte[][hash_t] classInstancesOne; // or ubyte[][MyClass]
ubyte[][hash_t] classInstancesTwo; // or ubyte[][MyClass]

but I thought one map for the same sense is better.

Btw: I've two classes where one inherits:

class MyClassOne {

   protected {
  static __gshared {
 uint counter;
 uint[MyClassOne] fixedData;
  }
  uint otherData;

  this(uint d) {
 otherData = d;
  }
   }

   this() {
  fixedData[this] = ++counter;
   }

   @property ref {
  uint myPropOne() { return fixedData[this]; }
  uint myPropTwo() { return otherData; }
   }

}

class MyClassTwo : MyClassOne {

   shared(MyClassOne) supInstance;

   this(uint d, MyClassOne mco) {
  super(d);
  supInstance = mco;
   }

   override ref alias supInstance.myPropOne myPropOne;

}

When I create an instance of MyClassOne and call myPropOne on it, I get 1. 
When I'm using this instance to create an instance of
MyClassTwo and call myPropOne, I get 0. Is there anything I'm doing wrong?
What I'm trying to do is: One super-class which contains some fixed data (not 
inheritable) and some data which are different for each
class.


Insert array into an AA

2011-08-16 Thread nrgyzer
Hi everyone,

I've the following:

private static ubyte[][2][hash_t] classInstances;

this() {

   classInstances[toHash()] = new ubyte[2]; // does not work

}

I want insert every class instance into the hashmap. Every class
instance should be contained in the map after the constructor was
called. When I compile my code, I get Error: cannot implicitly
convert expression (new ubyte[](2u)) of type ubyte[] to ubyte[][]
which is logical. But is there any way to insert every instance into
the array and define the array/map for this entry?

Thanks in advance!


Read property using std.stream.Stream.read

2011-08-13 Thread nrgyzer
Hi guys,

I'm trying to read a property of a class like:

class MyClass {

   private ubyte pToRead;

   @property ubyte toRead() { return pToRead; }

}

...
File f = new File(...);
MyClass c = new MyClass();
f.read(c.toRead);
...

but when I compile my code, I always get:

executable.d(389): Error: function std.stream.Stream.read (ubyte[]
buffer) is not callable using argument types (ubyte)
executable.d(389): Error: cannot implicitly convert expression
(c.toRead()) of type ubyte to wchar[]


Re: Read property using std.stream.Stream.read

2011-08-13 Thread nrgyzer
== Auszug aus nrgyzer (nrgy...@gmail.com)'s Artikel
 Hi guys,
 I'm trying to read a property of a class like:
 class MyClass {
private ubyte pToRead;
@property ubyte toRead() { return pToRead; }
 }
 ...
 File f = new File(...);
 MyClass c = new MyClass();
 f.read(c.toRead);
 ...
 but when I compile my code, I always get:
 executable.d(389): Error: function std.stream.Stream.read (ubyte[]
 buffer) is not callable using argument types (ubyte)
 executable.d(389): Error: cannot implicitly convert expression
 (c.toRead()) of type ubyte to wchar[]

Answering my own question ;D - I solved it by adding ref to my
property like:

@property ref ubyte toRead() { return pToRead; }


exe-Icon

2011-08-01 Thread Nrgyzer
Hi guys,

the most applications using there own icons for the exe-file. I'm
currently using external tools to set my own icon for the exe, but is
there any chance to automatically set the icon using the dmd compiler?


Re: exe-Icon

2011-08-01 Thread Nrgyzer
== Auszug aus Jimmy Cao (jcao...@gmail.com)'s Artikel
 --0015174780ae3c394704a9748211
 Content-Type: text/plain; charset=ISO-8859-1
 Yes, add it as an ICON resource.
 In a .rc file:
 100 ICON icon.ico
 Then compile the resource file with your favorite resource compiler.
 Then pass the .res file as an argument to dmd.
 On Mon, Aug 1, 2011 at 10:27 AM, Nrgyzer nrgy...@gmail.com wrote:
  Hi guys,
 
  the most applications using there own icons for the exe-file. I'm
  currently using external tools to set my own icon for the exe,
but is
  there any chance to automatically set the icon using the dmd
compiler?
 
 --0015174780ae3c394704a9748211
 Content-Type: text/html; charset=ISO-8859-1
 Content-Transfer-Encoding: quoted-printable
 Yes, add it as an ICON resource.divIn a .rc file:brblockquote
class=3D=
 webkit-indent-blockquote style=3Dmargin: 0 0 0 40px; border:
none; paddi=
 ng: 0px;divspan class=3DApple-style-span style=3Dfont-
family: Monac=
 o, #39;DejaVu Sans Mono#39;, #39;Bitstream Vera Sans Mono#39;,
#39;Luc=
 ida Console#39;, monospace; font-size: 12px; white-space: pre;
background-=
 color: rgb(255, 255, 255); 100 ICON quot;icon.icoquot;/span/
div
 /blockquotedivdivThen compile the resource file with your
favorite re=
 source compiler./divdivThen pass the .res file as an argument
to dmd./=
 divdivbrdiv class=3Dgmail_quoteOn Mon, Aug 1, 2011 at
10:27 AM, Nr=
 gyzer span dir=3Dltrlt;a
href=3Dmailto:nrgy...@gmail.com;nrgyzer@gm=
 ail.com/agt;/span wrote:br
 blockquote class=3Dgmail_quote style=3Dmargin:0 0 0 .8ex;border-
left:1p=
 x #ccc solid;padding-left:1ex;Hi guys,br
 br
 the most applications using there own icons for the exe-file.
I#39;mbr
 currently using external tools to set my own icon for the exe, but
isbr
 there any chance to automatically set the icon using the dmd
compiler?br
 /blockquote/divbr/div/div/div
 --0015174780ae3c394704a9748211--

Works - thanks :)


Re: Sending messages using socket

2011-07-25 Thread nrgyzer
== Auszug aus Adam Ruppe (destructiona...@gmail.com)'s Artikel
 Browsers speak HTTP, which is a higher level protocol than
 plain sockets.
 If you connect to your app with a simpler program, like nc,
 you'll probably see the message.
 If you want to serve web pages, consider one of these options:
 a) Looking up the HTTP protocol itself. You've gotta send headers
 before you send data or the browser won't understand what you are
 replying to.
 b) Use an existing web server, like Apache, and write your app as
 a cgi program
 The HTTP headers you need to send on a plain socket look like this:
 =
 HTTP/1.0 200 OK
 Content-Length: 11
 Content-Type: text/html
 hello world
 =
 instead of just plain hello world.

The message exchange works, but I've some trouble in getting the messages 
correctly. I've the following, small apps:

module server;

import std.socket;
import std.stream;
import std.socketStream;

void main() {

TcpSocket s = new TcpSocket();
s.bind(new InternetAddress(5088));
s.listen(1);

while(true) {

Socket a = s.accept();
SocketStream cs = new SocketStream(a);

string response = HELLO WORLD!;
cs.writeBlock(response.ptr, response.length);

a.close();

}

}

module client;

import std.socket;
import std.math;
import std.stream;
import std.socketStream;
import std.stdio : writeln;

void main() {

TcpSocket s = new TcpSocket();
s.connect(new InternetAddress(127.0.0.1, 5088));

while(true) {

void[] msg;
SocketStream cs = new SocketStream(s);
cs.readBlock(msg.ptr, 12);
writeln(msg);

}

}

But... when I start the server and client, I don't get any response/and or my 
message is empty. When I use the simply methods of streams
(like write()), it works but the problem is, that the following will end in an 
endless loop:

module client;

import std.socket;
import std.math;
import std.stream;
import std.socketStream;
import std.stdio : writeln;

void main() {

TcpSocket s = new TcpSocket();
s.connect(new InternetAddress(127.0.0.1, 5088));

while(true) {

uint len;
string msg;
SocketStream cs = new SocketStream(s);
while(!cs.eof()) { // this loop repeats forever, although the 
stream is empty
cs.read(len);
cs.readString(msg, len);
}

}

}


Sending messages using socket

2011-07-24 Thread nrgyzer
Hi guys,

I'm trying to work with sockets but I've some trouble with them. I
implemented a really simple Socket which should simply send a text
message after accepting the request. My code is the following:

module server;

import std.socket;

void main() {

TcpSocket server = new TcpSocket();
server.bind(new InternetAddress(8080));
server.listen(1);

while(true) {
Socket cs = server.accept();
cs.send(test);
}

}

When I start my small sample application and tries to connect (http://
localhost:8080) to them using a browser I don't get any message. It
seems to work forever and sometimes I get my message test, but the
connection between my browser and my application won't finished.
When I add cs.close() after cs.send(test), the connection will be
closed, but I don't get any message in my browser - the browser says
that the service isn't available (error-page).

What's wrong with my code? = Thanks for any help :)


Re: Sending messages using socket

2011-07-24 Thread nrgyzer
== Auszug aus Adam Ruppe (destructiona...@gmail.com)'s Artikel
 Browsers speak HTTP, which is a higher level protocol than
 plain sockets.
 If you connect to your app with a simpler program, like nc,
 you'll probably see the message.
 If you want to serve web pages, consider one of these options:
 a) Looking up the HTTP protocol itself. You've gotta send headers
 before you send data or the browser won't understand what you are
 replying to.
 b) Use an existing web server, like Apache, and write your app as
 a cgi program
 The HTTP headers you need to send on a plain socket look like this:
 =
 HTTP/1.0 200 OK
 Content-Length: 11
 Content-Type: text/html
 hello world
 =
 instead of just plain hello world.

Great - works, thanks :)


Re: Runtime evaluation

2011-07-09 Thread nrgyzer
== Auszug aus Mafi (m...@example.org)'s Artikel
 Am 07.07.2011 23:23, schrieb nrgyzer:
  Hi guys,
 
  I'm trying to read a string from a text file which contains a
value of an enumeration like:
 
  enum MyEnum : string {
  Entry_1 = abc,
  Entry_2 = def,
  Entry_3 = ghi,
  }
 
  Stream s = new File(myFile.ext, FileMode.In);
  uint len;
  s.read(len);
  string entry = cast(string) s.readString(len);
  s.close();
 
  writeln(mixin(MyEnum. ~ entry));
 
  myFile.ext may contain:
  ...
  Entry_2
  Entry_1
  Entry_2
  Entry_3
  ...
 
  But mixin's are for compile time only... is there any chance to
do this or do I've to use another method (like if/else or switch/
case):
 
  if (entry == Entry_1) ...
  else if (entry == Entry_2) ...
  ...
 
  Thanks a lot!
 Metaprogramming is the keyword but you don't have to do it yourself.
 Just use std.conv.to!MyEnum(string_without_the prefix).
 Mafi

Thanks Mafi, exactly what I'm looking for :)


Runtime evaluation

2011-07-07 Thread nrgyzer
Hi guys,

I'm trying to read a string from a text file which contains a value of an 
enumeration like:

enum MyEnum : string {
   Entry_1 = abc,
   Entry_2 = def,
   Entry_3 = ghi,
}

Stream s = new File(myFile.ext, FileMode.In);
uint len;
s.read(len);
string entry = cast(string) s.readString(len);
s.close();

writeln(mixin(MyEnum. ~ entry));

myFile.ext may contain:
...
Entry_2
Entry_1
Entry_2
Entry_3
...

But mixin's are for compile time only... is there any chance to do this or do 
I've to use another method (like if/else or switch/case):

if (entry == Entry_1) ...
else if (entry == Entry_2) ...
...

Thanks a lot!


Int within ranges

2011-06-13 Thread nrgyzer
Hi there,

is there any possibility to get a sliced array from another array
between two ranges like:

int[uint] myArray;
myArray[10] = 1000;
myArray[20] = 2000;
myArray[30] = 3000;
myArray[40] = 4000;
myArray[50] = 5000;

int[] newArray = myArray[= 20 .. = 40]; // not able to do this
writeln(newArray); // should print [2000, 3000, 4000]

Is there any way to do this?


Re: Int within ranges

2011-06-13 Thread nrgyzer
 On Mon, 13 Jun 2011 12:15:40 -0400, nrgyzer nrgy...@gmail.com
wrote:
  Hi there,
 
  is there any possibility to get a sliced array from another array
  between two ranges like:
 
  int[uint] myArray;
  myArray[10] = 1000;
  myArray[20] = 2000;
  myArray[30] = 3000;
  myArray[40] = 4000;
  myArray[50] = 5000;
 
  int[] newArray = myArray[= 20 .. = 40]; // not able to do this
  writeln(newArray); // should print [2000, 3000, 4000]
 
  Is there any way to do this?
 import dcollections.TreeMap;
 auto myArray = new TreeMap!(uint, int);
 myArray[10] = 1000;
 myArray[20] = 2000;
 myArray[30] = 3000;
 myArray[40] = 4000;
 myArray[50] = 5000;
 // this is a little kludgy, but necessary since you require = 40
 auto c = myArray.elemAt(40);
 c.popFront();
 int newArray = array(myArray[20..c]);
 Note two things:
 1. int[uint] is a hash, and so has no particular order.  Therefore,
there
 is no guarantee of iteration order, or that a range of such a
container
 (if one existed) would be properly constructed with two keys.  A
TreeMap,
 or RedBlackTree, is sorted, and so the order is guaranteed.
 2. dcollections.TreeMap is implemented with the same collection as
 std.container.RedBlackTree, so you could potentially do the same
thing
 with it.  But the dcollections.TreeMap API is more polished.
 -Steve

Exactly what I'm looking for, but how can I realize that it also
gives me the elements when the key doesn't exists like:

import std.range;
import dcollections.TreeMap;

auto myArray = new TreeMap!(uint, int);

myArray[10] = 1000;
myArray[20] = 2000;
myArray[30] = 3000;
myArray[45] = 4500;
myArray[50] = 5000;

auto c = myArray.elemAt(40);
c.popFront();
int[] newArray = array(myArray[20..c]);
writeln(newArray);

This will throw an exception because element 40 doesn't exist. Is
there any possibility to get the element 20 and 30 from this map?


Re: Int within ranges

2011-06-13 Thread nrgyzer
 On Mon, 13 Jun 2011 14:52:24 -0400, nrgyzer nrgy...@gmail.com
wrote:
  On Mon, 13 Jun 2011 12:15:40 -0400, nrgyzer nrgy...@gmail.com
  wrote:
   Hi there,
  
   is there any possibility to get a sliced array from another
array
   between two ranges like:
  
   int[uint] myArray;
   myArray[10] = 1000;
   myArray[20] = 2000;
   myArray[30] = 3000;
   myArray[40] = 4000;
   myArray[50] = 5000;
  
   int[] newArray = myArray[= 20 .. = 40]; // not able to do
this
   writeln(newArray); // should print [2000, 3000, 4000]
  
   Is there any way to do this?
  import dcollections.TreeMap;
  auto myArray = new TreeMap!(uint, int);
  myArray[10] = 1000;
  myArray[20] = 2000;
  myArray[30] = 3000;
  myArray[40] = 4000;
  myArray[50] = 5000;
  // this is a little kludgy, but necessary since you require = 40
  auto c = myArray.elemAt(40);
  c.popFront();
  int newArray = array(myArray[20..c]);
  Note two things:
  1. int[uint] is a hash, and so has no particular order.
Therefore,
  there
  is no guarantee of iteration order, or that a range of such a
  container
  (if one existed) would be properly constructed with two keys.  A
  TreeMap,
  or RedBlackTree, is sorted, and so the order is guaranteed.
  2. dcollections.TreeMap is implemented with the same collection
as
  std.container.RedBlackTree, so you could potentially do the same
  thing
  with it.  But the dcollections.TreeMap API is more polished.
  -Steve
 
  Exactly what I'm looking for, but how can I realize that it also
  gives me the elements when the key doesn't exists like:
 
  import std.range;
  import dcollections.TreeMap;
 
  auto myArray = new TreeMap!(uint, int);
 
  myArray[10] = 1000;
  myArray[20] = 2000;
  myArray[30] = 3000;
  myArray[45] = 4500;
  myArray[50] = 5000;
 
  auto c = myArray.elemAt(40);
  c.popFront();
  int[] newArray = array(myArray[20..c]);
  writeln(newArray);
 
  This will throw an exception because element 40 doesn't exist. Is
  there any possibility to get the element 20 and 30 from this map?
 It might be useful to have elemAt return an empty range that is
located at
 the place the element *would* be.
 When this code was first written, in order to detect whether elemAt
found
 your element, you compared it to container.end (similar to C++'s
STL).
 But now that cursors are tiny ranges, and have an empty property, I
can
 use that to indicate the element wasn't exactly found.  So I can
change
 the semantics to find the place the element *would* be.
 myArray[20..41];
 and it will find all elements = 20 and  41, regardless of whether
20 and
 41 were valid elements.
 Hm... can you post this as an enhancement to dcollections so it's
not
 forgotten?
 http://www.dsource.org/projects/dcollections/newticket
 -Steve

Thanks! I created a new ticket... by the way - is there any bug in
DMD 2.053 by using my own opCmp? The following code throws me an
HiddenFuncException:

private import std.stdio : writeln;

class Example {

int pId;

this(int id) {

pId = id;

}

int opCmp(ref Example other) {

return pId - other.pId;

}

}

int main(string[] args) {

Example[] exps;
exps ~= new Example(1);
exps ~= new Example(2);
writeln(exps.sort);

return 1;

}


Re: Int within ranges

2011-06-13 Thread nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Mon, 13 Jun 2011 15:44:01 -0400, nrgyzer nrgy...@gmail.com
wrote:
  On Mon, 13 Jun 2011 14:52:24 -0400, nrgyzer nrgy...@gmail.com
  wrote:
   On Mon, 13 Jun 2011 12:15:40 -0400, nrgyzer
nrgy...@gmail.com
   wrote:
Hi there,
   
is there any possibility to get a sliced array from another
  array
between two ranges like:
   
int[uint] myArray;
myArray[10] = 1000;
myArray[20] = 2000;
myArray[30] = 3000;
myArray[40] = 4000;
myArray[50] = 5000;
   
int[] newArray = myArray[= 20 .. = 40]; // not able to do
  this
writeln(newArray); // should print [2000, 3000, 4000]
   
Is there any way to do this?
   import dcollections.TreeMap;
   auto myArray = new TreeMap!(uint, int);
   myArray[10] = 1000;
   myArray[20] = 2000;
   myArray[30] = 3000;
   myArray[40] = 4000;
   myArray[50] = 5000;
   // this is a little kludgy, but necessary since you require
= 40
   auto c = myArray.elemAt(40);
   c.popFront();
   int newArray = array(myArray[20..c]);
   Note two things:
   1. int[uint] is a hash, and so has no particular order.
  Therefore,
   there
   is no guarantee of iteration order, or that a range of such a
   container
   (if one existed) would be properly constructed with two
keys.  A
   TreeMap,
   or RedBlackTree, is sorted, and so the order is guaranteed.
   2. dcollections.TreeMap is implemented with the same
collection
  as
   std.container.RedBlackTree, so you could potentially do the
same
   thing
   with it.  But the dcollections.TreeMap API is more polished.
   -Steve
  
   Exactly what I'm looking for, but how can I realize that it
also
   gives me the elements when the key doesn't exists like:
  
   import std.range;
   import dcollections.TreeMap;
  
   auto myArray = new TreeMap!(uint, int);
  
   myArray[10] = 1000;
   myArray[20] = 2000;
   myArray[30] = 3000;
   myArray[45] = 4500;
   myArray[50] = 5000;
  
   auto c = myArray.elemAt(40);
   c.popFront();
   int[] newArray = array(myArray[20..c]);
   writeln(newArray);
  
   This will throw an exception because element 40 doesn't exist.
Is
   there any possibility to get the element 20 and 30 from this
map?
  It might be useful to have elemAt return an empty range that is
  located at
  the place the element *would* be.
  When this code was first written, in order to detect whether
elemAt
  found
  your element, you compared it to container.end (similar to C++'s
  STL).
  But now that cursors are tiny ranges, and have an empty
property, I
  can
  use that to indicate the element wasn't exactly found.  So I can
  change
  the semantics to find the place the element *would* be.
  myArray[20..41];
  and it will find all elements = 20 and  41, regardless of
whether
  20 and
  41 were valid elements.
  Hm... can you post this as an enhancement to dcollections so it's
  not
  forgotten?
  http://www.dsource.org/projects/dcollections/newticket
  -Steve
 
  Thanks! I created a new ticket... by the way - is there any bug in
  DMD 2.053 by using my own opCmp? The following code throws me an
  HiddenFuncException:
 
  private import std.stdio : writeln;
 
  class Example {
 
  int pId;
 
  this(int id) {
 
  pId = id;
 
  }
 
  int opCmp(ref Example other) {
 The signature of this function must be
 int opCmp(Object other)
 Note, also, that ref is unnecessary, as all objects (i.e. class
instances)
 are passed by reference.
 -Steve

Works, thanks for all that!


Re: Interface/abstract constructors

2011-05-16 Thread nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Mon, 16 May 2011 15:32:43 -0400, useo unkn...@unknown.com
wrote:
  Hey guys,
 
  is there any chance to create an abstract constructor like:
 
  abstract class ABC {
 
 abstract this();
 
  }
 
  DMD always says ...this non-virtual functions cannot be
abstract -
  when I use an interface like:
 
  interface ABC {
 
 this();
 
  }
 
  I get a similar error: ...constructors, destructors, postblits,
  invariants, unittests, new and delete functions are not allowed in
  interface ABC
 
  Is there any solution or is it possible to create such
inheritances
  in DMD?
 I think what you are trying to do is say, if a class implements
interface
 ABC, it must have a default constructor.  Such a requirement is
faulty.
 The point of an interface is to able to pass a portion of a class'
 functionality to a function during runtime.  However, the instance
must
 *already exist*.  It makes no sense to posit requirements on the
 constructor.
 What you want is a compile-time requirement using a template
constraint.
 You may think damn, but I don't want to make my function a
template, I'd
 say see previous point ;)
 -Steve

Okay, thanks... perhaps someone know a better solution: I have one
big file which contains some other files (let's say: blocks). Each
block has it's own signature... by reading the big file, I read the
signature of each block. Based on the signature, I read block A,
block B or another Block. To do that, I want call the block-specific
constructor which reads the next bytes.

!Semicode:

...
ABC[] blocks;
...
while (!eof(bigfile)) {
  read(signature);
  if (signature==A) blocks ~= new A(bigfile);
  else if (signature==B) blocks ~= new B(bigfile);
  ...
}
...


Re: Interface/abstract constructors

2011-05-16 Thread nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Mon, 16 May 2011 16:12:05 -0400, nrgyzer nrgy...@gmail.com
wrote:
  == Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
  On Mon, 16 May 2011 15:32:43 -0400, useo unkn...@unknown.com
  wrote:
   Hey guys,
  
   is there any chance to create an abstract constructor like:
  
   abstract class ABC {
  
  abstract this();
  
   }
  
   DMD always says ...this non-virtual functions cannot be
  abstract -
   when I use an interface like:
  
   interface ABC {
  
  this();
  
   }
  
   I get a similar error: ...constructors, destructors,
postblits,
   invariants, unittests, new and delete functions are not
allowed in
   interface ABC
  
   Is there any solution or is it possible to create such
  inheritances
   in DMD?
  I think what you are trying to do is say, if a class implements
  interface
  ABC, it must have a default constructor.  Such a requirement is
  faulty.
  The point of an interface is to able to pass a portion of a
class'
  functionality to a function during runtime.  However, the
instance
  must
  *already exist*.  It makes no sense to posit requirements on the
  constructor.
  What you want is a compile-time requirement using a template
  constraint.
  You may think damn, but I don't want to make my function a
  template, I'd
  say see previous point ;)
  -Steve
 
  Okay, thanks... perhaps someone know a better solution: I have one
  big file which contains some other files (let's say: blocks). Each
  block has it's own signature... by reading the big file, I read
the
  signature of each block. Based on the signature, I read block A,
  block B or another Block. To do that, I want call the block-
specific
  constructor which reads the next bytes.
 
  !Semicode:
 
  ...
  ABC[] blocks;
  ...
  while (!eof(bigfile)) {
read(signature);
if (signature==A) blocks ~= new A(bigfile);
else if (signature==B) blocks ~= new B(bigfile);
...
  }
  ...
 No special requirements are necessary.  How would this compile if A
or B
 did not have a bigfile constructor?  The interface specification is
not
 needed.
 If D supported runtime reflection (and it does to a very very small
 degree), then you could use it to ensure the correct constructor is
 available.
 -Steve

It's semicode, so I haven't try to implement it... it should only
show what I'm trying to do.
I'm currently thinking about an empty constructor in an abstract
class like:

abstract class ABC {
   this(Stream) {
  // do nothing
   }
}

class A : ABC {

   this(Stream s) {
  super(s);
  // read my block-specific bytes
   }

}


Re: toHash() and Interfaces

2011-05-06 Thread Nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Thu, 05 May 2011 17:03:51 -0400, Nrgyzer nrgy...@gmail.com
wrote:
  Hey guys,
 
  I'm trying to call toHash() in a class which receives an interface
  class as input param. But I always get Error: no property
'toHash'
  for type
 
  My code looks like:
 
  module iFBlock;
 
  private {
 import std.stream;
  }
 
  interface IFBlock {
 public {
void write(Stream);
 }
  }
 
  module myFile;
 
  private {
 import iFBlock;
  }
 
  class MyFile {
 private {
 IFBlock[hash_t] pBlocks;
 }
 public {
 void addBlock(IFBlock b) {
 pBlocks[b.toHash()] = b;
 }
 }
  }
 
  Is there any chance to get the hash of the FBlock-interface?
 (cast(Object)b).toHash()
 D has this horrible notion that any interface can be for a COM
object,
 even though COM interfaces can only inherit from IUnknown (known
 statically).  Therefore, interfaces that don't inherit from
IUnknown are
 not considered Objects, even though they could and should be.
 So you have to manually cast an interface to Object in order to
call an
 Object function.
 -Steve

Ah, okay - a bit dirty solution, but it works, thanks!


toHash() and Interfaces

2011-05-05 Thread Nrgyzer
Hey guys,

I'm trying to call toHash() in a class which receives an interface
class as input param. But I always get Error: no property 'toHash'
for type

My code looks like:

module iFBlock;

private {
   import std.stream;
}

interface IFBlock {
   public {
  void write(Stream);
   }
}

module myFile;

private {
   import iFBlock;
}

class MyFile {
   private {
   IFBlock[hash_t] pBlocks;
   }
   public {
   void addBlock(IFBlock b) {
   pBlocks[b.toHash()] = b;
   }
   }
}

Is there any chance to get the hash of the FBlock-interface?

Thanks in advance!


Re: Assertion failure: '!vthis-csym' on line 703 in file 'glue.c'

2011-03-27 Thread nrgyzer
== Auszug aus David Nadlinger (s...@klickverbot.at)'s Artikel
 On 3/26/11 11:08 PM, bearophile wrote:
  I suggest to copy your code, and then keep removing lines from
your copy, making sure it keep showing the same compiler error. In
some time you will probably be able to produce a small program, fit
for this newsgroup or even for Bugzilla. (There are tools to do this
reduction automatically in Python, I think).
 You don't necessarily need fancy tools to do that – as I recently
 pointed out in another thread, the Tigris »delta« tool worked
fine for
 me on several occasions (http://delta.tigris.org/). Just write a
simple
 shell script looking for the error message in the compiler output,
and
 delta will try to automatically reduce the file for you.
 There is some room for improvement though when you have an actual
 lexer/parser available for heuristically determining what pieces of
code
 to delete – this might be a nice demonstration project for a D
parsing
 library.
 David

I figured out what produces the error - import
dcollections.LinkList; (declared as private) in one source file. But
I'm still unable to reproduce that error in a sample-application.
What I currently can say, that I have two source files like:

module firstModule;

private {
   import dcollections.LinkList;
   LinkList!(uint) myPrivateList;
}

static this() {
   myPrivateList = new LinkList!(uint);
}

module secondModule;

import firstModule;
import dcollections.LinkList;

LinkList!(uint) list;

void main(string[] args) {
   list = new LinkList!(uint);
}

In my tests, that code above doesn't produces the assertion failure,
but my original source code looks very similar.


Re: Assertion failure: '!vthis-csym' on line 703 in file 'glue.c'

2011-03-27 Thread nrgyzer
== Auszug aus bearophile (bearophileh...@lycos.com)'s Artikel
 nrgyzer:
  In my tests, that code above doesn't produces the assertion
failure,
  but my original source code looks very similar.
 You may have to start over then. I suggest to duplicate the whole
code, and then start on the copied version removing modules and lines
of code, compiling it every time you remove something, making sure
you keep seeing the error message every time, and undoing the change
when you see the error vanish or change.
 Bye,
 bearophile

That's a bit mysterious... I replaced firstModule with the source
which produces the error. Now... when I run my test application, I
get the same failure - but... that's not all - when I restore
firstModule to the version which didn't produce the failure, I just
get the same error. When I copy the source files to a new location
and compile it, I didn't get the error.
It seems that there is anything like a cache, but I removed all
produced (obj, rsp...) files, expect the exe- and d-files. Thus I
think there should be something like a cache.
I currently haven't any idea what I can do to reproduce the failure
efficently.


Assertion failure: '!vthis-csym' on line 703 in file 'glue.c'

2011-03-26 Thread nrgyzer
Hey guys,

I got Assertion failure: '!vthis-csym' on line 703 in file 'glue.c'
after I add LinkList!(uint) myList; to my source file. I figured out
that the same bug was already reported on http://lists.puremagic.com/
pipermail/digitalmars-d-bugs/2010-October/019237.html
Ticket 4129 describes a bug in glue.c but for DMD 1.x and I'm using DMD
2.052. I can't also reproduce the error in other projects - it seems
that it only exists in this project. In this case I think it makes no
sense to post thousand lines of code. Thus I hope anyone know what can
be wrong = thanks!


Read file/stream

2011-03-11 Thread nrgyzer
I'm trying to read a png file and I'm having some trouble with the
chunk-size. Each chunk of a png file begins with a 4 byte (unsigned)
integer. When I read this 4 byte integer (uint) I get an absolutely
incorrect length. My code currently looks like:

void main(string args) {

   File f = new File(test.png, FileMode.In);

   // png signature
   ubyte[8] buffer;
   f.read(buffer);

   // first chunk (IHDR)
   uint size;
   f.read(size);

   f.close();
}

When I run my code, I get 218103808 instead of 13 (decimal) or 0x0D
(hex). When I try to read the 4 byte integer as a ubyte[4]-array, I
get [0, 0, 0, 13] where 13 seems to be the correct ones because my
hex-editor says [0x00 0x00 0x00 0x0D] for these 4 bytes.

I hope anyone know where my mistake is. Thanks!


Re: OpenGL in D2

2011-02-23 Thread Nrgyzer
== Auszug aus Sequ (u...@example.net)'s Artikel
 Quoted from Nrgyzer:
  On windows you've to create a folder called lib
  before you run the command above - I currently
  can't say it exactly if it's needed on linux, too.
 I did need to create a 'lib' directory before running 'make -
flinux.mak DC=dmd'.
  After it compiled, you can copy all the created
  lib-files to the lib-folder
 My 'lib' folder was in /usr/lib, although that folder didn't
contain 'phobos.lib',
 but 'libphobos2.a'. Hopefully that works correctly.
  Copy the content of the import-dir to a
  location where you've all your binding for D
 For now, I've just copied it into an 'import' folder in the same
folder as my
 source code. I suspect the correct directory is '/usr/include/d/dmd/
druntime/import'.
 I got an SDL example working by then using the command:
 dmd -L-lDerelictGL -L-lDerelictGLU -L-lDerelictUtil -L-lDerelictSDL
test_sdl.d
 but unfortunately I couldn't get my example working, because it
requires GLUT and
 the derelict library doesn't have that included. I'd actually
prefer to use GLUT
 and also, eventually, other obscure C libraries that I know no-one
else would have
 ported, but I suppose I'll take a look at the links provided in
Trass3r's post
 before asking more about that.

As I know, GLUT was also ported (http://www.yage3d.net/host/
derelict.glut.zip). I also tried it with DMD and Derelict - both V1,
but I can't get it to work. I think the mistake was on my own, but I
didn't spend them much time. The binding is from 2006 (or 2007) and
for those I don't suggest you to use it, especially I think it
doesn't work with DMD 2 and/or Derelict 2.

  I hope this helped :)
 Thanks, yes that was quite helpful!
 Quoted from Dmitry Olshansky:
  Sadly your file goes like rubbish for me, is
  that base64 ?
 Yeah, I see it turned out odd, but I'm using the web interface to
post here (it
 seems my Thunderbird in the Lab can't access the news server from
behind all the
 firewalls - or something). The file is actually just one of the
first examples
 from the OpenGL tutorials.



Re: Read non-UTF8 file

2011-02-22 Thread Nrgyzer
== Auszug aus Stewart Gordon (smjg_1...@yahoo.com)'s Artikel
 What compiler version/platform are you using?  I had to fix some errors 
 before it would
 compile on mine (1.066/2.051 Windows).
 On 19/02/2011 13:42, Nrgyzer wrote:
 snip
  Now... and with writefln(%s, cast(ubyte[]) convertToUTF8(f.readLine())); 
  I get the following:
 
  [195, 131, 164]
  [195, 131, 182]
  [195, 131, 188]
 It took a while for me to make sense of what's going on!
 The expressions (0xC0 | (ch  6)) and (0x80 | (ch  0x3F)) both have type 
 int.  It
 appears that, in D2, if you append an int to a string then it treats the int 
 as a Unicode
 codepoint and automagically converts it to UTF-8.  But why is it doing it on 
 the first
 byte and not the second?  This looks like a bug.
 Casting each UTF-8 byte value to a char
  if (ch  0x80) {
  result ~= cast(char) ch;
  } else {
  result ~= cast(char) (0xC0 | (ch  6));
  result ~= cast(char) (0x80 | (ch  0x3F));
  }
 gives the expected output
 [195, 164]
 [195, 182]
 [195, 188]
 HTH
 Stewart.

I also wondered because I've used the same code in D1 and it worked without any 
problems. Anyway... thanks :)


Re: OpenGL in D2

2011-02-21 Thread Nrgyzer
== Auszug aus Siqu (u...@example.net)'s Artikel
 Hi,
 I'm trying to figure out how I could get a simple OpenGL/GLUT
program working
 in DMD2. As an attachment, I've added a C version of what I'd like
to do. I'd
 compile the C version using:
 gcc simple.c -lglut -lGLU -o simple
 I've found a few OpenGL projects, like bindings
 (http://www.dsource.org/projects/bindings/) and derelict
 (http://www.dsource.org/projects/derelict/), but I still can't find
any way to
 easily use or install them (for D2 on Ubuntu). I'd have thought
that, since D
 interfaces so well with C, just using C libraries wouldn't require
specific
 wrapper libraries, but it seems an automated method for converting
C headers
 to D isn't currently possible?
 Anyway, any help would be appreciated,
 Thanks.
   simple.c 

I'm using derelict, primary on windows, but I've also a running
version on Ubuntu.
You can download derelict at http://www.dsource.org/projects/derelict/
changeset/525/branches/Derelict2?old_path=%2Fformat=zip

I think you've already a running version of the dmd-compiler? If yes,
you can simply extract the package, open your shell browse to the
extracted folder and run make -flinux.mak DC=dmd which worked for
me on windows and linux (make sure you've installed make and dmd is
in your environment-values). On windows you've to create a folder
called lib before you run the command above - I currently can't say
it exactly if it's needed on linux, too.
After it compiled, you can copy all the created lib-files to the lib-
folder (I think this should be /usr/lib or something like this - run
find / -name 'phobos.lib' and copy the lib-files to the same
directory where phobos.lib is located. Copy the content of the
import-dir to a location where you've all your binding for D, so
that you can simply use import derelict.sdl.sdl or similar.

When you've installed it correctly, you can use derelict/opengl like
described on the derelict site. Note that you have to use 'pragma
(lib, DerelictSDL)' or similar to use the binding. It is also
important the you insert 'pragma(lib, dl)' in you source that you
can compile it successfully.

I hope this helped :)


Re: Read non-UTF8 file

2011-02-20 Thread Nrgyzer
== Auszug aus spir (denis.s...@gmail.com)'s Artikel
 On 02/19/2011 02:42 PM, Nrgyzer wrote:
  == Auszug aus Stewart Gordon (smjg_1...@yahoo.com)'s Artikel
  On 13/02/2011 21:49, Nrgyzer wrote:
  snip
  It compiles and works as long as the returned char-array/string
of f.readLine() doesn't
  contain non-UTF8 character(s). If it contains such chars,
writeln() doesn't write
  anything to the console. Is there any chance to read such files?
  Please post sample input that shows the problem, and the output
generated by replacing the
  writeln call with
writefln(%s, cast(ubyte[]) convertToUTF8(f.readLine()));
  so that we can see what it is actually reading in.
  Stewart.
 
  My file contains the following:
 
  �
  �
  �
 
  Now... and with writefln(%s, cast(ubyte[])
convertToUTF8(f.readLine())); I get the following:
 
  [195, 131, 164]
  [195, 131, 182]
  [195, 131, 188]
 At first sight, I find your input strange. Actually, it looks like
utf-8 (195
 is common when representing converted latin text). But having 3
times (195,
 131) which is the code for 'Ã' is weird.
 What is your source text, what is its encoding, and where does it
come from?
 What don't you /start/ and tell us about that?
 Denis

It seems that my input chars doesn't show correctly above... it
contains the following chars:

0xE4 (or 228), 0xF6 (or 246) and 0xFC (or 252)

I used notepad to create the file and saved it as ANSI encoding. The
file is for testing purposes only.


Re: Read non-UTF8 file

2011-02-19 Thread Nrgyzer
== Auszug aus Stewart Gordon (smjg_1...@yahoo.com)'s Artikel
 On 13/02/2011 21:49, Nrgyzer wrote:
 snip
  It compiles and works as long as the returned char-array/string of 
  f.readLine() doesn't
  contain non-UTF8 character(s). If it contains such chars, writeln() doesn't 
  write
  anything to the console. Is there any chance to read such files?
 Please post sample input that shows the problem, and the output generated by 
 replacing the
 writeln call with
  writefln(%s, cast(ubyte[]) convertToUTF8(f.readLine()));
 so that we can see what it is actually reading in.
 Stewart.

My file contains the following:

�
�
�

Now... and with writefln(%s, cast(ubyte[]) convertToUTF8(f.readLine())); I 
get the following:

[195, 131, 164]
[195, 131, 182]
[195, 131, 188]


Read non-UTF8 file

2011-02-13 Thread Nrgyzer
Hey guys,

I've the following source:

module filereader;

import std.file;
import std.stdio : writeln;

void main(string[] args) {
File f = new File(myFile.ext, FileMode.In);
while(!f.eof()) {
writeln(convertToUTF8(f.readLine()));
}
f.close();
}

string convertToUTF8(char[] text) {
string result;
for (uint i=0; itext.length; i++) {
wchar ch = text[i];
if (ch  0x80) {
result ~= ch;
} else {
result ~= 0xC0 | (ch  6);
result ~= 0x80 | (ch  0x3F);
}
}
return result;
}

It compiles and works as long as the returned char-array/string of f.readLine() 
doesn't contain non-UTF8 character(s). If it contains such
chars, writeln() doesn't write anything to the console. Is there any chance to 
read such files?

Thanks a lot!


foreach over string enum

2011-02-10 Thread Nrgyzer
Hey guys,

I'm trying to iterate over an enumeration which contains strings like
the this:

enum FileName : string {
file1 = file1.ext,
file2 = file2.ext
}

I already found this article: http://lists.puremagic.com/pipermail/
digitalmars-d/2007-July/021920.html but it's an enum which contains
integers instead of strings, thus I can't use min- or max-property.

Any suggestions - thanks in advance!


Re: foreach over string enum

2011-02-10 Thread Nrgyzer
== Auszug aus Jesse Phillips (jessekphillip...@gmail.com)'s Artikel
 Nrgyzer Wrote:
  Hey guys,
 
  I'm trying to iterate over an enumeration which contains strings
like
  the this:
 
  enum FileName : string {
  file1 = file1.ext,
  file2 = file2.ext
  }
 
  I already found this article: http://lists.puremagic.com/
pipermail/
  digitalmars-d/2007-July/021920.html but it's an enum which
contains
  integers instead of strings, thus I can't use min- or max-
property.
 
  Any suggestions - thanks in advance!
 I'll just be leaving this here, if you need more explanation ask,
but maybe you'll understand:
 import std.stdio;
 enum FileName : string {
 file1 = file1.ext,
 file2 = file2.ext
 }
 void main(string args[])
 {
 foreach(a; __traits(allMembers, FileName))
 writeln(mixin(FileName. ~ a));
 }

I've already worked with the mixin-statement, but the __trait is new.
As I can see in the documentation, it provides some interesting
features.

Your solution works great, thanks!


Re: Associative array and ranges

2011-02-03 Thread Nrgyzer
== Auszug aus bearophile (bearophileh...@lycos.com)'s Artikel
 Nrgyzer:
  Is there any chance to cast/convert this array to an indexed
array or
  is it possible to iterate over specific indices? I know that
there is
  something like next() for the foreach-statement but when the array
  contains some thousand instances and I only want iterate over (for
  example) 5 elements I think that's the wrong way.
 Show a hypothetical code example of what you desire to do, please.
 Bye,
 bearophile

Example:

...
class Example(T : Drawable) : Drawable {

T[hash_t] pObjectsToDraw;

uint pFrom, pTo;

void setLimit(from, to) {
pFrom = from;
pTo = to;
}

void remove(T objToRemove) {
pObjectsToDraw.remove(objToRemove.toHash());
}

override void draw() {
for (uint i = pFrom; i  pTo; i++) {
pOjectsToDraw[i].draw(); // cannot call
because pObjectsToDraw is an associative and no static or dynamic
array
}
}

}


Re: Associative array and ranges

2011-02-03 Thread Nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Thu, 03 Feb 2011 09:35:44 -0500, Nrgyzer nrgy...@gmail.com
wrote:
  == Auszug aus bearophile (bearophileh...@lycos.com)'s Artikel
  Nrgyzer:
   Is there any chance to cast/convert this array to an indexed
  array or
   is it possible to iterate over specific indices? I know that
  there is
   something like next() for the foreach-statement but when the
array
   contains some thousand instances and I only want iterate over
(for
   example) 5 elements I think that's the wrong way.
  Show a hypothetical code example of what you desire to do,
please.
  Bye,
  bearophile
 
  Example:
 
  ...
  class Example(T : Drawable) : Drawable {
 
  T[hash_t] pObjectsToDraw;
 
  uint pFrom, pTo;
 
  void setLimit(from, to) {
  pFrom = from;
  pTo = to;
  }
 
  void remove(T objToRemove) {
  pObjectsToDraw.remove(objToRemove.toHash());
  }
 
  override void draw() {
  for (uint i = pFrom; i  pTo; i++) {
  pOjectsToDraw[i].draw(); // cannot call
  because pObjectsToDraw is an associative and no static or dynamic
  array
  }
  }
 
  }
 First, hashes are not stored in any particular order, so I'm not
sure what
 you expect to accomplish except give me (pTo - pFrom) random
elements
  from the array
 Second, you can use a foreach loop to get data out of an AA, and
then
 break when you've retrieved enough elements.
 Again, I'm not sure what the point is of starting in the middle of
the
 array.  Are you expecting something different from a hashtable?
 -Steve

I know that hashes aren't stored in any order... but lets take the
LinkedHashSet in Java. The LinkedHashSet/Map stores the hashes in
order of inserting. With the toArray()-method I can loop over
specific elements/indices... but I can also remove the elements by
their hash. I'm looking for a similar technique in D - you can find
an Java example on http://www.java2s.com/Code/JavaAPI/java.util/
LinkedHashSettoArray.htm.


Re: Associative array and ranges

2011-02-03 Thread Nrgyzer
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
 On Thu, 03 Feb 2011 10:41:16 -0500, Nrgyzer nrgy...@gmail.com wrote:
  == Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
  On Thu, 03 Feb 2011 09:35:44 -0500, Nrgyzer nrgy...@gmail.com
  wrote:
   == Auszug aus bearophile (bearophileh...@lycos.com)'s Artikel
   Nrgyzer:
Is there any chance to cast/convert this array to an indexed
   array or
is it possible to iterate over specific indices? I know that
   there is
something like next() for the foreach-statement but when the
  array
contains some thousand instances and I only want iterate over
  (for
example) 5 elements I think that's the wrong way.
   Show a hypothetical code example of what you desire to do,
  please.
   Bye,
   bearophile
  
   Example:
  
   ...
   class Example(T : Drawable) : Drawable {
  
T[hash_t] pObjectsToDraw;
  
uint pFrom, pTo;
  
void setLimit(from, to) {
pFrom = from;
pTo = to;
}
  
void remove(T objToRemove) {
pObjectsToDraw.remove(objToRemove.toHash());
}
  
override void draw() {
for (uint i = pFrom; i  pTo; i++) {
pOjectsToDraw[i].draw(); // cannot call
   because pObjectsToDraw is an associative and no static or dynamic
   array
}
}
  
   }
  First, hashes are not stored in any particular order, so I'm not
  sure what
  you expect to accomplish except give me (pTo - pFrom) random
  elements
   from the array
  Second, you can use a foreach loop to get data out of an AA, and
  then
  break when you've retrieved enough elements.
  Again, I'm not sure what the point is of starting in the middle of
  the
  array.  Are you expecting something different from a hashtable?
  -Steve
 
  I know that hashes aren't stored in any order... but lets take the
  LinkedHashSet in Java. The LinkedHashSet/Map stores the hashes in
  order of inserting. With the toArray()-method I can loop over
  specific elements/indices... but I can also remove the elements by
  their hash. I'm looking for a similar technique in D - you can find
  an Java example on http://www.java2s.com/Code/JavaAPI/java.util/
  LinkedHashSettoArray.htm.
 The AA does not do that.  Note that there is no builtin 'set' type in D
 (there is one in dcollections).
 Note that your worry about performance when iterating the AA is completely
 negated by the toArray call -- this allocates space for your temporary
 array, and necessarily iterates all elements, even if you only want 5.
 You are better off not to do things this way.
 Incidentally, I do plan on adding a Link*Set/Map to dcollections, because
 I really like the array type in php (same thing).  But this will not
 provide constant access to the nth element, so it still will fail your
 requirements.
 The only thing I can think of is to store the elements in an array
 alongside the hash map (do you need to look up elements by hash_t?  If
 not, why not just use an array directly?) to store the order of
 insertion.  This only works if you rarely remove elements (removal in an
 array is an O(n) operation).
 -Steve

I already thought about using an dynamic array like T[] (which contains all
elements that should be drawn) and a second like uint[hash_t] which contains
the indices in the first array. But it does only shit the problem that I can't
remove an index from a dynamic array.

Thanks for your suggestions.


Re: Associative array and ranges

2011-02-03 Thread Nrgyzer
== Auszug aus Stanislav Blinov (bli...@loniir.ru)'s Artikel
 03.02.2011 19:34, Nrgyzer пишет:
  == Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel
  This only works if you rarely remove elements (removal in an
  array is an O(n) operation).
  -Steve
  I already thought about using an dynamic array like T[] (which
contains all
  elements that should be drawn) and a second like uint[hash_t]
which contains
  the indices in the first array. But it does only shit the problem
that I can't
  remove an index from a dynamic array.
 
  Thanks for your suggestions.
 
 Why can't you?
 You can:
 1) Get an index i from hash, do arr = arr[0..i] ~ arr[i+1..$] and
then
 reindex all arr[i..$] elements. This is costly, because, as Steven
 mentioned, such removal is O(n) plus you have to iterate all
elements
 with index = i, and this traversal is O(n) in the worst case.
 2) Use unstable removal. Since you store indices separately, you can
 just swap an element to be removed with last element in the array,
 shrink array using slicing (arr = arr[0..$-1]) and reindex a single
 element (the one that was previously last in the array). The
drawback is
 that this approach doesn't preserve order of elements in the array.

Ah, okay... I already tried some things with [0..i] ~ [i + 1..$] but
there was always an error and I thought, it must be done more simply.
I'm just using a simple, dynamic array and use a for-loop to remove
them. I don't need remove() often, but I thought there is any way to
do it in O(1).


Associative array and ranges

2011-02-02 Thread Nrgyzer
Hey guys,

I have an associative array like this: T[hash_t] myArray; (T means
the template type).

Is there any chance to cast/convert this array to an indexed array or
is it possible to iterate over specific indices? I know that there is
something like next() for the foreach-statement but when the array
contains some thousand instances and I only want iterate over (for
example) 5 elements I think that's the wrong way. It's for a game and
I think every next()-call influences the fps.

I hope there is any solution for my problem :) - Thanks!


Threads fibers

2011-01-30 Thread Nrgyzer
Hey guys,

I already posted a thread in the wrong section (digitalmars.D instead of
digitalmars.D.learn) - sorry for that. I'm looking for a solution to suspend/
interrupt threads which are sleeping.

In the last few minutes I figured out some things I didn't understand exactly. I
tested thread and fibers from the core.thread-package.

My first test-code is the following:

import std.stdio;
import core.thread;

a testInstance;

class a {

void writeTest() {

writeln(test);

}

}

void main(string[] args) {

testInstance = new a();

Thread t = new Thread(threadFunc);
t.start();

Thread.yield(); // give the thread a chance to call threadFunc()

}

void threadFunc() {

writeln(testInstance is null);

}

The result is: true which means that testInstance of type a is null - but I
already created a instance and if I write writeln(testInstance is null); after
Thread.yield(); in the main, it says false which means testInstance is a valid
instance of the class a. - Why does threadFunc() says true, when testInstance
should be a valid instance of a?

Next question: When I extend my threadFunc()... like the following:

void threadFunc() {

writeln(testInstance is null);
Thread.sleep(milliseconds(10_000));

}

... is there any chance to interrupt the Thread.sleep-command or to suspend the
thread? As I know, the join()-method does wait until the thread is finished, but
does not interrupt the sleep()-command.

I hope anyone can help and know how I can do this all.

... sorry for double posting in digitalmars.d!

Thanks in advance!


Re: Threads fibers

2011-01-30 Thread Nrgyzer
 Nrgyzer nrgy...@gmail.com wrote:
  The result is: true which means that testInstance of type a is
null -
  but I
  already created a instance and if I write writeln(testInstance is
  null); after
  Thread.yield(); in the main, it says false which means
testInstance is
  a valid
  instance of the class a. - Why does threadFunc() says true, when
  testInstance
  should be a valid instance of a?
 The default storage in D is in TLS, that is, changes in one thread
will
 not be visible to others.
 If instead you mark your class a as 'shared class a', it works the
way
 you'd expect it to.
  ... is there any chance to interrupt the Thread.sleep-command or
to
  suspend the
  thread? As I know, the join()-method does wait until the thread is
  finished, but
  does not interrupt the sleep()-command.
 I think the best way to do this would be using std.concurrency, and
 passing it a message. Not sure, though.

Thanks, marking a as shared class works :)... I already used threads
in D1 but there as I just know - since 2.030 I need shared-
decleration.


Re: (coff)-Implib lib from dll

2011-01-15 Thread nrgyzer
I just used implib libmysql.lib libmysql.dll /system but it produces
the same errors.


Re: (coff)-Implib lib from dll

2011-01-15 Thread Nrgyzer
Thanks, but didn't help to change to implib /system libmysql.lib
libmysql.dll  - some errors.


Re: (coff)-Implib lib from dll

2011-01-15 Thread Nrgyzer
This solved the problems, thanks - but, when the line mysql =
mysql_init(null); produces an access violation.


abstract function templates

2010-12-26 Thread Nrgyzer
Hey guys,

I've the following class:

abstract class Drawable {

public {

uint getHeight() { ... }
uint getWidth() { ... }

abstract {
void draw(T = void*)(uint zPos, T obj = null);
}

}

}

When I compile this code, it compiles without any errors.

Now... I have the following class:

class Texture : Drawable {

public {

override {
void draw(T = void*)(uint zPos, T obj = null)
{ ... }
}

}

}

When I create a new instance of Texture and try to call
newInstance.draw(50), I always get the following error:

Error: variable Texture.draw!(void*).draw.this override cannot be
applied to variable
Error: variable Texture.draw!(void*).draw.zPos override cannot be
applied to variable
Error: variable Texture.draw!(void*).draw.pbo override cannot be
applied to variable
Error: variable ... Texture.draw!(void*).draw.zPos override cannot
be applied to variable

I hope anyone can help me - thanks!


Re: abstract function templates

2010-12-26 Thread Nrgyzer
Ah, okay - remove override is enough.

Thanks :)


Re: abstract function templates

2010-12-26 Thread Nrgyzer
I just figured out that this doesn't work, when I use a array with
super class as base type, for example: Drawable[] textures;

Then, I'll get the following error:

Error: function draw!(void*).draw non-virtual functions cannot be
abstract.

I just implemented the draw-function as empty function, which doesn't
create any errors, but I seems that it's not calling the draw-
function of any texture instance. It seems that it is always calling
Drawable.draw() - the empty function. When I create a new instance of
my Texture-class, it calls the draw-function of the texture-instance.


Re: abstract function templates

2010-12-26 Thread Nrgyzer
The sense is that I have different, drawable classes/object - for
example a simple texture (not clickable) and a button (clickable).
When the user clicks the mouse, the obj-param which is defined by
using draw!(T = void*)(uint zPos, T obj = null) will be saved in a
template-struct which should have the type of obj - struct myStruct
(T). The advantage is, that I can use the obj referenced in the
struct without any casting.

I just solved the problem by declaring draw() as final-function and
used a new value as callback in the final draw()-function - for
example:

...
private void delegate() drawCallback;

public final void draw(T = void*)(uint zPos, T obj = null) {

drawCallback();

// ... do additional work
}


function pointers in D2

2010-12-12 Thread Nrgyzer
Hey guys,

I've used D1 in the past and D1 seems to check for correct function
pointers. In D2 I can pass any function pointer to an function, for
example:

...
void example(void function(int, int) fp) {
...
}

...
void callback1(int x, int y) {
}
void callback2() {
}
...

example(callback1); // Works in D1 and D2
example(callback2); // Works in D2, but D1 says that example needs
an pointer (int, int) signature which is logical. D1 says ... (void
function(int, int)) does not match parameter types void function())

But... why does D2 accept callback2? When I compile an application by
using debug mode in D2, the callback works... in release mode it
produces an object.Error: Access Violation.

Is there any chance to check for correct function pointers in D2?


undefined identifier getch()

2010-12-08 Thread Nrgyzer
Hey guys,

I'm writing a console based tool for windows. To receive the users input, I
try to use getch() but the compiler always says Error: undefined identifier
getch. When I use getchar() it compiles successfully, but getchar() doesn't
returns after a single input.

Is there any equivalent version in D for getch?

Thanks  regards...


Re: undefined identifier getch()

2010-12-08 Thread Nrgyzer
Okay, but what function can I use to get the pressed key?
kbhit/_kbhit seems to do what I want, but hwo can I use it in D? I
always get the error, that kbhit (or similar functions) are not
available.

import std.stdio;
import std.c.stdlib;
import std.c.windows.windows;

void main(string[] args) {
kbhit();
_kbhit();
}


Re: undefined identifier getch()

2010-12-08 Thread Nrgyzer
Great, thanks :)


Base64 - Encoding and decoding

2010-11-27 Thread Nrgyzer
Hey guys,

I want encode and decode binary files like images, documents and similar file 
types to use it in an binary xml. For those I created a
simple command line tool which encode or decode an file.

The encoding of files will be processed by these lines:

...
ubyte[] buffer;
buffer.length = source.available();
source.read(buffer);

string content;

for (uint i = 0; i  buffer.length; i++) {
content ~= to!(char)(buffer[i]);
}

destination.write(encode(content));
...

This seems to work correctly, but when I want decode the file, I always get 
std.base64.Base64CharException: Invalid base64 character.
I'm currently using the following to decode the file:

char[] content;

for (uint i = 0; i  source.available(); i++) {
content ~= source.getc();
}

decode(to!(string)(content));

But... when I directly decode the encoded (without read the encoded content 
from external file), the decoded file is valid.

I hope anyone know where's my mistake :)

Thanks!


Append wchar enumeration to string

2010-11-21 Thread Nrgyzer
Hello guys,

I have an enumeration which contains symbols of different currencies
like the following:

enum CURRENCY : wchar {

DOLLAR = '$',
EURO = '�',
YEN = ...

}

When I try to append it to a string like

char[] myString = Currency:  ~ CURRENCY.DOLLAR

I get the following error: Error: incompatible types for... 'char[]'
and 'int'

But... when I try the following:

char[] myString = Currency:  ~ cast(char) CURRENCY.DOLLAR

It works, but not for all currencies.
What can I do to support all currencies?

Thanks for any help.


Re: Append wchar enumeration to string

2010-11-21 Thread Nrgyzer
But for enums I can't use char[] as basetype and when I use cast(dchar)
or cast(wchar) I also get Error: incompatible types for


Re: Append wchar enumeration to string

2010-11-21 Thread Nrgyzer
I solved the problem by using toUTF8 from std.utf but I think it's a
dirty solution because I have to cast wchar to wchar[] because a
simple toUTF8(CURRENCY.DOLLAR) matches wchar[] and dchar[] signatures.


opIndex() overloading for multiple arrays

2010-09-11 Thread Nrgyzer
Hey guys,

is it possible to overload opIndex() with a multiple array, for
example:

class Example {
...
char[] opIndex(uint index1, uint index2) {
return my text to return;
}
...
}

Example t = new Example();
writefln(t[0][10]);

Looking forward to hearing from anyone :)


Re: opIndex() overloading for multiple arrays

2010-09-11 Thread Nrgyzer
Thanks for reply... exactly, what I need.


  1   2   >