Re: Making sense of recursion

2018-06-25 Thread Colin via Digitalmars-d-learn

On Monday, 25 June 2018 at 17:45:01 UTC, zbr wrote:
Hi, this question is not specifically D related but I'll just 
ask anyway. Consider the following snippet:


[...]


Your mistake is in your visualization :-)

But... more like:

0 < 4 ? true : mergeSort(0,2) && mergeSort(3, 4)
And so on.

I.e, the it's not either or to run the second mergeSort, they 
both happen.


Re: Auto keyword and when to use it

2018-08-20 Thread Colin via Digitalmars-d-learn

On Monday, 20 August 2018 at 17:52:17 UTC, QueenSvetlana wrote:

Great!

So I can't declare class level variables with auto, correct? 
only local method variables?


You can use auto if you're setting the class level variable to a 
default.


class X {
  auto i = 42; // i will be an int

}


Re: Process Pipes

2018-10-10 Thread Colin via Digitalmars-d-learn

On Tuesday, 9 October 2018 at 09:15:09 UTC, Gorker wrote:

Hi all,

I'm on macOS 10.11.6 with dmd 2.081.2 and I've a problem with 
std.process.


---
gork ():foo gorker$ gcc -c -Iinclude -o foo.cpp.o src/foo.cpp
In file included from src/foo.cpp:2:
include/foo/foo.hpp:22:10: warning: scoped enumerations are a 
C++11 extension [-Wc++11-extensions]

enum class foo_event_type_t
 ^


56 warnings and 9 errors generated.
---
No output, (zero bytes) in stdout.

If I use standard process to collect both stream with:
---
auto processPipes = pipeProcess(args, Redirect.all, null, 
Config.none, workDir);
foreach (c; pipes.stdout.byChunk(100)) writeln(cast(string) c); 
// <<< it halts here: stdout file is empty, but not EOF

foreach (c; pipes.stderr.byChunk(100)) writeln(cast(string) c);
---
Everything is fine if I don't redirect the stderr to a pipe.

Suggestions?


If you want to use asynch io - you'll have to fork and use 
NONBLOCK output on the file descriptor.


I wrote this years ago (not sure if it still compiles tbh, but it 
should)


https://github.com/grogancolin/dexpect

Specifically this block should help you: 
https://github.com/grogancolin/dexpect/blob/master/source/dexpect.d#L343-L352


Re: static if and early exit from function doesn't seem to work?

2017-12-31 Thread Colin via Digitalmars-d-learn

On Sunday, 31 December 2017 at 13:32:03 UTC, aliak wrote:
Alo! I'm making a recursive concat function that is similar to 
chain. The following code works:


[...]


I suspect it's because you've no 'else static if'.


Re: Error: variable foo conflicts with struct foo

2018-01-04 Thread Colin via Digitalmars-d-learn

On Thursday, 4 January 2018 at 17:45:35 UTC, Stijn wrote:
Why is it not allowed for a variable name to match a type name? 
The following example fails with "Error: variable foo conflicts 
with struct foo"


struct foo {}
foo foo;


How can the compiler know which symbol is which symbol if 
everything has the same name?


Standard practice is to capitalise type names and camelCase 
variable names.


Re: Basics of calling C from D

2014-06-11 Thread Colin via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 14:28:49 UTC, belkin wrote:

On Wednesday, 11 June 2014 at 14:02:08 UTC, John Colvin wrote:

On Wednesday, 11 June 2014 at 13:52:09 UTC, belkin wrote:
Example: I have this C function that is compiled into a 
library


//File: factorial.h
int factorial(int n);


//File: factorial.c
#include "factorial.h"

int factorial(int n)
{
  if(n!=1)
   return n*factorial(n-1);
}

Question: How do I use it from D?


//File: blah.d

extern(C) int factorial(int n); //coincidentally identical to 
the C declaration.


void main()
{
   assert(factorial(3) == 6);
}


$ gcc -c factorial.c -ofactorial.o
$ dmd blah.d factorial.o
$ ./blah

or

$ gcc -c factorial.c -ofactorial.o
$ ar rcs libfactorial.a factorial.o
$ dmd blah.d -L-lfactorial
$ ./blah



Basically, you just translate the header files from C to D, 
then link to the C implementation. See 
http://code.dlang.org/packages/dstep for automatic translation 
of headers.


This is great.
How practical (reliable ) is it to translate a large and 
complex header file like oci.h ( the interface for Oracle's 
database API ) to D?


You can do a lot of it by simply doing a find and replace in the
file.
For example, all C definitions of:
unsigned char x
become:
ubyte x

So a find an replace will do that for you quite easily.
Other things like structs and typedefs are a bit more difficult
to do with a find & replace.
All the info you need is here anyway:
wiki.dlang.org/Bind_D_to_C


Re: Basics of calling C from D

2014-06-11 Thread Colin via Digitalmars-d-learn

On Wednesday, 11 June 2014 at 15:14:19 UTC, Colin wrote:

On Wednesday, 11 June 2014 at 14:28:49 UTC, belkin wrote:

On Wednesday, 11 June 2014 at 14:02:08 UTC, John Colvin wrote:

On Wednesday, 11 June 2014 at 13:52:09 UTC, belkin wrote:
Example: I have this C function that is compiled into a 
library


//File: factorial.h
int factorial(int n);


//File: factorial.c
#include "factorial.h"

int factorial(int n)
{
 if(n!=1)
  return n*factorial(n-1);
}

Question: How do I use it from D?


//File: blah.d

extern(C) int factorial(int n); //coincidentally identical to 
the C declaration.


void main()
{
  assert(factorial(3) == 6);
}


$ gcc -c factorial.c -ofactorial.o
$ dmd blah.d factorial.o
$ ./blah

or

$ gcc -c factorial.c -ofactorial.o
$ ar rcs libfactorial.a factorial.o
$ dmd blah.d -L-lfactorial
$ ./blah



Basically, you just translate the header files from C to D, 
then link to the C implementation. See 
http://code.dlang.org/packages/dstep for automatic 
translation of headers.


This is great.
How practical (reliable ) is it to translate a large and 
complex header file like oci.h ( the interface for Oracle's 
database API ) to D?


You can do a lot of it by simply doing a find and replace in the
file.
For example, all C definitions of:
unsigned char x
become:
ubyte x

So a find an replace will do that for you quite easily.
Other things like structs and typedefs are a bit more difficult
to do with a find & replace.
All the info you need is here anyway:
wiki.dlang.org/Bind_D_to_C


And here:
http://dlang.org/interfaceToC.html


Re: monodevelop mono-d versions

2014-08-01 Thread Colin via Digitalmars-d-learn

On Friday, 1 August 2014 at 09:12:49 UTC, sclytrack wrote:
I can't seem to install mono-d. It always seems to want a newer 
version of MonoDevelop.


I'm on Ubuntu 14.04 LTS and it has version 4.0.12 of 
MonoDevelop. Has anybody else got this to work with this 
version?


I have this file called

MonoDevelop.D-1.9.6.mpack


Tools->Add In Manager->Install From File
Select the MonoDevelop.D-1.9.6.mpack file.
Press "Open"



Dialog Window:
  The Following Packages will be Installed.
  D Language Binding v2.1.14 (In User Directory)


Follow the info here:
http://wiki.dlang.org/Mono-D


Mono-d requires a MonoDevelop > 5.0, which at the moment you have 
to build yourself on Ubuntu 14.04.


You can find a precompiled version of it here:
 http://simendsjo.me/files/abothe (Which is also linked to in the 
wiki above)


Hope that helps!


Re: monodevelop mono-d versions

2014-08-01 Thread Colin via Digitalmars-d-learn

On Friday, 1 August 2014 at 13:15:25 UTC, Dicebot wrote:

On Friday, 1 August 2014 at 09:12:49 UTC, sclytrack wrote:
I can't seem to install mono-d. It always seems to want a 
newer version of MonoDevelop.


I'm on Ubuntu 14.04 LTS and it has version 4.0.12 of 
MonoDevelop. Has anybody else got this to work with this 
version?


I have this file called

MonoDevelop.D-1.9.6.mpack


Tools->Add In Manager->Install From File
Select the MonoDevelop.D-1.9.6.mpack file.
Press "Open"



Dialog Window:
 The Following Packages will be Installed.
 D Language Binding v2.1.14 (In User Directory)


MonoDevelop has a terrible plugin API compatibility policy 
which makes Mono-D author only stick to latest released API 
version unless he wants to maintain dozen of different Mono-D 
builds :(


In practice that means that you pretty much will never be able 
to use MonoDevelop version from repositories in Ubuntu - need 
to either build recent version on your own or use /opt/ bundle 
by simendsjo


Which is a pity, as it's otherwise a pretty nice IDE.

Still, vim with NERDTree + dub on the command line.
What more do you need?



Can you explain this?

2014-08-20 Thread Colin via Digitalmars-d-learn

Hi,

I'm implementing some template checks on some types I'm using in 
a project, and went to phobos for some indications on how to use 
them.


In std.range, I see this construct quite a bit:

template isInputRange(R)
{
enum bool isInputRange = is(typeof(
(inout int = 0)
{
R r = R.init; // can define a range object
if (r.empty) {}   // can test for empty
r.popFront(); // can invoke popFront()
auto h = r.front; // can get the front of the range
}));
}

Can anyone explain the:
 is(typeof(
(inout int = 0) {}
  );

section to me?

It looks veryhacky.

I see 3 distinct parts playing a role in my confusion:
A) The 'is' keyword. What does it do when you have is(expression);
B) typeof( expression ); whats this doing? Particularly when the 
expression its acting on is a closure that returns nothing? (at 
least as far as I can see)

C) The closure expression:
(inout int = 0) {
   // Check to see if I can do InputRangy stuff...
}
Why is there a need for that inout int = 0 clause at the start of 
it?


Sorry for the long question!

Thanks,
Colin


Re: Can you explain this?

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

On Wednesday, 20 August 2014 at 20:18:15 UTC, Dicebot wrote:

On Wednesday, 20 August 2014 at 20:01:05 UTC, Colin wrote:

I see 3 distinct parts playing a role in my confusion:
A) The 'is' keyword. What does it do when you have 
is(expression);


http://dlang.org/expression.html#IsExpression

It is a tool for type checking. It has many options but plain 
`is(T)` checks if `T` is a valid type and returns `true` if it 
is. `void` is considered a valid type.


B) typeof( expression ); whats this doing? Particularly when 
the expression its acting on is a closure that returns 
nothing? (at least as far as I can see)


typeof(() {}) evaluates to void:

static assert(is(typeof(() {}) == void));

However, if any compilation errors happen inside the delegate, 
it evaluates to special invalid type which yield `false` when 
supplied to `is` expression.


Thus `is(typeof(expr))` is a way to express a concept "if 
`expr` compiles". Delegate is necessary to test statements 
because `typeof` only accepts expressions.



C) The closure expression:
(inout int = 0) {
  // Check to see if I can do InputRangy stuff...
}
Why is there a need for that inout int = 0 clause at the start 
of it?


Now this is a really weird one. This is necessary for input 
ranges with `inout` functions to fit the trait because `inout` 
variables can be declared only inside `inout` functions. See 
this bug report for details : 
https://issues.dlang.org/show_bug.cgi?id=7824


It is one of surprising feature inter-operation cases you don't 
expect when designing features :)


Thanks all, that explains it.

It is weird looking code alright, but I guess it has its uses.

I think I prefer the __traits(compiles,...) construct, as it is a 
bit more obvious as to what I'm checking. So will use that I 
suspect.


Cheers!


Re: Learning D

2014-08-25 Thread Colin via Digitalmars-d-learn

On Monday, 25 August 2014 at 17:57:54 UTC, Ryan wrote:

Anyone know MonoDevelop?

Why is the "Edit References" context menu item missing.  I have 
it at the top (Project->Edit References...) but when I click it 
nothing happens. Grrr.


I couldnt figure it out either tbh (creating dub projects using 
MonoD)


I just fire up a command line, go to my workspace folder, and do
dub init 

Then, in monoD, File -> Open -> C:\Path\To\Project\dub.json

Then your good to go regarding MonoD.



std.algorithm.reduce on an array of structs

2014-09-11 Thread Colin via Digitalmars-d-learn

I have this test code:

struct Thing {
uint x;
}

void main(){
uint[] ar1 = [1, 2, 3, 4, 5];
auto min1 = ar1.reduce!((a,b) => a < b);
writefln("%s", min1);  // prints 1 as expected

Thing[] ar2 = [Thing(1), Thing(2), Thing(4)];
auto min2 = ar2.reduce!((a,b) => a.x < b.x);  //  <- Wont 
Compile

writefln("%s", min2);
}

The line with "Wont Compile" on it has this error message:
/usr/include/dmd/phobos/std/algorithm.d(770): Error: cannot 
implicitly convert expression (__lambda2(result, 
front(_param_1))) of type bool to Thing
/usr/include/dmd/phobos/std/algorithm.d(791): Error: template 
instance t.main.reduce!((a, b) => a.x < b.x).reduce!(Thing, 
Thing[]) error instantiating

t.d(16):instantiated from here: reduce!(Thing[])


Any idea what I'm doing wrong here?
To me, the operation on ar2 should be pretty much identical to 
ar1, except for the use of the struct.


Re: std.algorithm.reduce on an array of structs

2014-09-11 Thread Colin via Digitalmars-d-learn
On Thursday, 11 September 2014 at 13:27:39 UTC, Daniel Kozak 
wrote:

On Thursday, 11 September 2014 at 13:06:05 UTC, Colin wrote:

I have this test code:

struct Thing {
   uint x;
}

void main(){
   uint[] ar1 = [1, 2, 3, 4, 5];
   auto min1 = ar1.reduce!((a,b) => a < b);
   writefln("%s", min1);  // prints 1 as expected

   Thing[] ar2 = [Thing(1), Thing(2), Thing(4)];
   auto min2 = ar2.reduce!((a,b) => a.x < b.x);  //  <- Wont 
Compile

   writefln("%s", min2);
}

The line with "Wont Compile" on it has this error message:
/usr/include/dmd/phobos/std/algorithm.d(770): Error: cannot 
implicitly convert expression (__lambda2(result, 
front(_param_1))) of type bool to Thing
/usr/include/dmd/phobos/std/algorithm.d(791): Error: template 
instance t.main.reduce!((a, b) => a.x < b.x).reduce!(Thing, 
Thing[]) error instantiating

t.d(16):instantiated from here: reduce!(Thing[])


Any idea what I'm doing wrong here?
To me, the operation on ar2 should be pretty much identical to 
ar1, except for the use of the struct.



You are try to put uint to Thing. This is corect version:

import std.stdio;
import std.algorithm;

struct Thing {
uint x;
}

void main(){
uint[] ar1 = [1, 2, 3, 4, 5];
auto min1 = ar1.reduce!((a,b) => a < b);
writefln("%s", min1);  // prints 1 as expected

Thing[] ar2 = [Thing(1), Thing(2), Thing(4)];
auto min2 = ar2.reduce!((a,b) => a.x < b.x ? a : b);  //  <-
Wont Compile
writefln("%s", min2);
}


Ah ok. I get it.

Thanks daniel!


Re: std.algorithm.reduce on an array of structs

2014-09-11 Thread Colin via Digitalmars-d-learn

On Thursday, 11 September 2014 at 14:49:03 UTC, bearophile wrote:

Daniel Kozak:

You can just use min:

import std.stdio, std.algorithm;

struct Thing {
uint x;
alias x this;
}

alias minimum = reduce!min;

void main() {
immutable ar1 = [10, 20, 30, 40, 50];
ar1.minimum.writeln;

immutable ar2 = [Thing(10), Thing(20), Thing(40)];
ar2.minimum.writeln;
}

Bye,
bearophile


Using the "alias x this" solution would work, but my actual 
struct is not a simple struct, so the comparison isn't exactly 
(a.x < b.x).




Parsing a date string into a std.datetime.datetime

2014-10-23 Thread Colin via Digitalmars-d-learn

Hi,

I'm looking for an easy way to parse a dates into a datetime 
object.


Most of my dates will be of the form:
mmm dd,  HH:MM AM|PM

So like: "May 30, 2014 12:12 PM"

I can easily write a regex or whatever to pull these out of that 
one format, but it's not guaranteed they'll all be in the one 
format and I may have to deal with others.


Is there a helper function that I'm missing that can parse these 
dates? Maybe something similar to pythons dateutil.parser [1] ?


If not maybe adding this function to std.datetime would be a good 
project to undertake for myself...


[1] - https://labix.org/python-dateutil



Re: Parsing a date string into a std.datetime.datetime

2014-10-24 Thread Colin via Digitalmars-d-learn
On Thursday, 23 October 2014 at 21:17:23 UTC, Jonathan M Davis 
wrote:

On Thursday, 23 October 2014 at 11:13:26 UTC, Colin wrote:

Hi,

I'm looking for an easy way to parse a dates into a datetime 
object.


Most of my dates will be of the form:
mmm dd,  HH:MM AM|PM

So like: "May 30, 2014 12:12 PM"

I can easily write a regex or whatever to pull these out of 
that one format, but it's not guaranteed they'll all be in the 
one format and I may have to deal with others.


Is there a helper function that I'm missing that can parse 
these dates? Maybe something similar to pythons 
dateutil.parser [1] ?


If not maybe adding this function to std.datetime would be a 
good project to undertake for myself...


[1] - https://labix.org/python-dateutil


std.datetime supports the ISO formats but, it does not 
currently support generating or parsing custom strings for 
dates or times. It's on my todo list (probably after splitting 
std.datetime into a package), but I don't know exactly when I'm 
going to get to it. The first step will be figuring out what 
the format strings will look like, since what languages like C 
do is a complete mess. I had a proposal on it that was 
discussed a while ago, but it was too complicated. It'll 
probably end up being something closer to this 
http://pr.stewartsplace.org.uk/d/sutil/datetime_format.html 
though I'm afraid that that approach as it's presented might 
not be flexible enough. I'll probably need to do something like 
add a templated function that returns a custom struct with the 
values that you want so that you can get them effeiently to 
build the string yourself in the cases where you need to do 
something wacky enough that the normal custom string formatting 
functions aren't flexible enough. Then leaving the normal 
custom string format generating and parsing functions simpler 
works better.


In any case, I intend to get to it, but I've been dreadfully 
slow about it. It's the number one thing missing from 
std.datetime. I'd prefer to do it myself, but there's certainly 
no reason why someone else can't do it if they really want to.


- Jonathan M Davis


Ok, thanks for the informative reply Jonathan.

For now I'll go with parsing the few types of dates I may need, 
and maybe port over in the future when you get to it.


Cheers!


std.file.readText() extra Line Feed character

2014-12-18 Thread Colin via Digitalmars-d-learn
Why does std.file.readText() append a Line Feed char onto the end 
of the string?


I have a file with the following contents in it:
Name   =   Int
Other=Float
One More = String(Random;)

I then have the code:

void main(string[] args){
const text = "Name   =   Int
Other=Float
One More = String(Random;)";

string input = readText(args[1]);

writefln("Raw data");
writefln("D)%s", cast(ubyte[])text[$-5..$]);
writefln("File) %s", cast(ubyte[])input[$-5..$]);

}

This produces:
Raw data
D)[100, 111, 109, 59, 41]
File) [111, 109, 59, 41, 10]

Any Idea why the reading from the File adds on that extra '10' 
character?


I don't think it's my editor adding chars to the end of the file, 
as I'm using vi.


Re: std.file.readText() extra Line Feed character

2014-12-18 Thread Colin via Digitalmars-d-learn
On Thursday, 18 December 2014 at 09:25:47 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Thu, 18 Dec 2014 09:18:35 +
Colin via Digitalmars-d-learn 
 wrote:


Why does std.file.readText() append a Line Feed char onto the 
end of the string?


I have a file with the following contents in it:
Name   =   Int
Other=Float
One More = String(Random;)

I then have the code:

void main(string[] args){
 const text = "Name   =   Int
Other=Float
One More = String(Random;)";

 string input = readText(args[1]);

 writefln("Raw data");
 writefln("D)%s", cast(ubyte[])text[$-5..$]);
 writefln("File) %s", cast(ubyte[])input[$-5..$]);

}

This produces:
Raw data
D)[100, 111, 109, 59, 41]
File) [111, 109, 59, 41, 10]

Any Idea why the reading from the File adds on that extra '10' 
character?


I don't think it's my editor adding chars to the end of the 
file, as I'm using vi.


you *definetely* has the last line ended with '\n'.


I dont see how, I copy and pasted from the string definition in 
D, directly after the first " and directly before the last ".


If I look at the file in vim with line numbers turned on, the 
file is like this. So I really dont think I have a new line in 
the file...


  1 Name   =   Int
  2 Other=Float
  3 One More = String(Random;)


Re: std.file.readText() extra Line Feed character

2014-12-18 Thread Colin via Digitalmars-d-learn

On Thursday, 18 December 2014 at 10:43:32 UTC, yazd wrote:

On Thursday, 18 December 2014 at 10:16:38 UTC, Colin wrote:
On Thursday, 18 December 2014 at 09:25:47 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Thu, 18 Dec 2014 09:18:35 +
Colin via Digitalmars-d-learn 
 wrote:


Why does std.file.readText() append a Line Feed char onto 
the end of the string?


I have a file with the following contents in it:
Name   =   Int
Other=Float
One More = String(Random;)

I then have the code:

void main(string[] args){
   const text = "Name   =   Int
Other=Float
One More = String(Random;)";

   string input = readText(args[1]);

   writefln("Raw data");
   writefln("D)%s", cast(ubyte[])text[$-5..$]);
   writefln("File) %s", cast(ubyte[])input[$-5..$]);

}

This produces:
Raw data
D)[100, 111, 109, 59, 41]
File) [111, 109, 59, 41, 10]

Any Idea why the reading from the File adds on that extra 
'10' character?


I don't think it's my editor adding chars to the end of the 
file, as I'm using vi.


you *definetely* has the last line ended with '\n'.


I dont see how, I copy and pasted from the string definition 
in D, directly after the first " and directly before the last 
".


If I look at the file in vim with line numbers turned on, the 
file is like this. So I really dont think I have a new line in 
the file...


 1 Name   =   Int
 2 Other=Float
 3 One More = String(Random;)


You can make sure using `hexdump -C file`. I tested locally 
creating a file using vi, and it does indeed have a '\n' at the 
end of file.


Ah, I see. That's a little annoying.
Thanks folks!


Re: std.file.readText() extra Line Feed character

2014-12-19 Thread Colin via Digitalmars-d-learn

On Thursday, 18 December 2014 at 22:29:30 UTC, Ali Çehreli wrote:

On 12/18/2014 02:51 AM, Colin wrote:

> > vi, and it does indeed have a '\n' at the end of file.
>
> Ah, I see. That's a little annoying.

It looks like there are ways of dealing with it:


http://stackoverflow.com/questions/1050640/vim-disable-automatic-newline-at-end-of-file

Ali
"happy with Emacs :p"


Does emacs do this aswell? :)

Anyway, I'm making a tool which will be in use by a range of
people, so making the tool accept inputs with \n or not would be
the better choice than getting everyone to ensure they dont have
\n at the end of every file.


Re: Compile for other OS's on Windows?

2015-01-05 Thread Colin via Digitalmars-d-learn

On Monday, 5 January 2015 at 15:00:05 UTC, Bauss wrote:
On Monday, 5 January 2015 at 12:54:00 UTC, Gary Willoughby 
wrote:

On Monday, 5 January 2015 at 11:49:32 UTC, Bauss wrote:

Is it possible to compile for other OS's on Windows using dmd?


This is what's known as cross compiling and is not currently 
supported by DMD at this time.


Any alternatives?


Fire up a VM of the target machine (easy with any of the *nix 
systems) and compile on that?


Re: Accessing class with module name as Java's

2015-01-13 Thread Colin via Digitalmars-d-learn

Have the following directory structure?

~/testModule$ find . -print
.
./net
./net/http_.d# **
./net/http
./net/http/Mod1.d
./net/http/Mod2.d
./main.d

** I put the _ here to make it seperate from the net/http
directory. Probably, a better solution exists, this was hacked 
together quickly :)


In http_.d have:
module net.http_;  // again, a better solution surely exists
public import net.http.Mod1;
public import net.http.Mod2;

Then in your main have
import net.http_;

You can then use whatever's in Mod1 and Mod2 modules.
In your case, Mod1/Mod2 will be like
HTTPConnectionRequest/HTTPConnectionResponse and will only
contain a single class. This works for me.

You can also go a little further and have renamed imports.
Something like:
public import Renamed = net.http.Mod2;

Then in main.d call it with:
Renamed.Mod2 mod2 = new renamed.Mod2;

Feels just like Java :)


Re: Accessing class with module name as Java's

2015-01-13 Thread Colin via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 09:22:04 UTC, Colin wrote:

Have the following directory structure?

~/testModule$ find . -print
.
./net
./net/http_.d# **
./net/http
./net/http/Mod1.d
./net/http/Mod2.d
./main.d

** I put the _ here to make it seperate from the net/http
directory. Probably, a better solution exists, this was hacked 
together quickly :)


In http_.d have:
module net.http_;  // again, a better solution surely exists
public import net.http.Mod1;
public import net.http.Mod2;

Then in your main have
import net.http_;

You can then use whatever's in Mod1 and Mod2 modules.
In your case, Mod1/Mod2 will be like
HTTPConnectionRequest/HTTPConnectionResponse and will only
contain a single class. This works for me.

You can also go a little further and have renamed imports.
Something like:
public import Renamed = net.http.Mod2;

Then in main.d call it with:
Renamed.Mod2 mod2 = new renamed.Mod2;

Feels just like Java :)


Ah, I just re-read your OP. Your already at this point :)


Re: building a simple json tree

2015-01-15 Thread Colin via Digitalmars-d-learn
On Thursday, 15 January 2015 at 12:50:59 UTC, Rikki Cattermole 
wrote:

On 16/01/2015 1:37 a.m., anonymous wrote:
On Thursday, 15 January 2015 at 12:10:09 UTC, Rikki Cattermole 
wrote:

On 16/01/2015 12:16 a.m., anonymous wrote:
what's the right syntax for building a JSON tree ? I try to 
do like in

an AA but the program throw because the Key doesn't exist:

---
import std.stdio, std.json;

void main(string[] args)
{
   struct Foo{
   string a,  b;
   void writeToJson(ref JSONValue target) {
   target["a"] = JSONValue(a);
   target["b"] = JSONValue(b);
   }
   }

   JSONValue root = parseJSON("{}");
   root["items"] = JSONValue([""]);

   Foo*[] foos;
   foos ~= new Foo("a1","b1");
   foos ~= new Foo("a2","b2");

   foreach(foo; foos) {
   root["items"].array.length += 1;
   root["items"].array[$-1] = parseJSON("{}");
   foo.writeToJson(root["items"].array[$-1]);
   }
}
---


import std.stdio, std.json;

void main(string[] args)
{
   struct Foo{
   string a,  b;
   void writeToJson(ref JSONValue target) {
   target["a"] = JSONValue(a);
   target["b"] = JSONValue(b);
   }
   }

   JSONValue root = ["items": cast(string[])[]];

   Foo[] foos;
   foos ~= Foo("a1","b1");
   foos ~= Foo("a2","b2");

   foreach(foo; foos) {
   root["items"].array ~= JSONValue(foo.a);
   root["items"].array ~= JSONValue(foo.b);
   }

   writeln(root.toString());
}

I would recommend keeping away from std.json. Its an old 
piece of

code, that needs to be replaced.
Vibe.d has a much nicer implementation that is really decent. 
I would

recommend that, if you are up to using the build manager dub.


Thx, but actually I initially liked to get an array of object 
with each

identifier:

currently it produces:

{"items":["a1","b1","a2","b2"]}

while it'd be more desirable to have

{"items":[{"a":"a1","b":"b1"}, {"a":"a2","b":"b2"}]}

because the reader will test the presence of each the key "a" 
and "b" in

each element of "items".

Would it be a complete non-sense to assign an element with
opIndexAssign(), just like I wrote initially ? I know this is 
wrong but

the syntax seemed natural and logic.
Reading from std.json is straightforward but writing looks a 
bit messy.


It makes sense to do it. But like I said std.json is rubbish.
Just so you can see why I'm saying vibe.d's json implementation 
is better[0].


[0] 
https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/data/json.d#L1670


Also, look at the new std.json candidate:
http://code.dlang.org/packages/std_data_json


Re: How to make a Currency class from std.BigInt?

2015-01-31 Thread Colin via Digitalmars-d-learn

On Saturday, 31 January 2015 at 12:07:23 UTC, RuZzz wrote:
How to get amount of digit after point in a double for to get 
integer from a double?

assert(amountAfterPoint(1.456) == 3);
assert(amountAfterPoint(0.6) == 5);


How about a loop like

import std.stdio;

void main(){
writefln("%s", 1.45.numDigits);// prints 2
writefln("%s", 1.452343.numDigits);// prints 6
writefln("%s", 1.0.numDigits);// prints 0
}

long numDigits(double num){
 long i=0;
 double n=num;
 while(true){
if(n - (cast(long)n) == 0){
return i;
}
i++;
 n *= 10;
 }
}


Re: How to make a Currency class from std.BigInt?

2015-01-31 Thread Colin via Digitalmars-d-learn

On Saturday, 31 January 2015 at 14:26:45 UTC, RuZzz wrote:

The next version, which does not work:
https://bpaste.net/show/b9c85de68d07


I really dont understand what your trying to achieve here.

Maybe you can articulate it in one post what this class is trying 
to achieve?


rdmd with a file with no extension

2017-03-01 Thread Colin via Digitalmars-d-learn
When running a small D program through rdmd, it seems the file 
needs a .d extension to work.


```
$ ./testscript2
Error: module testscript2 is in file './testscript2.d' which 
cannot be read


$ cat testscript2
#!/usr/bin/env rdmd

void main(string[] args){
import std.stdio;

writeln(args);
}

```

Trying the above on OSX if that makes a difference.

Any way to get these to work short of renaming it testscript2.d?


'real' not able to store it's largest value

2017-05-22 Thread colin via Digitalmars-d-learn

Am I doing something wrong here?

real.max evaluates to: 1.18973e+4932

So, I'd expect to be able to store any value up to that... however
```
void main()
{
writeln("Real max: ", real.max);
foreach(i; 0..10){
writefln!("1024 ^^ %s = %s")(i, real(1024 ^^ i));
}
}

```
Output:
```
Real max: 1.18973e+4932
1024 ^^ 0 = 1
1024 ^^ 1 = 1024
1024 ^^ 2 = 1.04858e+06
1024 ^^ 3 = 1.07374e+09
1024 ^^ 4 = 0
1024 ^^ 5 = 0
1024 ^^ 6 = 0
1024 ^^ 7 = 0
1024 ^^ 8 = 0
1024 ^^ 9 = 0
```


Re: 'real' not able to store it's largest value

2017-05-22 Thread colin via Digitalmars-d-learn

D'oh!

Thanks Adam and Ali :)