Re: `static` function ... cannot access variable in frame of ...

2024-01-15 Thread Dukc via Digitalmars-d-learn

On Monday, 15 January 2024 at 18:16:44 UTC, Bastiaan Veelo wrote:
Hey people, I can use some help understanding why the last line 
produces a compile error.


```d
import std.stdio;

struct S
{
static void foo(alias len)()
{
writeln(len);
}
}

void S_foo(alias len)()
{
writeln(len);
}

void main()
{

const five = 5;
S_foo!five; // Fine
S.foo!five; // Error
}
```

The error is
```
onlineapp.d(7): Error: `static` function 
`onlineapp.main.foo!(5).foo` cannot access variable `five` in 
frame of function `D main`

onlineapp.d(19):`five` declared here
onlineapp.d(21): Error: template instance 
`onlineapp.main.foo!(5)` error instantiating

```

It seems to me this should just work.


It seems that since you write `static` to the member function 
signature, the compiler thinks the function shouldn't be allowed 
to have a hidden parameter that is needed to access `const five` 
from `foo`.


At a first glance it seems this should be allowed, since `static` 
means "no access to the type or function enclosing the member 
function", which wouldn't appear to say anything about the hidden 
frame pointer to the `alias` context as opposed to the enclosing 
struct.


But thinking about it, function templates are a shorthand for 
epnymous templates. I think the code get's rewritten to:


```D
struct S
{
template foo(alias len)
{
static void foo()
{
writeln(len);
}
}
}
```

. As you can see, in the rewritten form you actually are 
accessing the outer scope, which is exactly what `static` is 
supposed to prevent.


On the other hand, if you move the template out of the struct you 
say this still works, even when it shouldn't according to my 
theory. I'm of the opinion that something in the compiler needs 
fixing here, but I'm not quite sure what.


Re: pointer to std.algorithm.iteration : splitter

2023-08-31 Thread Dukc via Digitalmars-d-learn

On Thursday, 31 August 2023 at 05:16:02 UTC, Vino wrote:

Hi All,

  Request your help on the below error

Program
```
void main()
{
import std.stdio:writeln;
import std.algorithm.iteration : splitter;

auto splitter_ptr = !((a, b) => a.splitter(b).array);
string str = "TEST1;TEST2;TEST3";
auto words = splitter_ptr(str, ';');
foreach (word; words) { writeln(word); }
}
```
```
Error: template instance `splitter!((a, b) => 
a.splitter(b).array)` does not match any template declaration

```

From,
Vino


I'm assuming you want to instantiate `splitter` and take the 
address of the resulting function, so that `splitter_ptr` will be 
a function pointer or a delegate.


You are getting the compile time arguments to `splitter` utterly 
wrong. It should take:


 - A function that checks equality between an element and a 
separator.


 - a `keepSeparators` flag.

 - type of the range you're passing in, `string` in this case.

 - type of the separator, `char` or `dchar` in this case.

You can find this all in [the 
docs](https://dlang.org/phobos/std_algorithm_iteration.html#.splitter). I think you accidentally passed what you wanted to do with `splitter` as a compile-time parameter to it.


I don't think it's very practical to try instantiating a complex 
templated function like `splitter` without calling it. It's just 
not designed for that. I'd rather define a function that wraps a 
call to it, like (not tested, may have errors):


```D
auto splitter_ptr = (string str, dchar sep) => 
str.splitter(sep).array;

```

Maybe that's what you tried in the first place. You don't need 
`&` here, because a lambda (which we use here) is already a 
function pointer (or a delegate).


Re: Advice on debugging possible exception or crash

2023-07-06 Thread Dukc via Digitalmars-d-learn

On Thursday, 6 July 2023 at 06:00:04 UTC, Cecil Ward wrote:
In my limited experience, exceptions produce an error message 
though, and I’m not seeing anything. Any advice on how to debug 
this, silent termination ?


If unsure on cases like this, test. Intentionally throw an 
exception and don't catch it, what happens? Same for any other 
way of termination you're suspecting.


Re: Compiling to RiscV32

2023-07-06 Thread Dukc via Digitalmars-d-learn

On Wednesday, 5 July 2023 at 17:00:53 UTC, HuskyNator wrote:
Using a simple single '.d' file with no imports: `Error: cannot 
find program 'cc'`


I haven't tried to compile to RiscV32, nor do know how it works. 
But this reads like LDC is not finding the C compiler it's trying 
to use.


LDC uses a C compiler to call the linker, instead to calling the 
linker directly.


Re: Indenting standards religions K, whitesmiths etc

2023-06-01 Thread Dukc via Digitalmars-d-learn

On Wednesday, 31 May 2023 at 16:24:38 UTC, Cecil Ward wrote:
I wanted to ask how some of the leaders of our group feel about 
D indentation standards. `i realise that this causes some 
religious fervour in C. I could be in trouble here because in 
all my years at work, we never used K & R ‘one true brace 
style’ indenting, with the house style I’m used to being more 
like whitesmiths. Wikipedia explains this better. Something 
like the following below.


So my question: would I get lynched for the following? (below)


Check out this module from me: 
https://github.com/dukc/nuklearbrowser/blob/master/source/nuklearbrowser.d


Plus similar style in most of my posts and bug reports. I'm still 
alive :D.


Your code is your code. There, you may do as you wish. You have 
to aknowledge that an esoteric style may make it more difficult 
to read for some, but we're not lynching people for other factors 
of code readability either. Brace style is no different.


Plus, what brace style is considered readable by the majority is 
a culture issue. There has to be some way to challege the 
established culture. If you don't exercise your power to code as 
you wish, someone will make your choice for you. Coding culture, 
or even culture in general, cannot develop if people never 
challege the present status quo.


When you're coding with others, though, then you should obey the 
style guideline of that project if there is one. Even there 
you're as entitled as anyone for an opinion what the style policy 
should be (and to whether there should be style policy at all), 
but you then should (usually) obey the decision regardless 
whether it's the one you were advocating for.






Re: A Programmer's Dilema: juggling with C, BetterC, D, Macros and Cross Compiling, etc.

2023-05-01 Thread Dukc via Digitalmars-d-learn

On Monday, 1 May 2023 at 09:17:14 UTC, Eric P626 wrote:

This is a false dilemma: D has full C compatibility.


From what I understand, D can use C, but C cannot use D? It's 
like C++: C++ can call C but C cannot call C++.


50% or more of my code will be put in re-usabled libraries. If 
I want people to use those libs, I would need to compile them 
in C or better C. Because betterC seems to create C libraries. 
If D can make C libraries, then indeed, I could do everything 
in D.


D can make C libraries, BetterC or no.

The difference is that a vanilla D library has a DRuntime 
dependency, meaning the runtime has to be initialised. You can do 
that by either writing the `main()` function in D, or manually 
initialising the runtime from C before calling other D functions. 
Not sure of the specifics but I'm sure it's not too hard. Seems 
the C-linked functions in 
[core.runtime](https://dlang.org/phobos/core_runtime.html#.Runtime.initialize) ought to do the trick.


In BetterC, there is no DRuntime that needs initialising, but for 
a common application DRuntime is worth the hassle to initialise 
it many times.




Re: A Programmer's Dilema: juggling with C, BetterC, D, Macros and Cross Compiling, etc.

2023-05-01 Thread Dukc via Digitalmars-d-learn
As others have said, you have no reason to restrict yourself to 
BetterC. If you dislike objects and/or other high-level features, 
you can simply use D in a low-level way like you'd use C. That 
works just as well from normal D as from BetterC. Both the C 
standard library and third-party C libraries are available in 
both cases.


And I do encourage that over time you gradually try the 
high-level features you don't have in C or even BetterC. It's 
likely you won't like all of them, and that's fine. For instance, 
it's pretty common for a D codebase to use object-oriented 
programming and exception only minimally or not at all. Still, 
almost certainly you will like something better than the C 
equivalent. For example, I've heard no-one preferring the 
`concat` function of C standard library over append operator 
(`~`) of a D string, except when it's necessary to do without the 
GC (and even then, A D programmer would likely devise something 
that works with slices and non-zero-terminated strings rather 
than `concat`).


On Sunday, 30 April 2023 at 18:15:31 UTC, Guillaume Piolat wrote:
You could use BetterC for sure, but it's more practical in the 
long term to just learn to live with the GC: it is a one-time 
mental cost.


Plus, even if you were to avoid the garbage collector, BetterC is 
not needed for that.


You want BetterC only if you want to avoid depending on DRuntime 
at all - maybe to write a library to be used from C or to write 
code to a platform without DRuntime port. And even in those 
cases, you have alternative ways to accomplish the same.





Re: short guide on getting started with D

2023-04-18 Thread Dukc via Digitalmars-d-learn

On Monday, 3 April 2023 at 07:29:01 UTC, cgenie wrote:

Hello,

I created a short guide on getting started with D: 
https://blog.mmksoft.uk/#A%20short%20guide%20on%20getting%20started%20with%20D%20programming


This is because I recently I started to explore the language 
and, having read the forum, I see DUB being discouraged quite 
often.


I would appreciate any remarks.

Best,
Przemek


Sorry for the very late reply. I've been thinking on commenting 
on this but I'm lazy.


You're saying you don't want to use DUB? In that case, I think 
you should not add it to your dependencies at all. DUB is both a 
package manager and a build tool, but here Nix is answering for 
the package management and Meson is your build system. Have Meson 
to use LDC directly instead.


Since you're using Nix, in case you change your mind about DUB 
(maybe to build a third-party package), it needs to be said that 
using it isn't straightforward since Nix won't let DUB download 
the dependencies from the Internet on it's own. There's a 
solution, though: [dub2nix](https://github.com/lionello/dub2nix). 
If you're interested, watch it's authors [DConf 
talk](https://dconf.org/2019/talks/lunesu.html) for more info.


Anyway, there are not many examples about using D with Nix. Your 
post is addressing that, so thanks for writing it up.


Re: pointer escaping return scope bug?

2022-11-19 Thread Dukc via Digitalmars-d-learn
On Saturday, 19 November 2022 at 15:02:54 UTC, Nick Treleaven 
wrote:

On Saturday, 19 November 2022 at 14:52:23 UTC, ag0aep6g wrote:
That's essentially just a function that returns its pointer 
parameter. So the program boils down to this:


```D
@safe:
int* fp(return scope int* p) { return p; }
void main()
{
int* p;
{
auto lf = new int;
p = fp(lf);
}
assert(p != null); // address escaped
}
```

Which is fine, as far as I can tell. `lf` is not `scope`. And 
when you pass it through `fp`, the result is still not 
`scope`. So escaping it is allowed.


You do get an error when you make `lf` `scope` (explicitly or 
implicitly). So everything seems to be in order.


OK, so how do I make `lf` implicitly scope?


Have the `int*` inside it to point to a local, or assign another 
`scope int*` to it.




Re: Is defining get/set methods for every field overkill?

2022-11-19 Thread Dukc via Digitalmars-d-learn
On Saturday, 19 November 2022 at 09:49:18 UTC, thebluepandabear 
wrote:
On Saturday, 19 November 2022 at 09:26:49 UTC, Andrey Zherikov 
wrote:
On Saturday, 19 November 2022 at 09:12:26 UTC, 
thebluepandabear wrote:
That's the point many people have given here which is not 
convincing him, even though it is quite great.


I think we all know the answer here 


IMHO you are both right :)
You are speaking about API compatibility, `[]() {}()` speaks 
about ABI compatibility. The latter makes sense in 
long-running production software. So we know that there are no 
issues in API compatibility but we don't know anything about 
ABI.


I am too dumb to know what ABI is


ABI is short for application binary interface. Where API means 
how you use another module in source code, ABI means how you 
would use that module in assembly langauge or machine code.


If two versions of a library have the same ABI, the program using 
the library does not have to be recompiled, only relinked to the 
new library (which happens at runtime if it's a dynamically 
linked library).


It tends to be of less importance in D than in C or C++. First, D 
modules usually compile quickly enough that premade binaries 
(which would be hard to keep up to date with the source code 
headers) don't make sense. Second, DUB standardises the build 
process so binaries aren't needed for user convenience either. 
Maybe the most important remaining use case is building a library 
that can be used from other languages.


Re: Is defining get/set methods for every field overkill?

2022-11-19 Thread Dukc via Digitalmars-d-learn
On Saturday, 19 November 2022 at 09:26:49 UTC, Andrey Zherikov 
wrote:
On Saturday, 19 November 2022 at 09:12:26 UTC, thebluepandabear 
wrote:
That's the point many people have given here which is not 
convincing him, even though it is quite great.


I think we all know the answer here 


IMHO you are both right :)
You are speaking about API compatibility, `[]() {}()` speaks 
about ABI compatibility. The latter makes sense in long-running 
production software. So we know that there are no issues in API 
compatibility but we don't know anything about ABI.


Yes, this is a good summary. Redefining a raw field as a 
getter/setter pair keeps the API but breaks the ABI, so in some 
cases conservative getters/setters can be justified.


Another problem with raw fields:

```D
struct S{int field;}

@safe clientCode()
{   auto s = new S();
doSomething();
}
```

This will break if S is rewritten as

```D
struct S
{   int field_;
auto field(){return field_;}
auto field(int val){return field_ = val;}
}
```

I though at first that breakage could still be avoided by instead 
writing


```D
struct S
{   int field_;
ref field(){return field_;}
}
```

...but I tested and actually it does not work because in this 
case `` takes the address of the getter function, not the 
field.


Now, despite all this I don't think it'd be a good idea to write 
everything to getters/setters just in case. The binary interface 
issue is frankly secondary: most structs and classes are just 
compiled along with their client code. And even separately 
compiled libraries only have to do this if they strive to provide 
a stable ABI between releases, which is not nearly always the 
case. Nor needs to be.


But still the pointer problem in the above example stands, so 
conservative getters/setters are justified in an API that's used 
widely enough. But probably not for something internal to a ten 
thousand line long package.


Re: Is defining get/set methods for every field overkill?

2022-11-19 Thread Dukc via Digitalmars-d-learn
On Saturday, 19 November 2022 at 03:52:41 UTC, thebluepandabear 
wrote:
Say you want to write 'SET' now whenever someone sets a 
width/height value for the rect (as an example), and 'GET' when 
someone gets the width/height value for the rect, what you 
could do is do this:


```
class Rect2D {
int rectWidth;
int rectHeight;

int width() {
writeln("GET");
return rectWidth;
}

void width(int rectWidth) {
writeln("SET");
this.rectWidth = rectWidth;
}

int height() {
writeln("GET");
return rectHeight;
}

void height(int rectHeight) {
writeln("SET");
this.rectHeight = rectHeight;
}
}
```

Honestly, it may not be a magic bullet, but still useful.


Yes, this is what I meant. I did use the UFCS name inaccurately: 
I believe UFCS means the ability to write `y.x(z)` in place of 
`x(y, z)`, and maybe the ability to write `y.x = z` in place of 
`y.x(z)`, but it does not mean the ability to omit empty 
parenthesis in a function call. The latter is what enables 
getters that don't break the API.


Re: Is defining get/set methods for every field overkill?

2022-11-17 Thread Dukc via Digitalmars-d-learn
On Thursday, 17 November 2022 at 04:39:35 UTC, thebluepandabear 
wrote:
I am debating whether or not I should add getter methods to 
these properties. On one hand, it will inflate the codebase by 
a lot, on the other hand -- in other languages like Java it is 
a good practice


D has far less need for getters/setters than Java or C++. The 
reason is [Uniform Function Call 
Syntax](https://ddili.org/ders/d.en/ufcs.html). This means that a 
member of a `struct` or `class` can start out as a normal field 
and be later converted to getter/setter if needed, without 
breaking calling code.


You still might want to use setters when you want to be extra 
conservative (client code taking address of a struct field will 
still break if your getter replacing it can't return by `ref`), 
but for the vast majority of purposes that is an overkill IMO.


Re: Making sense out of scope and function calls

2022-11-14 Thread Dukc via Digitalmars-d-learn

On Sunday, 13 November 2022 at 19:06:40 UTC, 0xEAB wrote:

Why does only the latter sample compile?
The former leads to the following warning:


Are you using the `-preview=dip1000` compiler flag?

I didn't manage to reproduce this in a simple example of my own. 
The closest I equivalent I accomplished is this:

```
enum LowerCaseToken { u, l, c }

struct Foo {
@safe:
int* dummy;
string[int][LowerCaseToken] _headers;

this(return ref int i)
{
dummy = 
}

string[] getHeader(LowerCaseToken name) scope return
{
return _headers[name].values;
}

string[] getHeader(string name)() scope return
{
enum token = LowerCaseToken.l;
// Error. Remove to compile
auto x = 
return this.getHeader(token);
}
}

@safe void main()
{
int x;
auto foo = Foo(x);
foo.getHeader!"h1"();
}
```

With `-preview=dip1000` this fails, but with a slightly different 
message to yours, "cannot take address of `scope` parameter 
`this` in `@safe` function `getHeader`". It's right to fail, 
because you cannot have any pointer (or array, or class) to point 
to a `scope` variable. D does not have any storage class for `x` 
that would protect the int pointed to by `dummy`, because 
`scope(Foo*)` means address of Foo is protected, not the address 
of whatever `dummy` and `_headers` point to.


However, this error only happens if I try to create a pointer to 
`this`, not when simply using `this`, plus the error is a bit 
different, so I'm not sure what's going on.




(and why is the deprecation message printed twice?)


The function is a template. Perhaps it's instantiated twice. 
Another possibility, you have instantiated the mixin template 
that contains that function in your project twice.





Re: How to build DMD/Phobos on Windows

2022-09-01 Thread Dukc via Digitalmars-d-learn
On Wednesday, 24 August 2022 at 18:06:29 UTC, Dmitry Olshansky 
wrote:
It's been a long time but I've found some spare hours I want to 
devote to finally updating our std.uni to Unicode 14 (soon to 
migrate to 15 I guess).


Thanks, much appreciated!

So what is the canonical way to build D on Windows? Any 
pointers would be greately appreciated.


Don't know since I don't use Windows anymore but if all else 
fails it probably works on WSL.


Re: How to use a non-static objects in string `mixin`?

2022-08-29 Thread Dukc via Digitalmars-d-learn

On Saturday, 27 August 2022 at 13:20:13 UTC, hype_editor wrote:
I need to use function `eval` sometimes, but compiler throws an 
error: `Error: variable `firstOperand` cannot be read at 
compile time`.


You're probably misunderstanding `mixin`. It does not work like 
an eval function at Lisp or
 JavaScript or such. Instead, it evaluates it's contents at 
compile time, meaning that you can only use compile-time data in 
it, `enum` variables and template arguments for example.


Because the operator is not known at compile time, this means you 
need something else. Switch statement Paul Backus suggested is 
one option. You could alternatively try an associative array that 
maps the operators to the respective functions, something like 
(untested):

```D
enum opMap =
[ "+": (double a, double b) => a+b,
  "-": (double a, double b) => a-b,
  //...
];

//in the eval function
return opMap[operator](firstOperand, secondOperand);
```


Re: DIP1000

2022-06-24 Thread Dukc via Digitalmars-d-learn
On Friday, 24 June 2022 at 05:11:13 UTC, Ola Fosheim Grøstad 
wrote:


No, the lifetime is the same if there is no destructor. Being 
counter intuitive is poor usability.


It depends on whether you expect the rules to be smart or simple. 
Smart is not necessarily better, as the Unix philosophy tells 
you. I'm sure you have experience about programs that are 
unpredictable and thus frustating to use because they try to be 
too smart.





Re: Bug in dmd?

2022-06-15 Thread Dukc via Digitalmars-d-learn

On Tuesday, 14 June 2022 at 23:56:58 UTC, Andrey Zherikov wrote:

On Tuesday, 14 June 2022 at 21:44:48 UTC, Dukc wrote:
No idea. The functions seems indeed to be exactly the same, so 
I assume this is a DMD bug. It cannot be a bug in 
`std.sumtype`, since that would trigger in both of the 
templates.


This definitely triggers some bug in DMD because this `private 
void printHelp ...` function is not really `private` as it's 
called from [another 
module](https://github.com/andrey-zherikov/argparse/blob/bug/source/argparse/internal.d#L786) and DMD doesn't catch this.


Now when I think of it, perhaps the fact that private `printHelp` 
has the same name as the public `printHelp` is somehow confusing 
dmd. If you try to rename the private `printHelp` and it's call 
in the public one to something else, you might get some insight 
on what triggers this behaviour.


Re: Bug in dmd?

2022-06-14 Thread Dukc via Digitalmars-d-learn

On Tuesday, 14 June 2022 at 13:39:12 UTC, Andrey Zherikov wrote:
I have [pretty simple code in my 
library](https://github.com/andrey-zherikov/argparse/blob/bug/source/argparse/help.d#L27-L47):

```d
alias CC = SumType!(AA,BB);
struct AA {}
struct BB
{
CC[] c;
}

private void ppp(T, Output)(auto ref Output output, in 
CommandArguments!T cmd, in Config config)

{
auto cc = CC(AA());  // (1)
}
private void printHelp(T, Output)(auto ref Output output, in 
CommandArguments!T cmd, in Config config)

{
auto cc = CC(AA());  // (2)
}

void printHelp(T, Output)(auto ref Output output, in Config 
config)

{
ppp(output, CommandArguments!T(config), config);
printHelp(output, CommandArguments!T(config), config);
}
```

[Line (2) 
produces](https://github.com/andrey-zherikov/argparse/runs/6880350900?check_suite_focus=true#step:5:12) `undefined reference to '_D3std7sumtype__T7SumTypeTS8argparse4help2AATSQtQm2BBZQBl6__dtorMFNaNbNiNfZv'` (it demangles to `pure nothrow @nogc @safe void std.sumtype.SumType!(argparse.help.AA, argparse.help.BB).SumType.__dtor()`)


If I comment line (2) then everything is good (no link errors). 
Note that there is the same code at (1) which doesn't produce 
any error. Any idea what's going on?


No idea. The functions seems indeed to be exactly the same, so I 
assume this is a DMD bug. It cannot be a bug in `std.sumtype`, 
since that would trigger in both of the templates.


BTW, thanks for taking the effort to write your question this 
well (demagling, link to your library and all).


Re: What's a good way to disassemble Phobos?

2022-04-30 Thread Dukc via Digitalmars-d-learn

On Saturday, 30 April 2022 at 18:49:27 UTC, Adam D Ruppe wrote:

On Saturday, 30 April 2022 at 18:18:02 UTC, Dukc wrote:
I'm looking for something where I could search for the call to 
the DRuntime functions in question, from an already combined 
.o or .a. What do you suggest? I'm on Linux.


objdump -d works on .o files


Indeed, this seems workable output. Thanks.


What's a good way to disassemble Phobos?

2022-04-30 Thread Dukc via Digitalmars-d-learn
I have figured out that my development build of Phobos is for 
some reason including instances of `__cmp` and `dstrcmp` 
templates from DRuntime in the Phobos binary. Since `-betterC` 
client code does not link Phobos in, it fails if it tries to use 
those functions.


The problem: how do I track down what includes those functions in 
the Phobos binary? The -vasm switch of DMD gives a neat output, 
but I can get it to only show the disassembly of files I'm 
compiling (not already combined files), and before the linking 
phase. So no info where the function calls point to.


I also tried ndisasm. It can disassemble already compiled 
binaries, but it's output is utter trash. It can't even figure 
where a function begins or ends, let alone displaying their name. 
Instead it displays just a sea of `add` instructions for the 
areas between the functions.


I'm looking for something where I could search for the call to 
the DRuntime functions in question, from an already combined .o 
or .a. What do you suggest? I'm on Linux.


Re: How to use destroy and free.

2022-04-30 Thread Dukc via Digitalmars-d-learn

On Saturday, 30 April 2022 at 11:37:32 UTC, Tejas wrote:
Hell, just using `scope int[] i` should be enough to trigger 
deterministic destruction, no? `typecons`'s `Scoped!` template 
can be used if 100% guarantee is needed _and_ the memory has to 
be stack allocated


Didn't think of that. To be frank, I don't know if `scope int[] 
i` means deterministic destruction. `Scoped` does IIRC.


Re: How to use destroy and free.

2022-04-30 Thread Dukc via Digitalmars-d-learn

On Sunday, 24 April 2022 at 21:00:50 UTC, Alain De Vod wrote:

Is this a correct program to explicit call destroy & free ?

```
void main(){
int[] i=new int[1];
import object: destroy;
destroy(i);
import core.memory: GC;
GC.free(GC.addrOf(cast(void *)(i.ptr)));
}
```


A few picks.

1: You do not need to import `destroy`. Everything in `object` is 
automatically imported.


2: As others have said, destroying an int, or an array if them, 
is meaningless, since they do not have destructors. The only 
thing your call does is to set `i` to `null`. In this case it 
means that there are no more references to the array, so the 
garbage collector can collect it at some point.


3: Because `i` is now null, `GC.free` also does nothing. If you 
had something that really mandated using `destroy`, you'd want to 
use `destroy!false(i)` to avoid setting `i` to `null`.


4: Manually freeing garbage collected memory is just as dangerous 
as freeing manually managed memory. It's preferable to just let 
the GC collect the memory. Also like said, there's probably no 
point to allocate with GC in the first place if you're going to 
manually free the memory.


5: If you're in a hurry to free the memory, a safer way is to 
call `GC.collect`. It will most likely free your old data 
immediately. Don't trust it quite 100% though, since it's 
possible that some unlucky bit pattern in your remaining data, 
that isn't really a pointer, "points" to your old data and it 
won't get collected. Using a precise GC would eliminate that risk 
I think.


This is rarely a problem though, as long as you either don't do 
anything mandatory in destructors, or use `destroy` before 
forgetting the data. The GC can still usually free the majority 
of your memory.


Re: print ubyte[] as (ascii) string

2022-01-07 Thread Dukc via Digitalmars-d-learn

On Thursday, 30 December 2021 at 09:34:27 UTC, eugene wrote:


```d
char[] s = cast(char[])ioCtx.buf[0 .. 
strlen(cast(char*)ioCtx.buf.ptr) - 1];

// -1 is to eliminate terminating '\n'
writefln("got '%s' from '%s:%d'", s, client.addr, client.port);
```

Is there some more concise/elegant way to do that?


Try `auto s = fromStringz(cast(char*)ioCtx.buf.ptr)`.




Re: Why do we have Dmain?

2021-10-22 Thread Dukc via Digitalmars-d-learn

On Friday, 22 October 2021 at 07:00:25 UTC, Mike Parker wrote:
The entry point for your program is a function `_start`. That's 
implemented in the C runtime, which all D programs depend on. 
It in turn calls `main`, as it does for C and C++ programs.


It is possible, in both C and D, to write your own `_start` and 
not depend on the C runtime.


This is something you want to do only if necessary though - C 
runtime is so small that you don't want to drop it for any 
realistic desktop or even a smartphone program. The usual reason 
to do this is if there is no C runtime easily available - meaning 
mainly embedded targets.


Re: better c fibers

2021-09-27 Thread Dukc via Digitalmars-d-learn

On Tuesday, 21 September 2021 at 09:37:30 UTC, Abby wrote:

Hi there,
I'm new in dlang I specially like betterC. I was hoping that d 
fibers would be implemented in without using classes, but there 
are not. Is there another way how to use async/await in dlang 
better c?


Thank you for your help
Abby


A C or C++ concurrency library should work.

Another option, if you just want fibers but not true concurrency, 
would be to do some assembly trickery. Probably not too hard if 
you know assembly, but not very portable.


If the reason you're using `-betterC` is targeting asm.js or 
WebAssembly, you will need to use the JavaScript APIs of your 
environment for concurrency.


Re: Array permutations

2021-09-11 Thread Dukc via Digitalmars-d-learn

On Saturday, 11 September 2021 at 19:37:42 UTC, Vino wrote:
   Request your help on the below to print the below array as 
"Required output", Was able to get these values 
"[1,2],[2,3],[3,4],[4,5]" by using list.slide(2), need your 
help to get values "1,3],[1,4],[1,5],[2,4],[2,5],[3,5]"


```d
import std;
auto slideEnds(List)(List list, size_t slideLen)
{	return list.slide(slideLen).map!(window => [window.front, 
window.back]);

}
void main()
{   auto list = [1,2,3,4,5];

iota(2, list.length)
.map!(slideLen => list.slideEnds(slideLen))
.joiner
.writeln;
}
```

This almost does the trick. It leaves out `[1, 5]` for some 
reason I didn't bother to check though.


Re: Ali's Book - Programming in D

2021-09-11 Thread Dukc via Digitalmars-d-learn

On Friday, 10 September 2021 at 22:26:34 UTC, Ali Çehreli wrote:

  https://bitbucket.org/acehreli/ddili/commits/


Ah it's there - gotta remember that place if I want to make 
corrections. Good book - It's the one that got me up to speed 
with D before I was commited enough to pay for anything.


Now while I'm talking, I'll tell the one error I have already 
spotted, in the `ranges` chapter. It claims that 
`std.range.generate` calls the underlying function on `front`, 
not `popFront`. This used to be true long ago, but nowadays the 
call is done on `popFront` and the call result is cached for 
`front`.


Re: How to Fix Weird Build Failure with "-release" but OK with "-debug"?

2021-07-21 Thread Dukc via Digitalmars-d-learn
On Wednesday, 21 July 2021 at 14:15:51 UTC, Steven Schveighoffer 
wrote:
2. It's hard for me to see where the null dereference would be 
in that function (the `bool` implementation is pretty simple).


-Steve


DMD complains about dereferences in three different lines. I 
suspect it's `this` reference that is `null`.


Re: Can static variables in methods be local for each object?

2021-07-20 Thread Dukc via Digitalmars-d-learn

On Tuesday, 20 July 2021 at 09:24:07 UTC, Mark Lagodych wrote:
Is there a way to make myvar local to each instance of `X` 
without making it a variable of `X`? Just curious.


Yes.

```d
import std.stdio;

class X {
int x(int param) {
static int[typeof(this)] myvar;

if (param == 0) return myvar.get(this, 1234);
else return myvar[this] = param;
}

}

void main()
{
X x1 = new X;
X x2 = new X;

x1.x(0).writeln; //1234
x2.x(0).writeln; //1234

x1.x(17).writeln; //17
x2.x(0).writeln; //1234

x1.x(0).writeln; //17
x2.x(0).writeln; //1234
}
```

However, this is definitely not recommended. When you are calling 
a function with any particular object and argument set, you want 
it to do the same thing and return the same result, regardless of 
what's called before. Otherwise you're making debugging much more 
difficult than it needs to be.


This means that `static` variables should generally be used only 
for two things:
1: data that is only set at the beginning of the program, or at 
first use, and then left to the initial value.
2: caching results of expensive computation. Even this is a bit 
controversal, as it's easy to screw up - often it's just better 
to split the function in two, and let the caller to cache the 
results.


In this case, consider passing `myvar` explicitly:

```d
import std.stdio;

class X {
int x(int param, ref int[typeof(this)] myvar) {
if (param == 0) return myvar.get(this, 1234);
else return myvar[this] = param;
}

}

void main()
{
X x1 = new X;
X x2 = new X;
int[X] myvar;

x1.x(17, myvar).writeln; //17
x2.x(0, myvar).writeln; //1234

x1.x(0, myvar).writeln; //17
x2.x(0, myvar).writeln; //1234

myvar = null; //Forget all calls made so far
x1.x(0, myvar).writeln; //1234
x2.x(0, myvar).writeln; //1234
}
```


Re: Why can't we transpile C++ to D?

2021-06-10 Thread Dukc via Digitalmars-d-learn

On Thursday, 10 June 2021 at 15:09:02 UTC, Tejas wrote:
Sorry, I'm rather ignorant when it comes to this, but why can't 
we use [pegged](https://github.com/PhilippeSigaud/Pegged) to 
transpile C++ code to D? Then we won't need a nogc compatible 
std library and so many other things could get easier, like 
getting legacy code to use Dlang. It might not be worth it for 
C+17 and beyond, but older codebases could benefit 
significantly, right?


This is article is about transpiling old C++ to newer C++, but 
the same problem applies with translating C++ to D: 
https://scottmeyers.blogspot.com/2015/11/the-brick-wall-of-c-source-code.html


Re: coreutils with D trials, wc, binary vs well formed utf

2021-05-24 Thread Dukc via Digitalmars-d-learn
Is there a(n easy-ish) way to fix up that wc.d source in the 
blog to fallback to byte stream mode when a utf-8 reader fails 
an encoding?


Rewrite `toLine`:

```
Line toLine(char[] l) pure
{ import std.array : array;
  import std.algorithm : filter;
  import std.utf : byDchar, replacementDchar;

  auto valid = l.byDchar.filter!(c => c!=replacementDchar).array;
  return Line(valid.byCodePoint.walkLength, 
valid.splitter.walkLength);

}
```

This just ignores malformed UTF without counting it in. It has 
one problem though, for some reason it seems to ignore one 
character after a malformed cone unit. I don't know why.


Re: dlang opengl / gl / glu /glut library.

2021-04-21 Thread Dukc via Digitalmars-d-learn

On Sunday, 18 April 2021 at 23:36:58 UTC, Alain De Vos wrote:

When doing graphics the number of functions explodes.
So one needs always a list, compare to a header file in c.
If there are "modern" alternatives to opengl feel free.


More modern from which perspective? Simpler to use (non-inclusive 
list of options: SDL2/Allegro/SFML bindings, cairod, DLib, 
dgame)? Or more modern from GPU acceleration perspective (you're 
probably wanting derelict-vulkan or derelict-bgfx)?


Re: Dlang equivalent of #define/#ifdef : not... version

2021-04-21 Thread Dukc via Digitalmars-d-learn
On Tuesday, 20 April 2021 at 23:58:46 UTC, Steven Schveighoffer 
wrote:

static if(i_am_a_feature) {
   ...
}
This would be correct if `i_am_a_feature` would be always 
defined, just set to `false` if not existent. But I think the 
idea was to not define the symbol at all if feature does not 
exists. In that case, the condition should be `static 
if(is(typeof(i_am_a_feature)))`.


Re: How to get Laptop battery level

2021-02-22 Thread Dukc via Digitalmars-d-learn

On Monday, 22 February 2021 at 21:14:48 UTC, Dukc wrote:
Note that DGame seems to be currently unmaintained - it might 
have some bits that do not compile anymore. SDL2 is a commonly 
used library though - you should be able to find more examples 
about it if you need to.


Plus, the example I linked is not really the simple minimalistic 
one you want if battery level is all you want to figure out. 
Probably the derelict-sdl2 front page is what you're looking for 
that instead:


https://code.dlang.org/packages/derelict-sdl2


Re: How to get Laptop battery level

2021-02-22 Thread Dukc via Digitalmars-d-learn

On Monday, 22 February 2021 at 20:59:01 UTC, Greatsam4sure wrote:
Dlang is a system programming language. How do I access the 
battery level of my system using code in dlang?


As a systems language, D could access the hardware interface 
directly, if you knew it and loaded your program as a kernel 
driver - if your operating system lets you do that.


Now, I don't think that was the most practical way to approach 
the problem :-). Instead, I recommend you use the SDL2 multimedia 
library to give you a more portable interface. Usage example in D 
here: 
https://github.com/Dgame/Dgame/blob/master/source/Dgame/System/Battery.d


Note that the D module I linked does not contain the machinery to 
initialize SDL2. This module seems to contain that:

https://github.com/Dgame/Dgame/blob/master/source/Dgame/Window/Window.d

Note that DGame seems to be currently unmaintained - it might 
have some bits that do not compile anymore. SDL2 is a commonly 
used library though - you should be able to find more examples 
about it if you need to.


Re: Profiling

2021-02-09 Thread Dukc via Digitalmars-d-learn

On Tuesday, 9 February 2021 at 16:39:25 UTC, Dukc wrote:
You may have or may not have done it wrong, but in any case 
this is a bug. If you do something wrong, the program should 
tell you what you did wrong, instead of telling you that 
character '-' does not belong to middle of a long int.


Oh wait a bit. The stack trace shows calling some function of 
'app.d' - that's presumably your program.


I wonder why it's being called - aren't you supposed to be 
viewing the profiling results instead of profiling? I'm not sure 
what's happening.


Re: Profiling

2021-02-09 Thread Dukc via Digitalmars-d-learn

On Tuesday, 9 February 2021 at 07:45:13 UTC, JG wrote:
Is d-profile-viewer no longer working? Or did I do something 
wrong?


You may have or may not have done it wrong, but in any case this 
is a bug. If you do something wrong, the program should tell you 
what you did wrong, instead of telling you that character '-' 
does not belong to middle of a long int.


You can try older d-profile-viewers as a workaround. Or you can 
try different ways to invoke the profile viewer or to profile 
different programs and see if you can pinpoint the cause.


Re: Open question: what code pattern you use usually for null safety problem

2021-01-15 Thread Dukc via Digitalmars-d-learn

On Thursday, 14 January 2021 at 18:24:44 UTC, ddcovery wrote:
This is only an open question to know what code patterns you 
usually use to solve this situation in D:


  if(person.father.father.name == "Peter") doSomething();
  if(person.father.age > 80 ) doSomething();

knowing that *person*, or its *father* property can be null



Probably the incremental check solution. A helper function if I 
find myself doing that more than two or three times.


On the other hand, I don't have to do this that often. I usually 
design the functions to either except non-null values, or to 
return early in case of null.





Re: Why many programmers don't like GC?

2021-01-14 Thread Dukc via Digitalmars-d-learn
On Thursday, 14 January 2021 at 14:28:43 UTC, Виталий Фадеев 
wrote:

On Wednesday, 13 January 2021 at 18:58:56 UTC, Marcone wrote:
I've always heard programmers complain about Garbage Collector 
GC. But I never understood why they complain. What's bad about 
GC?


How write quickly without GC ?


In DMD style: never release memory!

This is not an option for long-running programs though, nor for 
anything that otherwise uses significant amounts of memory.


Better to just use the GC if unsure.


Re: DConf talk : Exceptions will disappear in the future?

2021-01-06 Thread Dukc via Digitalmars-d-learn

On Monday, 4 January 2021 at 15:39:50 UTC, ludo456 wrote:
Listening to the first visioconf of the Dconf 2020, titled 
Destroy All Memory Corruption, 
(https://www.youtube.com/watch?v=XQHAIglE9CU) Walter talks 
about not using exceptions any more in the future. He says 
something like "this is where languages are going" [towards no 
using exceptions any more].


I don't think exceptions are going anywhere. It might be that new 
libraries tend to avoid them (to work with @nothrow and @live), 
but there is no reason to banish them from the whole language - 
that would only result in huge breakage for limited benefit.


And I suspect Walter didn't mean all code -just the relatively 
low-level stuff that might want to use `@live`. Even if he did, 
community will force him to reconsider.





Re: Floating point values in structs.

2020-12-22 Thread Dukc via Digitalmars-d-learn

On Friday, 18 December 2020 at 16:18:12 UTC, Dave P. wrote:
If the compiler is going to introduce the overhead of 
initializing all the variables anyway, why set it to nan when 
integer types get set to the useful default of 0?


Consider default value of `int*`. It is `null`, not a pointer to 
a newly-allocated 0. Most would probably agree that `null` works 
better, because it stands for "empty". 0 may or may not, 
depending on context.


It's this philosophy with floating-point values also. `0.0` might 
seem like a value when no value is intended, with `nan` there are 
no ambiguities.


More about this:
https://digitalmars.com/articles/b81.html
https://dlang.org/blog/2018/10/17/interfacing-d-with-c-arrays-part-1/




Re: Is there a standard function that combines take() and popFrontExactly()

2020-12-14 Thread Dukc via Digitalmars-d-learn

On Friday, 11 December 2020 at 19:07:23 UTC, realhet wrote:
I've just made this unicode wordreplacer function working, but 
It seems not too nice and functional-ish.

Are there ways to make it more simple?



To answer the title, yes there is:

```
foreach(isWord, len; str.map!fun.group){
   auto act = ().refRange.take(len).text;

   res.put(isWord && act==from ? to : act);
}
```

But personally I think it does not pay to try to be more 
functional than what this snippet already is. The most important 
thing is that the program is functional on the high level. This 
means avoiding globals and static variables (`pure` may help), 
big monolithic functions, god classes and functions which get 
needless info by their parameters. Being functional in the low 
level is secondary and not always worth it.


Re: where is the memory corruption?

2020-12-09 Thread Dukc via Digitalmars-d-learn

On Wednesday, 9 December 2020 at 20:35:21 UTC, Jack wrote:

the output is "h" rather "hello". What am I missing?


In the sayHello function, you are converting a pointer to utf16 
character into utf8 string, not utf16 string to utf8 string. 
Convert the C wstring to a D `wstring` first 
(std.string.fromStringz).




Re: To use or not immutable?

2020-12-09 Thread Dukc via Digitalmars-d-learn

On Wednesday, 9 December 2020 at 16:47:43 UTC, Jack wrote:
Do you use it in your code base? are there some design flaws, 
like there's in C++'s const, which I'm not aware of?


There are downsides, Jonathan Davis has written about them: 
http://www.jmdavisprog.com/articles/why-const-sucks.html


But the downside of D's `const` or `immutable` are mainly that 
you can't use them everywhere you might wish to. A good rule of 
thumb is that if you can get it to pass compilation as `const` or 
`immutable` without any hacks, there is no problem going ahead 
with it.


Re: how to print progress of a long running parallel() loop?

2020-12-07 Thread Dukc via Digitalmars-d-learn

On Monday, 7 December 2020 at 08:16:50 UTC, mw wrote:
r = Parallel(n_jobs=2, verbose=10)(delayed(sleep)(.2) for _ in 
range(10))


to print out the progress.

How to do this in D's parallel loop?

thanks.


Allocate a `shared int` before the foreach loop. In the loop 
when, let's say `!(i & 0xFFF)`,  atomically increment the shared 
variable and print it's number.


Disclaimer: no experience about using `shared`, but this is what 
I'd try.


Re: Automatic update system

2020-11-26 Thread Dukc via Digitalmars-d-learn

On Thursday, 26 November 2020 at 12:13:59 UTC, vnr wrote:

Hello,

I have a program written in D which is open-source on GitHub.

I would appreciate it if, when I release a new version, users 
would be notified by the program and that it offers an 
automatic update, i.e. the user doesn't have to reinstall the 
whole repository himself, but that it is updated automatically.


I haven't found any packages that directly meet my needs, but 
in the meantime I imagine that I will have to use the GitHub 
API, as well as Curl to make such a system.


Do you have any resources or suggestions as to how I could 
implement this? Thank you!


Make it a DUB package. It does not update 100% automatically, but 
notifies when updates are available.


You could also make an auto-updater by hand, but that requires a 
networking library and won't work anyway if the user does not 
have permissions to change the executable. This is often the 
case, as the often recommended places to store the programs are 
`/usr/bin/` or `c:/program files/`. Neither is accessible by 
default priviledges. In addition, it is a lot more work to 
implement than making a dub package. I don't recomment absent a 
strong reason.


If you publish your program in some other package format (apt, 
rpm, flatpak or nix for example), you can try to get your package 
into some official repository. There you can publish updates 
easily, and the program gets updated among the regular software 
updates the users do.


Re: Simulating computed goto

2020-11-26 Thread Dukc via Digitalmars-d-learn

On Wednesday, 25 November 2020 at 20:05:28 UTC, NonNull wrote:

So to simulate computed goto have to
1. wrap switch(x) in a loop [ while(0) ]
2. inside each case recompute x (instead of jump to computed y)
3. jump back to execute switch again [ continue ]

It does look as if a nested switch can contain case labels from 
an outer switch which is very good. Did not try this out.


Any more ideas, advice?


I quess you could define a string or a template mixin to automate 
this, if there are many functions doing this.


Then again, you probably should NOT have many functions working 
this way -it is not at all a scalable way to program. It might be 
good for something that is called very often and thus needs to be 
fast, but not for regular code. Computed `goto`s are even worse 
in maintainability than normal `goto`s.


Re: Simulating computed goto

2020-11-25 Thread Dukc via Digitalmars-d-learn

On Wednesday, 25 November 2020 at 18:44:52 UTC, NonNull wrote:

Is there a good way to simulate computed goto in D?


I haven't used assembly myself, but it's possible that you can 
define a mixin that does this, using inline assembly.


Re: Vibe.D TLS problem

2020-11-05 Thread Dukc via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 17:36:53 UTC, Dukc wrote:

```
HTTP connection handler has thrown: Accepting SSL tunnel: 
error:1408F09C:SSL routines:ssl3_get_record:http request 
(336130204)

```


I figured out from the Vibe.D source code that if I enable the 
debug level of the console logger, I should get more info. How do 
I do that (dub project, main controlled by Vibe.D)?





Re: How kill executables started with spawnShell or executeShell when program finish?

2020-10-27 Thread Dukc via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 15:16:33 UTC, Marcone wrote:
Becouse my program use plink.exe running with spawnShell or 
executeShell.
But when my program finish with some crash, or killed with 
windows task manager by user, Plink still running. How can I 
stop all process initialized with spawnShell or executeShell 
when program finish? I another works, how can I make plink.exe 
only lives when program is running?


This is a bit heavyweight, but should be doable: have your 
primary process to start a watchdog process for itself. The 
watchdog continuosly sends messages to the primary process. If 
the message gets blocked or the watchdog receives no answer, it 
assumes the primary process has stopped working and thus 
terminates first plink.exe first and then itself.


In fact, while you're on it you can make the watchdog to 
terminate the primary process too, so the user won't have to kill 
the program manually in case of infinite loop.


Vibe.D TLS problem

2020-10-27 Thread Dukc via Digitalmars-d-learn
I have a Vibe.D server binary that, locally at least, works. But 
only without TLS. I want to add TLS to it and test it locally 
with a self-signed certificate. I made one with LibreSSL, stored 
in `cert.crt` and `key.key`. The application main function:


```
shared static this()
{   import vibe.d;

//the program does check the key files are there before 
starting to listen

foreach(fileCheck;
[   tuple("salasanatiivisteet", "generoi salasanojen 
tarkistuslista ennen palvelimen käynnistämistä, 
salasanageneraattorilla"),
tuple("key.key", "TLS-avain puuttuu. Sen pitäisi olla 
nimeltään key.key"),
tuple("cert.crt", "TLS-sertifikaatti puuttuu. Sen pitäisi 
olla nimeltään cert.crt"),

])
if (!fileCheck[0].exists || !fileCheck[0].isFile)
{   fileCheck[1].logInfo;
return;
}

auto settings = new HTTPServerSettings;
enum portNumber = 8080;
settings.port = portNumber;
settings.bindAddresses = ["::1", "127.0.0.1"];
settings.sessionStore = new MemorySessionStore;

// these three lines added
settings.tlsContext = createTLSContext(TLSContextKind.server);
settings.tlsContext.useCertificateChainFile("cert.crt");
settings.tlsContext.usePrivateKeyFile("key.key");


// inrelevant stuff...

listenHTTP(settings, router);
}
```

It compiles and starts to listen just like normal, but when 
trying to enter the localhost URL, the browser announces "the 
connection was reset" and this is logged ten times in the server 
side:

```
HTTP connection handler has thrown: Accepting SSL tunnel: 
error:1408F09C:SSL routines:ssl3_get_record:http request 
(336130204)

```

The server then resumes listening, printing another ten errors if 
trying to re-enter the page. Linked openssl.sa is 1.1.1g (the 
original, not LibreSSL). Relevant DUB package configuration:

```
"dependencies": {
  "vibe-d": "~>0.9.2",
  "vibe-d:tls": "*"
},
"subConfigurations": {"vibe-d:tls": "openssl-1.1"},
"versions": [ "VibeHighEventPriority" ],
"versions": [ "VibeDefaultMain" ]
```




Re: Memory management

2020-10-02 Thread Dukc via Digitalmars-d-learn

On Tuesday, 29 September 2020 at 10:57:07 UTC, novice3 wrote:

Naive newbie question:

Can we have (in theory) in D lang memory management like V lang?

I don't know V so can't be sure, but doing it the same way as in 
the examples sounds possible.


The first two calls are easy. D string literals are stored in the 
read-only memory that is uploaded together with the machine code 
before execution. So the naive implementation wouldn't allocate 
any more than the V version.


The third one is more difficult. To allocate without using GC or 
RC means using an owning container, that releases memory when 
exiting the scope. While they can be checked against leaking 
referenced using the `-dip1000` feature, it's practical only when 
the memory has a single clear owner and there is no need to store 
references to it elsewhere. The GC and RC are better as a 
general-purpose solution.


On the other hand, D could avoid all allocation in the third 
example by using ranges. That would cause the printing function 
to figure out the message as it prints.




Re: Accessing non-binary Unicode properties with std.uni

2020-09-29 Thread Dukc via Digitalmars-d-learn

On Monday, 28 September 2020 at 18:23:43 UTC, Chloé Kekoa wrote:
The documentation of std.uni [1] says that the unicode struct 
provides sets for several binary properties. I am looking for a 
way to query non-binary properties of a character. Is that 
possible with std.uni or do I need to use a third-party library?


I am specifically interested in the East_Asian_Width property 
[2] (which has six allowed values). Trying to access 
std.uni.unicode.East_Asian_Width results in the error message:



No unicode set by name East_Asian_Width was found.


[1]: https://dlang.org/library/std/uni.html
[2]: https://www.unicode.org/reports/tr11/tr11-38.html


It seems the East Asian width is Unicode standard 13.0, while 
Phobos implements 6.2. So seems like ca case for a third-party 
library :(.





Re: Good way to send/receive UDP packets?

2020-07-22 Thread Dukc via Digitalmars-d-learn

On Wednesday, 22 July 2020 at 13:17:11 UTC, wjoe wrote:
- Choosing a port which isn't in use right now isn't good 
enough because a few minutes later there may be another program 
using it, too, and for the same reason.


But doesn't the UDP header include the sender IP address? So 
together with the magic number, shouldn't it be good enough? I 
know it definitely is not going to hold against jamming or a man 
in the middle, but it isn't supposed to, at this stage. It's used 
only for simulations that have the criticality of a casual Tetris 
server.


I do acknowledge that the needs may rise later on. And if so, I 
understand that I'm much better off switching the protocol than 
trying to hardening the UDP.


Re: Good way to send/receive UDP packets?

2020-07-19 Thread Dukc via Digitalmars-d-learn
Thank you everybody - Especially for the links to the blogs. This 
is just the kind of stuff I seek (didn't give a close look yet, 
though).


I think I'm going to try std.socket first, since it's in the 
standard library. If it feels like it could be easier, I'll 
consider Libasync.


Re: My RPN calculator code review?

2020-07-18 Thread Dukc via Digitalmars-d-learn

On Friday, 17 July 2020 at 21:37:46 UTC, AB wrote:
I'd appreciate your opinions regarding style, mistakes/code 
smell/bad practice. Thank you.


In a project this small, implementability (meaning, ease of 
writing) is really the main guideline, readability is a 
non-issue. When your codebase hits a few hundred lines in size 
you should start to gradually pay more attention to 
readability/scalablity.


In fact, things that are recommended in 2000-line projects may 
even be antipatterns in 100-line projects. For example, unit 
testing greatly reduces bugs, so it's highly recommended in 
general. But if your project is so small that normal manual 
testing covers most everything anyway, unit testing is just 
needless bloat.


A github gist might be better when doing style reviews, because 
the forum snippets tend to have wandering indentation and line 
wrapping.


Good way to send/receive UDP packets?

2020-07-18 Thread Dukc via Digitalmars-d-learn
I have a project where I need to take and send UDP packets over 
the Internet. Only raw UDP - my application uses packets 
directly, with their starting `[0x5a, packet.length.to!ubyte]` 
included. And only communication with a single address, no need 
to communicate with multiple clients concurrently.


I understand that I could do it either with the Curl library 
bundled with Phobos, or use Vibe.D or Hunt instead. But it's the 
first time I'm dealing with low-level networking like this, and 
my knowledge about it is lacking. So seek opinions about what 
library I should use, and more importantly, why.


Other advice about projects like this is also welcome, should 
anyone wish to share it.


Re: Arduino and MCU Support

2020-06-26 Thread Dukc via Digitalmars-d-learn

On Thursday, 25 June 2020 at 03:00:04 UTC, Dylan Graham wrote:
I'm currently making an automatic transmission controller with 
Arduino. C++ just has too many traps that I keep falling into. 
Since stability is critical (if the code screws up at 100km/h 
I'm dead), I'd rather use a sane language like D.


No, don't! Regardless of the language, you should never trust 
your safety on one single program. See 
https://www.digitalmars.com/articles/b39.html


Realistically, doing such a controller cannot be one man/woman 
endeavour.


Re: "if not" condition check (for data validation)

2020-06-18 Thread Dukc via Digitalmars-d-learn

On Thursday, 18 June 2020 at 12:50:35 UTC, Stanislav Blinov wrote:


auto not(alias cond)() { return !cond(); }

if (not!(() => abra && cadabra)) ...

but that is indeed even less readable.


No reason to use templates here

```
pragma(inline, true) auto not(bool cond) { return !cond(); }

if (not!(abra && cadabra)) ...
//same as above
if (abra.not || cadabra.not) ...
```


Re: "if not" condition check (for data validation)

2020-06-18 Thread Dukc via Digitalmars-d-learn

On Thursday, 18 June 2020 at 13:57:39 UTC, Dukc wrote:

if (not!(abra && cadabra)) ...

if (not(abra && cadabra)) ...


Re: unit test that show more than one failure

2020-06-16 Thread Dukc via Digitalmars-d-learn

On Tuesday, 16 June 2020 at 06:19:51 UTC, Joel wrote:
I've tired different unit test libraries, but they jump out on 
errors instead of just adding to failed numbers.


I'm thinking like this:

```
@("dummy");
unittset {
  0.shouldEqual(0);
  1.shouldEqual(2);
  2.shouldEqual(3);
}
```

Test: dummy
test passed line 10: 0 is equal to 0
test failed line 11: 1 is not equal to 2
test failed line 12: 2 is not equal to 3

1 passed
2 failed

The unit tests I tried would jump out on the first failure.


I have solved this. In my project, I have two modules like this:

```
module assertions;

auto assert_(A)(A canditate)
{   assert(canditate);
}

auto assertOp(alias pred, A)(A canditate)
if (is(typeof(cast(bool) pred(canditate
{   assert(pred(canditate));
}

auto assertOp(alias pred, A, B)(A canditate, B check)
if (is(typeof(cast(bool) pred(canditate, check
{   assert(pred(canditate, check));
}

auto assertEmpty(A)(A aEl)
{   assertOp!(a => a.empty)(aEl);
}

auto assertEqual(A, B)(A aEl, B bEl)
{   assertOp!((a,b) => a == b)(aEl, bEl);
}

auto assertClose(A, B)(A aEl, B bEl)
{   import std.math;
assertOp!((a,b) => a.isClose(b))(aEl, bEl);
}
```

```
module assertions.characterization;

auto assert_(A)(A canditate)
{   import std.stdio : writeln;
	writeln(canditate, cast(bool) canditate? " (passes)": " 
(fails)");

}

auto assertOp(alias pred, A)(A canditate)
if (is(typeof(cast(bool) pred(canditate
{   import std.stdio : writeln;
	writeln(canditate, cast(bool) pred(canditate)? " (passes)": " 
(fails)");

}

auto assertOp(alias pred, A, B)(A canditate, B check)
if (is(typeof(cast(bool) pred(canditate, check
{   import std.stdio : writeln;
	writeln(canditate, cast(bool) pred(canditate, check)? " 
(passes)": " (fails)");

}

auto assertEmpty(A)(A aEl)
{   assertOp!(a => a.empty)(aEl);
}

auto assertEqual(A, B)(A aEl, B bEl)
{   assertOp!((a,b) => a == b)(aEl, bEl);
}

auto assertClose(A, B)(A aEl, B bEl)
{   import std.math;
assertOp!((a,b) => a.isClose(b))(aEl, bEl);
}
```

So I usually have the test like this:
```
@safe unittest
{  import assertions;
   0.assertEqual(0);
   1.assertEqual(2);
   2.assertEqual(3);
}
```

...but when it fails, I just change the import to 
`assertions.characterization`, and all test results, along with 
info whether they're correct, are printed.


Re: Windows + LDC/DMD installation nightmare when changing VS versions

2020-06-12 Thread Dukc via Digitalmars-d-learn

On Friday, 12 June 2020 at 15:21:12 UTC, Guillaume Piolat wrote:

Any idea what could be causing this?

Please help. This was a living nightmare. I just want a working 
setup...


I don't know if this is any help, as I don't use Visual Studio 
myself, but:


You're trying to build for a 32-bit architechture, but the DUB 
receives `--arch=x86_64`. It should be receiving `--arch=x86`. 
It's likely that due to this it builds a 64-bit binary and then 
fails to link into something that was correctly built as 32-bit.


Re: Why is there no range iteration with index by the language?

2020-06-10 Thread Dukc via Digitalmars-d-learn
On Wednesday, 10 June 2020 at 15:34:57 UTC, Steven Schveighoffer 
wrote:
My biggest problem with enumerate is that you can't bind the 
tuple to parameters for something like map:


arr.enumerate.map!((idx, val) => ...)

doesn't work. Instead you have to do:

arr.enumerate.map!((tup) => ...)

And use tup[0] and tup[1].

-Steve


```
alias tupArg(alias func) = x => func(x.expand);
arr.enumerate.map!(tupArg!((idx, val) => ...))
```

Somewhat heavy on syntax, but better than `tup[0]` or `tup[1]` 
IMO.


Re: how to append (ref) int[] to int[][]?

2020-06-08 Thread Dukc via Digitalmars-d-learn

On Monday, 8 June 2020 at 06:13:36 UTC, mw wrote:


what I really want in (a) is append `ref arr` and output [[3], 
[3], [3]], i.e. the real `arr` be appended instead of its copy.


I tried to change arrs' decl to:

(ref (int[]))[] arrs;  // the intended semantics I want

1) I'm wondering how to achieve what I want? and
2) why "~=" here will append a copy rather than the real `arr` 
itself to arrs?



Thanks.


```
import std.stdio;

void f(ref int[] arr) {
arr ~= 3;
}

void main() {
import std.algorithm;

int[]*[] arrs;
int[]* arr;
foreach (i; 0 .. 3) {
		//stack allocated array pointer would expire on end of 
scope, so must allocate the them on heap since we're keeping 
refeerences on them.

auto arrayAllocation = new int[][1];
arr = [0];
*arr = new int[0];
arrs ~= arr;
f(*arr);
}

//will print an array of addresses otherwise
arrs.map!(ptr => *ptr).writeln;
}
```

But I must say I would generally prefer just calling `f()` on 
`arrs[i]` directly after appending, or calling the function 
before appending. One reason is that needless heap usage is 
generally less efficient than using the stack.


Re: Distinguish between a null array and an empty array

2020-05-26 Thread Dukc via Digitalmars-d-learn

On Sunday, 24 May 2020 at 12:29:23 UTC, bauss wrote:
Dang, that sucks there is no proper way and I would say that's 
a big flaw of D.


Because what I need it for is for some data serialization but 
if the value is an empty array then it should be present and if 
it's null then it should not be present.


Since null is used to say "ignore this" in the data 
serialization.


Oh well.


If you want to avoid the memory cost of `Nullable`, I think you 
could still have a special value for "no data". But I wouldn't 
use D `null` for it, because it's so common for it to be used for 
empty values. Instead, I'd define a small data section somewhere. 
You test whether the array points to it (`[0] == 
[0]`), and if, it means no data.


Re: redirect std out to a string?

2020-05-21 Thread Dukc via Digitalmars-d-learn

On Thursday, 21 May 2020 at 04:29:30 UTC, Kaitlyn Emmons wrote:
is there a way to redirect std out to a string or a buffer 
without using a temp file?


If you want to do the redirection at startup, it's possible. Have 
an another program to start your program by std.process functions 
and redirect stdout to a pipe. The outer program can then handle 
the output of the inner program however it wishes. Clumsy but 
possible.


But I don't know whether a process can redirect it's own standard 
input or output.


Re: How to use this forum ?

2020-05-20 Thread Dukc via Digitalmars-d-learn

On Wednesday, 20 May 2020 at 20:49:52 UTC, Vinod K Chandran wrote:

Hi all,
I have some questions about this forum.
1. How to edit a post ?
No can do :(. Well, moderators can delete posts so you could try 
to ask them nicely in some cases but the primary way tends to be 
the same as with email: send a correction message.


And if I recall correctly, this forum is based on some email 
system, so even if a moderator deletes something, it'll probably 
only be hidden from those that talk via forum.dlang.org - not 
from those that use their email.



2. How to edit a reply ?

Same as above.


3. How to add some code(mostly D code) in posts & replies.

Matter of taste. I personally tend to do it like this:

```
void main()
{   import std.stdio;
writeln("hello world!");
}
```

Another good way is to use https://run.dlang.io/ and export your 
code as gist from there.



4. How to add an image in posts & replies.

Add it somewhere else and post a link to it.


5. Is there a feature to mark my post as "[SOLVED]" ?

Alas, no.



Re: Why emsi containers have @disabled this(this) ?

2020-05-20 Thread Dukc via Digitalmars-d-learn

On Tuesday, 19 May 2020 at 20:51:01 UTC, Luis wrote:
I saw that they have postblit operator... But i don't 
understand exactly why. In special, when they implement 
InputRange over the containers, but having disabled postblit, 
make nearly useless (at least as I see on this old post 
https://forum.dlang.org/thread/n1sutu$1ugm$1...@digitalmars.com?page=1 )


You have to understand the memory management difference between 
EMSI-containers and regular D slices. A normal slice won't worry 
about freeing the memory used. It just assumes that either the 
garbage collector will take care of it (the usual case), or that 
the code will tell manually when the memory really needs to be 
freed (possibly by some other reference to the same memory).


EMSI-containers, however, are designed to free their memory after 
use themselves. They do it by the Resource Acquisition Is 
Initialization principle: when the container gets deleted, the 
underlying data gets freed right away.


This leads to that there must be only one container using the 
same memory. It would not do to make a copy of it, unless it's a 
deep copy (Deep copy means that also the underlying memory is 
copied. It tends to take long.). This is the reason that 
postblits are disabled in EMSI-containers. It wants to protect 
you from accidents. If you want to store the same container in 
many places, store references to it instead. And when iterating 
over it, you get the underlying range first, like Mike said. The 
underlying range can likely be copied freely.


Re: variant visit not pure?

2020-05-08 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 20:12:03 UTC, learner wrote:


Modules of D standard library aren't in a good shape, if 
everyone suggests alternatives for a basic building block as 
variant.


I don't think Variant as a whole is the problem, when one uses it 
as the infinite variant it does fairly much what one can expect. 
The finite-field specialization of it is the one that's badly 
implemented.




The types VariantN can hold are known at compile time, why 
can't it be specialized?


It could, probably. This shows the biggest weakness (and 
strength) of D development: It's voluntary, so people work on 
that they happen to want to. That makes it unevenly developed 
compared to financially backed projects. We have both plenty of 
cool & rare features and lack of many relatively basic ones at 
the same time.


Re: variant visit not pure?

2020-05-08 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 15:36:36 UTC, Ben Jones wrote:
I've been using SumType... What are the main differences 
between it and TaggedAlgebraic?


I have not used the the algebraic type of Taggedalgebraic tbh, 
but it also has a tagged union type that I have good experiences 
with. Unlike Phobos algebraic or SumType, it can have multiple 
fields of same type that are still separate by the tag value. 
Also unlike the two others I mentioned, you can handily define a 
`Void` field (or many of them) if you want special values for the 
tag that don't come with a value. In essence, 
`Taggedalgebraic.TaggedUnion` it's the D equivalent of Rust 
`enum`[1].


1: https://doc.rust-lang.org/book/ch06-00-enums.html


Re: variant visit not pure?

2020-05-08 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 10:21:26 UTC, Dukc wrote:


that's the reason why `std.range.enumerate` does not infer 
attributes for example


This was wrong. `enumerate` can infer. It's `lockstep` that 
cannot.





Re: variant visit not pure?

2020-05-07 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 13:17:21 UTC, learner wrote:

I've find this: https://issues.dlang.org/show_bug.cgi?id=16662


Hmm, that explains why it can't infer attributes. An unlimited 
variant could contain an object, and using it might or might not 
be .


Of course, it could still infer the attribute for algebraic types 
were the wrapper a bit smarter. But `Algebraic` is inferior to 
the DUB packages anyway. Bad performance like Simen said, and can 
always be `null` regardless of requested types. With 
Taggedalgebraic, you can insert `Void` to allowed types if you 
want `null` value but you don't have it just because.


Re: Is there a way to benchmark/profile portably?

2020-05-07 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 10:51:27 UTC, Simen Kjærås wrote:


If I understand correctly, you want to measure how many cycles 
pass, rather than clock time?


Something like that. Well, I would also like to eliminate 
differences based on different memory caches between machines.


In addition, if the profiler could eliminate the randomness of 
the benchamrks that results from memory aligment, context 
switches and dunno, that would obviously be a big plus for 
automatic testing.




If so, it seems perf can do that: 
https://perf.wiki.kernel.org/index.php/Tutorial



Sounds worth a look. Thanks!


Re: Is there a way to benchmark/profile portably?

2020-05-07 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 11:06:17 UTC, Dennis wrote:


You can make a reference program that you use to get a measure 
for how fast the computer is that you run the benchmark on. 
Then you can use that to scale your actual benchmark results.


When testing regressions there's a fairly obvious choice for 
this reference program: the old version. You can compare those 
results with the new version and report the relative difference.


I have to keep that in mind, but I'd prefer something that does 
not require keeping old sources working, or floating their 
binaries around.




Re: variant visit not pure?

2020-05-07 Thread Dukc via Digitalmars-d-learn

On Thursday, 7 May 2020 at 09:22:28 UTC, learner wrote:

Good morning,

Is there a reason why std.variant.visit is not inferring pure?



I think `variant` will not infer any trributes. I'm not sure why. 
It could be some language limitation (that's the reason why 
`std.range.enumerate` does not infer attributes for example). Or 
it could be just badly implemented.


Either way, there are DUB packages that are better in this (and 
other) regards. I recommend Taggedalgebraic[1].


[1] https://code.dlang.org/packages/taggedalgebraic



Is there a way to benchmark/profile portably?

2020-05-07 Thread Dukc via Digitalmars-d-learn
Is there some way to measure the performance of a function so 
that the results will be same in different computers (all x86, 
but otherwise different processors)? I'm thinking of making a 
test suite that could find performance regressions automatically.


I figured out Bochs[1] could be used for that, but it seems an 
overkill for me to install a whole virtual operating system just 
to benchmark functions. Does anybody know more lightweight way?


[1] http://bochs.sourceforge.net/


Re: How to get Code.dlang.org to update the package?

2020-02-12 Thread Dukc via Digitalmars-d-learn
On Wednesday, 12 February 2020 at 13:05:00 UTC, Petar Kirov 
[ZombineDev] wrote:

On Wednesday, 12 February 2020 at 12:42:32 UTC, Dukc wrote:
I have pushed a new release tag in Github around two weeks 
ago, and ordered a manual update at DUB, yet DUB has still not 
aknowledged the new tag. Is there some requirement for the 
release tag for it to be recognized?


Hi Dukc,

I'm not sure which dub package you're referring to, but I'm 
gonna guess that it's this one: 
http://code.dlang.org/packages/nuklearbrowser, which 
corresponds to this github repo:

https://github.com/dukc/nuklearbrowser.


Correct

I think the problem is that your latest tag is 0.0.2, instead 
of v0.0.2 (https://github.com/dukc/nuklearbrowser/tags).


I hope this helps!

Cheers,
Petar


Certainly does, thank you.




How to get Code.dlang.org to update the package?

2020-02-12 Thread Dukc via Digitalmars-d-learn
I have pushed a new release tag in Github around two weeks ago, 
and ordered a manual update at DUB, yet DUB has still not 
aknowledged the new tag. Is there some requirement for the 
release tag for it to be recognized?


Re: How to set up multi-dimensional DUB package configuration?

2020-02-12 Thread Dukc via Digitalmars-d-learn
Illustration, I want to choose both an edition and marked 
copyright holder:


```
configuration "inhouse" {
targetType "executable"
versions "InhouseEdition"
}
configuration "salesmen" {
targetType "executable"
versions "SalesmenEdition"
}
configuration "internet" {
targetType "executable"
versions "InternetEdition"
}
configuration "copyrightcompanya" {
versions "CopyrightCompanyA"
}
configuration "copyrightcompanyb" {
versions "CopyrightCompanyB"
}
```





How to set up multi-dimensional DUB package configuration?

2020-02-12 Thread Dukc via Digitalmars-d-learn
My application has two copyright holders, so I want to be able to 
specify in the build command whose copyright marks get compiled 
to the program. D part of the application is built by DUB. DUB 
configurations would do the trick, but they are already used to 
define different editions of the application. I have to be able 
to choose the edition indepently of the copyright holder.


I don't necessarily need two-dimensional configuration. If there 
a way to order DUB to define an extra D version without altering 
`dub.sdl` to do that, it would suffice. But is there?


Re: why local variables cannot be ref?

2019-11-25 Thread Dukc via Digitalmars-d-learn

On Monday, 25 November 2019 at 03:07:08 UTC, Fanda Vacek wrote:

Is this preferred design pattern?

```
int main()
{
int a = 1;
	//ref int b = a; // Error: variable `tst_ref.main.b` only 
parameters or `foreach` declarations can be `ref`

ref int b() { return a; }
b = 2;
assert(a == 2);
return 0;
}
```

Fanda


It's okay, but I'd prefer an alias, because your snippet uses the 
heap needlessly (it puts variable a into heap to make sure there 
will be no stack corruption if you pass a pointer to function b() 
outside the main() function)


Re: Troubleshooting DUB invocations

2019-11-19 Thread Dukc via Digitalmars-d-learn
On Tuesday, 19 November 2019 at 13:41:32 UTC, Sebastiaan Koppe 
wrote:
A @disabled function stub would serve better, unless I'm 
missing something.


Either way, as long as there is a clear way to debug why it 
ended up there. Unlike what we have now where you need to dig 
endlessly.


But the @disabled function stub (if my thinking is sound) would 
have the advantage that it'd prevent compilation only if called 
-not if only imported.


Re: Troubleshooting DUB invocations

2019-11-19 Thread Dukc via Digitalmars-d-learn
On Monday, 18 November 2019 at 19:35:13 UTC, Sebastiaan Koppe 
wrote:
Kinke made some changes in dub to facilitate separate linking 
for ldc. I am not aware of all the details but the major 
benefit is that it allows cross compilation with dub and ldc.




Yeah, definitely useful if you want to link in, say, a C-borne 
wasm

binary.

Because of the separate linking the --no-as-needed turned up. 
As far as I can see it is only needed when compiling for linux.


Which brings up the question, why linux? Aren't we compiling 
for wasm?


Well yes. But that is just the way things worked up until now, 
ldc and dub just pick the host machine.


Luckily there is the new dub `--arch` argument that can take a 
llvm triple, in our case wasm32-unknown-unknown-wasm. This 
causes dub not to add the `--no-as-needed`.


That was news to me - I thought everything was always being 
compiled to WASM.




Except, that it also passes the triple upwards the dependency 
tree. Now all the dependencies of spasm get compiled targeting 
wasm. This is a good thing, except that the optional package 
which spasm depends on fails to compile with it. There is a 
newer version that fixes the configuration, but that one fails 
because of the `from.std` import idiom (it imports the std 
package from phobos which doesn't recognise wasm and fails with 
"Unknown OS").


I have sometimes thought that perhaps a static assert isn't the 
best thing to use for unimplemented features in Phobos, precisely 
because of this issue. A @disabled function stub would serve 
better, unless I'm missing something.




In the meantime I am going to make a PR for the optional 
package to avoid the `from.std` idiom. Although I might end up 
playing whack-a-mole here, as there might be more dependencies 
that need a fix now.


"ending up"? If it's like what getting Phobos to work has been 
for me, you're continuing the game, not ending up playing it ;D.




Another workaround that you can use right now is by adding the 
`--build-mode=allAtOnce` argument to dub. It effectively gets 
you the old behaviour. It is what I am using in my CI to get it 
to go green again.


Do not hurry more than you want -I already got my 
extract-dub-failure workaround working.





Re: Troubleshooting DUB invocations

2019-11-13 Thread Dukc via Digitalmars-d-learn
On Wednesday, 13 November 2019 at 15:41:01 UTC, Sebastiaan Koppe 
wrote:
It has been on the back of my mind since 1.18-beta came out. I 
am going to reserve a little time tomorrow to work on it.


Regarding that, perhaps I can save you a bit trouble if you also 
try to get 1.19 working: if you get compile errors related to 
SortedRange, the fix is https://github.com/dlang/phobos/pull/7266.


Re: Should I stop being interested in D language if I don't like to see template instantiation in my code?

2019-11-13 Thread Dukc via Digitalmars-d-learn

On Wednesday, 13 November 2019 at 14:59:57 UTC, Dukc wrote:

4: Templates. Same code size bloat as with options 1 and 3,


Meant binary size bloat




Re: Why same pointer type for GC and manual memory?

2019-11-13 Thread Dukc via Digitalmars-d-learn

On Wednesday, 13 November 2019 at 11:07:12 UTC, IGotD- wrote:
I'm trying to find the rationale why GC pointers (should be 
names managed pointers) are using the exact same type as any 
other pointer.


Doesn't this limit the ability to change the default GC type?

What does grabage collector type mean?

Doesn't this confusion make GC pointers just as unsafe as raw 
pointers?
It does if you pass the pointers to somewhere the garbage 
collector does not know about. However, normally it has a list of 
all memory used by the program -even the memory that is not 
managed by it. But if you, for example, put a pointer to memory 
allocated by some C program that is totally unaware of the GC, 
you need to either manually register (and unregister) the memory 
to the GC, or keep a copy of the pointer in somewhere the GC 
knows about. Assuming the pointed memory is controlled by GC, 
that is. Otherwise, the GC will not find the pointer during 
collection and think you have stopped using the memory it points 
to.


Has there been any prior discussion about introducing managed 
pointers in D?
I'm not 100% sure what managed pointers mean -Are they so that 
you can't pass them to unregistered memory? A library solution 
would likely do -wrap the pointer in a struct and make it @system 
to extract it's pointer as "raw". So you cannot put it to 
C-allocated arrays without type casting, which you probably don't 
do accidently.


Re: Troubleshooting DUB invocations

2019-11-13 Thread Dukc via Digitalmars-d-learn

On Tuesday, 12 November 2019 at 18:32:32 UTC, kinke wrote:


Dub is open-source, so you can grep the source. - Dub uses it 
for all 3 compilers (e.g., 
https://github.com/dlang/dub/blob/f87302dd206b0e5871b39704e694b2194e294aa5/source/dub/compilers/ldc.d#L249), and I'm not sure it's really needed. Anyway, you can also use another linker that supports this flag (e.g., via `-linker=gold`).


Thanks. At first it didn't seem to work. Then I realized that the 
`--link-internally` flag that's specified in `ldc.conf` prevents 
changing the linker. Took it off, and the gold linker understood 
the flag in question, but had problems with others. I tried 
removing some, but there were still more to remove. Getting WASM 
code to link tends to be trial and error in my experience, so I 
decided best not to stray far from what Spasm does.


I also tried LDC 1.18, but the dub also added that unwanted flag 
here. I don't wan't to use older LDC than that.


However, extracting the LDC invocation and manually calling it 
without `--no-as-needed` appears to work. Solution? I'm going to 
write my `build.d` to do just that automatically.


Is there an issue about that already, or should I open one?


Re: Should I stop being interested in D language if I don't like to see template instantiation in my code?

2019-11-13 Thread Dukc via Digitalmars-d-learn

On Wednesday, 13 November 2019 at 14:01:13 UTC, BoQsc wrote:
I don't like to see exclamation marks in my code in as weird 
syntax as these ones:

to!ushort(args[1])
s.formattedRead!"%s!%s:%s"(a, b, c);


No pressure to use templates. D is designed to be multi-paradigm, 
and in many was combines the advantages of c++ and c# even if you 
use just traditional imperative or object oriented ways. For 
example, C# has array bounds checking, C++ has raw type casting, 
but D has both. And neither of the mentioned languages have 
`scope (exit`. Granted, some other new language, like Go, might 
be even better if you don't care about templates.


That being said, I think you definitely should learn about 
templates. First, it let's you understand code written by others, 
and secondly you can evaluate whether you really want to code 
without them. There are problems you simply cannot deal with as 
efficiently as you can with templates. For example, if you write 
a math function you want to work with both integers and floats, 
you basically have four options:


1: Code duplication.
2: Runtime casting of the argument to the type the function is 
implemented in, wasting computational power. Traditional 
object-oriented solution falls in this category.
3: Using a macro preprocessor. Macros are unaware of code 
semantics and thus are known for making codebases buggy and hard 
to maintain.
4: Templates. Same code size bloat as with options 1 and 3, but 
otherwise basically no downsides.


Troubleshooting DUB invocations

2019-11-12 Thread Dukc via Digitalmars-d-learn
When trying to compile a project including newest Spasm (DUB 
package) using the newest LDC via DUB, the result is:

```
lld: error: unknown argument: --no-as-needed
```

I then ran DUB with -v switch and it turned out the invocation 
contained `-L--no-as-needed` as first of all the -L arguments. 
The trouble is, how do I know what causes DUB to add that 
argument to the invocation? I could find no reason in 
`dub.` files of either my package, Spasm or any package 
in Spasm dependency tree.


Re: Good way let low-skill people edit CSV files with predefined row names?

2019-10-30 Thread Dukc via Digitalmars-d-learn

On Friday, 25 October 2019 at 21:58:27 UTC, Laeeth Isharc wrote:


Another Symmetry project allows reading Excel files and a third 
is wrapper and bindings around a C library to write Excel 
files.  We use them in production daily though there may be 
rough edges for features we don't use.


I should think you can use a Javascript library and call it 
from D.  See trading views repo by Sebastian Koppe for an 
example of this.  Bindings are manual currently but he will 
work on generating them from the Typescript bindings in time.


Sorry for late reply. I was told that I can do this by writing 
the key field only as a comment (so changing it will do no harm - 
the real key would be dictated either by an ID number or simply 
row index). In the case they want me to do it without writing my 
own GUI, I'm going to consider the DUB solutions first but look 
at what you said if I still miss something. Thank you.


Re: Good way let low-skill people edit CSV files with predefined row names?

2019-10-24 Thread Dukc via Digitalmars-d-learn

On Thursday, 24 October 2019 at 16:50:17 UTC, Dukc wrote:

Hmm, I need to check whether I can do that on LibreOffice Calc.


Unfortunately, no. If there's a way to do that, it's not obvious.


I should be able to make an easy-to-use excel-to-csv translator 
using Atilas Excel utilites without too much effort.


This was wrong: Atila's Excel-d enables writing plugin functions, 
but not reading the spreadsheets. There are other DUB utilities 
for that, though.


I quess I will give my employer two options: Either the price 
variables are in an one-column CSV and I distribute the key 
column separately so they don't mess it up, or I take my time to 
do a GUI solution.


Unless somebody has better ideas?


Re: Good way let low-skill people edit CSV files with predefined row names?

2019-10-24 Thread Dukc via Digitalmars-d-learn

On Thursday, 24 October 2019 at 16:20:50 UTC, jmh530 wrote:
If they are only opening it in Excel, then you can lock cells. 
You should be able to do that with VBA.


At least I know it works with xlsx files. Not sure on csv now 
that I think on it.


Hmm, I need to check whether I can do that on LibreOffice Calc. I 
do not to rely on Ms Excel -in part because I don't have one 
myself! But if the answer is positive, it might be worth 
considering. I should be able to make an easy-to-use excel-to-csv 
translator using Atilas Excel utilites without too much effort.


Good way let low-skill people edit CSV files with predefined row names?

2019-10-24 Thread Dukc via Digitalmars-d-learn
We're planning to have our product preview program to calculate 
and suggest a price for the product displayed. There are a lot of 
variables to take into account, so it's essential the users can 
edit the price variables themselves.


The problem is that many of them are not the best computer users 
around, even by non-programmer standards. I'd like the price 
variable file to be in CSV format, so I don't have to go looking 
for a new file parser (the preview program is mostly compiled to 
JavaScript from C# with some D (spasm) and native JavaScript in 
the mix). I know I can tell the users to use spreadsheet programs 
to edit CSV, but they are still going to get the variable field 
names wrong, and I do not want that.


Another option would be for me to write an editor for them 
specially for this purpose. The editor would not have to be 
embeddable into a browser, so I could write it in D. But it'd 
have to use a GUI, which would likely take a relatively long time 
to develop, and thus costly for my employer.


Does anybody know a program/file format that could enable editing 
the fields while guarding against formatting/field naming errors? 
Even if it isn't CSV, it is going to be easier for me to write a 
translator than a GUI editor.


Re: Good way let low-skill people edit CSV files with predefined row names?

2019-10-24 Thread Dukc via Digitalmars-d-learn

On Thursday, 24 October 2019 at 16:03:26 UTC, Dukc wrote:
Even if it isn't CSV, it is going to be easier for me to write 
a translator than a GUI editor.


Assuming the file format is simple, of course


Re: Pro programmer

2019-08-27 Thread Dukc via Digitalmars-d-learn

On Sunday, 25 August 2019 at 21:30:10 UTC, GreatSam4sure wrote:
I am wondering as to what is the starting point of being a pro 
programmer. If I want to be a pro programmer what language must 
I start with?


Any general purpose language will do. Basically everything can be 
expressed in any language, through some tasks are very cumbersome 
in tasks they are not designed for.




Most pro programmer I have heard of are all C and C++ Guru. 
Most of the best guys on this D forum falls into that category.


C and C++ have steep learning curves, and tend to be better for 
professionals than amateurs. That does not mean C/C++ usage is 
what defines a pro. Even php, famous for being simple to learn 
but often hated by professionals, can be used professionally.




I really want to know programming to the core not just tied to 
a language or just at the level of drag and drop or use a 
framework or library.


Don't worry, learn to apply one language in practice and you'll 
usually figure out automatically how to apply any language you 
will learn. Well, sometimes when you transition to a new language 
you should learn new ways to do thing, because the new language 
is better suited for those than your old language.


Famous example is that C programmers that transitioned to C++ or 
Java in the 90's were encouraged to start to thinking in object 
oriented manner. They did not strictly have to, as C++ and Java 
can be used for same programming stye as C, and C can do sort-of 
object-oriented programming, but object-oriented designs were 
(and are) so much easier to implement in the newer languages that 
in practice, object design should be used a lot more now than in 
the 70's.


I will appreciate your help in this matter. I am ready to put 
in hard work. I ready know a little of java, actionscrip 3.0, 
kotlin, D but at the surface level but can use them to write 
app.


But I am concern with matter like how can I write a GUI toolkit 
from the ground up.


Basically, GUI libraries call the operating system API that is 
different for different operating systems.




Re: /usr/bin/ld.gold: error: failed to find object -lz

2019-08-15 Thread Dukc via Digitalmars-d-learn

On Thursday, 15 August 2019 at 12:02:00 UTC, kinke wrote:
That's the library you need. You may have messed things up by 
installing a non-dev package from Fedora (!).


Fortunately it's written in red at YAST, because it's not from 
the official repos. I can easily find it to get rid of it when I 
want.


Re: /usr/bin/ld.gold: error: failed to find object -lz

2019-08-15 Thread Dukc via Digitalmars-d-learn
Investigated this matter further. The most likely reason seems to 
be that the required library -zlib- (Yes, ld.gold was getting the 
arguments in correct form despite what I said. Sorry.) is 
installed only in dynamic form (.so), but ld.gold finds only 
static libraries (.a). Not 100% sure yet, because it wasn't worth 
the time to convert the libraries/get the linker to work with 
dynlibs right now, but this seems to be the cause.





Re: How to run the dub bundle with dmd

2019-08-10 Thread Dukc via Digitalmars-d-learn

On Saturday, 10 August 2019 at 13:18:19 UTC, greatsam4sure wrote:
I came across the problem recently. I have dub 1.11.0 install 
on my windows 10 core i7 but does not support the command "dub 
add package name" since all the packages in dub package 
register now use this command. I cannot find window binary for 
the recent version of dub


What did you precisely write on the console, and what was the 
output?




I have uninstalled the dub 1.11.0 on my machine, I have to use 
the one bundled with DMD 2.087.1. If I run dub -version, 
windows 10 throw an error that says " this app can run on this 
machine".


That means that either you installed wrong dub (linux version for 
example), or the executable file is corrupt. Download a new one.






Re: LNK4255 warning - should I be concerned?

2019-08-10 Thread Dukc via Digitalmars-d-learn

On Thursday, 8 August 2019 at 18:14:22 UTC, DanielG wrote:
"warning LNK4255: library contain multiple objects of the same 
name; linking object as if no debug info"


Is there some way to get more detail about this warning? Might 
help to know which objects ...


My program is working fine now, but is this going to cause 
problems later on? Like when I want to debug?


Let me guess, you're linking Vibe.D? I get those errors all the 
time while using it. Haven't noticed effect on behaviour but it 
might be related to why it won't compile as 32-bit.


  1   2   3   >