problems playing audio with mciSendString

2010-11-02 Thread Tyro[a.c.edwards]
Hello all,

I would really appreciate some assistance on this. The intent is to
create a vocabulary/flashcard program with proper pronunciations.
Pronunciations are saved as individual mp3 files which I want to
play whenever a new term is displayed. My current attempt is simply
to get the the file (any mp3 file really) to play. All indication
form the two references I'm using (http://msdn.microsoft.com/en-
us/library/dd757161(v=VS.85).aspx and
http://www.apitalk.com/windows-Programming/Play-Mp3,-Wav,-Wmv,-Mpg,-
Avi-Etc-Files-In-Win32-Api-Program.html) say that this little script
is supposed to work. The error codes as reported by mciSendString
even suggest that it is working, however I'm not hearing any sound
at all.

suggestions anyone?

import std.stdio : writeln;
import std.string : cstring = toStringz;
import std.c.windows.windows;

pragma(lib, "winmm.lib" );

extern(Windows) {
uint mciSendStringA(
LPCTSTR lpszCommand,
LPTSTR lpszReturnString,
uint cchReturn,
HANDLE hwndCallback);
}

uint mciSendString(string s)
{
return mciSendStringA( cstring(s), cast(LPTSTR)null, 0,
cast(HANDLE)0 );
}

void main()
{
auto exist = mciSendString("open CC_10_mins.mp3 type
mpegvideo alias myFile");

auto succeeded = mciSendString("play myFile");

auto closed = mciSendString("close myFile");

writeln( exist, " - ", succeeded, " - ", closed );
}


PROGRAM OUTPUT
==

when file exists:
D:\code>play
0 - 0 - 0

when file does not exist:
D:\code>play
275 - 263 - 263


Re: problems playing audio with mciSendString

2010-11-02 Thread Tyro[a.c.edwards]
Thanks,

The problem was that mciSendString was immediately returning control
to the caller after being called. This simple change fixed the
problem:

mciSendString("play myFile wait");


Unicode: how to properly read and display directory entries?

2010-11-05 Thread Tyro[a.c.edwards]

Hello,

What is the proper way to read a directory such that file names are not 
garbled? Here is the example I borrowed form the std.file documentation. 
Screen shots of folder is attached. Thanks.


void main(string[] args)
{
bool callback(DirEntry* de)
{
if (de.isfile)
mciPlay(toUTF8(de.name));
return true;
}

listdir("snd", &callback);
}

D:\code>play
snd\american.ogg
snd\bigdog.flac
snd\blackmail.mp3
snd\ding.wav
snd\kam.aif.aiff
snd\豺。縺・ogg
<>

Re: Unicode: how to properly read and display directory entries?

2010-11-05 Thread Tyro[a.c.edwards]

On 11/5/2010 10:51 PM, Kagamin wrote:

Tyro[a.c.edwards] Wrote:


Hello,

What is the proper way to read a directory such that file names are not
garbled? Here is the example I borrowed form the std.file documentation.
Screen shots of folder is attached. Thanks.

void main(string[] args)
{
bool callback(DirEntry* de)
{
if (de.isfile)
mciPlay(toUTF8(de.name));
return true;
}

listdir("snd",&callback);
}

D:\code>play
snd\american.ogg
snd\bigdog.flac
snd\blackmail.mp3
snd\ding.wav
snd\kam.aif.aiff
snd\豺。縺・ogg



http://d.puremagic.com/issues/show_bug.cgi?id=2742


Much appreciate the info. I'm not however interested in outputting to 
the console. I'm trying to call mciSendString with the name of each file 
contained in the directory. The process fails however, when it 
encounters a Japanese file name. Please see code below. Any idea what 
I'm doing wrong?


import std.file;
import std.string : cstring = toStringz;
import std.c.windows.windows;

pragma(lib, "winmm.lib" );

extern(Windows) {
uint mciSendStringW(
LPCWSTR lpszCommand,
LPWSTR lpszReturnString,
uint cchReturn,
HANDLE hwndCallback);
}

void main(string[] args)
{
bool callback(DirEntry* de)
{
if (de.isfile)
mciPlay(de.name);
return true;
}

listdir("snd", &callback);
}

void mciPlay(string audio)
{
uint mciSendString(string s)
{
		return mciSendStringW( cast(LPCWSTR)s, cast(LPWSTR)null, 0, 
cast(HANDLE)0 );

}

	auto exists = mciSendString(`open "` ~ audio ~ `" type mpegvideo alias 
myFile`);

auto played = mciSendString("play myFile wait");
scope(exit) mciSendString("close myFile");
}


Re: Unicode: how to properly read and display directory entries?

2010-11-05 Thread Tyro[a.c.edwards]

On 11/6/2010 2:10 AM, Dmitry Olshansky wrote:

On 05.11.2010 18:25, Tyro[a.c.edwards] wrote:

On 11/5/2010 10:51 PM, Kagamin wrote:

Tyro[a.c.edwards] Wrote:


Hello,

What is the proper way to read a directory such that file names are not
garbled? Here is the example I borrowed form the std.file
documentation.
Screen shots of folder is attached. Thanks.

void main(string[] args)
{
bool callback(DirEntry* de)
{
if (de.isfile)
mciPlay(toUTF8(de.name));
return true;
}

listdir("snd",&callback);
}

D:\code>play
snd\american.ogg
snd\bigdog.flac
snd\blackmail.mp3
snd\ding.wav
snd\kam.aif.aiff
snd\豺。縺・ogg



http://d.puremagic.com/issues/show_bug.cgi?id=2742


Much appreciate the info. I'm not however interested in outputting to
the console. I'm trying to call mciSendString with the name of each
file contained in the directory. The process fails however, when it
encounters a Japanese file name. Please see code below. Any idea what
I'm doing wrong?

import std.file;
import std.string : cstring = toStringz;
import std.c.windows.windows;

pragma(lib, "winmm.lib" );

extern(Windows) {
uint mciSendStringW(
LPCWSTR lpszCommand,
LPWSTR lpszReturnString,
uint cchReturn,
HANDLE hwndCallback);
}

void main(string[] args)
{
bool callback(DirEntry* de)
{
if (de.isfile)
mciPlay(de.name);
return true;
}

listdir("snd", &callback);
}

void mciPlay(string audio)
{
uint mciSendString(string s)
{
return mciSendStringW( cast(LPCWSTR)s, cast(LPWSTR)null, 0,
cast(HANDLE)0 );
}

auto exists = mciSendString(`open "` ~ audio ~ `" type mpegvideo alias
myFile`);
auto played = mciSendString("play myFile wait");
scope(exit) mciSendString("close myFile");
}

In short : never rely on the casts to do the right thing.
Bug is here:
return mciSendStringW( cast(LPCWSTR)s, cast(LPWSTR)null, 0,
cast(HANDLE)0 );
changing that to more accurate:
return mciSendStringW(toUTF16z(s) , cast(LPWSTR)null, 0, cast(HANDLE)0 );
works for me, even with this name:
snd\와카미야 온마쓰리.mp3

If you use W version you need to re-encode your UTF8 string to UTF16.
AFAIK Windows uses slightly outdated version of UTF16, check the web on
issues.



That's it! Thank you much. I tried the toUTFXX() function calls but 
completely missed toUTF16z.


Re: C++ to D: Help please

2011-02-24 Thread Tyro[a.c.edwards]

On 2/25/2011 3:33 AM, Jesse Phillips wrote:

Well using one language you aren't familiar with to learn another is probably 
not the best strategy.

For one thing C++ uses namespaces and D uses modules. They are both about 
name-space but are very different approaches. If you want to learn about 
modules then write a simple application. Place all functions in one module/file 
and import that into a file that contains the main function. Then call $ dmd 
file1.d file2.d


Right again. It would be great to have complete tutorials for D. But the 
fact is we don't, so one has little choice but to use another language's 
tutorial. Truth be told, I was hoping that Bartosz Milewski, a very 
active programmer in the D community would see my post and, would 
realize that I was using his tutorials and offer to port them to D so 
that the community as a whole would benefit from them. I've gotten away 
of trying to ask authors directly to convert their material to D because 
that rarely ever works.


As far as learning the differences between C++ and D, I really have no 
desire. I'm what you might call an advanced beginning D programmer. Lost 
but not dumb: I do know how the D module system works and I have an 
inkling of how C++ namespaces work. I know the basics of programming (in 
D language, but the basics translate to any other language quite easily) 
and am looking for ways to use that to do something useful. 
Unfortunately, the more complete/useful tutorials are written in C/C++ 
and not my language of choice: D. The authors of those tutorials have no 
interest in D or probably have never even heard of D and would care less 
about it's existence because it does not positively affect their 
financial well being.


I will eventually port the program, because that is what I want to do. 
But the fact is, that will take several months using a trial and error 
approach. I was just hoping to get through the process a little faster 
and learning from that example, go ahead and port the rest of the 
tutorials on Bartosz's site. Sorry for assuming someone would be willing 
to offer to lend a hand in doing so. I would offer to compensate that 
individual for time lost doing the conversion but I have no idea what 
would be a reasonable offer and refrained from doing so because I had no 
desire to offend anyone here.


Well, thank you all.


Initializing a class pointer

2011-02-26 Thread Tyro[a.c.edwards]

class Class{}

void main()
{
Class myClass;
Class* pClass0 = &myClass;  // OK

Class* pClass1 = new Class; // Error: cannot implicitly convert [8]
// expression (new Class) of type t.Class
// to test.Class*

Class* pClass2 = &(new Class);
// Error: new Class is not an lvalue[12]

Class mClass = &(new Class);// Error: cannot implicitly convert [14]
// expression (&new Class) of type Class*
// to test.Class
}

C++ uses the process on line [8] above to initialize a class pointer. 
Obviously it does not work in D. But given the error message at [14], I 
thought [12] would have been allowed. What is the proper way to convert 
[8] to D?


Thanks


Re: Initializing a class pointer

2011-02-26 Thread Tyro[a.c.edwards]

On 2/27/2011 8:10 AM, Simen kjaeraas wrote:

Tyro[a.c.edwards]  wrote:


class Class{}

void main()
{
Class myClass;
Class* pClass0 = &myClass; // OK

Class* pClass1 = new Class; // Error: cannot implicitly convert [8]
// expression (new Class) of type t.Class
// to test.Class*

Class* pClass2 = &(new Class);
// Error: new Class is not an lvalue [12]

Class mClass = &(new Class);// Error: cannot implicitly convert [14]
// expression (&new Class) of type Class*
// to test.Class
}

C++ uses the process on line [8] above to initialize a class pointer.
Obviously it does not work in D. But given the error message at [14],
I thought [12] would have been allowed. What is the proper way to
convert [8] to D?


Classes in D are already references (like Class& in C++), thus line [8]
would be a pointer to a reference to a class, something which may make
some kind of sense, but is unlikely to be what you want.

Perhaps this question is better answered if you explain why you want a
pointer to a class?




I'm trying to convert some c++ code that defines

T func(par...)
{   
  Controller * pCtrl = WinGetLong (hwnd);
  .
  .
  .
  switch(msg)
  {
  case FirstMatch:
 pCtrl = new Controller (hwnd, reinterpret_cast 
(lParam));

 break;
  }
}

I'm not sure why I need a pointer to the class, just trying to figure it 
out.


Re: Initializing a class pointer

2011-02-26 Thread Tyro[a.c.edwards]

On 2/27/2011 8:52 AM, Simen kjaeraas wrote:

Tyro[a.c.edwards]  wrote:


I'm trying to convert some c++ code that defines

T func(par...)
{
Controller * pCtrl = WinGetLong (hwnd);
.
.
.
switch(msg)
{
case FirstMatch:
pCtrl = new Controller (hwnd, reinterpret_cast (lParam));
break;
}
}

I'm not sure why I need a pointer to the class, just trying to figure
it out.


Ah. You would not need a pointer to the class in D. Instead, your function
would look something like this:

T funct(par...)
{
auto pCtrl = WinGetLong!Controller(hwnd);
...
switch(msg)
{
case FirstMatch:
pCtrl = new Controller(hWnd, cast(CREATESTRUCT*)lParam);
break;
}
}

C++ classes are in some ways more akin to D structs, in that:

class A {};

void foo(){
A bar;
}

bar would be allocated on the stack in C++, while in D bar would be a
pointer to a class instance on the heap. (well, it would be null, but
when you set it to something, that something would reside on the heap)



Ok, that's essentially what I have, except that I used Controller pCtrl 
vice auto. WinGetLong however, is a template that calls 
GetWindowLongPtrA() and casts it's result (in this case) to Controller. 
 GetWindowLongPtrA() returns LONG_PTR (aka int) and therefore fails 
miserably on the cast attempt. On the reverse, there is a WinSetLong 
that attempts to cast Controller to int for use with 
SetWindowLongPtrA(). Neither of these functions complain when I use 
Controller* but I end up with the problem of trying to initialize a 
pointer with a reference to Controller.


Re: Initializing a class pointer

2011-02-26 Thread Tyro[a.c.edwards]

On 2/27/2011 9:46 AM, Tyro[a.c.edwards] wrote:

On 2/27/2011 8:52 AM, Simen kjaeraas wrote:

Tyro[a.c.edwards]  wrote:


I'm trying to convert some c++ code that defines

T func(par...)
{
Controller * pCtrl = WinGetLong (hwnd);
.
.
.
switch(msg)
{
case FirstMatch:
pCtrl = new Controller (hwnd, reinterpret_cast
(lParam));
break;
}
}

I'm not sure why I need a pointer to the class, just trying to figure
it out.


Ah. You would not need a pointer to the class in D. Instead, your
function
would look something like this:

T funct(par...)
{
auto pCtrl = WinGetLong!Controller(hwnd);
...
switch(msg)
{
case FirstMatch:
pCtrl = new Controller(hWnd, cast(CREATESTRUCT*)lParam);
break;
}
}

C++ classes are in some ways more akin to D structs, in that:

class A {};

void foo(){
A bar;
}

bar would be allocated on the stack in C++, while in D bar would be a
pointer to a class instance on the heap. (well, it would be null, but
when you set it to something, that something would reside on the heap)



Ok, that's essentially what I have, except that I used Controller pCtrl
vice auto. WinGetLong however, is a template that calls
GetWindowLongPtrA() and casts it's result (in this case) to Controller.
GetWindowLongPtrA() returns LONG_PTR (aka int) and therefore fails
miserably on the cast attempt. On the reverse, there is a WinSetLong
that attempts to cast Controller to int for use with
SetWindowLongPtrA(). Neither of these functions complain when I use
Controller* but I end up with the problem of trying to initialize a
pointer with a reference to Controller.


By the way, in original C++ code WinGetLong and WinSetLong are both 
using a reinterpret_cast to achieve this monkey magic. To the best of my 
knowledge, there is no reinterpret_cast facility in D. So the question 
would be, why would it have been necessary to use reinterpret_cast in 
the first place and how can similar effect be obtained in D? What was 
being reinterpreted? Was it the address of the class or the value some 
private value contained therein?


Re: Initializing a class pointer

2011-02-28 Thread Tyro[a.c.edwards]

On 2/27/2011 10:39 PM, Steven Schveighoffer wrote:

On Sat, 26 Feb 2011 19:46:18 -0500, Tyro[a.c.edwards] 
wrote:


On 2/27/2011 8:52 AM, Simen kjaeraas wrote:

Tyro[a.c.edwards]  wrote:


I'm trying to convert some c++ code that defines

T func(par...)
{
Controller * pCtrl = WinGetLong (hwnd);
.
.
.
switch(msg)
{
case FirstMatch:
pCtrl = new Controller (hwnd, reinterpret_cast
(lParam));
break;
}
}

I'm not sure why I need a pointer to the class, just trying to figure
it out.


Ah. You would not need a pointer to the class in D. Instead, your
function
would look something like this:

T funct(par...)
{
auto pCtrl = WinGetLong!Controller(hwnd);
...
switch(msg)
{
case FirstMatch:
pCtrl = new Controller(hWnd, cast(CREATESTRUCT*)lParam);
break;
}
}

C++ classes are in some ways more akin to D structs, in that:

class A {};

void foo(){
A bar;
}

bar would be allocated on the stack in C++, while in D bar would be a
pointer to a class instance on the heap. (well, it would be null, but
when you set it to something, that something would reside on the heap)



Ok, that's essentially what I have, except that I used Controller
pCtrl vice auto. WinGetLong however, is a template that calls
GetWindowLongPtrA() and casts it's result (in this case) to
Controller. GetWindowLongPtrA() returns LONG_PTR (aka int) and
therefore fails miserably on the cast attempt. On the reverse, there
is a WinSetLong that attempts to cast Controller to int for use with
SetWindowLongPtrA(). Neither of these functions complain when I use
Controller* but I end up with the problem of trying to initialize a
pointer with a reference to Controller.


You almost certainly do not want a pointer to a class reference. A class
typically resides on the heap, but the reference typically does not.
Therefore, by using a pointer to a class reference, you run very high
risk of escaping stack data, leading to memory corruption.

Looking at the documentation for GetWindowLongPtr, it appears to get
data associated with a window. Likely, this information is the a pointer
to the Controller class.

I would recommend doing this:

T WinGetLong(T)(HWND hwnd)
{
return cast(T)cast(void*)GetWindowLongPtrA(hwnd, ...);
}

and

void WinSetLong(T)(HWND hwnd, T t)
{
SetWindowLongPtrA(hwnd, ..., cast(LONG_PTR)cast(void*)t);
}

where the ... is the index copied from the C++ code (guessing it's
GWLP_USERDATA?).

btw, reinterpret_cast(x) is equivalent to (T)(void *)x;

-Steve


Thank you all (Steve, Bekenn, and Simen) for your assistance on this.


string vs. w/char*

2011-02-28 Thread Tyro[a.c.edwards]
The bellow code attempts to use LoadStringA() to initialize _buf. 
However, regardless of what form _buf takes, the body of the if 
statement is always executed. I've attempted to use every type of string 
available in D to include char* _buf[MAX_RESSTRING+1] and setting 
_buf[MAX_RESSTRING] = '\0'; What am I doing incorrectly?

Any assistance is greatly appreciated.

class ResString
{
  enum { MAX_RESSTRING = 255 }

  alias getBuffer this;
  @property string getBuffer() { return _buf; }

  this(HINSTANCE hInst, int resId)
  {
_buf.length = MAX_RESSTRING;

SetLastError(0);

if(!LoadStringA(hInst, resId, cast(char*)toStringz(_buf), 
_buf.length + 1))

{
  throw new WinException("Load String failed");
}
  }

private:
  string _buf;
}


Re: string vs. w/char*

2011-02-28 Thread Tyro[a.c.edwards]

On 2/28/2011 9:58 PM, Steven Schveighoffer wrote:

On Mon, 28 Feb 2011 07:34:39 -0500, Tyro[a.c.edwards] 
wrote:


The bellow code attempts to use LoadStringA() to initialize _buf.
However, regardless of what form _buf takes, the body of the if
statement is always executed. I've attempted to use every type of
string available in D to include char* _buf[MAX_RESSTRING+1] and
setting _buf[MAX_RESSTRING] = '\0'; What am I doing incorrectly?
Any assistance is greatly appreciated.

class ResString
{
enum { MAX_RESSTRING = 255 }

alias getBuffer this;
@property string getBuffer() { return _buf; }

this(HINSTANCE hInst, int resId)
{
_buf.length = MAX_RESSTRING;

SetLastError(0);

if(!LoadStringA(hInst, resId, cast(char*)toStringz(_buf), _buf.length
+ 1))
{
throw new WinException("Load String failed");
}
}

private:
string _buf;
}


You should not be overwriting buf, it is immutable. You need to make a
new buffer each time.

this(HINSTANCE hInst, int resId)
{

auto mybuf = new char[MAX_RESSTRING];
auto nchars = LoadStringA(hInst, resId, mybuf.ptr, mybuf.length);
if(!nchars)
{
throw new WinException("Load String failed");
}
_buf = assumeUnique(mybuf[0..nchars]);

SetLastError(0);
}

If this isn't working, you might consider that the string you are trying
to load doesn't actually exist (that is a valid condition). What is the
error from GetLastError ?

-Steve


Both implementations results in error code 1812 being returned from 
GetLastError. explanation of the code reads:


 ERROR_RESOURCE_DATA_NOT_FOUND
 1812 (0x714)
 The specified image file did not contain a resource section.

The code I'm porting initially consisted of a resource.h file, a 
generic.rc file and two icons. I have not tried to include the icons and 
generic.rc file in the compilation because I do not know how to as yet 
and I've only used half of the resource.h file: didn't think I need the 
whole thing. Could this be the reason for the error? If so could you 
direct me to the explanation of how to prepare these files for inclusion 
in the compilation process?


Thanks,
Andrew


Re: string vs. w/char*

2011-02-28 Thread Tyro[a.c.edwards]

On 2/28/2011 11:08 PM, J Chapman wrote:

== Quote from Tyro[a.c.edwards] (nos...@home.com)'s article

Both implementations results in error code 1812 being returned from
GetLastError. explanation of the code reads:
   ERROR_RESOURCE_DATA_NOT_FOUND
   1812 (0x714)
   The specified image file did not contain a resource section.
The code I'm porting initially consisted of a resource.h file, a
generic.rc file and two icons. I have not tried to include the icons and
generic.rc file in the compilation because I do not know how to as yet
and I've only used half of the resource.h file: didn't think I need the
whole thing. Could this be the reason for the error? If so could you
direct me to the explanation of how to prepare these files for inclusion
in the compilation process?
Thanks,
Andrew


You need to compile the .rc file (see
http://www.digitalmars.com/ctg/rcc.html), then add the resulting .res file
to dmd's command line.


Awesome, this does the trick. However I get get a "GP Fault"? during 
execution. Using windbg, I tracked it down to this piece of code:


void Create()
{
  _hwnd = CreateWindowExA(
_exStyle,
cast(const(char*))_wc.GetName(), // returns string
cast(const(char*))_windowName,   // string variable
_style,
_x,
_y,
_width,
_height,
_hWndParent,
_hMenu,
_wc.GetInstance(),
_data);

assert(_hwnd, "Internal error: Window Creation Failed.");
}

The program craps at assert() but the error is generated. It just 
displays a dialog box with the message: "test.exe has stopped working, 
Windows is checking for a solution to the problem..."


I'm thinking that _hwnd was never initialized and that assert is access 
a null pointer but I cannot be sure. Any suggestions or ideas?


Re: string vs. w/char*

2011-02-28 Thread Tyro[a.c.edwards]
== Quote from Denis Koroskin (2kor...@gmail.com)'s article
> On Mon, 28 Feb 2011 19:35:47 +0300, Tyro[a.c.edwards]

> wrote:
> > On 2/28/2011 11:08 PM, J Chapman wrote:
> >> == Quote from Tyro[a.c.edwards] (nos...@home.com)'s article
> >>> Both implementations results in error code 1812 being
returned from
> >>> GetLastError. explanation of the code reads:
> >>>ERROR_RESOURCE_DATA_NOT_FOUND
> >>>1812 (0x714)
> >>>The specified image file did not contain a resource
section.
> >>> The code I'm porting initially consisted of a resource.h
file, a
> >>> generic.rc file and two icons. I have not tried to include
the icons
> >>> and
> >>> generic.rc file in the compilation because I do not know how
to as yet
> >>> and I've only used half of the resource.h file: didn't think
I need the
> >>> whole thing. Could this be the reason for the error? If so
could you
> >>> direct me to the explanation of how to prepare these files
for
> >>> inclusion
> >>> in the compilation process?
> >>> Thanks,
> >>> Andrew
> >>
> >> You need to compile the .rc file (see
> >> http://www.digitalmars.com/ctg/rcc.html), then add the
resulting .res
> >> file
> >> to dmd's command line.
> >
> > Awesome, this does the trick. However I get get a "GP Fault"?
during
> > execution. Using windbg, I tracked it down to this piece of
code:
> >
> > void Create()
> > {
> >_hwnd = CreateWindowExA(
> >  _exStyle,
> >  cast(const(char*))_wc.GetName(), // returns string
> >  cast(const(char*))_windowName,   // string variable
> >  _style,
> >  _x,
> >  _y,
> >  _width,
> >  _height,
> >  _hWndParent,
> >  _hMenu,
> >  _wc.GetInstance(),
> >  _data);
> >
> >  assert(_hwnd, "Internal error: Window Creation Failed.");
> > }
> >
> > The program craps at assert() but the error is generated. It
just
> > displays a dialog box with the message: "test.exe has stopped
working,
> > Windows is checking for a solution to the problem..."
> >
> > I'm thinking that _hwnd was never initialized and that assert
is access
> > a null pointer but I cannot be sure. Any suggestions or ideas?
> The
> >  cast(const(char*))_wc.GetName()
> line look *very* suspicious. You can't get a string and just
cast it to
> const(char)*. Most importantly, the string (most likely) is not
> null-terminated.
> What you need to do here is the following:
> auto className = toStringz(_ws.GetName());
> auto caption = toStringz(_windowName);
> and pass those 2 to the function.

Actually I've already tried that, it has no effect on the outcome.
>From your suggestion though, I've gone back and replace all the
cast(const(char*)) usage throughout the program. Final verdict:
the program still crashes it the same location. It actually never
returns from CreateWindowExA().

> Alternatively, you could make sure your strings are null-
terminated and
> pass the pointer directly (e.g. _windowName.ptr):
> string _windowName = "foo"; // null-terminated automatically
> string _caption = ("Hello, World" ~ "\0")[0..$-1]; // append
trailing zero
> to an existing string but exclude it from result (so that it's
not
> included in _caption.length)



Re: string vs. w/char*

2011-03-01 Thread Tyro[a.c.edwards]
== Quote from Denis Koroskin (2kor...@gmail.com)'s article
> On Tue, 01 Mar 2011 02:08:48 +0300, Tyro[a.c.edwards]

> wrote:
> > == Quote from Denis Koroskin (2kor...@gmail.com)'s article
> >> On Mon, 28 Feb 2011 19:35:47 +0300, Tyro[a.c.edwards]
> > 
> >> wrote:
> >> > On 2/28/2011 11:08 PM, J Chapman wrote:
> >> >> == Quote from Tyro[a.c.edwards] (nos...@home.com)'s article
> >> >>> Both implementations results in error code 1812 being
> > returned from
> >> >>> GetLastError. explanation of the code reads:
> >> >>>ERROR_RESOURCE_DATA_NOT_FOUND
> >> >>>1812 (0x714)
> >> >>>The specified image file did not contain a resource
> > section.
> >> >>> The code I'm porting initially consisted of a resource.h
> > file, a
> >> >>> generic.rc file and two icons. I have not tried to include
> > the icons
> >> >>> and
> >> >>> generic.rc file in the compilation because I do not know
how
> > to as yet
> >> >>> and I've only used half of the resource.h file: didn't
think
> > I need the
> >> >>> whole thing. Could this be the reason for the error? If so
> > could you
> >> >>> direct me to the explanation of how to prepare these files
> > for
> >> >>> inclusion
> >> >>> in the compilation process?
> >> >>> Thanks,
> >> >>> Andrew
> >> >>
> >> >> You need to compile the .rc file (see
> >> >> http://www.digitalmars.com/ctg/rcc.html), then add the
> > resulting .res
> >> >> file
> >> >> to dmd's command line.
> >> >
> >> > Awesome, this does the trick. However I get get a "GP
Fault"?
> > during
> >> > execution. Using windbg, I tracked it down to this piece of
> > code:
> >> >
> >> > void Create()
> >> > {
> >> >_hwnd = CreateWindowExA(
> >> >  _exStyle,
> >> >  cast(const(char*))_wc.GetName(), // returns string
> >> >  cast(const(char*))_windowName,   // string variable
> >> >  _style,
> >> >  _x,
> >> >  _y,
> >> >  _width,
> >> >  _height,
> >> >  _hWndParent,
> >> >  _hMenu,
> >> >  _wc.GetInstance(),
> >> >  _data);
> >> >
> >> >  assert(_hwnd, "Internal error: Window Creation
Failed.");
> >> > }
> >> >
> >> > The program craps at assert() but the error is generated. It
> > just
> >> > displays a dialog box with the message: "test.exe has
stopped
> > working,
> >> > Windows is checking for a solution to the problem..."
> >> >
> >> > I'm thinking that _hwnd was never initialized and that
assert
> > is access
> >> > a null pointer but I cannot be sure. Any suggestions or
ideas?
> >> The
> >> >  cast(const(char*))_wc.GetName()
> >> line look *very* suspicious. You can't get a string and just
> > cast it to
> >> const(char)*. Most importantly, the string (most likely) is
not
> >> null-terminated.
> >> What you need to do here is the following:
> >> auto className = toStringz(_ws.GetName());
> >> auto caption = toStringz(_windowName);
> >> and pass those 2 to the function.
> >
> > Actually I've already tried that, it has no effect on the
outcome.
> > From your suggestion though, I've gone back and replace all the
> > cast(const(char*)) usage throughout the program. Final verdict:
> > the program still crashes it the same location. It actually
never
> > returns from CreateWindowExA().
> >
> >> Alternatively, you could make sure your strings are null-
> > terminated and
> >> pass the pointer directly (e.g. _windowName.ptr):
> >> string _windowName = "foo"; // null-terminated automatically
> >> string _caption = ("Hello, World" ~ "\0")[0..$-1]; // append
> > trailing zero
> >> to an existing string but exclude it from result (so that it's
> > not
> >> included in _caption.length)
> >
> This is indeed strange, but it has nothing to do with the
function itself.
> I still think the parameters you are passing might be invalid.
Try setting
> them to default values and see if that helps. Also try wrapping
the call
> with a try/catch block and output an exception you are getting
(if any).


The problem occurs at the site of the assertion. I wrapped the
function in a try/catch block and placed a call to MessageBoxA()
on either end of the the try block. Both calls to MessageBox fires
and the appropriate messages displayed. No exception is thrown:
made evident my the fact that the third call to MessageBox,
embeded in catch{}, is not fired. Nevertheless, execution haults
at the very next line following/catch and Create() never returns.


Re: string vs. w/char*

2011-03-01 Thread Tyro[a.c.edwards]

On 3/1/2011 7:18 PM, Bekenn wrote:

On 3/1/2011 12:25 AM, Tyro[a.c.edwards] wrote:

Nevertheless, execution haults
at the very next line following/catch and Create() never returns.


CreateWindow sends a few messages to your window proc; anything
interesting happening there?


Not sure how to check those messages, but I guess that's a cue for me to 
do some more research. Off to Google land I go...


Re: string vs. w/char*

2011-03-03 Thread Tyro[a.c.edwards]

On 3/1/2011 8:25 PM, Tyro[a.c.edwards] wrote:

On 3/1/2011 7:18 PM, Bekenn wrote:

On 3/1/2011 12:25 AM, Tyro[a.c.edwards] wrote:

Nevertheless, execution haults
at the very next line following/catch and Create() never returns.


CreateWindow sends a few messages to your window proc; anything
interesting happening there?


Not sure how to check those messages, but I guess that's a cue for me to
do some more research. Off to Google land I go...


After much searching, I've finally located the actual cause of the problem:

class TopWinClass: WinClass
{
this(ushort resId, HINSTANCE hInst, WNDPROC wndProc)
{
super(resId, hInst, wndProc);
SetResIcons(resId);
wc.lpszMenuName = MAKEINTRESOURCEA(resId);  // [PROBLEM]
}
}

The root cause of the problem begins with a lack of understanding of how 
to create a proper resource file for D. I simply took the C++ version, 
compiled it with rcc and linked it to my project: No changes whatsoever. 
Turn out that made the compiler/linker stop complaining, however 
MAKEINTRESOURCEA(resId) still cannot locate the correct resources or 
cannot properly use the resource it finds to initialize wc.lpszMenuName. 
Every access to wc.lpszMenuName after this point fails. If initialize 
wc.lpszMenuName with one of the default strings, say "STATIC" at this 
point, the program runs to completion. I've attached the resource file, 
it hopes that someone could help me with it's conversion.


Thanks.
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"

#define APSTUDIO_READONLY_SYMBOLS
/
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include 

/
#undef APSTUDIO_READONLY_SYMBOLS

/
// English (U.S.) resources

#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32

/
//
// Dialog
//

IDD_ABOUT DIALOG DISCARDABLE  20, 20, 145, 82
STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE
FONT 8, "MS Sans Serif"
BEGIN
DEFPUSHBUTTON   "OK",IDOK,47,62,50,14,WS_GROUP
ICONID_RS,IDC_RS,7,7,20,20,WS_GROUP
CTEXT   "Generic",IDC_STATIC,51,17,42,11
CTEXT   "(c) Reliable Software 1997, 98",IDC_STATIC,19,30,103,11
CTEXT   "http://www.relisoft.com",IDC_STATIC,7,47,130,10
END


#ifdef APSTUDIO_INVOKED
/
//
// TEXTINCLUDE
//

1 TEXTINCLUDE DISCARDABLE 
BEGIN
"resource.h\0"
END

2 TEXTINCLUDE DISCARDABLE 
BEGIN
"#include \r\n"
"\0"
END

3 TEXTINCLUDE DISCARDABLE 
BEGIN
"\r\n"
"\0"
END

#endif// APSTUDIO_INVOKED


/
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
ID_MAIN ICONDISCARDABLE "generic.ico"
ID_RS   ICONDISCARDABLE "rs.ico"

/
//
// Menu
//

ID_MAIN MENU DISCARDABLE 
BEGIN
POPUP "&Program"
BEGIN
MENUITEM "&About...",   IDM_ABOUT
MENUITEM SEPARATOR
MENUITEM "E&xit",   IDM_EXIT
END
POPUP "&Help", HELP
BEGIN
MENUITEM "&Please", IDM_HELP
END
END


/
//
// String Table
//

STRINGTABLE DISCARDABLE 
BEGIN
ID_MAIN "GenericClass"
ID_CAPTION  "Generic Windows Program"
END

#endif// English (U.S.) resources
/



#ifndef APSTUDIO_INVOKED
/
//
// Generated from the TEXTINCLUDE 3 resource.
//


/
#endif// not APSTUDIO_INVOKED



Re: Want to help DMD bugfixing? Write a simple utility.

2011-03-20 Thread Tyro[a.c.edwards]
Not very elegant but this should get the job done:

000 module strip;
001 import std.algoritm : countUntil;
002 import std.array: strip;
003 import std.file : read;
004 import std.string   : splitlines;
005 import std.stdio: writeln;
006
007 void main(string[] args)
008 {
009 bool start = false;
010 bool end = false;
011
012 bool comment = false;
013 bool nested  = false;
014
015 int lBrace, rBrace;
016
017 auto f = cast(char[]) read(args[1]);
018 auto file = splitlines(f);
019
020 foreach(ref ndx, line; file)
021 {
022 if(countUntil(strip(line), "//") == 0)
023 {
024 continue;
025 }
026
027 if(!comment && countUntil(line, "/+", != -1)
028 {
029 nested = true;
030
031 if(countUntil(line, "+/") != -1)
032 nested = false;
033
034 continue;
035 }
036
037 while(nested)
038 {
039 if(countUntil(file[ndx], "+/") != -1)
040 {
041 nested = false;
042 end = true;
043 goto endTest;
044 }
045 ndx++;
046 }
047
048 if(!nested && countUntil(line, "/*", != -1)
049 {
050 comment = true;
051
052 if(countUntil(line, "*/") != -1)
053 comment = false;
054
055 continue;
056 }
057
058 while(comment)
059 {
060 if(countUntil(file[ndx], "*/") != -1)
061 {
062 comment = false;
063 end = true;
064 goto endTest;
065 }
066 ndx++;
067 }
068
069 if(!end && countUntil(line, "unittest") != -1)
070 {
071 start = true;
072 }
073
074 if(!nested && start)
075 {
076 if(countUntil(line, "{") != -1)
077 {
078 lBrace++;
079 }
080
081 if(countUntil(line, "}") != -1)
082 {
083 rBrace++;
084 if(rBrace > 0 && lBrace == rBrace)
085 {
086 end = true;
087 lBrace = rBrace = 0;
088 }
089 }
090 }
091
092 if(!start)
093 writeln(line);
094
095 endTest:;
096 if(end)
097 {
098 start = false;
099 end = false;
100 }
101 }
102 }

cheers.


Re: Want to help DMD bugfixing? Write a simple utility.

2011-03-20 Thread Tyro[a.c.edwards]
The following patch addresses the following issues:

1) fixed improper handling of nested and multiline comments that
do not take up a complete line.

2) eliminate extra blank lines where unit tests and comments are
removed.

Replace lines 31 & 32 with:

# auto n = countUntil(line, "+/");
# if(n != -1 && n < line.lenght - 2)
# {
#   nested = false;
#   goto output;
# }

Replace lines 52 & 53 with:

# auto n = countUntil(line, "*/");
# if(n != -1 && n < line.lenght - 2)
# {
#   comment = false;
#   goto output;
# }

Replace lines 92 - 100 with;

# output:;
# if(!start)
# {
# if(line.length == 0 && !blankLine)
# {
# blankLine = true;
# writeln(line);
# }
# else if(line.length == 0 && blankLine)
# {
# goto endTest;
# }
#
# endTest:;
# if(end)
# {
# start = false;
# end = false;
# blankLine = true;
# }
# }


Re: Want to help DMD bugfixing? Write a simple utility.

2011-03-20 Thread Tyro[a.c.edwards]
Messed that up again: see embeded change. Wish I could just copy
and pase but that's not possible with my current setup.

== Quote from Tyro[a.c.edwards] (nos...@home.com)'s article
> The following patch addresses the following issues:
> 1) fixed improper handling of nested and multiline comments that
> do not take up a complete line.
> 2) eliminate extra blank lines where unit tests and comments are
> removed.
> Replace lines 31 & 32 with:
> # auto n = countUntil(line, "+/");
> # if(n != -1 && n < line.lenght - 2)
> # {
> #   nested = false;
> #   goto output;
> # }
> Replace lines 52 & 53 with:
> # auto n = countUntil(line, "*/");
> # if(n != -1 && n < line.lenght - 2)
> # {
> #   comment = false;
> #   goto output;
> # }
> Replace lines 92 - 100 with;
> # output:;
> # if(!start)
> # {
> # if(line.length == 0 && !blankLine)
> # {
> # blankLine = true;
> # writeln(line);
> # }
> # else if(line.length == 0 && blankLine)
> # {
> # goto endTest;
> # }

#else
#{
#writeln(line);
#}

> #
> # endTest:;
> # if(end)
> # {
> # start = false;
> # end = false;
> # blankLine = true;
> # }
> # }



Re: template instance cannot use local 'f' as parameter to non-global template

2011-07-13 Thread Tyro[a.c.edwards]

On 7/13/2011 11:35 PM, Trass3r wrote:

Am 13.07.2011, 16:02 Uhr, schrieb Steven Schveighoffer
:


void h() {}

class Bla
{
mixin wrap!h;
}

mixin template wrap(alias f)
{
void blub(alias g = f)()
{

g();

}
}



As a workaround, is there a reason you need blub to be parameterized?
I mean, f is already part of the template.


Yep, a default function is passed to wrap and in most cases blub just
calls that one.
But sometimes I need blub to use a function other than the default one.


Don't know it this is the right answer or a possible bug but it does the 
trick:


void h() { import std.stdio; write("h()"); }

class Bla
{
mixin wrap!h;
}

mixin template wrap(alias f)
{
void blub(typeof(&f) g = &f)
{
g();
}
}

void main()
{
Bla b = new Bla();
b.blub();
}


Re: template instance cannot use local 'f' as parameter to non-global template

2011-07-13 Thread Tyro[a.c.edwards]

On 7/14/2011 12:24 AM, Trass3r wrote:

Am 13.07.2011, 16:58 Uhr, schrieb Tyro[a.c.edwards] :

Don't know it this is the right answer or a possible bug but it does
the trick:

void h() { import std.stdio; write("h()"); }

class Bla
{
mixin wrap!h;
}

mixin template wrap(alias f)
{
void blub(typeof(&f) g = &f)
{
g();
}
}

void main()
{
Bla b = new Bla();
b.blub();
}


Thanks!
Unfortunately it doesn't work with more complex functions:

Error: arithmetic/string type expected for value-parameter, not
cl_errcode C function(cl_program program, uint param_name, ulong
param_value_size, void* param_value, ulong* param_value_size_ret)



I gusss the simplest example of the problem you're experiencing would be 
this:


void h() { import std.stdio; write("h()"); }

void function() fp = &h;

class Bla
{
mixin wrap!(fp);
}

mixin template wrap(alias f)
{
void blub()
{
typeof(&f) g = &f;
g();  // <--- source of error [1]
}
}

void main()
{
Bla b = new Bla();
b.blub();
}

edit1.d(19): Error: function expected before (), not g of type uint* C 
function()*


[1] Here you are calling a function pointer which simply returns the 
address of the function... hence your error!


Try calling the function (differencing the pointer as such: (*g)()) and 
your problem is solved.


Re: template instance cannot use local 'f' as parameter to non-global template

2011-07-13 Thread Tyro[a.c.edwards]

On 7/14/2011 12:24 AM, Trass3r wrote:

Am 13.07.2011, 16:58 Uhr, schrieb Tyro[a.c.edwards] :

Don't know it this is the right answer or a possible bug but it does
the trick:

void h() { import std.stdio; write("h()"); }

class Bla
{
mixin wrap!h;
}

mixin template wrap(alias f)
{
void blub(typeof(&f) g = &f)
{
g();
}
}

void main()
{
Bla b = new Bla();
b.blub();
}


Thanks!
Unfortunately it doesn't work with more complex functions:

Error: arithmetic/string type expected for value-parameter, not
cl_errcode C function(cl_program program, uint param_name, ulong
param_value_size, void* param_value, ulong* param_value_size_ret)


I guess the simplest example of the problem you're experiencing would be 
this:


void h() { import std.stdio; write("h()"); }

void function() fp = &h;

class Bla
{
mixin wrap!(fp);
}

mixin template wrap(alias f)
{
void blub()
{
typeof(&f) g = &f;
g();  // <--- source of error [1]
}
}

void main()
{
Bla b = new Bla();
b.blub();
}

edit1.d(19): Error: function expected before (), not g of type void 
function()*


[1] Here you are calling a function pointer which simply returns the 
address of the function... hence your error!


Try calling the function pointed to by differencing the pointer as such: 
(*g)() and your problem is solved.


How does one correct shadowing (hidden by) errors?

2011-07-22 Thread Tyro[a.c.edwards]
While attempting to build the DFL libraries, I encountered the following 
three errors:


[1] tabcontrol.d(18): Error: class dfl.tabcontrol.TabPage use of 
dfl.control.Control.opEquals(Control ctrl) hidden by TabPage is deprecated


[2] tabcontrol.d(18): Error: class dfl.tabcontrol.TabPage use of 
dfl.control.Control.opCmp(Control ctrl) hidden by TabPage is deprecated


[3] imagelist.d(22): Error: class 
dfl.imagelist.ImageList.ImageCollection use of 
dfl.imagelist.ImageList.ImageCollection.ListWrapArray!(Image,_images,_adding,_added,_blankListCallback,_removed,false,false,false).insert(int 
index, Image value) hidden by ImageCollection is deprecated


Now I know I can bypass this with the -d switch but I'm more interested 
in fixing the problem than bypassing it.


Control defines the following two functions:

override Dequ opEquals(Object o)
{
Control ctrl = cast(Control)o;
if(!ctrl)
return 0; // Not equal.
return opEquals(ctrl);
}

override int opCmp(Object o)
{
Control ctrl = cast(Control)o;
if(!ctrl)
return -1;
return opCmp(ctrl);
}

Whereas TabPage defines the following:

override Dequ opEquals(Object o)
{
return text == getObjectString(o);
}

override int opCmp(Object o)
{
return stringICmp(text, getObjectString(o));
}

How does one correct this such that the latter does not hide the first?

Problem [3] on the other hand is caused by a template mixin in the 
dfl.imagelist.ImageList.ImageCollection. ImageCollection is not a 
derived class so I do not understand what is being hidden. Please 
explain. Also, a suggestion on how to correct the issue would be 
helpful. The code is as follows:


class ImageList
{
class ImageCollection
{
...
public:
mixin ListWrapArray!(Image, _images,
_adding, _added,
_blankListCallback!(Image), _removed,
false, false, false);
}
...
}

Thanks


Re: How does one correct shadowing (hidden by) errors?

2011-07-23 Thread Tyro[a.c.edwards]

On 7/23/2011 7:49 PM, bearophile wrote:

Tyro[a.c.edwards]:


[3] imagelist.d(22): Error: class
dfl.imagelist.ImageList.ImageCollection use of
dfl.imagelist.ImageList.ImageCollection.ListWrapArray!(Image,_images,_adding,_added,_blankListCallback,_removed,false,false,false).insert(int
index, Image value) hidden by ImageCollection is deprecated

Now I know I can bypass this with the -d switch but I'm more interested
in fixing the problem than bypassing it.


There is a trick based on explicit alias to avoid those errors. I'd like the 
idea of using this alias to be present in that error message...

Bye,
bearophile


Please do share. I thought the concept explicit alias simply requires me 
to do his:


alias ListWrapArray LWA;
mixin LWA!(Image, _images,
_adding, _added,
_blankListCallback!(Image), _removed,
false, false, false);

This did not work... resulted in the same error. On closer look it seems 
the actual problem is not the template but the definition of "insert" 
therein. It is being hidden by the definition of insert in ImageCollection.


ImageCollection definition:

void insert(int index, Image img)
{
if(index >= _images.length)
{
add(img);
}
else
{
assert(0, "Must add images to the end of the image 
list");
}
}

ListWrapArray definition:

void insert(int index, TValue value)
{
_insert(index, value);
}

In the end it turns out to be the same problem as one and two. Any 
suggestion on how to deal with these correctly? I can resolve this 
particular error by renaming the function to "Insert" in 
ImageCollection. But even though it appeases the compiler, is that the 
correct solution? Is there something else that I'm not taking into 
consideration? How do I fix the other two since there is no way to 
rename opApply and opCmp that I'm aware of?


Thanks


Compiling DMD on MAC OS X

2012-02-19 Thread Tyro[a.c.edwards]

Hi all,

I've just installed DMD 2.058 and attempted to compile a little 
script but was greeted with the following error:


gcc: Invalid argument

I used the .dmg installer from http://www.dlang.org/download.html 
and issued the command:


dmd average

Is there something I'm missing?

Thanks,
Andrew


Re: Compiling DMD on MAC OS X

2012-02-20 Thread Tyro[a.c.edwards]

On Sunday, 19 February 2012 at 11:39:15 UTC, kraybourne wrote:

On 2/19/12 09:20 , Tyro[a.c.edwards] wrote:

Hi all,

I've just installed DMD 2.058 and attempted to compile a 
little script

but was greeted with the following error:

gcc: Invalid argument

I used the .dmg installer from 
http://www.dlang.org/download.html and

issued the command:

dmd average

Is there something I'm missing?

Thanks,
Andrew


Hi!

Could you try

dmd -v avarage

and tell us what comes out?
Also, how does avarage.d look? Also what does

uname -a

and
gcc --version

say? Also, just in case

which dmd


I made the mistake of assuming that gcc was automatically 
installed in MAC OSX. After installing Xcode the problem went 
away. To answer your questions though:


I'm using DMD version 2.058 for MAC OSX which I installed using 
the .dmg package available at 
"http://www.dlang.org/download.html";.


"gcc --version" yields:

i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. 
build 5658) (LLVM build 2336.9.00)

Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  
There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE.


"uname -a" yields:

Darwin Andrews-MacBook-Pro.local 11.3.0 Darwin Kernel Version 
11.3.0: Thu Jan 12 18:47:41 PST 2012; 
root:xnu-1699.24.23~1/RELEASE_X86_64 x86_64


the average program is as follows:

[code]
import std.stdio: stdin, writefln;
import std.conv: to;

void main(string[] args)
{
   double sum = 0.0;
   int cnt = 0;
   foreach(line; stdin.byLine())
   {
  if(line.length)
  {
 sum += to!double (line);
 cnt++;
  }
   }

   double avg = sum / cnt;
   writefln("Average is %.5f", avg);
}
[/code]

and I doubt you want me to put all of what "dmd -v" spits out for 
this little script.


Thanks,
Andrew



ftp connection with socket

2009-04-12 Thread Tyro[a.c.edwards]
Hi,

I hoping someone could whip up an example of how to check if it's possible to 
connect to a given site: eg. ftp.digitalmars.com and display a message if 
unsuccessful. If one is already available, could someone please point me to it?

Thanks,
Andrew


Re: ftp connection with socket

2009-04-12 Thread Tyro[a.c.edwards]
Per Jarrett Billingsley's advice, the following is provided:

   I am using DMD v2.028 w/Phobos 2

Thanks again.

Tyro[a.c.edwards] Wrote:

> Hi,
> 
> I hoping someone could whip up an example of how to check if it's possible to 
> connect to a given site: eg. ftp.digitalmars.com and display a message if 
> unsuccessful. If one is already available, could someone please point me to 
> it?
> 
> Thanks,
> Andrew



Re: When asking for help on how to do something...

2009-04-12 Thread Tyro[a.c.edwards]
Jarrett Billingsley Wrote:

> Please, *please* indicate whether you are using Phobos 1, Phobos 2, or Tango.
> 
> It's hard enough trying to read your mind about what you're trying to
> do.  It's even harder when there are two or three completely different
> solutions to it.

Jarrett,

I've always used the most recent version of DMD, and being that I only work on 
extremely short code to help me automate my job, I've always managed to stay on 
the bleeding edge (ie. 2.029 if it shows up two seconds after I send this 
response).  The only other library I use is DFL so the thought has actually 
never crossed my mind. Thank you much for the guidance. I will be sure to 
provide that info in the future.

R/S,
Andrew


Re: When asking for help on how to do something...

2009-04-12 Thread Tyro[a.c.edwards]
Jarrett Billingsley Wrote:

> Please, *please* indicate whether you are using Phobos 1, Phobos 2, or Tango.
> 
> It's hard enough trying to read your mind about what you're trying to
> do.  It's even harder when there are two or three completely different
> solutions to it.

Jarrett,

I've always used the most recent version of DMD, and being that I only work on 
extremely short code to help me automate my job, I've always managed to stay on 
the bleeding edge (ie. 2.029 if it shows up two seconds after I send this 
response).  The only other library I use is DFL so the thought has actually 
never crossed my mind. Thank you much for the guidance. I will be sure to 
provide that info in the future.

R/S,
Andrew


static initialization of associative arrays

2009-04-15 Thread Tyro[a.c.edwards]
Is it yet possible to statically initialize an associative array? If so, 
please point me to the documentation. I am using DMD v2.028.


Thanks,
Andrew


static initialization of associative arrays

2009-04-15 Thread Tyro[a.c.edwards]
Is it yet possible to statically initialize an associative array? If so, 
please point me to the documentation. I am using DMD v2.028.


Currently I'm able to do this:

import std.stdio;

string[string] types;
static this(){
types = [ "void":"void", "bool":"bool" ];
}

void main(){
writeln(types);
}

Output = [void:void,bool:bool] which is exactly what I want.

However, removing static this() results in an error.

string[string] types = [ "void":"void", "bool":"bool" ];

Result:
api.d(77): Error: non-constant expression ["void":"void","bool":"bool"]

How do I make the initialization constant?

Thanks,
Andrew


std.range this._input.opIndex(index) error

2009-04-22 Thread Tyro[a.c.edwards]

Attempting to compile the following from snippet

auto r = iota(0, 10, 1);
assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][]));

from the documentation, I encountered following error

range.d(1184): Error: this._input.opIndex(index) is not an lvalue

Looking at the code I find "return _input[index];" on line 1184. The 
variable _input is defined as R _input in the template Take(R) which is 
the template instantiated to create iota. Problem is, it is obvious why 
this doesn't work since the Range data variable "_input" is accessed the 
same way on multiple occasions throughout the file, a Range variable can 
obviously supports random access, and no attempt is being made to modify 
the range at this point in the code. Any information would be greatly 
appreciated?


Thanks in advance,
Andrew


std.range this._input.opIndex(index) error

2009-04-22 Thread Tyro[a.c.edwards]

Attempting to compile the following from snippet

auto r = iota(0, 10, 1);
assert(equal(r, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][]));

from the documentation, I encountered following error

range.d(1184): Error: this._input.opIndex(index) is not an lvalue

Looking at the code I find "return _input[index];" on line 1184. The 
variable _input is defined as R _input in the template Take(R) which is 
the template instantiated to create iota. Problem is, it is not obvious 
why this doesn't work since the Range data variable "_input" is accessed 
the same way on multiple occasions throughout the file, a Range variable 
can obviously supports random access, and no attempt is being made to 
modify the range at this point in the code. Any information would be 
greatly appreciated?


Thanks in advance,
Andrew


How to check for internet connectivity and download file?

2009-04-26 Thread Tyro[a.c.edwards]
I've used Burton Radons' "urllib" in the past to get download files from the 
internet, however the library has atrophied and can no longer be used with DMD 
v2.029 (not how long it's been this way because I haven't tried to compile it 
since 2006).

I'm wondering if someone could point me to an example of how to check for 
internet connectivity and if available download the latest version of a given 
file.

Thanks in advance.
Andrew


Re: How to check for internet connectivity and download file?

2009-04-26 Thread Tyro[a.c.edwards]
Unknown W. Brackets Wrote:

> Well, checking for internet connectivity is a tricky and 
> operating-specific thing.
> 
> Would you rather check for connectivity with a specific host?  I gather 
> that would be more than appropriate for what you're wanting.

This should do just fine. Afterall it would do no good if I have connectivity 
but cannot reach the intended host.

> Are you wanting to download over HTTP, or a different protocol?  If over 
> HTTP, there are a ton of libraries that may be useful to you, and 
> there's also building your own HTTP request (which is actually pretty 
> trivial.)

I'm trying to download over both FTP and HTTP. Not sure if the same process is 
applicable to both protocols but I'm assuming not. 

> If you're using Tango, it has classes in it for these things.

Unfortunately I haven't played with Tango many years now and got away from D1 
as soon D2 forked back in 2007.

> -[Unknown]
> 
> 
> Tyro[a.c.edwards] wrote:
> > I've used Burton Radons' "urllib" in the past to get download files from 
> > the internet, however the library has atrophied and can no longer be used 
> > with DMD v2.029 (not how long it's been this way because I haven't tried to 
> > compile it since 2006).
> > 
> > I'm wondering if someone could point me to an example of how to check for 
> > internet connectivity and if available download the latest version of a 
> > given file.
> > 
> > Thanks in advance.
> > Andrew



Re: How to check for internet connectivity and download file?

2009-04-27 Thread Tyro[a.c.edwards]

On 4/27/2009 5:14 PM, Unknown W. Brackets wrote:

If you want both HTTP and FTP, it's definitely worth using a library for
it. There are a lot of options, but almost all of them are out of date I
suppose for 2.x...

I've always hated curl, but you might look at how hard it is to get/make
d headers for it. This might work fine for you.


Apparently Kenneth Bogert did some work on curl a while back. cURL 
happens to host it on their site so I'll give it a shot.



HTTP is relatively easy. You can see a sample in
dmd/samples/d/htmlget.d. This isn't exactly a right example, because it
completely ignores Transfer-Encoding, but if you search and replace
HTTP/1.1 with HTTP/1.0, it should be usable although the check for
 is an ugly hack and 100% wrong.


I'll take a look at it. I'm sure there is something there worth learning.


FTP is more work. You have to send and receive commands, so it's slower.
It's also worth maintaining state if you download more than one file
from the same server.

I have a library that does it, but unfortunately it's for 1.x. I'm
planning to update it, but I won't be able to for a little while. I
could explain what you need to do if you want to mess with the socket
stuff...


I'm virtually hopeless when it comes to these things so will happily 
accept assistance in whatever form I can get it. If you are willing to 
explain I will graciously accept the lesson.



But again, it's complicated enough it's not a good idea to do it
yourself imho unless you like reading RFCs (I do, but I'm a strange one.)


Can't say I have much fondness for RFCs but over time that might change. 
As for being a strange one... well I'm as strange as they come so I will 
not be passing judgment anytime soon.



-[Unknown]


How-to: input/output "Japanese Characters"?

2009-05-02 Thread Tyro[a.c.edwards]

I'm on a Japanese system attempting to input/output Japanese Characters
and cannot seem to accomplish it. How would I read
"憲法記念日 理念と現実、広がる格差" from stdin/file and output the same 
to stdout/file?


Thanks,
Andrew


Re: How-to: input/output "Japanese Characters"?

2009-05-02 Thread Tyro[a.c.edwards]

On 5/3/2009 7:41 AM, Georg Wrede wrote:

Tyro[a.c.edwards] wrote:

I'm on a Japanese system attempting to input/output Japanese Characters
and cannot seem to accomplish it. How would I read
"憲法記念日 理念と現実、広がる格差" from stdin/file and output the
same to stdout/file?


import std.stdio;

void main()
{
auto lin = readln();
writeln(lin);
}

Works with your Japanese strings. It just works(tm).


Interesting... for whatever reason I thought I had to cast/convert
to!dstring in order to get the correct output. Which kept resulting in:

 std.utf.UtfException: 4invalid UTF-8 sequence

thank you very much.


Resource availability: fonts

2009-05-05 Thread Tyro[a.c.edwards]
One cannot necessarily rely on particular font being available on a system, and 
for security reasons asminsistrators restrict instalation of fonts (among other 
things) onto systems in a network. I would like to know if it is possible to 
embed a font into my code so that I know that it will always be there, or can I 
provide it with the exe but not have to rely on it being "installed" (i.e. use 
it from the same folder in which the exe resides)? 

Thanks,
Andrew


Re: Resource availability: fonts

2009-05-06 Thread Tyro[a.c.edwards]

On 5/6/2009 12:30 PM, Daniel Keep wrote:


Tyro[a.c.edwards] wrote:

One cannot necessarily rely on particular font being available on a system, and for 
security reasons asminsistrators restrict instalation of fonts (among other things) onto 
systems in a network. I would like to know if it is possible to embed a font into my code 
so that I know that it will always be there, or can I provide it with the exe but not 
have to rely on it being "installed" (i.e. use it from the same folder in which 
the exe resides)?

Thanks,
Andrew


That depends.  What are you using the font for?

If you're using a library that requires a family name, then probably
not.  If you're using a library that can accept a file name, then
probably yes.


I'm using DFL which uses family names (eg. "Times New Roman").


Remember that the system doesn't care if you append crap to the end of
an executable.  One trick you can use is to just append whatever files
you want to the end of the executable, and then have a little 1K block
at the end that tells you where the files are and how big they are; you
can then extract the files at run time and delete them when you terminate.



When I do this, how do I ensure that the program is able to locate the 
font after extraction without "installing" it?



   -- Daniel


Re: Resource availability: fonts

2009-05-06 Thread Tyro[a.c.edwards]

On 5/6/2009 1:39 PM, grauzone wrote:

Use
ubyte[] fontbytes = cast(ubyte[])import("yourfont.ttf");


This will take care of making sure the font is available. How do you 
instruct the library (DFL in this case) that this variable contains the 
font or that after you write it back to the hard drive to refer to the 
file? A font that is not installed, but instead, simply residing in a 
folder of your choosing?


Re: Resource availability: fonts

2009-05-06 Thread Tyro[a.c.edwards]

On 5/6/2009 9:50 PM, John C wrote:

Tyro[a.c.edwards] Wrote:


When I do this, how do I ensure that the program is able to locate the
font after extraction without "installing" it?



I think AddFontResource from the SDK will do that. 
http://msdn.microsoft.com/en-us/library/dd183326(VS.85).aspx


That was it... Aswesome! Thank you all very much for your assistance.


std.random:uniform - uncompilable example from docs

2009-05-09 Thread Tyro[a.c.edwards]

http://www.digitalmars.com/d/2.0/phobos/std_random.html#uniform

Above documentation  provides the following example:

Random gen(unpredictableSeed);
// Generate an integer in [0, 1023]
auto a = uniform(0, 1024, gen);
// Generate a float in [0, 1)
auto a = uniform(0.0f, 1.0f, gen);

Which, when complied, produces the following errors:

C:\Users\Andrew\code>dmd eds32
eds32.d(9): Error: function std.random.unpredictableSeed is used as a type
eds32.d(9): Error: cannot have parameter of type void
eds32.d(10): Error: function learn.eds32.randNum.gen (void) does not 
match parameter types ()

eds32.d(10): Error: expected 1 function arguments, not 0
eds32.d(10): Error: template std.random.uniform(immutable(char)[] 
boundaries = "[)",T1,T2,UniformRandomNumberGenerator) if 
(is(CommonType!(T1,UniformRandomNumberGenerator) == void) && 
!is(CommonType!(T1,T2) == void)) does not match any function template 
declaration
eds32.d(10): Error: template std.random.uniform(immutable(char)[] 
boundaries = "[)",T1,T2,UniformRandomNumberGenerator) if 
(is(CommonType!(T1,UniformRandomNumberGenerator) == void) && 
!is(CommonType!(T1,T2) == void)) cannot deduce template function from 
argument types !()(int,int,MersenneTwisterEngine!(uint,32,624,397,

31,-1727483681u,11,7,-1658038656u,15,-272236544u,18))

Suggest that the first line of the example be changed to:

auto gen = Random(unpredictableSeed);

Or that a correctly working example be provided.

Andrew


D input: how-to (RFC)

2009-05-10 Thread Tyro[a.c.edwards]
I am looking for a D version of scanf() but I'm sure there is no such 
thing so I tried contrived one. I am sure I missed a slew of obvious 
things and that this cannot be used for much more than a little toy on 
my personal computer. I would like to make it usable for others so I am 
asking for some guidance/suggestions for making it better.


Thanks,
Andrew

This is written in D2 v2.029 with an updated std.random to fix a problem 
I was having with the current release.


module ace.io;

private import std.conv: to, ConvError;
private import std.string: split, stripr;

public import std.stdio;

int read(/+File inFile = stdin,+/ A...)(out A a) /+Uncommenting results
in: Error: arithmetic/string type expected for value-parameter, not
File+/
{  start:
   auto data = stripr(readln());
   auto input = split(data);

   string assign()
   {
   return
   `  try {
if(a.length != input.length)
return -1;
a[i] = to!(typeof(t))(input[i]);
  } catch (ConvError e) {
  writeln("Invalid input!");
  goto start;
  }`;
   }

   foreach(i, t; a)
   {
 static if(is(typeof(t) == void))
   {}
 else static if(is(typeof(t) == bool))
   {}
 else static if(is(typeof(t) == byte))
   mixin(assign);
 else static if(is(typeof(t) == ubyte))
   mixin(assign);
 else static if(is(typeof(t) == short))
   mixin(assign);
 else static if(is(typeof(t) == ushort))
   mixin(assign);
 else static if(is(typeof(t) == int))
   mixin(assign);
 else static if(is(typeof(t) == uint))
   mixin(assign);
 else static if(is(typeof(t) == long))
   mixin(assign);
 else static if(is(typeof(t) == ulong))
   mixin(assign);
 /+static if(is(typeof(t) == cent))
   mixin(assign);
 static if(is(typeof(t) == ucent))
   mixin(assign);+/
 else static if(is(typeof(t) == float))
   mixin(assign);
 else static if(is(typeof(t) == double))
   mixin(assign);
 else static if(is(typeof(t) == real))
   mixin(assign);
 else static if(is(typeof(t) == ifloat))
   a[i] = ifloat.max;
 else static if(is(typeof(t) == idouble))
   a[i] = idouble.max;
 else static if(is(typeof(t) == ireal))
   a[i] = ireal.max;
 else static if(is(typeof(t) == cfloat))
   a[i] = cfloat.max;
 else static if(is(typeof(t) == cdouble))
   a[i] = cdouble.max;
 else static if(is(typeof(t) == creal))
   a[i] = creal.max;
 else static if(is(typeof(t) == char))
   a[i] = input[i][0];
 else static if(is(typeof(t) == wchar))
   mixin(assign);
 else static if(is(typeof(t) == dchar))
   a[i] = input[i][0];
 else static if(is(typeof(t) == string))
   if(a.length > 1)
 a[i] = input[i];
   else
 a[i] = data;
 else static if(is(typeof(t) == dstring))
   {}
 else static if(is(typeof(t) == char[]))
   a[i] = stripr(data).dup;
   }
   return 0;
}


Re: D input: how-to (RFC)

2009-05-11 Thread Tyro[a.c.edwards]

On 5/11/2009 2:35 PM, grauzone wrote:

Tyro[a.c.edwards] wrote:

I am looking for a D version of scanf() but I'm sure there is no such
thing so I tried contrived one. I am sure I missed a slew of obvious


There's readf() in std.stream. I think you have to use std.cstream : din
to use it with stdin.


Thanks, but I'm trying to learn here... Hoping I can get a better
understanding of how things work or are supposed to work. I'll probably 
change it back from read() to get().





int read(/+File inFile = stdin,+/ A...)(out A a) /+Uncommenting results
in: Error: arithmetic/string type expected for value-parameter, not
File+/


That would make inFile a template parameter, which obviously doesn't
make sense with objects, and I guess File is an object. This should work:

int read(A...)(File inFile, out A a)


OK... that works, but how would I set stdin as the default input "file"?

I tried: int read(A...)(out A a, File inFile = stdin) but the compiler 
hangs trying to compile it whenever I call read() using 50% of the CPU 
resource in the process.



{ start:
auto data = stripr(readln());
auto input = split(data);

string assign()
{
return
` try {
if(a.length != input.length)
return -1;
a[i] = to!(typeof(t))(input[i]);
} catch (ConvError e) {
writeln("Invalid input!");
goto start;
}`;
}


If the user types in too much or too less input, read() returns with an
error (-1), and the caller has to deal with it.
If the user typed in something unparseable, the function prompts an
error and lets the user retry.
This is inconsistent.


Got it... would it be better for the caller handles such problems or the 
compiler?



Also, instead of using CTFE to return a const string, why not simply

const assign = `  ` ;


tried that but kept tying "string assign = " and "auto assign = "; both 
of which kept failing until I placed it in a function. Thanks I have 
changed it to enum.



You're using D 2.0, you probably have to replace "const" by "enum". I
don't know.

You use goto to retry. I'd replace it by a loop. If someone wants to
argue with me if goto is or is not evil, go ahead.


foreach(i, t; a)
{
static if(is(typeof(t) == void))
{}
else static if(is(typeof(t) == bool))
{}


bools can't be read? If the implementation is incomplete, there should
be at least an "assert(false);", maybe even a "static assert(false);".


Got it. What value would you read for a bool though? to me it can be 
0||1, true||false, yes||no, etc... Would I simply use 0 && 1 and forget 
about the rest?



else static if(is(typeof(t) == byte))
mixin(assign);
else static if(is(typeof(t) == ubyte))
mixin(assign);
else static if(is(typeof(t) == short))
mixin(assign);
else static if(is(typeof(t) == ushort))
mixin(assign);
else static if(is(typeof(t) == int))
mixin(assign);
else static if(is(typeof(t) == uint))
mixin(assign);
else static if(is(typeof(t) == long))
mixin(assign);
else static if(is(typeof(t) == ulong))
mixin(assign);
/+static if(is(typeof(t) == cent))
mixin(assign);
static if(is(typeof(t) == ucent))
mixin(assign);+/
else static if(is(typeof(t) == float))
mixin(assign);
else static if(is(typeof(t) == double))
mixin(assign);
else static if(is(typeof(t) == real))
mixin(assign);


Oh god, what the fuck! String mixins are the new #define! OK, at least


ROTFDWL - that was truly unexpected. Thanks.


this reduces the code duplication, but the code duplication shouldn't be
there in the first place.

You could just throw all the types into a tuple, and then foreach() on
it, checking for the type in each iteration.


Awesome... I didn't even think about that. Got it!


Or just make a single giant if() statement to check for all types to!()
supports (like if(is(typeof(t) == int) && is(typeof(t) == uint)...). In
any case, you could reduce the number of is() parts by using isNumeric()
from std.traits.

Or find a way to check for to!() supported data types automatically (but
I don't know to!() well enough if this is possible).


else static if(is(typeof(t) == ifloat))
a[i] = ifloat.max;
else static if(is(typeof(t) == idouble))
a[i] = idouble.max;
else static if(is(typeof(t) == ireal))
a[i] = ireal.max;
else static if(is(typeof(t) == cfloat))
a[i] = cfloat.max;
else static if(is(typeof(t) == cdouble))
a[i] = cdouble.max;
else static if(is(typeof(t) == creal))
a[i] = creal.max;


What?


That's a residue of my first try... I will take care of those. I really 
should have replaced those with "assert(false);" because I didn't 
understand how to implement them. Will read some more and try again in.





else static if(is(typeof(t) == char))
a[i] = input[i][0];


input could be an empty string, and random things could happen.


got it...


else static if(is(typeof(t) == wchar))
mixin(assign);
else static if(is(typeof(t) == dchar))
a[i] = input[i][0];
else static if(is(typeof(t) == 

Re: Simple file manipulation

2009-05-20 Thread Tyro[a.c.edwards]

On 5/20/2009 6:19 PM, BLS wrote:

Sam Hu wrote:

I looked up in D2 in std.stdio,std.file,std.cstream and std.stream and
try to find a very simple method which can read from a file once a
value other than once an entire row.I just can not find it maybe this
idea is wrong.Say how to simply read & write key/value pairs to and
from a file like this format:

//file "data.dat"
Tommy M 22

where the keys are name,gender and age while the values are Tommy,M ,22.

I found there is methods that can read from a file once an entire
row.But is there a simple method which can read once a value?In C++
one can do like this:

#include 
#include 
using namespace std;
ifstream inData;
inData.open("data.dat");
inData>>name;
inData>>gender;
inData>>age;

cout<<"Info:"<

IN D2 you can use std.file and slurp (cool name, beside)
slurp reads an entire file into an array.

// Load file; each line is an string followed by whitespace , another
//string followed by whitespace and a int.

auto a = slurp!(string, string, int)("data.dat", "%s %s %s");

Now you can go on an play a bit with the new range stuff. (std.range)

Enjoy, Björn


Unfortunately, that will not work. DMD fails with a Stack Overflow 
whenever upon encountering any of the string types (dstring, string, 
char[], wstring, etc...) being passed to this template. Works fine or 
other types as far as I can tell (including arrays).



import std.file;

void main()
{
auto a = slurp!(string)("", "%s");
}

results in Stack Overflow during compilation.


How does one properly display an animated GIF using DFL?

2009-08-26 Thread tyro[a.c.edwards]
I am able to display the GIF but all animation ceases. How would I activate 
this feature?

Thanks,
Andrew