Re: unittest blocks not being run inside of class and struct templates

2017-07-24 Thread NoBigDeal256 via Digitalmars-d-learn

On Tuesday, 25 July 2017 at 02:18:41 UTC, Adam D. Ruppe wrote:

On Tuesday, 25 July 2017 at 02:11:20 UTC, NoBigDeal256 wrote:
it passes when it should fail because the unittest block is 
never executed. Why is this?


Did you actually instantiate the class somewhere? A template 
has no concrete code unless created with an argument 
somewhere...


What if it's instantiated in another module? Right now I'm having 
issues where if I run 'dmd a.d b.d -unittest' and the class 
template in b.d is instantiated in a.d and it compiles and the 
tests inside my class template run as they should, but when using 
'dub test' the tests in my class template don't run at all as if 
it isn't instantiated in a.d even though it is. This is the 
original issue that I had that prompted me to create this thread.


Re: unittest blocks not being run inside of class and struct templates

2017-07-24 Thread NoBigDeal256 via Digitalmars-d-learn

On Tuesday, 25 July 2017 at 02:18:41 UTC, Adam D. Ruppe wrote:

On Tuesday, 25 July 2017 at 02:11:20 UTC, NoBigDeal256 wrote:
it passes when it should fail because the unittest block is 
never executed. Why is this?


Did you actually instantiate the class somewhere? A template 
has no concrete code unless created with an argument 
somewhere...


Well shit that was the issue. My mistake, I should have thought 
of that, but it makes total sense now.


What is the standard way of testing class templates in the 
context of a library where some of the classes may never actually 
be used by the library itself? I know I could just make a private 
module-level field declaration that just instantiates a template 
but that seems like an ugly way of handling it. Any suggestions 
on how you would handle this?


Re: unittest blocks not being run inside of class and struct templates

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

On Tuesday, 25 July 2017 at 02:11:20 UTC, NoBigDeal256 wrote:
it passes when it should fail because the unittest block is 
never executed. Why is this?


Did you actually instantiate the class somewhere? A template has 
no concrete code unless created with an argument somewhere...


unittest blocks not being run inside of class and struct templates

2017-07-24 Thread NoBigDeal256 via Digitalmars-d-learn

For example this code:

class Test {
unittest {
assert(false);
}
}

fails when ran with dmd test.d -unittest like you'd expect. But 
if I make it a class template:


class Test(T) {
unittest {
assert(false);
}
}

it passes when it should fail because the unittest block is never 
executed. Why is this? While googling I found this thread 
http://forum.dlang.org/thread/Xns98A859B0CD274pchapinsovernet@63.105.9.61 but surely that bug hasn't gone unfixed for 11 years...


Re: Csharp para Digital Mars D[AJUDA]

2017-07-24 Thread Nick B via Digitalmars-d-learn

On Monday, 24 July 2017 at 22:15:05 UTC, dark777 wrote:
Eu tenho um projeto em windows form C# feito no virual studio 
um amigo meu e eu criamos para a semana academica ele faz 
cadastros e marca a presença das visitas na semana por um id de 
quem ja pagou pelas palestras queria portar ele para D.


Que biblioteca para forms vcs me recomendam para desenvolver o 
mesmo?


o que eu teria que dar mais atenção em Csharp para portar para 
a linguagem D?



PS: ele é desktop mas faz redirecionamento para um banco de 
dados mysql para salvar os dados direto no servidor...


translation via Google translate ...

I have a project in windows form C # made in the virtual studio a 
friend of mine and I created for the academic week he makes 
registrations and marks the presence of the visits in the week by 
an id of who already paid for the talks wanted to port him to D.


What library for forms vcs recommend me to develop the same?

What would I have to pay more attention in Csharp to port to the 
D language?



PS: it is desktop but it does redirect to a mysql database to 
save the data directly on the server ...


Re: Why D have two function contains and canFind?

2017-07-24 Thread Timon Gehr via Digitalmars-d-learn

On 24.07.2017 20:19, Suliman wrote:

Why D have two function `contains` and `canFind`


`contains` guarantees logarithmic running time, while `canFind` can be 
linear.


Csharp para Digital Mars D[AJUDA]

2017-07-24 Thread dark777 via Digitalmars-d-learn
Eu tenho um projeto em windows form C# feito no virual studio um 
amigo meu e eu criamos para a semana academica ele faz cadastros 
e marca a presença das visitas na semana por um id de quem ja 
pagou pelas palestras queria portar ele para D.


Que biblioteca para forms vcs me recomendam para desenvolver o 
mesmo?


o que eu teria que dar mais atenção em Csharp para portar para a 
linguagem D?



PS: ele é desktop mas faz redirecionamento para um banco de dados 
mysql para salvar os dados direto no servidor...


traits compiles does not work for symbols from other modules

2017-07-24 Thread Andre Pany via Digitalmars-d-learn

Hi,

I want to validate whether a class contains a specific attribute. 
I have the attribute name as compile time string. This string 
could either be a direct attribute of the class or a hierarchy 
(TextSettings.Font.Size).


As example T is the class Label and p.name contains the text 
"TextSettings.Font.Size".

TextSettings and Font are again classes.

mixin(`static if (__traits(compiles, 
`~fullyQualifiedName!T~`.`~p.name~`)) {...}


__traits(compiles, ...) only works for symbols of the same 
module, but not for symbols contained in other modules. I reduced 
it to this example coding:


m1.d
-
module m1;

import m2;

class Foo
{
int foo;
}

void main()
{
static assert(__traits(compiles, m1.Foo.foo));
static assert(__traits(compiles, m2.Bar.bar));
}

m2.d
---
module m2;

class Bar
{
int bar;
}

Why does the second assert throws? What can I use instead of 
__traits(compiles,...) ?


Kind regards
André


Re: criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread dark777 via Digitalmars-d-learn

On Monday, 24 July 2017 at 20:33:42 UTC, dark777 wrote:

On Monday, 24 July 2017 at 20:06:37 UTC, ag0aep6g wrote:

On 07/24/2017 09:45 PM, dark777 wrote:
principal.d(18): Error: octal literals 01023040 are no longer 
supported, use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]

[...]

https://pastebin.com/CYinHWyQ


From there:

e = new Endereco();
e.setCidade("São Paulo");
e.setCEP(01023040);


Google's translator says (from Portuguese):
Endereco = address,
Cidade = City,
CEP = ZIP code.

Don't store ZIP codes as numbers. Store them as strings. 
Leading zeroes have meaning in ZIP codes. You don't do math on 
ZIP codes.


deu certo aqui agora valeu ai..



Eu tenho um projeto em windows form C# feito no virual studio um 
amigo meu e eu criamos para a semana academica ele faz cadastros 
e marca a presença das visitas na semana por um id de quem ja 
pagou pelas palestras queria portar ele para D. que biblioteca 
para forms vcs me recomendam para desenvolver o mesmo? PS: ele é 
desktop mas faz redirecionamento para um banco de dados mysql 
para salvar os dados direto no servidor...


Re: criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread dark777 via Digitalmars-d-learn

On Monday, 24 July 2017 at 20:06:37 UTC, ag0aep6g wrote:

On 07/24/2017 09:45 PM, dark777 wrote:
principal.d(18): Error: octal literals 01023040 are no longer 
supported, use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]

[...]

https://pastebin.com/CYinHWyQ


From there:

e = new Endereco();
e.setCidade("São Paulo");
e.setCEP(01023040);


Google's translator says (from Portuguese):
Endereco = address,
Cidade = City,
CEP = ZIP code.

Don't store ZIP codes as numbers. Store them as strings. 
Leading zeroes have meaning in ZIP codes. You don't do math on 
ZIP codes.


deu certo aqui agora valeu ai..


Re: Why D have two function contains and canFind?

2017-07-24 Thread Seb via Digitalmars-d-learn

On Monday, 24 July 2017 at 19:53:34 UTC, Cym13 wrote:

On Monday, 24 July 2017 at 18:31:09 UTC, Ali Çehreli wrote:

On 07/24/2017 11:19 AM, Suliman wrote:
> [...]
only
> [...]

std.algorithm.canFind and std.range.SortedRange.contains:

[...]


I'm gessing this predates design by introspection as it would 
be cleaner to let the compiler do the switch itself.



Yes - since end of 2016 `find` (and thus `canFind`) do 
introspection:


https://github.com/dlang/phobos/pull/4907
https://github.com/dlang/phobos/blob/57b8d2511ea37cd01665b9b663d8ba246144b1f9/std/algorithm/searching.d#L1509

Thus, I believe it would be best to deprecate 
SortedRange.contains:


https://github.com/dlang/phobos/pull/5651


Re: criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread SrMordred via Digitalmars-d-learn

On Monday, 24 July 2017 at 20:14:23 UTC, SrMordred wrote:

On Monday, 24 July 2017 at 19:45:03 UTC, dark777 wrote:
pessoal eu tenho umas classes java e estava portando para D e 
para usar as importaçoes criei os modules nescessarios todos 
estao dentro da mesma pasta porem ao fazer:


$rdmd principal

ele retorna o seguinte erro:

principal.d(18): Error: octal literals 01023040 are no longer 
supported, use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]


Os codigos sao os que estao abaixo no pastebin

https://pastebin.com/CYinHWyQ


Erro está aqui:
e.setCEP(01023040);

um número seguido de zero é considerado um octal (este o erro 
que está dando)

Você provavelmente quer gravar o cep como string:
e.setCEP("01023040");


Ou melhor você *deveria* gravar como string.




Re: criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread SrMordred via Digitalmars-d-learn

On Monday, 24 July 2017 at 19:45:03 UTC, dark777 wrote:
pessoal eu tenho umas classes java e estava portando para D e 
para usar as importaçoes criei os modules nescessarios todos 
estao dentro da mesma pasta porem ao fazer:


$rdmd principal

ele retorna o seguinte erro:

principal.d(18): Error: octal literals 01023040 are no longer 
supported, use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]


Os codigos sao os que estao abaixo no pastebin

https://pastebin.com/CYinHWyQ


Erro está aqui:
e.setCEP(01023040);

um número seguido de zero é considerado um octal (este o erro que 
está dando)

Você provavelmente quer gravar o cep como string:
e.setCEP("01023040");




Re: criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread ag0aep6g via Digitalmars-d-learn

On 07/24/2017 09:45 PM, dark777 wrote:
principal.d(18): Error: octal literals 01023040 are no longer supported, 
use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]

[...]

https://pastebin.com/CYinHWyQ


From there:

e = new Endereco();
e.setCidade("São Paulo");
e.setCEP(01023040);


Google's translator says (from Portuguese):
Endereco = address,
Cidade = City,
CEP = ZIP code.

Don't store ZIP codes as numbers. Store them as strings. Leading zeroes 
have meaning in ZIP codes. You don't do math on ZIP codes.


Re: Why D have two function contains and canFind?

2017-07-24 Thread Cym13 via Digitalmars-d-learn

On Monday, 24 July 2017 at 18:31:09 UTC, Ali Çehreli wrote:

On 07/24/2017 11:19 AM, Suliman wrote:
> [...]
only
> [...]

std.algorithm.canFind and std.range.SortedRange.contains:

[...]


I'm gessing this predates design by introspection as it would be 
cleaner to let the compiler do the switch itself.


Re: criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread Cym13 via Digitalmars-d-learn

On Monday, 24 July 2017 at 19:45:03 UTC, dark777 wrote:
pessoal eu tenho umas classes java e estava portando para D e 
para usar as importaçoes criei os modules nescessarios todos 
estao dentro da mesma pasta porem ao fazer:


$rdmd principal

ele retorna o seguinte erro:

principal.d(18): Error: octal literals 01023040 are no longer 
supported, use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]


Os codigos sao os que estao abaixo no pastebin

https://pastebin.com/CYinHWyQ


Sorry, I don't know what language you're talking so I hope I'll 
get it right anyway ;)


D used to have octal numbers. They started with a 0 so 0100 == 
64. This was deprecated in favour of std.conv.octal which 
explains the error message. To fix, remove the 0:   
e.setCEP(1020304)


criando modulos em D para classe pessoa[AJUDA]

2017-07-24 Thread dark777 via Digitalmars-d-learn
pessoal eu tenho umas classes java e estava portando para D e 
para usar as importaçoes criei os modules nescessarios todos 
estao dentro da mesma pasta porem ao fazer:


$rdmd principal

ele retorna o seguinte erro:

principal.d(18): Error: octal literals 01023040 are no longer 
supported, use std.conv.octal!1023040 instead

Failed: ["dmd", "-v", "-o-", "principal.d", "-I."]


Os codigos sao os que estao abaixo no pastebin

https://pastebin.com/CYinHWyQ


Re: No polymorphism?

2017-07-24 Thread Dgame via Digitalmars-d-learn
On Monday, 24 July 2017 at 18:15:20 UTC, Steven Schveighoffer 
wrote:

On 7/24/17 1:29 PM, Dgame wrote:

Why isn't the compiler able to deduce S[] => I[]? Or is it 
just me?

I've tried dmd 2.075


I know you got the explanation already, but just in case you 
actually need to call something like test1 but only have an S[]:


test1(ss.map!((I i) => i).array)

-Steve


Thanks.


Re: Why D have two function contains and canFind?

2017-07-24 Thread Ali Çehreli via Digitalmars-d-learn

On 07/24/2017 11:19 AM, Suliman wrote:
> Why D have two function `contains` and `canFind` if C# have only
> contains and it's enough?

std.algorithm.canFind and std.range.SortedRange.contains:

  https://dlang.org/phobos/std_algorithm_searching.html#.canFind

  https://dlang.org/phobos/std_range.html#.SortedRange.contains

canFind() is more general because it works with any input range. For 
that reason, it has to walk from the beginning to the end. (O(N) complexity)


contains() requires a sorted random access range so that it can use the 
O(log N) binary search algorithm.


When you have a large sorted array, use contains(). Even if the array is 
not sorted but there are many searches to be performed, sorting first 
and then calling contains() many times may be faster than canFind().


Even if the array is not sorted but it's small, you can use canFind() 
without worrying about performance. Of course it all depends on what 
small and large mean. :)


Ali



Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread Clinton via Digitalmars-d-learn

On Monday, 24 July 2017 at 18:01:19 UTC, ketmar wrote:

Clinton wrote:

On Monday, 24 July 2017 at 14:51:04 UTC, rikki cattermole 
wrote:

Stuff the GC.
You don't need it to care about collecting (or destroying for 
that matter).


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);
```

Normally I would suggest to create your own buffer, but 
because of the DB library probably doesn't support that, no 
point trying to force it.


[0] http://dlang.org/phobos/core_memory.html#.GC.free


BTW, how would I do this with associative arrays?


you can't. you can `.clear` 'em, though, but this won't 
immediately free the internal storage.


Meh.. Okay, well using these two should make things a lot better. 
Thanks for the help and clearing up my confusion.


Re: howto touch a file - setTimes

2017-07-24 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/24/17 1:11 PM, Martin Tschierschke wrote:

When I tried to set the atime and mtime of a file (f) via:

import std.datetime;
auto time = Clock.currTime();
setTimes(f,time,time);

I get "Operation not permitted."

This is caused on linux by the rule, that if you are not the owner of 
the file

you may only set the mtime of a file to current time.

A simple "touch filename" in terminal works.

Any hint? Do I have to use execute("touch filename")?


Hm... looking at the man page, it appears that you need to call the 
system call (e.g. utimes) with a null array.


This isn't possible via the current API. You could call it yourself 
instead of executing touch.


Would be a good enhancement request, please file: https://issues.dlang.org

-Steve


Why D have two function contains and canFind?

2017-07-24 Thread Suliman via Digitalmars-d-learn
Why D have two function `contains` and `canFind` if C# have only 
contains and it's enough?





Re: No polymorphism?

2017-07-24 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/24/17 1:29 PM, Dgame wrote:


Why isn't the compiler able to deduce S[] => I[]? Or is it just me?
I've tried dmd 2.075


I know you got the explanation already, but just in case you actually 
need to call something like test1 but only have an S[]:


test1(ss.map!((I i) => i).array)

-Steve


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread ketmar via Digitalmars-d-learn

Clinton wrote:


On Monday, 24 July 2017 at 14:51:04 UTC, rikki cattermole wrote:

Stuff the GC.
You don't need it to care about collecting (or destroying for that 
matter).


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);
```

Normally I would suggest to create your own buffer, but because of the 
DB library probably doesn't support that, no point trying to force it.


[0] http://dlang.org/phobos/core_memory.html#.GC.free


BTW, how would I do this with associative arrays?


you can't. you can `.clear` 'em, though, but this won't immediately free 
the internal storage.


Re: No polymorphism?

2017-07-24 Thread Dgame via Digitalmars-d-learn

On Monday, 24 July 2017 at 17:33:48 UTC, Adam D. Ruppe wrote:

On Monday, 24 July 2017 at 17:29:55 UTC, Dgame wrote:

S[] ss = [new S()];
test1(ss); // Fails

Why isn't the compiler able to deduce S[] => I[]? Or is it 
just me?


This is exactly because of polymorphism. Consider the following:

```
S[] ss = [new S()];
I[] i = ss; // pass it to the function or whatever for implicit 
conversion


class OtherDerived : I {}

i[0] = new OtherDerived(); // looks OK, otherDerived is also 
interface I

```

But now, ss[0], the same array as i, no longer points to an S! 
You broke the type system.


So, tired it is. Thanks a lot.


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread Clinton via Digitalmars-d-learn

On Monday, 24 July 2017 at 14:51:04 UTC, rikki cattermole wrote:

Stuff the GC.
You don't need it to care about collecting (or destroying for 
that matter).


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);
```

Normally I would suggest to create your own buffer, but because 
of the DB library probably doesn't support that, no point 
trying to force it.


[0] http://dlang.org/phobos/core_memory.html#.GC.free


BTW, how would I do this with associative arrays?


Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/24/17 11:45 AM, Houdini wrote:

On Monday, 24 July 2017 at 15:41:33 UTC, Steven Schveighoffer wrote:

Because types with inheritance generally don't work right if you pass 
by value (i.e. the slicing problem).


structs don't support inheritance or virtual functions, so they can be 
safely passed by value.


But in C++, we pass them by reference also to avoid copies (const &).
The potential polymorphic usage is not the only point to consider.



In C++ class and struct are pretty much interchangeable, so technically, 
class is a wasted keyword for default visibility.


In D, I would use classes for any time I need polymorphism, and use 
structs otherwise.


-Steve


VibeD - RestInterfaceClient - non-constant expression

2017-07-24 Thread holo via Digitalmars-d-learn

Hello

I'm trying to move forward with my code from here: 
https://forum.dlang.org/post/yftgpzlotuqzechcn...@forum.dlang.org


I create my client app and trying to use RestInterfaceClient to 
connect to my api. Here is my present code for client:


module sites.frontpage;


import vibe.d;
import msfrontpage;

final class SilesianCloud {

  private:
  auto api = new 
RestInterfaceClient!IfFrontPageAPI("http://127.0.0.1:8090/api/;);


  public:
// GET /
void get()
{
Json result = api.getHome();
logInfo(result.toString);
render!"frontpage.dt";
}
}

When i try to compile it im getting:

../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/http/server.d(286,33): 
Deprecation: alias diet.traits.FilterCallback is deprecated - Use 
SafeFilterCallback instead.
Compiling Diet HTML template frontpage.dt...
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/inet/url.d(61,18): Error: 
non-constant expression "http://127.0.0.1:8090/api/"[0..4]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/inet/url.d(129,15): Error: 
non-constant expression "http://127.0.0.1:8090/api/"[21..26]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/inet/url.d(123,23): Error: 
non-constant expression "http://127.0.0.1:8090/api/"[7..16]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/web/internal/rest/common.d(136,29):
 Error: non-constant expression ['h', 't', 't', 'p', ':', '/', '/', '1', '2', 
'7', '.', '0', '.', '0', '.', '1', ':', '8', '0', '9', '0', '/', 'a', 'p', 'i', 
'/', 'a', 'p', 'i'][0..29]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/web/internal/rest/common.d(156,46):
 Error: non-constant expression ['h', 'o', 'm', 'e'][0..4]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/web/internal/rest/common.d(156,46):
 Error: non-constant expression ['h', 'o', 'm', 'e'][0..4]
dmd failed with exit code 1.

What did i miss? I was trying to do it according to vibed 
documentation: 
http://vibed.org/api/vibe.web.rest/RestInterfaceClient


Re: No polymorphism?

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

On Monday, 24 July 2017 at 17:29:55 UTC, Dgame wrote:

S[] ss = [new S()];
test1(ss); // Fails

Why isn't the compiler able to deduce S[] => I[]? Or is it just 
me?


This is exactly because of polymorphism. Consider the following:

```
S[] ss = [new S()];
I[] i = ss; // pass it to the function or whatever for implicit 
conversion


class OtherDerived : I {}

i[0] = new OtherDerived(); // looks OK, otherDerived is also 
interface I

```

But now, ss[0], the same array as i, no longer points to an S! 
You broke the type system.




No polymorphism?

2017-07-24 Thread Dgame via Digitalmars-d-learn
I may be just tired, but could somebody explain this behaviour to 
me? It seems odd to me:



interface I
{
}

class S : I
{
}

void test1(I[])
{
}

void test2(I)
{
}

void main()
{
test1([new S()]); // Works
test2(new S()); // Works

I i = new S();
test2(i); // Works

S s = new S();
test2(s); // Works

I[] si = [new S()];
test1(si); // Works

S[] ss = [new S()];
test1(ss); // Fails
}


Compiler output: test.d(32): Error: function test1 (I[] _param_0) 
is not callable using argument types (S[])


Why isn't the compiler able to deduce S[] => I[]? Or is it just 
me?

I've tried dmd 2.075


howto touch a file - setTimes

2017-07-24 Thread Martin Tschierschke via Digitalmars-d-learn

When I tried to set the atime and mtime of a file (f) via:

import std.datetime;
auto time = Clock.currTime();
setTimes(f,time,time);

I get "Operation not permitted."

This is caused on linux by the rule, that if you are not the 
owner of the file

you may only set the mtime of a file to current time.

A simple "touch filename" in terminal works.

Any hint? Do I have to use execute("touch filename")?



Re: Best syntax for a diagonal and vertical slice

2017-07-24 Thread Timon Gehr via Digitalmars-d-learn

On 22.07.2017 22:55, kerdemdemir wrote:

We have awesome way for creating slices like:

 a = new int[5];
 int[] b = a[0..2];

But what about if I have 2D array and I don't want to go vertical. 
Something like :


int[3][3] matrix = [
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
];

I believe I can use std.range function "RoundRobin"(or maybe it won't 
work with 2D array directly) for having a good looking vertical slice 
which will have 1,4,7 or 2,5,8 or 3,6,9 in my example above.


And what if I want to go diagonal like 1,5,9 or 3,5,7 in the example 
above. Is there a good solution in std without using for loops?


I have one more requirement for fulfilling the task that I working on. 
This slices do not have to be the same size as the array. For example in 
the example above slice size could have 2 instead of 3. In this case I 
need to have slices like 1,5;2,6;4,8;5,9 ... and so on for diagonal case.


Erdem

Ps: Converting the 2D array to 1D array is possible in my case.



horizontal: matrix[i][j..j+k]
vertical:   matrix[i..i+k].map!(x=>x[j])
diagonal 1: iota(k).map!(x=>matrix[i+x][j+x])
diagonal 2: iota(k).map!(x=>matrix[i+x][j-x])


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread Clinton via Digitalmars-d-learn

On Monday, 24 July 2017 at 14:51:04 UTC, rikki cattermole wrote:

Stuff the GC.
You don't need it to care about collecting (or destroying for 
that matter).


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);
```

Normally I would suggest to create your own buffer, but because 
of the DB library probably doesn't support that, no point 
trying to force it.


[0] http://dlang.org/phobos/core_memory.html#.GC.free


Thanks! I didn't know I could do that with the GC enabled.


Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread via Digitalmars-d-learn
On Mon, Jul 24, 2017 at 03:45:29PM +, Houdini via Digitalmars-d-learn wrote:
> But in C++, we pass them by reference also to avoid copies (const &).

Exactly... in C++ you basically always pass by reference, so D made that the 
default.



Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread Houdini via Digitalmars-d-learn
On Monday, 24 July 2017 at 15:41:33 UTC, Steven Schveighoffer 
wrote:


Because types with inheritance generally don't work right if 
you pass by value (i.e. the slicing problem).


structs don't support inheritance or virtual functions, so they 
can be safely passed by value.


But in C++, we pass them by reference also to avoid copies (const 
&).

The potential polymorphic usage is not the only point to consider.



Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread Houdini via Digitalmars-d-learn

On Monday, 24 July 2017 at 15:37:51 UTC, Andrea Fontana wrote:


Maybe this will help you:
https://stackoverflow.com/questions/10965577/usage-preference-between-a-struct-and-a-class-in-d-language


Thanks for this informative link.


Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/24/17 11:21 AM, Houdini wrote:

Hello,

I am a C++ coder, and I am learning D (just reading a book, for now).

D is very similar to C++ (and also grabs godd ideas from Python), but I 
have a naive question : why does Walter Bright chose to instanciate 
classes like in Java ? And why is it different for structs ?


Because types with inheritance generally don't work right if you pass by 
value (i.e. the slicing problem).


structs don't support inheritance or virtual functions, so they can be 
safely passed by value.


-Steve


Re: Why structs and classes instanciations are made differently ?

2017-07-24 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 24 July 2017 at 15:21:54 UTC, Houdini wrote:

Hello,

I am a C++ coder, and I am learning D (just reading a book, for 
now).


D is very similar to C++ (and also grabs godd ideas from 
Python), but I have a naive question : why does Walter Bright 
chose to instanciate classes like in Java ? And why is it 
different for structs ?


Maybe this will help you:
https://stackoverflow.com/questions/10965577/usage-preference-between-a-struct-and-a-class-in-d-language





Why structs and classes instanciations are made differently ?

2017-07-24 Thread Houdini via Digitalmars-d-learn

Hello,

I am a C++ coder, and I am learning D (just reading a book, for 
now).


D is very similar to C++ (and also grabs godd ideas from Python), 
but I have a naive question : why does Walter Bright chose to 
instanciate classes like in Java ? And why is it different for 
structs ?


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread ketmar via Digitalmars-d-learn

rikki cattermole wrote:


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);


or just `delete arr;`. it is marked as "deprecated" in changelog, but who 
cares? it works.


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread rikki cattermole via Digitalmars-d-learn

Stuff the GC.
You don't need it to care about collecting (or destroying for that matter).

Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);
```

Normally I would suggest to create your own buffer, but because of the 
DB library probably doesn't support that, no point trying to force it.


[0] http://dlang.org/phobos/core_memory.html#.GC.free


Cleaning/Releasing large arrays from memory

2017-07-24 Thread Clinton via Digitalmars-d-learn
Hi guys, I have a question on how to free large arrays in D after 
they're no longer needed.


Let's say I have this:


SomeKey[] getKeys() {
  SomeKey[] n;

  foreach(batching stuff...) {
   SomeKey newstuff = db.select!(SomeKey[])(...); // gets around 
6M of these from db


   redis.send("newItems", newStuff.length);

   n ~= newStuff;

   destroy(newStuff);
  }

  return n;
}

void main() {
  SomeKey[] myarray = getKeys();
  ulong[string] mappedValues;

  foreach(i, item; myArray) {
   mappedValues[item.name] = i;
  }

  // No longer need myarray, and we need the memory back
  destory(myarray);
  GC.collect;

  // Another memory intensive operation below
}


This seems to work for me to a point, but I notice my program 
still holds a lot in memory even after certain memory intensive 
arrays should have been collected.


Is this just a hit and miss with the GC or am I doing something 
wrong? Uses around 40% less memory forcing the GC and cleaning 
arrays but seems like a lot is left over, especially for threads 
that have already finished(I've expect a thread to free all it's 
memory). I'm not sharing anything across threads besides a config 
struct.


This is a simplified version of my app. At the moment when at 
around 9GB at it's peak instead of 19GB like before.


Re: Check whether string value represents a type

2017-07-24 Thread Timoses via Digitalmars-d-learn

On Monday, 24 July 2017 at 07:08:56 UTC, Basile B. wrote:

On Friday, 21 July 2017 at 14:21:37 UTC, Timoses wrote:
I'd love to check whether a string value is the name of a type 
at run-time.

[...]
The goal is to identify whether a string represents a custom 
type within a package. I'm also trying to iterate over all 
modules within the package to get the struct name. However, 
that seems like a struggle...


Any ideas?..


I used custom Runtime Type Infos for this:
https://github.com/BBasile/iz/blob/master/import/iz/rtti.d#L550
Each type for which that's interesting to have extra 
information is registered.
When a type is not registered than it can be considered as not 
a type.


Awesome, that's helping a lot : D.


Re: Best syntax for a diagonal and vertical slice

2017-07-24 Thread pineapple via Digitalmars-d-learn

On Saturday, 22 July 2017 at 20:55:06 UTC, kerdemdemir wrote:
And what if I want to go diagonal like 1,5,9 or 3,5,7 in the 
example above. Is there a good solution in std without using 
for loops?


I suggest using an actual matrix type for tasks like this. I 
don't know about diagonal slicing, but the implementation here at 
least provides accessors for both rows and columns.


https://github.com/pineapplemachine/mach.d/blob/master/mach/math/matrix.d



Re: map on char[] converts to dchar?

2017-07-24 Thread pineapple via Digitalmars-d-learn
It is worth noting too that mach's map function will not behave 
this way; UTF encoding and decoding is instructed explicitly and 
is not done implicitly like in phobos.


https://github.com/pineapplemachine/mach.d

import mach.range : map, asarray;
import mach.text.ascii : toupper;

void main(){
char[] x = ['h', 'e', 'l', 'l', 'o'];
char[] y = x.map!toupper.asarray();
assert(y == "HELLO");
}



Re: map on char[] converts to dchar?

2017-07-24 Thread Seb via Digitalmars-d-learn

On Monday, 24 July 2017 at 09:05:43 UTC, Johan wrote:

Hi all,
  What am I doing wrong here?
```
import std.algorithm;
int foo(char c) {
return 123;
}
auto mapFoo(char[] chars) {
return chars.map!(a => a.foo);
}
```
errors with:
main.d(14): Error: function main.foo (char c) is not callable 
using argument types (dchar)

/Library/D/dmd/src/phobos/std/algorithm/iteration.d(492):
 instantiated from here: MapResult!(__lambda2, char[])
main.d(14):instantiated from here: map!(char[])

(Things work after changing foo to accept dchar, but I don't 
want that.)


Thanks,
  Johan


Have a look at https://tour.dlang.org/tour/en/gems/unicode

tl;dr: it's auto-decoding and you can avoid it with e.g. byChar


map on char[] converts to dchar?

2017-07-24 Thread Johan via Digitalmars-d-learn

Hi all,
  What am I doing wrong here?
```
import std.algorithm;
int foo(char c) {
return 123;
}
auto mapFoo(char[] chars) {
return chars.map!(a => a.foo);
}
```
errors with:
main.d(14): Error: function main.foo (char c) is not callable 
using argument types (dchar)
/Library/D/dmd/src/phobos/std/algorithm/iteration.d(492):
instantiated from here: MapResult!(__lambda2, char[])

main.d(14):instantiated from here: map!(char[])

(Things work after changing foo to accept dchar, but I don't want 
that.)


Thanks,
  Johan



Re: Check whether string value represents a type

2017-07-24 Thread Basile B. via Digitalmars-d-learn

On Friday, 21 July 2017 at 14:21:37 UTC, Timoses wrote:
I'd love to check whether a string value is the name of a type 
at run-time.

[...]
The goal is to identify whether a string represents a custom 
type within a package. I'm also trying to iterate over all 
modules within the package to get the struct name. However, 
that seems like a struggle...


Any ideas?..


I used custom Runtime Type Infos for this:
https://github.com/BBasile/iz/blob/master/import/iz/rtti.d#L550
Each type for which that's interesting to have extra information 
is registered.
When a type is not registered than it can be considered as not a 
type.


Re: Check whether string value represents a type

2017-07-24 Thread Timoses via Digitalmars-d-learn
On Friday, 21 July 2017 at 14:44:23 UTC, Steven Schveighoffer 
wrote:

On 7/21/17 10:21 AM, Timoses wrote:
I'd love to check whether a string value is the name of a type 
at run-time.


E.g.:


string a = "int";
string b = "im no type";
assert( isStringType(a) );
assert( !isStringType(b) );

or

struct TestStruct
{
 int test;
}

string t = "TestStruct";
assert( isStringType(t) );


Is anything like this possible?

The goal is to identify whether a string represents a custom 
type within a package. I'm also trying to iterate over all 
modules within the package to get the struct name. However, 
that seems like a struggle...


Any ideas?..


In order to do this, the list of types must be stored somewhere 
to compare with at runtime.


At this time, this is not done. You could potentially do this 
with the RTInfo template, but it would have to be part of a 
custom druntime.


-Steve


Thanks Steve!
That's sound too much of a strugge for a newbie like me : D. I'll 
probably evaluate and compare the type names as strings then and 
derive further processing from there.