Re: Get and set terminal size

2014-04-19 Thread Adam D. Ruppe via Digitalmars-d-learn

Blargh, I don't know teh ldc switch for it :(

Try adding pragma(lib, curses); (or ncurses) to your file with 
main in it, i think ldc supports that.


Re: toString() through interface

2014-04-19 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 20 April 2014 at 00:35:30 UTC, David Held wrote:
Since all implementations of an interface must derive from 
Object


That's not true. They can also come from IUnknown or a C++ 
interface.



cast(Object)(foo).toString();


(cast(Object)foo).toString() might work


This might return null tho if it is a non-D object through the 
interface!


Re: Writing to stdin of a process

2014-04-26 Thread Adam D. Ruppe via Digitalmars-d-learn
On Saturday, 26 April 2014 at 08:45:59 UTC, Craig Dillabaugh 
wrote:

Can anyone tell me what I am dong wrong.


In this case, I'd close the pipe when you're done.


pipes.stdin().writeln(Hello world);
pipes.stdin.close;


myecho loops on stdin until it receives everything; until the 
pipe is closed.


testpipes waits for myecho to complete before termination.


The two processes are waiting on each other: testpipes won't 
close the file until it exits, and myecho won't exit until 
testpipes closes the file.


an explicit call to close breaks the deadlock.


In this case, flushing would cause the one line to appear, 
because of the buffering yazd talked about, but the program still 
wouldn't terminate since a flushed buffer still potentially has 
more coming so echo would see that line, then wait for  more..


Re: Socket server + thread: cpu usage

2014-04-29 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 29 April 2014 at 17:16:33 UTC, Tim wrote:

Is there anything I'm doing wrong?


You should be using a blocking socket. With them, the operating 
system will put your thread on hold until a new connection comes 
in. Without them, it will endlessly loop doing absolutely nothing 
except checking if a new connection is there yet. Horribly, 
horribly inefficient.


Re: Socket server + thread: cpu usage

2014-05-01 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 1 May 2014 at 08:08:37 UTC, Tim wrote:
... the CPU usage goes up. I think that SocketShutdown.BOTH 
causes Socket.select to fail which results in an endless loop. 
Any suggestions how to handle that problem?


It shouldn't be here, disconnect would affect the new socket, and 
you're calling select on the accepting socket, which is still 
good to accept a new connection.


What's your code look like for handing a socket returned by 
accept?


Re: Decoding HTML escape sequences

2014-05-12 Thread Adam D. Ruppe via Digitalmars-d-learn
You should use decodeComponent instead of decode in your matchAll 
loop.


IMO encodeComponent and decodeComponent are the only two useful 
uri encode functions (btw same in JS, use decodeURIComponent 
instead of the other functions). The other ones have weird rules.


Re: Can't call isDir on linux on const object

2014-05-19 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 19 May 2014 at 20:11:45 UTC, Spacen wrote:

The same code works on windows DMD 1.65. But on linux:


It's because of caching. isDir on Linux calls a function with 
this comment:


/++
This is to support lazy evaluation, because doing 
stat's is

expensive and not always needed.

Try both stat and lstat for isFile and isDir
to detect broken symlinks.
 +/
void _ensureStatOrLStatDone()


Simple solution is to just take a plain DirEntry instead of in 
DirEntry so it isn't const.


Re: [std.c.stdlib] (malloc(something) is null) or (malloc(something) == 0)?

2014-05-20 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 20 May 2014 at 14:03:17 UTC, Alexandr Druzhinin wrote:

if(data ?) // is null vs == 0


Both would work and do the same thing, but I prefer is null 
because that is most consistent with other D code (where there 
might be a difference between the two).


Re: How to get struct's members ?

2014-05-22 Thread Adam D. Ruppe via Digitalmars-d-learn
allMembers yields the names of all the members. Try .tupleof on 
an object instead, that might work better.


Re: Building and using a function library

2014-05-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 25 May 2014 at 19:07:10 UTC, Charles Parker wrote:
./min_cut.d(15): Error: module line_count from file 
../my_utils/line_count.d must be imported as module 'line_count'


That means you forgot the module line in line_count.d

At the top of that file, add:

module my_utils.line_count;

and leave everything else the same and you should be ok.

The error is saying that the name of the import line should 
always match the name of the module line which wasn't the case 
here.


Re: Looping over all enum values

2014-05-28 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 28 May 2014 at 20:19:45 UTC, Mark Isaacson wrote:

Is there a mechanism that allows you to loop over all of an
enum's values? I've wanted to do so a couple times now for
CTFE/mixin templates.


__traits(allMembers) on the enum can do it or this can help too 
http://dlang.org/phobos/std_traits.html#EnumMembers


Re: Read file on compiler time.

2014-05-29 Thread Adam D. Ruppe via Digitalmars-d-learn

string a = import(file.txt);

dmd yourprogram.d -Jlocation_of_file


so for example

dmd yourprogram.d -J.


if file.txt is in the same directory as the .d file.


Re: Read file on compiler time.

2014-05-29 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 29 May 2014 at 20:38:30 UTC, Remo wrote:
Now another question is it also possible to save/write string 
at compile time?


Sort of, use

pragma(msg, some string);

and it will be printed out when that code is compiled. Important 
that it is when the code is compiled, NOT when the code is 
executed at compile time. So


void foo() { pragma(msg, here); }

will say here even if you never call foo. So you can't use it 
to print stuff out inside CTFE loops, and you might need to 
shield it with version {} or static if() {} to suppress printing.


But you can use it to print a completed string or something and 
then redirect it to a file in your makefile to do something:


string myfunction() {
   string value;
   foreach(a; [a, b]) value ~= a;
   return value;
}

pragma(msg, myfunction()); // would say ab

dmd yourfile.d 21  foo.txt # redirect all compiler output into 
foo.txt





If you find yourself wanting to print a lot, I say you should 
just use a regualr program that runs normally instead of CTFE. 
Since most the language works the same way, transitioning to and 
from regular execution and compile time execution is easy and 
generally doesn't need you to change most the code.


Re: Kernel in D

2014-05-31 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 31 May 2014 at 07:28:32 UTC, Mineko wrote:

Any ideas? :P


Buy my book, chapter 11 talks about it a little to get you 
started :P


http://www.packtpub.com/discover-advantages-of-programming-in-d-cookbook/book


The summary of my approach there is:

1) Use a regular linux compiler and a custom linker script to 
make an ELF executable, I wouldn't worry about making a cross 
compiler or anything fancy like that.


2) Use GRUB or qemu -kernel to boot that executable. No need to 
write your own bootloader.


3) Compile without the runtime, instead using a minimal object.d, 
here's a fairly simple one for example: 
http://arsdnet.net/dcode/bare/object.d or a more complete one can 
be found in here: http://arsdnet.net/dcode/minimal.zip


4) Add back features from teh real druntime as needed, but I say 
avoid those that are too hard to do memory management manually 
(so like just leave array concatenation unimplemented, instead 
write a regular struct that owns its own memory and has append 
methods and use it)


5) Love inline asm and naked functions for interrupt handlers

6) Pay attention to struct alignment (also see chapter 7 of my 
book if you decide to go that route) when defining hardware 
layouts!


7) Don't try to use TLS variables, always use __gshared on module 
level or static variables cuz tls won't actually work.




That should get you started to play around!


Re: Forward reference to nested function not allowed?

2014-05-31 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 31 May 2014 at 16:18:35 UTC, DLearner wrote:

Is this intended?


Yes, nested functions access local variables and thus follow the 
same order of declaration rules as they do; you can't use a local 
variable before it is declared so same with a nested function.


Re: Kernel in D

2014-05-31 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 31 May 2014 at 22:54:48 UTC, Qox wrote:

scope(exit) foo();


uses exception handling in the background.


That just works with dmd even in the bare metal environmnet.

Throwing an exception needs library support with dmd but you can 
copy/paste it from druntime - I did that in my minimal.zip.


Re: Separate allocation and construction?

2014-06-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 5 June 2014 at 22:22:16 UTC, Chris Williams wrote:
If I wanted to allocate memory for a class and then call its 
constructor as two separate steps, while still having the 
object be managed by the garbage collector, is there any way to 
do that?



Check out std.conv.emplace
http://dlang.org/phobos/std_conv.html#emplace

First, allocate the memory block for the class. The size is 
__traits(classInstanceSize, Yourclass). Then slice it:


enum size = __traits(classInstanceSize, YourClass);
auto memory = GC.malloc(size)[0 .. size];


Then use emplace to do the construction:

auto obj = emplace!YourClass(memory, ctor_args...);


GC.malloc can be found in import core.memory; 
http://dlang.org/phobos/core_memory.html#malloc



Note that you can also use other memory allocators here if you 
didn't want it gc'd.


Re: Can't link libs?

2014-06-06 Thread Adam D. Ruppe via Digitalmars-d-learn
When you compile the final program, the library .d file needs to 
be available too, either in the folder based on its name or 
passed straight to dmd explicitly.


Despite the presence of the .lib file, the .d file is still 
needed so it can get code prototypes and type names, etc., out of 
it.


(If you have the .d though, the lib is rarely needed. Indeed, the 
way I do most D libraries is to just pass all the .d files to the 
compiler at once and forget about lib files.)


Re: Can't link libs?

2014-06-06 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 6 June 2014 at 16:41:24 UTC, K.K. wrote:

I have kept all the files in one folder. So if I don't need to
explicitly call the .lib in DMD, does that mean the .lib is just
a passive object? Should I make libs in place of object files?


If you pass all the .d files at once, you don't need the .lib at 
all and the compiler will also just do one object file.


Simplest (and usually fastest!) way to build:

dmd yourfile.d otherfile.d lib/file.d lib/otherfile.d 
otherlib/file.d


and so on - then don't worry about object or lib files. Of course 
if you need a dll or something that's different...


Re: Can't link libs?

2014-06-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 6 June 2014 at 17:02:33 UTC, K.K. wrote:

Oh okay, I get what you mean. I guess I was really over
complicating it then? xD


Yea, I think a lot of people do: building C++ takes some extra 
steps out of necessity that you can just ignore in D for the most 
part :)



Thanks for the help Adam! -I'm totally digging your book btw!


Cool, write amazon reviews when you're done too if you feel like 
it :P


BTW also feel free to ask here or to even email me if you see 
anything in the book that you want clarification or more info on.


Re: Windows DLL / Windows service

2014-06-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 7 June 2014 at 14:41:15 UTC, Etienne Cimon wrote:
no documentation though. Any idea how to attach/detach with a 
known example? I'd also like to create a windows DLL that 
compiles through DMD/GDC/LDC with extern(c) so that folks from 
C++ can link with it .


Check this out: http://wiki.dlang.org/Win32_DLLs_in_D

should help you get started.


Re: Running a delegate inside a C function

2014-06-07 Thread Adam D. Ruppe via Digitalmars-d-learn

See my answer to this:

http://stackoverflow.com/questions/22845175/pass-delegates-to-external-c-functions-in-d


Since a delegate is two pointers and most C functions expect only 
one pointer, you need to do some kind of magic. There's one 
solution. Another is if the C function can pass a void* argument 
to the callback function, you pass your class that way and 
forward it to the method by casting it back.


But when interacting with C libraries, you should generally use a 
function pointer rather than a delegate.


Re: Class Data Members Name Reflection

2014-06-10 Thread Adam D. Ruppe via Digitalmars-d-learn
Two options: do allMembers and filter it out to only be data 
members, or do some slicing of tupleof.stringof:


S s;
foreach(idx, member; s.tupleof) {
   writeln(Name: , s.tupleof[idx].stringof[2..$]);
}


The tupleof[idx] inside the loop is important instead of just 
using member because then you get the name, then the slicing is 
because you get:


s.foo

for example, and you want to slice off the s. to leave just the 
name.


Re: Class Data Members Name Reflection

2014-06-10 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 10 June 2014 at 16:30:52 UTC, Nordlöw wrote:

What trait should I use to filter out data members?


No trait, more like an is thing to see if the thing has an init. 
I think


static if(is(typeof(__traits(getMember, Thing, name).init)) { }

will do it. (BTW the sample chapter of my book talks about 
reflection, I think I talked about some of this in there: 
http://www.packtpub.com/discover-advantages-of-programming-in-d-cookbook/book 
)



foreach (ix, memb; arg.args[0].front.tupleof)


Eeek, I actually used s for a reason there - it gives you a 
simple name that is easily repeated and filtered. The nasty 
string you're seeing is the name of a compiler-generated 
temporary variable in the foreach.


That said, your field names are in there at the end, so another 
option would be to run it through lastIndexOf(.) and then slice 
to that.


So it works backward to the dot and slices off the rest of the 
string.


string s = arg.args[0].front.tupleof[idx].stringof;
auto dotIndex = s.lastIndexOf(.);
assert(dotIndex = 0); // it ought to be there anyway
auto name = s[dotIndex + 1 .. $]; // slice off the temp name, 
whatever it is




Re: Basics of calling C from D

2014-06-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 13:52:09 UTC, belkin wrote:

Question: How do I use it from D?


Write the prototype in your D file with extern(C):
extern(C) int factorial(int n);

then just call the function normally in D. Make sure you include 
all the C object files when you compile the D program too so it 
all links together.


Re: Basics of calling C from D

2014-06-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 14:11:04 UTC, simendsjo wrote:

I believe the correct answer should be Buy my book!.


ah, of course! I should just make a .sig file lol

http://www.packtpub.com/discover-advantages-of-programming-in-d-cookbook/book

chapter 4 talks about this kind of thing :P


Re: modulo Strangeness?

2014-06-11 Thread Adam D. Ruppe via Digitalmars-d-learn
modulo of a negative number can give some surprising results. A 
negative index in that array would cause it to throw a range 
error, so my guess is that's what you're getting. If you do 
%array.length though it becomes an unsigned math and thus will 
never be negative, explaining the different result.


Remember btw that when foreaching over an array, the value you 
get is the number in the array, not the index.


Re: Basics of calling C from D

2014-06-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 14:45:22 UTC, simendsjo wrote:
I must say I really like your writing-style as well as the 
down-to-earth and precise and concise presentation of the 
material. So kudos to you!


thanks, don't forget to tell that to amazon review readers too :P

Really looking forward to reading some of the more advanced 
material as well as seeing your dconf presentation.


Based on the pace of dconf posting, it'll probably be early July 
before it is online :(




Re: Nameless Static Array

2014-06-12 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 12 June 2014 at 15:58:25 UTC, Taylor Hillegeist 
wrote:
But without the NEW strategy. I must allocate static arrays and 
set them to a pointer in my struct. Not too big of deal really.


Have you considered just making the buffer a struct member?


Re: Nameless Static Array

2014-06-12 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 12 June 2014 at 16:08:49 UTC, Taylor Hillegeist 
wrote:
I am considering having different sized arrays for the buffer. 
I just figured that meant having different structs with various 
sizes.


You might be able to do it with a templated struct and alias 
this. Check this out:


struct R_Buffer {
   int[] buffer;
}

struct R_Buffer_Sized(size_t bufferSize) {
   int[bufferSize] buffer;
   R_Buffer getGenericBuffer() { return R_Buffer(buffer[]); }
   alias getGenericBuffer this;
}

usage:

R_Buffer_Sized!48 buffer;

then you can pass buffer to any function expecting a regular 
R_Buffer and it will just work. Be careful not to store the 
buffer though, since it is stack allocated, escaping a reference 
to it will lead to crashes.




That's also the reason why something like this is a bit 
problematic:

R_R_Buffer RRB=R_R_Buffer(uint[12]);

What's the lifetime of the uint[12]? It is in the scope of the 
function call only, so if this were allowed, the compiler might 
consider it a temporary... and then you'd escape a reference to 
it and get corrupted data.


Putting the buffer up top as a separate variable at least gives 
it a clear lifetime scope.


Re: Cannot alias null

2014-06-12 Thread Adam D. Ruppe via Digitalmars-d-learn

since null is a value maybe you want

enum blah = null;

you may also give it a type after the enum word


Re: Regarding DConf 2014

2014-06-15 Thread Adam D. Ruppe via Digitalmars-d-learn
The videos are being posted at a rate of about two per week. So 
far talks 1-5 are up plus Scott Meyer's talk, you can find the 
links in the announce group. 
http://forum.dlang.org/group/digitalmars.D.announce


Re: Struct Constructors

2014-06-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 16 June 2014 at 22:03:28 UTC, Mark Blume wrote:
Why exactly isn't a constructor without any parameters is not 
allowed?


The idea is that declaring a plain struct always has almost zero 
cost - it is just static data with no extra code run. A zero-arg 
constructor (aka a default constructor in C++) that is run 
automatically on the declaration breaks that idea.


Since sometimes people want it anyway the compromise is to make a 
static opCall and explictly use it with parenthesis. This was 
introduced before D had any struct constructors at all.


Then struct constructors were added to D later and they override 
the old static opCall method... but they must have at least one 
parameter.



So short answer is the confusion is caused by two historical 
features that basically did the same thing. Nowadays, static 
opCall should mostly be avoided. Use constructors instead. Only 
if you need a zero arg constructor should you consider static 
opCall.



Does Struct(params) also call Struct.opCall(params)?


If there's no constructor, i think it can. But like i said above, 
you should avoid this because it is mostly just historical 
baggage. Use constructors.


BTW non-static opCall is a different story, that can be useful 
for defining functor objects. That only works on an instance 
object though:


struct Foo { void opCall() { } }

Foo foo; // doesn't call any code, just plain variable declaration
foo(); // calls foo.opCall();


Re: std.algorithm.map - function by reference

2014-06-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 24 June 2014 at 21:46:16 UTC, kuba wrote:

The main point here is to avoid unnecessary copies


You should make sure this actually matters - passing doubles by 
ref for example is probably slower than just passing a regular 
double.


Re: What is best way to communicate between computer in local network ?

2014-06-27 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 27 June 2014 at 12:51:45 UTC, bioinfornatics wrote:
I do not know if that is better to use websocket and if they 
exists into dlang:


you could use websocket in D but if you are talking between two 
separate D programs you can just use a regular socket


http://dlang.org/phobos/std_socket.html

If you have a copy of my book, I have a brief how-to on 
std.socket in chapter 2. But for two computers just talking to 
one another all you have to do is on one:


new Socket
bind
accept

and on the other one:

new Socket
connect


See the documentation for info on each of those methods.


Re: Why is the Win32 boilerplate the way it is?

2014-06-30 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 30 June 2014 at 15:14:24 UTC, Jeremy Sorensen wrote:

documentation means import core.sys.windows.windwos


The Windows headers that come with D are pathetically minimal. 
You'll need to grab a more complete win32 header OR copy/paste 
the individual prototypes off MSDN and use them that way.


So add this to your D file after importing 
core.sys.windows.windows:


extern(Windows)
void GetStartupInfoA(STARTUPINFO*); // the pathetic druntime 
Windows headers define TCHAR as ascii, so we'll use the A version



And try compiling it. If it complains that STARTUPINFO is 
undefined too, copy its prototype in:


struct STARTUPINFO {
  DWORD  cb;
  LPTSTR lpReserved;
  LPTSTR lpDesktop;
  LPTSTR lpTitle;
  DWORD  dwX;
  DWORD  dwY;
  DWORD  dwXSize;
  DWORD  dwYSize;
  DWORD  dwXCountChars;
  DWORD  dwYCountChars;
  DWORD  dwFillAttribute;
  DWORD  dwFlags;
  WORD   wShowWindow;
  WORD   cbReserved2;
  LPBYTE lpReserved2;
  HANDLE hStdInput;
  HANDLE hStdOutput;
  HANDLE hStdError;
}


And that should make it work.


Re: File needs to be closed on Windows but not on Posix, bug?

2014-07-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 5 July 2014 at 20:23:03 UTC, Joakim wrote:

This seems like inconsistent behavior: should I file a bug?


This is because the operating systems do it differently; I think 
D is doing the right thing by being a pretty thin wrapper around 
that functionality.


If anything, I'd just say deleting an open file may not be 
permitted in the docs, implying that the user should always close 
it themselves before deleting it.


Re: Using a delegate when interfacing with C

2014-07-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 5 July 2014 at 22:18:56 UTC, Marco Cosentino wrote:

   auto client = *(cast(ClientImplementation*) data);


Try just

auto client = cast(ClientImplementation) data;


and

 this.setProcessCallback(callback, cast(void *) this);

setProcessCallback(callback, cast(void*) this);


Can somebody help me in figuring out why this happens?



The reason is a class this in D is already a pointer (just a 
hidden one) so when you do this in a class, it is like a 
ClientImplementation** in C - a pointer to a (temporary) pointer. 
So by the time the callback runs, it is pointing to nonsense.


In general, remember any class reference in D is already 
equivalent to a pointer in C or C++ and can be casted straight to 
void* without needing to take its address.


Re: Introspecting a Module with Traits, allMembers

2014-07-10 Thread Adam D. Ruppe via Digitalmars-d-learn
The others have already given some answers, I just want to point 
out that the (free) sample chapter of my D book covers this topic 
too: 
http://www.packtpub.com/discover-advantages-of-programming-in-d-cookbook/book


Scanning a whole module and getting everything out takes a few 
tricks that I talk about in there.


Re: Question about @nogc in D 2.066

2014-07-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 11 July 2014 at 20:02:32 UTC, Weasel wrote:

Why does the s1 not throw an error, but the a1 does?


Strings don't allocate upon use whereas all other arrays do 
unless you specifically mark it as static - immutability isn't 
considered here (I think because the part of the compiler that 
looks at the array literal doesn't look at the type on the left 
hand side so it just doesn't know but i'm not sure about why).


But if you make the immutable other array static it shouldn't GC 
allocate.


Re: reference to delegates and garbage collection

2014-07-14 Thread Adam D. Ruppe via Digitalmars-d-learn
I'm just guessing, but it looks to me that the delegate's pointer 
might be on the stack there and isn't overwritten when the one 
function returns, so the gc still thinks there might be an active 
pointer to it.


Re: is there a way to pause a program and resume with just a key press (or enter key)

2014-07-15 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 15 July 2014 at 02:49:56 UTC, WhatMeWorry wrote:
Is there a way to continue with any old key press? or just the 
enter key?


Yeah. It is more complex than you'd think but my terminal library 
can do it:


https://github.com/adamdruppe/arsd/blob/master/terminal.d

Example usage:

import terminal;

void main() {
  auto terminal = Terminal(ConsoleOutputType.linear);

  // gives real time input capability
  auto input = RealTimeConsoleInput(terminal, 
ConsoleInputFlags.raw);


  // write to them
  terminal.writeln(Press any key to exit);

  // get a single key
  auto ch = input.getch();
  terminal.writeln(Bye!);
}


PS this is also described in my book 
http://www.packtpub.com/discover-advantages-of-programming-in-d-cookbook/book


Re: Problem with trying sample from doc page

2014-07-16 Thread Adam D. Ruppe via Digitalmars-d-learn
I would just change all the longs to ints and it would probably 
work. Or all the longs to ints.


It really should have been consistent in the docs, since the 
point of this is delegate vs function, not int vs long...


Re: Converting a POD struct to a class at compile-time ?

2014-07-16 Thread Adam D. Ruppe via Digitalmars-d-learn
Not a direct answer, but the way I'd do this is to just use 
composition:


class Foo {
   YourStruct _this;
   alias _this this;
}


boom, it'd work pretty well just like that...


Re: Converting a POD struct to a class at compile-time ?

2014-07-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 16 July 2014 at 17:43:03 UTC, Klb wrote:


auto names = __traits(allMembers, S);


Error: static variable _names_field_0 cannot be read at compile 
time.


The problem there is names is a regular runtime variable and 
mixins need to use compile time stuff. If you make that enum 
instead of auto, it'll probably work.


Re: Grabing C(++) stdout

2014-07-23 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 23 July 2014 at 15:30:53 UTC, Chris wrote:

Redirect it from stdout to somewhere else.


It might be writing to stderr instead of stdout... does anything 
change if you reopen stderr too?


Re: zlibs gzip dosent work with http

2014-07-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 24 July 2014 at 13:09:53 UTC, Sean Campbell wrote:
I'm trying to add gzip compression to a HTTP server i wrote in 
D. here is the code that dose the gzip encoding.


I know zlib gzip works for http, I used it in my cgi.d


if(gzipResponse  acceptsGzip  isAll) {
auto c = new Compress(HeaderFormat.gzip); 
// want gzip


auto data = c.compress(t);
data ~= c.flush();

t = data;
}


But your http server is buggy in a lot of ways. It doesn't reply 
to curl and doesn't keep the connection open to issue manual 
requests.



Among the bugs I see looking at it quickly:

server.d getRequestHeaderFieldValue, you don't check if epos is 
-1. If it is, you should return null or something instead of 
trying to use it - the connection will hang because of an 
out-of-bounds array read killing the handler.



You also wrote:

if ((Info.modGzip)  
(indexOf(client.getRequestHeaderFieldValue(Accept-Encoding),gzip) 
!= -1)){



Notice the  instead of . That's in fspipedserver.d.



Finally, you write client.client.send... which never sent the 
headers back to the client, so it didn't know you were gzipping! 
Change that to client.sendData (and change sendData in server.d 
to take in void[] instead of void[]) and then it sends the 
headers and seems to work by my eyeballing.




if ((Info.modGzip)  
(indexOf(client.getRequestHeaderFieldValue(Accept-Encoding),gzip) 
!= -1)){

writeln(gzip);
auto gzip = new Compress(HeaderFormat.gzip);
client.addToResponseHeader(Content-Encoding: gzip);
client.sendHeader(200 ok);
while (0  (filestream.readBlock(readbuffer))){
client.client.send(gzip.compress(readbuffer));
}
client.client.send(gzip.flush());
delete gzip;
delete filestream;
}

but when i test it Firefox, internet explorer and chrome says 
that the encoding or compression is bad. why? the data is 
compressed with gzip.


the rest of the code is available at 
http://sourceforge.net/p/netspark/netsparkb1/ci/master/tree/


Git
git clone git://git.code.sf.net/p/netspark/netsparkb1 
netspark-netsparkb1




Re: D JSON (WAT?!)

2014-07-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 24 July 2014 at 15:15:37 UTC, Pavel wrote:

  string s = parsed[fail].str;


Since there is no entry fail in the object, it returns a null 
JSON_VALUE pointer. Trying to get the string out of it is then 
seen as a null pointer access and kills the program.


Check for null on a key before trying to get a value out.


Re: Manually allocated structs

2014-07-27 Thread Adam D. Ruppe via Digitalmars-d-learn

I would do it something like this:

struct test {
size_t size;

@property char[] buf() {
return (_buf.ptr)[0 .. size];
}
private char[0] _buf;
}


The buf property returns a slice that uses the size member to 
give you bounds checking, but uses the ptr of the final member in 
the struct to bypass bounds checking on that array.


That way, you can allocate as much memory as you need without 
having to use the naked pointer anywhere outside, getting D to 
help you stay in bounds.


Re: Are there desktop appications being developed in D currently?

2014-08-10 Thread Adam D. Ruppe via Digitalmars-d-learn
I wrote a terminal emulator in D a while ago 
https://github.com/adamdruppe/terminal-emulator


terminal emulators are pretty boring as far as desktop 
applications go though. I have more on my to do list but haven't 
actually gotten to them yet.


Re: Are there desktop appications being developed in D currently?

2014-08-10 Thread Adam D. Ruppe via Digitalmars-d-learn
My thing works on Windows and Linux btw, though the windows 
version pipes to the plink program to talk to ssh. It'd be pretty 
easy to make it a stand alone thing though with a few tweaks, 
then it could be like an escape sequence handling library.


Re: Are there desktop appications being developed in D currently?

2014-08-10 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 10 August 2014 at 14:28:33 UTC, Puming wrote:
What do you mean by 'boring'? I think a shell in D would be 
awesome.


tbh I think shells are a bit boring too, but like you said in the 
other message, they are two different things.


But a terminal emulator isn't much of a gui because all it 
displays is text (and mine actually can display pictures too) - 
no buttons, text areas, checkboxes, etc. like typically comes to 
mind when you think of a desktop gui app.


I've been slowly writing a miniature gui widget library too, with 
the goal of zero dependencies and  300kb compiled executables... 
but I just haven't had the time. Whenever I need a quick gui for 
a personal project I've actually been outputting html or 
something and reading the response with my cgi.d. html forms 
cover like 95% of my use cases.


5. MVC style input/output. The out put of commands can be 
formated with a template (with color and indentations, even 
markdown support). traditional shell outputs are a mess.


I like what Windows Powershell does - it talks in objects which 
can be formatted to string or passed to other commands that 
understand them.


For a while, I was toying with doing that in D too. I don't 
remember where I put the file (a super-simplified version is in 
my book somewhere though)... but the shell commands were actually 
just D functions that return strongly typed stuff. When composing 
them, it calls the function directly and communicating with 
external commands  it does some simple toString serialization and 
deserialization so that works too.


But I haven't finished it in great part because I find regular 
old bash to work well enough for me.


7. autocomplete and auto style. write colorful code in the 
repl. Vi/emacs support of inline editing is also a plus.


gnu readline which bash uses allows the editing and autocomplete 
which is cool.


Re: RAII limitations in D?

2014-08-21 Thread Adam D. Ruppe via Digitalmars-d-learn
On Friday, 22 August 2014 at 02:22:16 UTC, Timothee Cour via 
Digitalmars-d-learn wrote:

What would be a good answer to this article?


It's own publication date: Feb 2009. The D struct has changed a 
lot since then, getting new features (@disable, postblit, more 
reliable destructor) and bugs notwithstanding is pretty well on 
point nowadays.


All the stuff mentioned in there works now.


Re: How to compare two types?

2014-08-31 Thread Adam D. Ruppe via Digitalmars-d-learn

There's two ways:

static if(is(One == Two)) {

}


That compares the static types in a form of conditional 
compilation. http://dlang.org/expression.html#IsExpression


If you want to compare the runtime type of a class object, you 
can do:


if(typeid(obj_one) == typeid(obj_two))

that should tell you if they are the same dynamic class type.


Re: How to compare two types?

2014-08-31 Thread Adam D. Ruppe via Digitalmars-d-learn

typeof() always gets the static type, typeid() is needed if you
want the dynamic type.


Re: How to compare two types?

2014-08-31 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 31 August 2014 at 23:53:31 UTC, bearophile wrote:

if (is(typeof(obj_one) == typeof(obj_two)))


You could, but since it is static info you might as well use 
static if.


Re: Downloading Files in D

2014-09-10 Thread Adam D. Ruppe via Digitalmars-d-learn
The curl one should be easiest for just downloading files. The 
big problems with it are that it can be a pain to get the library 
working with versioning and stuff and that it sometimes does the 
wrong thing in advanced use cases.


But if the curl library works for you at all, doing downloading 
with it is easy.


Re: when should I use a function call without parenteses?

2014-09-15 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 16 September 2014 at 01:11:49 UTC, AsmMan wrote:

In which context do you use a function call without paranteses?


It is really just personal preference, people tend to leave the 
parens off when they just add subjective noise. A good rule 
though would be to leave the parens off when it is an obvious 
function call or if the function is cheap enough that the call 
doesn't matter (if it is just a thin property for example).


I want to know when/why should I use or if it depends only to 
programmer's coding style..


basically yeah it is just that.


Re: Function Pointers with Type T

2014-09-15 Thread Adam D. Ruppe via Digitalmars-d-learn

You can get the code to compile with two changes:

bool function(T)(T val1,T val2) ptr=comp;

should be:

bool function(T val1,T val2) ptr=comp!T;



The function pointer itself isn't a template, so it doesn't need 
the (T) parameter. Instead, since it is inside a template, you 
can just use the T from the outside directly.


Moreover, comp has compile time arguments, so you can't take the 
address of it without forwarding the arguments. So instead of 
comp, you use comp!T - passing the T from the outside to the 
comparison function too.


and also

int partition(T)(T[]list,bool function(T)(T val1,T val2)ptr,int

should be:

int partition(T)(T[]list,bool function(T val1,T val2)ptr,int


Again because the pointer isn't a new template, it should just 
use the type T from the outer argument list.


Re: Why if(__ctfe)?

2014-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn
On Tuesday, 16 September 2014 at 13:11:50 UTC, Ilya Yaroshenko 
wrote:

Why not static if(__ctfe) ?


ctfe is a runtime condition. The function has the same code when 
run at compile time, it is just being run in a different 
environment.


Re: Function Pointers with Type T

2014-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 16 September 2014 at 17:32:02 UTC, amparacha wrote:
Thanks Adam you saved me from alot.Just one more question how 
can

I compare two arguments of type T.


If you want to compare the values, just use them like regular 
variables. If you want to compare the types, use:


static if(is(T == R)) { }

or one of the other forms here 
http://dlang.org/expression.html#IsExpression


For example:

bool typesMatch(T, R)() {
   static if(is(T == R)) return true;
   return false;
}

writeln(typesMatch!(int, float)); // false
writeln(typesMatch!(int, int)); // true


Re: Unicode arithmetic at run-time

2014-09-20 Thread Adam D. Ruppe via Digitalmars-d-learn
On Sunday, 21 September 2014 at 03:00:34 UTC, Charles McAnany 
wrote:

writefln(%c, '/U0001F0A1'+1); //


The problem here is just that arithmetic converts everything back 
to integers and writefln is a bit picky about types. You can 
print it though by casting it back to dchar:


writefln(%c, cast(dchar)('\U0001F0A1'+1));

My fonts don't support these chars but it should print out if you 
do that.


Re: sign oauth request

2014-09-25 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 25 September 2014 at 17:03:43 UTC, John Chapman 
wrote:

http://dlang.org/phobos/std_digest_sha.html#SHA1


Not quite the same, the oauth requires hmac.

When I did this in my oauth.d for twitter and stuff, I used the C 
library mhash


check out my code:

https://github.com/adamdruppe/arsd/blob/master/oauth.d#L796

The rest of that lib is kinda sloppy and has a few dependencies 
from my other modules but feel free to use whatever looks useful 
to you.


I think mhash is GPL licensed.


Re: What is a sink delegate?

2014-09-30 Thread Adam D. Ruppe via Digitalmars-d-learn
On Tuesday, 30 September 2014 at 17:22:44 UTC, Gary Willoughby 
wrote:

What is a sink delegate?


Instead of

string toString() { return foo; }

for example, you would use:

void toString(void delegate(string) sink) { sink(foo); }

The sink argument there is then free to view and discard the data 
or to make a private copy using whatever scheme it desires.


Re: cgi.d - fastcgi - how am i suppose to link in libfcgi.a or libfcgi.lib

2014-10-01 Thread Adam D. Ruppe via Digitalmars-d-learn
Try linking in these .obj files that I compiled for windows a 
while ago:


http://arsdnet.net/dcode/fcgi_win.zip

so unzip that, put it in your project directory and just add both 
.obj files to your compile command line along with 
-version=fastcgi.


It has been a LONG time since I used that, but I'm pretty sure 
that worked when I tried it on 32 bit windows and running the 
program through IIS.


Re: cgi.d - fastcgi - LightTPD is not cooperative

2014-10-02 Thread Adam D. Ruppe via Digitalmars-d-learn

Try running the program yourself with a port argument

yourprogram.exe --port 3000

for example, then have lighttpd configured to connect to that 
port for the application. That's what I had to do for nginx on 
Windows, lighttpd might be the same thing.


Re: cgi.d - fastcgi - LightTPD is not cooperative

2014-10-02 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 2 October 2014 at 13:53:48 UTC, Sycam_Inc wrote:
when running in the browser the page just continues to load and 
the lighttpd console shows no output from it and it dosent 
write anything in the file.


What url did you use in the browser and what's your lighttpd 
config look like? The program might be correct and the config is 
just off.


Re: How do I check if a function got CTFE?

2014-10-02 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 2 October 2014 at 17:56:29 UTC, AsmMan wrote:
I'd like to check if a function got CTFE, ie, the compiler was 
able to replace my foo(s); by the computed value at 
compile-time.


You have to explicitly force ctfe with context, it is never done 
automatically, and if it fails, the build will fail and you get a 
compile time error.


So if you write

enum f = foo();

or

static f = foo();

or similar initializations and the build succeeds, you know it 
got ctfe'd. Otherwise, it wasn't.


Re: cgi.d - fastcgi - LightTPD is not cooperative

2014-10-03 Thread Adam D. Ruppe via Digitalmars-d-learn
Hmm, I don't know and don't have it set up on windows to try 
right now. My suggestion is to look for getting it to work with C 
or C++ - since my cgi.d lib uses a C library, it should work 
exactly the same way in terms of configuration.


Re: 'write' crashes without extra window

2014-10-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 7 October 2014 at 23:41:14 UTC, Joel wrote:
it had been opening with a command prompt, so I got rid of the 
prompt and now it some times crashes.


That's a feature - writing to a non-existent handle fails, so it 
throws an exception. (The reason you don't notice this in 
something like C is you prolly don't check printf's return 
value...)


You could just wrap the write function in a try/catch to 
explicitly ignore the error.




Re: The module declaration is being ignored

2014-10-08 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wed, Oct 08, 2014 at 06:39:26PM +, Diffuse via Digitalmars-d-learn wrote:
 Everything works fine. But things also compile if I declare
 file2's module to be module candyfloss while still importing
 file2 within main.d

You should always import the same thing as the module, but you also
need to pass the file to the compiler explicitly so it can find it.

dmd main.d file2.d

would work if you did import candyfloss; and module candyfloss;


In general, I recommend always passing all files to the compiler explicitly
so it can build an accurate file to module mapping and link all code in.



Re: Simple import question

2014-10-09 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 9 October 2014 at 18:21:32 UTC, WhatMeWorry wrote:
To import one module from another, specify the name of the 
module in an import declaration. The name must include the 
relative path computed from the directory where compilation 
takes place


This is not true. It is a REALLY common misconception, but it is 
not true. The import name must match the name given in the module 
declaration of the file.


So in the file you're importing, add module your.name; to the 
top. In the main file, import it as import your.name;. If those 
two don't match, it will complain cannot import module foo as 
foo.bar or something like that.


It is recommended that the module name match the file name and 
folder name, but it is the module declaration at the top that 
matters, not the file/folder name.



Ok, but how does one determine where compilation takes place?


The directory from which you run the compiler. But the best way 
is to explicitly pass all the file names to the compiler:


dmd yourfile.d file2.d folder/file3.d and so on...

Doing that will serve you best in the long run, it will work with 
any module name and will link better too.


Re: When betterC triggers errors in compilation?

2014-10-14 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 14 October 2014 at 13:20:50 UTC, eles wrote:

http://forum.dlang.org/post/lddug4$jgv$1...@digitalmars.com


That was just a speculative thread, that stuff isn't implemented. 
(And I think that went way too far, IMO betterC should just 
remove the mandatory stuff like ModuleInfo and TypeInfo 
assumptions and leave the rest to be opt in. I'd be against it 
making exception handling an error).


-betterC right now is still an undocumented hack that doesn't do 
much.


Re: Mixin template functions are ignored in struct

2014-10-14 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 14 October 2014 at 20:58:19 UTC, tcak wrote:
So, thus this mean overloading is not supported with mixin 
templates?


Nope, what happens is mixin stuff adds items by name. If you have 
a variable or function in the object with the same name, it 
overrides the mixin one entirely.


This is really useful for customizing the behavior of a mixin by 
taking most but not all of its functions.


Re: Mixin template functions are ignored in struct

2014-10-14 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 14 October 2014 at 21:21:33 UTC, tcak wrote:
Anyway, that suggested usage is making my work harder. I am 
putting that mixin in many struct and defining each method one 
by one in that way doesn't seem like suitable to me.


You could rename the method in the struct then mixin the rest. 
Like


private mixin template TestCommonMethods(){
public bool apply( int d, int e ){
return false;
}
}

public struct Test{
public mixin TestCommonMethods;

public bool apply2( char c ){ // now named apply2
return true;
}
}

void main(){
Test t;
t.apply( 5, 3 ); // works
t.apply2('c'); // also works
}



The mixin template might also define an apply function that just 
forwards the call to the other name, similarly to how a final 
method in a class or interface might call a virtual function to 
allow customization.


Re: Why was scope for allocating classes on the stack marked for deprecation?

2014-10-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 17 October 2014 at 16:56:50 UTC, Jeremy DeHaan wrote:
I'm curious as to why using scope to allocate classes on the 
stack was marked for future deprecation.


It was never implemented correctly (it is supposed prove it never 
leaves the scope, and is thus safe to be on the stack), so rather 
than keep a half baked feature in the language, the gang wanted 
to move it to the library where at least the usage wouldn't look 
as normal given the memory safety problems.


Re: Initializing D in C to use?

2014-10-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 17 October 2014 at 16:35:46 UTC, Jeremy DeHaan wrote:
I remember reading something(but my googlefu is weak today) 
about having to initialize the runtime if you are using D 
inside another language. Can anyone confirm this is the case?


Yeah, unless the main() is in D, you need to run initialization 
functions.


The way I recommend doing it is to write your own extern(C) 
MyLib_Init and MyLib_Term functions. Then have their 
implementations call the import core.runtime; Runtime.initialize()


http://dlang.org/phobos/core_runtime.html#initialize

This way, you can do other init stuff for your lib too without 
the user worrying about those details. Furthermore, having to 
call a library init function is somewhat normal for C libs, so 
the user shouldn't think much of it.


Re: Initializing D in C to use?

2014-10-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 17 October 2014 at 17:14:30 UTC, K.K. wrote:

Sorry if this isn't the most helpful answer but.. Do you have
Adam Ruppe's book?


buy my book too, and write amazon reviews :P

A lot of the topics in there were chosen because there are 
questions that come up somewhat often on this forum or the D chat 
room. I answer a lot of questions here too, but the book is cool 
too!


Re: Generating code based on UDA

2014-10-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 25 October 2014 at 13:37:56 UTC, Rares Pop wrote:
Aiming to generate code based on UDA I wonder if the following 
is possible:


Yes, and copy/pasting that works for me...


Re: Generating code based on UDA

2014-10-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 25 October 2014 at 13:45:29 UTC, Rares Pop wrote:

What do you mean by copy/pasting ?


I literally copied the code in your post (and fixed a missing 
semicolon) and got it to compile.


Passing A as an argument to injections should work. You can also 
use this and typeof(this) inside the injections template code to 
access the class. It should all work.


Re: HTML Parsing lib

2014-10-25 Thread Adam D. Ruppe via Digitalmars-d-learn

Another option for html is my dom.d

https://github.com/adamdruppe/arsd

get dom.d and characterencodings.d in your project directory.

compile with dmd yourfile.d dom.d characterencodings.d

here's an example:

import arsd.dom;

void main() {
   auto document = new Document();

   // The example document will be defined inline here
   // We could also load the string from a file with
   // std.file.readText or the web with std.net.curl.get
   document.parseGarbage(`htmlhead
 meta name=author content=Adam D. Ruppe
 titleTest Document/title
   /head
   body
 pThis is the first paragraph of our a
href=test.htmltest document/a.
 pThis second paragraph also has a a
href=test2.htmllink/a.
 p id=custom-paragraphOld text/p
   /body
   /html`);

   import std.stdio;
   // retrieve and print some meta information
   writeln(document.title);
   writeln(document.getMeta(author));
   // show a paragraph’s text
   writeln(document.requireSelector(p).innerText);
   // modify all links
   document[a[href]].setValue(source, your-site);
   // change some html
   document.requireElementById(custom-paragraph).innerHTML =
New bHTML/b!;
   // show the new document
   writeln(document.toString());
}




You can replace the html string with something like
std.file.readText(yourfile.html); too


My library is meant to give an api similar to javascript.


I don't use dub so idk about how to use that, I just recommend
adding my files to your project if you wanna try it.


Re: Dart bindings for D?

2014-10-29 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 29 October 2014 at 22:12:32 UTC, Laeeth Isharc 
wrote:
I will have a crack at starting this unless anyone knows of any 
already in existence.


I haven't heard of any.

Rationale for using Dart in combination with D is that I am not 
thrilled about learning or writing in Javascript, yet one has 
to do processing on the client in some language, and there seem 
very few viable alternatives for that.


What kind of client are you doing? If you are writing a web page, 
you don't need any kind of script language API. JavaScript or 
dart or whatever talk with your server application through http 
requests or websockets, whereas script language APIs are meant 
for extending your application in the same process. For example, 
a text editor might have a script language to make custom 
functions for hotkeys.


Re: Dart bindings for D?

2014-10-29 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 29 October 2014 at 22:22:39 UTC, ketmar via 
Digitalmars-d-learn wrote:
it's not lightning fast, though, but the code is understandable 
and it's fairly easy to extend the language if necessary.


Curious, what have you tried with it?

I wanted to keep it simple but actually complicated it more than 
I wanted to, it is cool to know it isn't hard to use.


What I really like though is that the var type works in D too, 
making interoperation so easy. My only disappointment is 
@property still doesn't work, making foo.bar()() need the double 
parens!


you can take it in ARSD repository: 
https://github.com/adamdruppe/arsd
what you need is jsvar.d and script.d, just two files and no 
external libs required.


Here's an example usage:


import arsd.script;

void main() {
// this var holds the global variables of the script 
engine

var globals = var.emptyObject;

// you can set up values or functions with plain 
assignment in D

globals.myFunction = (int a, int b) { return a + b; };

import std.file;
// run the interpret function passing script code and the 
variables

interpret(readText(scriptcode.js), globals);

// you can then access script values or functions from D 
too

import std.stdio;
writeln(globals.foo()(adr));

// and also interpret strings here. The interpret function
// returns the value of the last expression
writeln(interpret(myFunction(12, 24);, globals));

}


Here's what my scriptcode.js looks like:

 // suppose the code there is:
 // the syntax is kinda like javascript and kinda like D
 // the concat operator is D style, but function decls 
are JS style
 function foo(name) { return hello,  ~ name ~  you are 
 ~ myFunction(12, 53) ~  years old; }

 // set a global variable too
 var myname = adam;


kinda like a hybrid of D and JavaScript.


Re: Pointer to constructor

2014-10-29 Thread Adam D. Ruppe via Digitalmars-d-learn
You can access constructors just like any other method if you use 
the __ctor name.


So like MyClass.__ctor.


Re: Dart bindings for D?

2014-10-30 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 30 October 2014 at 10:18:40 UTC, Suliman wrote:
No! I mean not translation to js. I mean theoretical ability of 
creation new programming language that can work every where!


The problem is getting new features into the browsers that people 
use.


You could also just write native programs and use the web as 
nothing more than a delivery system. You might have a harder time 
getting people to install it though.


Re: Dart bindings for D?

2014-10-30 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 30 October 2014 at 06:14:18 UTC, Suliman wrote:
Is it's possible to create single language that cover desktop 
and web? Like D+Dart?


You can also run D code on the web server and do very little on 
the web client itself for a lot of programs.


Re: Dart bindings for D?

2014-10-31 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 30 October 2014 at 02:27:58 UTC, ketmar via 
Digitalmars-d-learn wrote:

it was very funny to show some people D code with your jsvar
and listenting how they don't want to learn just another
scripting language. and then compile the code with DMD to
confuse them even more.


hehe, that was the main idea!



Re: string, char[], overloaded functions.

2014-10-31 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 31 October 2014 at 23:59:54 UTC, dajones wrote:

So shouldnt char[] implicity convert to string


Nope, char[] casting to string is generally a bad thing that 
should be avoided because it can leave you with a mutable string, 
which isn't supposed to happen.


In your case, why are you using char[] for the buf instead of 
just string?



BTW one could argue that char[] ~ operator should yield something 
that's implicitly convertable, since it allocates a new memory 
block anyway, but that's not how it works right now.


Re: rndtonl

2014-11-04 Thread Adam D. Ruppe via Digitalmars-d-learn
I think rndtonl is a C library function that isn't always present 
in the system.


It doesn't work on my computer either and I can't find any 
documentation about it. It is probably not meant to be called by 
end users.


Re: Access Violation Tracking

2014-11-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 5 November 2014 at 11:31:01 UTC, bearophile wrote:
This was discussed some times, and Walter is against this, but 
I think he is wrong, and eventually things will change.


An access violation already thrown on Win32. Just catch a 
Throwable in main and write out exception.toString. But you do 
need to have debugging info compiled in to get a readable 
backtrace with dmd -g.


Re: How to turn this C++ into D?

2014-11-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 5 November 2014 at 18:10:38 UTC, Ali Çehreli wrote:
If so, then that push_back would be adding an incomplete object 
to the list.


scope(success)?


But the D translation worries me too because the destructor won't 
run at the same time as the C++ version, unless you make it a 
scope class or something.


Re: How to tell how an object/class is declared

2014-11-06 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 6 November 2014 at 23:43:19 UTC, Meta wrote:
How can I tell at the points marked in the above code if the 
class or struct instance was declared as const, shared, etc.? 
Is this possible?


You can't do that, but you can overload on const

void doSomething() const { called on const instance }
void doSomething() { called on mutable }


Re: D1: Error: function ... cannot have an in contract when overriden function

2014-11-07 Thread Adam D. Ruppe via Digitalmars-d-learn
If it is just that one error, you could always just comment out 
the in contract and recompile.


Re: ODBC Library?

2014-11-10 Thread Adam D. Ruppe via Digitalmars-d-learn

I kinda slapped one together but idk if it actually works.

https://github.com/adamdruppe/arsd

database.d and mssql.d from that repo. I haven't even tried to 
compile it for a while though, so it might not work at all.


The way I made it was to write the extern(C) function 
declarations and then call it like in C.


Re: Strictness of language styling

2014-11-10 Thread Adam D. Ruppe via Digitalmars-d-learn
Personally, I don't really care about naming conventions. I 
prefer the camelCase and it seems most D people do, but if you're 
translating another library, there's value it keeping it the same 
for ease of documentation lookups from the original etc.


Re: passing duck-typed objects and retaining full type information

2014-11-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 12 November 2014 at 01:50:07 UTC, Adam Taylor wrote:

Adam Ruppe has an interesting example:


What that does is defer the type work to runtime, so a lot of 
type information is lost there too.


The big magic is that the wrapper object is a template, 
specialized for the compile time type, but once it is used it is 
still through an interface. This is similar to how the 
inputRangeObject+InputRange interface work in phobos 
http://dlang.org/phobos/std_range.html#inputRangeObject


Plain interface, templated implementation.


I don't really understand your question though


Re: Basically want to make a macro script

2014-11-12 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 13 November 2014 at 02:45:34 UTC, Israel wrote:

Do you have plans for making win32 bindings for the sendkeys?


I'm pretty sure it just calls this function:
http://msdn.microsoft.com/en-us/library/ms646310%28v=vs.85%29.aspx

with appropriate input prepared.


As to listen to keyboard input, I'm again pretty sure you just 
need to call this function:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309%28v=vs.85%29.aspx

It needs a window and event loop to receive the message, but 
that's not rocket science either, my simpledisplay.d can do it or 
it isn't really hard to just do with the low level calls.



I'm not sure about how to do it on X11 off the top of my head, 
but there's functions to add event messages and listen to input 
from multiple windows, or you could open the /dev/input for the 
keyboard too if root. I've looked into this before and found a 
few options, but don't remember the details right now.



I don't want to give a sample program without testing it, and I'm 
on my Linux box right now, but if you don't have something by 
tomorrow I'll play for a while when i'm on my laptop.


Re: Callbacks in D as void functions

2014-11-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 13 November 2014 at 14:50:00 UTC, Wsdes wrote:

I am trying to write a wrapper for a C API in D. In C I have the
following definition of a callback type:

typedef void (*Callback)(void*);


I would translate this directly to D:

extern(C) alias Callback = void function(void*);



Here the MyDtaCB function has no prototype but is defined as
follows:

void MyDtaCB(void* pVoid){
// Do stuff
}


And don't forget extern(C) on this too:

extern(C) void MyDtaCB(void* pVoid) {

}


And assign it to the struct:

Events.OnData = MyDtaCB;



Unless you have a link to the wiki that talks about ints, maybe 
that says something different, but I like to keep my C and D code 
that calls it looking pretty much the same when I can.


Re: Basically want to make a macro script

2014-11-13 Thread Adam D. Ruppe via Digitalmars-d-learn
I wrote a program to get you started. It needs simpledisplay.d 
and color.d from my github https://github.com/adamdruppe/arsd


Just download those two files and put them in your folder along 
with the following contents as hotkey.d and you should get 
started.


I tested on Windows 7 to hotkey type some stuff into a Notepad 
window.


Here's the code:



// compile: dmd hotkey.d simpledisplay.d color.d 
-L/SUBSYSTEM:WINDOWS:5.0


// helper function to send a string. Call with like hello!w -- 
notice

// the w at the end of the string literal.
void sendString(wstring s) {
INPUT[] inputs;
inputs.reserve(s.length * 2);

foreach(wchar c; s) {
// the basic pattern here is to send a unicode key
// pressed then released
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = c;
input.ki.dwFlags = KEYEVENTF_UNICODE;
inputs ~= input;

input.ki.dwFlags |= KEYEVENTF_KEYUP; // released...
inputs ~= input;
}

// then send it to the operating system
	if(SendInput(inputs.length, inputs.ptr, INPUT.sizeof) != 
inputs.length) {

import std.stdio;
writeln(SendInput failed);
}
}

// the SendInput function can also send other keys, see the MSDN 
link

// I gave in my last email for details.

void main() {
// uses my simpledisplay.d to pop up a quick window
import simpledisplay;

enum hotkey_id = 1; // arbitrary unique ID for the program

auto window = new SimpleWindow(100, 50);
	window.handleNativeEvent = delegate int(HWND hwnd, UINT msg, 
WPARAM wParam, LPARAM lParam) {

if(hwnd !is window.impl.hwnd)
return 1; // we don't care...
switch(msg) {
			// 
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646279%28v=vs.85%29.aspx

case WM_HOTKEY:
if(wParam == hotkey_id) {
 // *** This is what happens 
when it is pressed!!! ***
	// MessageBoxA(window.impl.hwnd, Hotkey, Pressed!, 
MB_OK);

sendString(Hey, it worked!w);
return 0;
}
goto default;
default: return 1; // not handled, pass it on
}
return 0;
};

string message = Hotkey ready;

// you can also pass modifiers or a capital ASCII char here
// warning though: when it sends input, it still considers the
	// modifiers down. So like if you make it MOD_ALT and 'K', and 
send
	// the string 'Hello'... alt is still down, so the program will 
think

// the user hit alt+H - and thus bring up the Help menu!
//
// *** This registers the key with the operating system 
***

if(!RegisterHotKey(window.impl.hwnd, hotkey_id, 0, VK_F2)) {
message = RegisterHotKey failed;
}

{
auto painter = window.draw();
painter.drawText(Point(0, 0), message);
}
window.eventLoop(0); // draw our window
}

// these are bindings to the necessary Windows API functions

import core.sys.windows.windows;

// 
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646309%28v=vs.85%29.aspx

extern(Windows) BOOL RegisterHotKey(HWND, int, UINT, UINT);
// 
http://msdn.microsoft.com/en-us/library/ms646310%28v=vs.85%29.aspx

extern(Windows) UINT SendInput(UINT, INPUT*, int);

struct INPUT {
DWORD type;
union {
MOUSEINPUT mi;
KEYBDINPUT ki;
HARDWAREINPUT hi;
}
}

struct MOUSEINPUT {
LONG  dx;
LONG  dy;
DWORD mouseData;
DWORD dwFlags;
DWORD time;
ULONG_PTR dwExtraInfo;
}

struct KEYBDINPUT {
WORD  wVk;
WORD  wScan;
DWORD dwFlags;
DWORD time;
ULONG_PTR dwExtraInfo;
}

struct HARDWAREINPUT {
DWORD uMsg;
WORD wParamL;
WORD wParamH;
}

enum INPUT_MOUSE = 0;
enum INPUT_KEYBOARD = 1;
enum INPUT_HARDWARE = 2;

enum MOD_ALT = 0x1;
enum MOD_CONTROL = 0x2;
enum MOD_NOREPEAT = 0x4000; // unsupported
enum MOD_SHIFT = 0x4;
enum MOD_WIN = 0x8; // reserved

enum WM_HOTKEY = 0x0312;

enum KEYEVENTF_EXTENDEDKEY = 0x1;
enum KEYEVENTF_KEYUP = 0x2;
enum KEYEVENTF_SCANCODE = 0x8;
enum KEYEVENTF_UNICODE = 0x4;


Re: Basically want to make a macro script

2014-11-13 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 13 November 2014 at 07:01:08 UTC, Rikki Cattermole 
wrote:
I did find this [0]. I don't know what state its in for 
compilating/running ext. But it might give you a good starting 
point.


[0] https://github.com/pythoneer/XInputSimulator


ooh there's some nice code for Linux in there! The Windows is 
only half implemented though... but this combined with my Windows 
code should get you enough example to write a cross-platform 
thing if you need it.


  1   2   3   4   5   6   7   8   9   10   >