Re: I need a detailed document about druntime.

2021-10-11 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 11 October 2021 at 15:24:07 UTC, Adam D Ruppe wrote:
On Monday, 11 October 2021 at 15:18:11 UTC, Ferhat Kurtulmuş 
wrote:
"Each call to initialize must be paired by a call to 
terminate.'


It is so the refcount works out.

When you call initialize, it does something like:

if(refcount == 0)
   actually intialize; // calls constructors etc
refcount++;


When you call terminate, it does:

refcount--;
if(refcount == 0)
   actually terminate; // calls destructors etc



If you don't pair it, the refcount will be off, so the next 
call to terminate will still see ref > 0 and not actually 
terminate.


The D main inserts a call to init before main and a call to 
terminate after main automatically.


That makes sense, now I see, thank you again Adam.


Re: I need a detailed document about druntime.

2021-10-11 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 11 October 2021 at 15:09:12 UTC, Adam D Ruppe wrote:
On Monday, 11 October 2021 at 14:56:19 UTC, Ferhat Kurtulmuş 
wrote:
What I want is to bypass runtime initialization if it is 
already initialized.


That what it does by itself, you can call it and it has an 
internal count.


Thank you for your response. But this confuses me:

"Each call to initialize must be paired by a call to terminate.'


https://dlang.org/library/core/runtime/runtime.initialize.html


I need a detailed document about druntime.

2021-10-11 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
I want to know what happens if either Runtime.initialize or 
terminate is called without matching each other. And why there is 
no ready-to-use thing like initCount which is accessible in the 
code? What I want is to bypass runtime initialization if it is 
already initialized. The below code is my workaround, but it can 
only keep track of my initializations, not the one that 
automatically get fired where there is a dmain.


Should İ use "bool runMain" to differentiate between the 
compilations of dll and executable?


```d
private {
import core.runtime;
import core.atomic;

shared size_t initCount;

void initRT(){
if(!atomicLoad!(MemoryOrder.acq)(initCount)){
Runtime.initialize();
atomicOp!"+="(initCount, 1);
}
}

void termRT(){
if(atomicLoad!(MemoryOrder.acq)(initCount) > 0){
Runtime.terminate();
atomicOp!"-="(initCount, 1);
}
}
}
```


Re: Template mixin problem with EnumMembers

2021-10-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 2 October 2021 at 22:24:56 UTC, Adam Ruppe wrote:
On Saturday, 2 October 2021 at 22:07:23 UTC, Ferhat Kurtulmuş 
wrote:

[...]


You used .stringof. That's undefined behavior. Never use 
stringof. (except for debugging writes)


[...]


Thank you Adam! I should stop using stringof. Even the docs say 
it, I ve just seen that 
https://dlang.org/spec/property.html#stringof.


Probably, I will go for your second solution.

I appreciate it.


Template mixin problem with EnumMembers

2021-10-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
The below code works as expected on https://run.dlang.io/, but 
not on my computer. And I don't know why?


I want to access enum members like Options.OUT_FILE_NAME instead 
of Options.StringOption.OUT_FILE_NAME.


Please note that the solutions like "alias something = int;" 
don't work for me. that is not what I need.


In my local computer, pragma(msg, fullname) outputs like:
cast(StringOption)0
cast(StringOption)1
cast(StringOption)2

some error messages I get:
...\options.d-mixin-86(86,11): Error: declaration expected, not )
...\options.d-mixin-86(86,11): Error: no identifier for 
declarator tion


```d
import std.stdio;

class Options{
public:

enum StringOption {
OUT_FILE_NAME,
RPT_FILE_NAME,
MAP_FILE_NAME
}

import std.traits: EnumMembers;
mixin template StrOptAliases()
{
static foreach(fullname; [EnumMembers!(StringOption)]){
mixin("alias " ~ fullname.stringof[13..$] ~ " = " ~ 
"Options." ~
   
fullname.stringof ~ ";\n");

pragma(msg, fullname);
}
}

mixin StrOptAliases;
}

void main()
{
int opt = Options.OUT_FILE_NAME;
writeln(opt);
}
```


Re: How to do "C++ classes"?

2021-09-20 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Monday, 20 September 2021 at 15:56:44 UTC, Ferhat Kurtulmuş 
wrote:
On Monday, 20 September 2021 at 15:45:08 UTC, Adam D Ruppe 
wrote:
On Monday, 20 September 2021 at 15:35:02 UTC, Ferhat Kurtulmuş 
wrote:

I thought it's stack-allocated and scoped.


It is.

But when I try to return a class instance from a function, it 
still works?


dmd only makes that an error if you specify `@safe` and i 
think `-dip1000`. Try adding one or both of those and 
recompiling and see what happens.


Note that even if the compiler doesn't error on it, it is 
undefined behavior to return the stack reference so be sure to 
treat it right.


That is what I thought too. I only tried this on the online 
compiler. Thank you. Have a great day or night captain.


I also think this is a dirty corner of the complier since it must 
raise an error for scoped instances of classes.




Re: How to do "C++ classes"?

2021-09-20 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 20 September 2021 at 15:45:08 UTC, Adam D Ruppe wrote:
On Monday, 20 September 2021 at 15:35:02 UTC, Ferhat Kurtulmuş 
wrote:

I thought it's stack-allocated and scoped.


It is.

But when I try to return a class instance from a function, it 
still works?


dmd only makes that an error if you specify `@safe` and i think 
`-dip1000`. Try adding one or both of those and recompiling and 
see what happens.


Note that even if the compiler doesn't error on it, it is 
undefined behavior to return the stack reference so be sure to 
treat it right.


That is what I thought too. I only tried this on the online 
compiler. Thank you. Have a great day or night captain.


Re: How to do "C++ classes"?

2021-09-20 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Saturday, 18 September 2021 at 22:16:32 UTC, Adam D Ruppe 
wrote:

On Saturday, 18 September 2021 at 15:38:38 UTC, rempas wrote:
I'm seeing in the page about "BeterC" and in the part about 
the [retained 
features](https://dlang.org/spec/betterc.html#retained), the 
#11 says about "COM classes and C++ classes". What are the 
"C++ classes"? I tried to create a class using "extern(C++)" 
but this didn't worked. Can someone make an example on that?


extern(C++)
class Foo {}

void main() {
scope Foo foo = new Foo();
}


I thought it's stack-allocated and scoped. But when I try to 
return a class instance from a function, it still works? Captain 
Adam I need an explanation please.


Re: How to simply parse and print the XML with dxml?

2021-09-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Thursday, 9 September 2021 at 17:17:23 UTC, tastyminerals 
wrote:
Maybe I missed something obvious in the docs but how can I just 
parse the XML and print its content?


```
import dxml.parser;

auto xml = parseXML!simpleXML(layout);
xml.map!(e => e.text).join.writeln;
```

throws 
`core.exception.AssertError@../../../.dub/packages/dxml-0.4.3/dxml/source/dxml/parser.d(1457): text cannot be called with elementStart`.


I am not fully experienced with it, but once I used it for 
reading glade files [1]. I used dxml.dom. Hope it helps.


1: 
https://github.com/aferust/makegtkdclass/blob/master/source/gladeparser.d#L43


Re: foreach() behavior on ranges

2021-08-24 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Tuesday, 24 August 2021 at 19:06:44 UTC, Alexandru Ermicioi 
wrote:

On Tuesday, 24 August 2021 at 09:15:23 UTC, bauss wrote:

[...]


Actually the range contracts don't mention that it needs to be 
a by value type. It can also be a reference type, i.e. a class.



[...]


True for any forward range and above, not true for input 
ranges. The problem with them is that some of them are structs, 
and even if they are not forward ranges they do have this 
behavior due to implicit copy on assignment, which can 
potentially make the code confusing.



[...]


If we follow the definition of ranges, they must not be 
copy-able at all. The only way to copy/save, would be to have 
.save method and call that method. This again is not being 
properly followed by even phobos implementations.


Note, that a better approach would be to replace .save in 
definition of forward range with a copy constructor, then all 
non-compliant ranges would become suddenly compliant, while 
those that have .save method should be refactored to a copy 
constructor version.



[...]


You should add .save on assignment if range is a forward range, 
or just remove the assignment if it is not.


Best regards,
Alexandru.


Just out of curiosity, if a range implementation uses malloc in 
save, is it only possible to free the memory with the dtor? I 
worry about that especially when using those nogc range 
implementations with standard library. I don't have a list of the 
functions calling save in phobos. Is a save function only 
meaningful for GC ranges?


Re: How to get element type of a slice?

2021-08-23 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 21 August 2021 at 02:59:39 UTC, Jesse Phillips wrote:

On Thursday, 19 August 2021 at 04:03:31 UTC, jfondren wrote:
On Thursday, 19 August 2021 at 03:32:47 UTC, Jesse Phillips 
wrote:
On Tuesday, 17 August 2021 at 12:33:03 UTC, Ferhat Kurtulmuş 
wrote:
Hey, thank you again but, I don't want an instance of 
Point[] I need:


alias T = Point[];

alias ElementOfPointSlice =  // element type of T





so, what's the problem? This passes tests:

```d
import std.range : ElementType;

struct Point { int x, y; }
alias T = Point[];
alias ElementOfPointSlice = ElementType!(T);

unittest {
assert(is(ElementOfPointSlice == Point));
}
```


No issue just trying to give Ferhat a final answer to his 
question.


Thank you. I appreciate it.



Re: How to call destructor before free without dropping @nogc?

2021-08-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 19 August 2021 at 15:38:19 UTC, evilrat wrote:

On Thursday, 19 August 2021 at 15:12:03 UTC, Ferhat Kurtulmuş


Btw, based on 
https://github.com/dlang/druntime/blob/master/src/object.d#L4209:


import core.lifetime;
import core.stdc.stdio;
import core.stdc.stdlib;

extern (C) void rt_finalize(void *data, bool det=true) @nogc 
nothrow; // cheap hack here

alias destroy = rt_finalize;

class SomeClass
{
int a = 42;

this() @nogc { }
~this() @nogc {printf("nogc\n");}
this(int val) @nogc { a = val; }
}



@nogc void main()
{
	SomeClass dynAlloc = cast(SomeClass) 
malloc(__traits(classInstanceSize, SomeClass));

dynAlloc = emplace!SomeClass(dynAlloc, 123);
printf("dynamic %d\n", dynAlloc.a); // 123
//rt_finalize(cast(void*)dynAlloc);
destroy(cast(void*)dynAlloc); // cast needed :/ dunno 
consequences though

}


Re: How to call destructor before free without dropping @nogc?

2021-08-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 19 August 2021 at 15:38:19 UTC, evilrat wrote:

On Thursday, 19 August 2021 at 15:12:03 UTC, Ferhat Kurtulmuş


This is cool, but even in unit tests for malloc wrapper there 
is only simple case with class without references to another 
class and no dtor.


If you examine the entire library, there are various use cases of 
nogc classes. For instance, a derived class containing references 
to other class objects [1]. I am not using classes heavily with 
D. I just once happily used dplug's nogc facilities. When I saw 
this thread, I just wanted to share it here.


Seems like the issue is that one have to add @nogc 
constructor/destructor overloads for emplace/destroy, and the 
author can't have @nogc dtor because of writeln (IIRC @nogc 
using GC is allowed with `debug` anyway), and all class members 
of another classes must recursively provide them as well.


I agree with you. D needs more nogc facilities for OOP. It would 
not be so hard to include those overloads. Probably, this would 
violate the strictly defended safety principles of D?


[1]: 
https://github.com/AuburnSounds/Dplug/blob/f67c14fd5ba44225d6669e87f942d641c8bf8ab8/window/dplug/window/cocoawindow.d


Re: How to call destructor before free without dropping @nogc?

2021-08-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 19 August 2021 at 07:30:38 UTC, Bienlein wrote:

Hello,

I allocate some instance of class C manually and then free the 
memory again:


[...]


I just wanted to leave this here.
https://github.com/AuburnSounds/Dplug/blob/master/core/dplug/core/nogc.d


Re: How to get element type of a slice?

2021-08-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Tuesday, 17 August 2021 at 13:14:44 UTC, Steven Schveighoffer 
wrote:

On 8/17/21 8:21 AM, Ferhat Kurtulmuş wrote:

Hello folks,

Hope everyone is doing fine. Considering the following code, 
in the first condition, I am extracting the type Point from 
the slice Point[]. I searched in the std.traits, and could not 
find a neater solution something like ElementTypeOf!T. Is 
there any neater solution for it? Thanks in advance.


```d
     static if (isArray!VecPoint){
     VecPoint dummy;
     alias Point = typeof(dummy[0]);
     } else static if (isRandomAccessRange!VecPoint){
     alias ASeq2 = TemplateArgsOf!VecPoint;
     alias Point = ASeq2[0];
     } else
     static assert(0, typeof(VecPoint).stringof ~ " type 
is not supported");

```


If you want the element type of a range (i.e. the thing 
returned by `range.front`), you can use `ElementType!T` (from 
std.range.primitives).


This returns the element type of the range, which for every 
array *except* character arrays, gives you the element type of 
the array.


If you want always the element type of the array, even for 
auto-decoded ranges, use `ElementEncodingType!T`.


If you know it's an array, you can just use Paul's solution.

Your `isRandomAccessRange` branch seems very suspect.

-Steve


Very informative, thanks. My code is lying here[1]. I want my 
struct to accept 2d static arrays, random access ranges, and 
"std.container.Array". I could achieve it with its present form, 
and I will probably slightly modify it based on your comments.


[1]: 
https://github.com/aferust/earcut-d/blob/master/source/earcutd.d#L34


Re: How to get element type of a slice?

2021-08-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 17 August 2021 at 12:49:02 UTC, drug wrote:

17.08.2021 15:21, Ferhat Kurtulmuş пишет:

[...]


https://dlang.org/library/std/range/primitives/element_type.html


Yes, that is neat. Thank you.


Re: How to get element type of a slice?

2021-08-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 17 August 2021 at 12:32:45 UTC, Paul Backus wrote:
On Tuesday, 17 August 2021 at 12:21:31 UTC, Ferhat Kurtulmuş 
wrote:

Hello folks,

Hope everyone is doing fine. Considering the following code, 
in the first condition, I am extracting the type Point from 
the slice Point[]. I searched in the std.traits, and could not 
find a neater solution something like ElementTypeOf!T. Is 
there any neater solution for it? Thanks in advance.


`typeof(T.init[0])`

Note that `std.range.ElementType` will probably not give the 
result you expect for character arrays (such as `char[]` and 
`wchar[]`), due to autodecoding.


Thank you. This one looks better.


Re: How to get element type of a slice?

2021-08-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 17 August 2021 at 12:26:36 UTC, jfondren wrote:
On Tuesday, 17 August 2021 at 12:21:31 UTC, Ferhat Kurtulmuş 
wrote:

[...]


This one's not in std.traits:

```d
import std.range : ElementType;

struct Point { int x, y; }

unittest {
Point[] points;
assert(is(ElementType!(typeof(points)) == Point));
}
```


Hey, thank you again but, I don't want an instance of Point[] I 
need:


alias T = Point[];

alias ElementOfPointSlice =  // element type of T



Re: How to get element type of a slice?

2021-08-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 17 August 2021 at 12:26:36 UTC, jfondren wrote:
On Tuesday, 17 August 2021 at 12:21:31 UTC, Ferhat Kurtulmuş 
wrote:

[...]


This one's not in std.traits:

```d
import std.range : ElementType;

struct Point { int x, y; }

unittest {
Point[] points;
assert(is(ElementType!(typeof(points)) == Point));
}
```


Awesome! Have a great day.


How to get element type of a slice?

2021-08-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

Hello folks,

Hope everyone is doing fine. Considering the following code, in 
the first condition, I am extracting the type Point from the 
slice Point[]. I searched in the std.traits, and could not find a 
neater solution something like ElementTypeOf!T. Is there any 
neater solution for it? Thanks in advance.


```d
static if (isArray!VecPoint){
VecPoint dummy;
alias Point = typeof(dummy[0]);
} else static if (isRandomAccessRange!VecPoint){
alias ASeq2 = TemplateArgsOf!VecPoint;
alias Point = ASeq2[0];
} else
static assert(0, typeof(VecPoint).stringof ~ " type is 
not supported");

```

Ferhat


Re: Can I make system calls directly from D?

2021-07-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 9 July 2021 at 08:08:57 UTC, rempas wrote:
I just wonder if I'm able to do system calls directly from D or 
If I have to create bindings from "unistd.h" from C


I don't know if it covers what you want but, druntime has those 
definitions:


https://github.com/dlang/druntime/blob/master/src/core/sys/posix/unistd.d

import core.sys.posix.unistd;

... do stuff


Re: Trivial simple OpenGl working example

2021-07-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 9 July 2021 at 06:16:08 UTC, Ferhat Kurtulmuş wrote:

On Friday, 9 July 2021 at 05:17:28 UTC, Виталий Фадеев wrote:

[...]



[...]


Dear Vitaly (Google translates it like that :)), I didn't touch 
that game for a while. I have just tried to compile and those 
are the steps to build and run it:


[...]


You may also need to use the exact version of "bettercmath": 
"0.3.1".


Re: Trivial simple OpenGl working example

2021-07-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 9 July 2021 at 05:17:28 UTC, Виталий Фадеев wrote:
On Thursday, 8 July 2021 at 17:20:14 UTC, Ferhat Kurtulmuş 
wrote:

On Thursday, 8 July 2021 at 13:51:51 UTC, Виталий Фадеев wrote:

Hi!




Each ends with error.


Dear Vitaly (Google translates it like that :)), I didn't touch 
that game for a while. I have just tried to compile and those are 
the steps to build and run it:


Using a Windows 10 x64. (Webassembly build needs crazy efforts, 
don't try it for now. If you are on a posix system please delete 
*.a folders from the root folder because they are for webassembly)


1) Open the dub.json or dub.selections.json, and change "bcaa": 
"~>0.0.5" to "bcaa": "0.0.5" (Recently a contributor and I have 
made some breaking changes in bcaa).


2) Have those lib and dll files in the root folder of the project:

chipmunk.lib // I manually compiled this one
libfreetype-6.dl
libjpeg-9.dll
libpng16-16.dll
libtiff-5.dll
libwebp-7.dll
SDL2_image.dll
SDL2_image.lib
SDL2_ttf.dll
SDL2_ttf.lib
SDL2.dll
SDL2.lib
zlib1.dll

basically, those are win 64-bit builds of SDL2, its friends, and 
their dependencies. If you provide an email, I can send them to 
you via wetransfer.


For posix builds, you will have to figure those out.


Re: Trivial simple OpenGl working example

2021-07-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 8 July 2021 at 13:51:51 UTC, Виталий Фадеев wrote:

Hi!

I searching trivial simple D/OpenGL working in 2021 year 
example.


It may be triangle.
It may be based on any library: SDL, GLFW, Derelict, etc.

Can you help me ?


this one of mine [1] was very simple in the beginning. It even 
runs on browser now.


[1] https://github.com/aferust/drawee


Re: How to use a shared library created in cython?

2021-04-12 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Sunday, 11 April 2021 at 20:08:15 UTC, affonso elias ferreira 
junior wrote:
Hi everyone, I'm trying to use a shared library created in 
Cython. example.


[...]


I am on my mobile phone, and cannot reproduce. But i see that 
this cast(int function()) should be cast(int function(int)). Try 
correcting function signatures throughout the code. And extern 
(c) int test() is irrelevant here because you are loading it via 
a different mechanism.


Re: Creating a .di file for a custom C library

2021-03-30 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 30 March 2021 at 04:01:12 UTC, Brad wrote:
I would like to use an updated version of the Termbox library 
(written in C) with D.  I have the .h file.  This is new 
territory for me (why try something easy - right?).  I think I 
need to create a .di file that corresponds to the .h file.  I 
also suspect that I need to put the library file (C code) into 
the project as a file somehow.  I am probably just not looking 
in the right place for the documentation, but I cannot seem to 
find a lot of guidance in this area.


Thanks in advance.


I never needed or used .di files. Dstep[1] can create d modules 
containing c header definitions. Recently, I used to create a d 
binding [2] for shapelib[3]. I just added "module shapelib;" at 
the beginning of the file, nothing else. Some c headers may 
require extra steps IMO.



1: https://github.com/jacob-carlborg/dstep
2: https://github.com/aferust/shapelib-d/blob/main/shapelib.d
3: https://github.com/OSGeo/shapelib



Re: Creating 1000 instances

2021-02-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 19 February 2021 at 10:02:05 UTC, Siemargl wrote:
On Friday, 19 February 2021 at 08:29:36 UTC, Ferhat Kurtulmuş 
wrote:


Since classes are reference types all instances of files will 
be the same reference of "new File()", which you probably 
don't want.


Is any differences between x and y definitions?

MyClass [] x, y;
x = new MyClass[7];

y= new MyClass[](8);


Although I don't usually use the latter, I can say online d 
editor yields the same ASM output for both:


File[] files = new File[10];
File[] files = new File[](10);


Re: Creating 1000 instances

2021-02-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 19 February 2021 at 08:29:36 UTC, Ferhat Kurtulmuş 
wrote:
On Friday, 19 February 2021 at 08:04:19 UTC, Виталий Фадеев 
wrote:

[...]


files = new File[]( 1000 );
files[] = new File(); // add this

Since classes are reference types all instances of files will 
be the same reference of "new File()", which you probably don't 
want.


You can do

files[].each!((ref a) => a = new File);


Re: Creating 1000 instances

2021-02-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 19 February 2021 at 08:41:06 UTC, Ferhat Kurtulmuş 
wrote:
On Friday, 19 February 2021 at 08:29:36 UTC, Ferhat Kurtulmuş 
wrote:
On Friday, 19 February 2021 at 08:04:19 UTC, Виталий Фадеев 
wrote:

[...]


files = new File[]( 1000 );
files[] = new File(); // add this

Since classes are reference types all instances of files will 
be the same reference of "new File()", which you probably 
don't want.


You can do

files[].each!((ref a) => a = new File);


oh, now we can remove brackets

files.each!((ref a) => a = new File);


Re: Creating 1000 instances

2021-02-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 19 February 2021 at 08:04:19 UTC, Виталий Фадеев wrote:

We have:
class File
{
// WIN32_FIND_DATAW data;
}

void fastReadDir()
{
File[] files;

// reserve space, allocating instances
files = new File[]( 1000 );  // <--- trouble here ?

// filling instances
auto file = files.ptr;

writeln( file.data );// <--- or trouble here ?

// ...
}

Got:
SegFault

Goal:
Allocate memory for 1000 instances at once.

Source:
https://run.dlang.io/is/xfaXcv

Question:
What is the true, fastest, beauty way to create 1000 
instances of the class File ?


files = new File[]( 1000 );
files[] = new File(); // add this

Since classes are reference types all instances of files will be 
the same reference of "new File()", which you probably don't want.




Re: Web crawler/scraping

2021-02-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Wednesday, 17 February 2021 at 12:12:56 UTC, Carlos Cabral 
wrote:

Hi,
I'm trying to collect some json data from a website/admin panel 
automatically, which is behind a login form.


Is there a D library that can help me with this?

Thank you


I found this but it looks outdated:

https://github.com/gedaiu/selenium.d


Re: Real simple unresolved external symbols question...

2021-02-10 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 9 February 2021 at 19:37:17 UTC, WhatMeWorry wrote:


I'm trying to create a super simple dynamic library consisting 
of two files:


[...]


remove /NOENTRY, and include "mixin SimpleDllMain;" in one of the 
sources. And link with druntime.


link /DLL file2.obj fileB.obj druntime-ldc.lib msvcrt.lib


Need help for opencvd git submoduling

2021-02-07 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
I am wrapping opencv::cuda modules based on c/c++ wrapper files 
of gocv. This might be more of a git question. Can one link a 
folder from a repo to be a subfolder of another git repo?

Do I have any option other than submoduling the entire Go repo?

I want "https://github.com/hybridgroup/gocv/tree/release/cuda; to 
be "https://github.com/aferust/opencvd/tree/master/c/cuda;


Re: list system drives

2021-02-01 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 2 February 2021 at 06:31:27 UTC, Виталий Фадеев wrote:

Give, please, Dlang tools for list system drives.

Some like a:
enumVolumes(); // [ 'C:\', 'D:\' ]


I have found this code by a google search. I don't know who the 
author was. I had to touch it a little since the codebase was old.


https://gist.github.com/aferust/5cc3209a6b6caf1062271a082c093b87


Re: How do I get the output of the time bash command?

2021-01-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 27 January 2021 at 09:35:21 UTC, Anthony wrote:


I'm trying to read the timed output of a pipeShell command but 
it only results in empty output.


Does anyone know why this is?


```
auto p = pipeShell("time ls");

foreach(str; p.stdout.byLine) {
writefln("%s",str);
}
```


Probably, just getting a string output is not enough. It looks a 
little outdated, but there is this library:


https://code.dlang.org/packages/dexpect


Re: How to covert dchar and wchar to string?

2021-01-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 25 January 2021 at 18:45:11 UTC, Rempas wrote:
Actually what the title says. For example I have dchar c = 
'\u03B3'; and I want to make it into string. I don't want to 
use "to!string(c);". Any help?


if you are trying to avoid GC allocations this is not what you 
want.


dchar c = '\u03B3';

string s = "";
s ~= c;

writeln(s);
writeln(s.length); // please aware of this

Some useful things:

string is immutable(char)[]
wstring is immutable(wchar)[]
dstring is immutable(dchar)[]

if you have a char[]:
you can convert it to a string using assumeUnique:

import std.exception: assumeUnique;

char[] ca = ...

string str = assumeUnique(ca); // similar for dchar->dstring and 
wchar->wstring




Re: Can we use strings with scanf?

2021-01-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 25 January 2021 at 17:38:21 UTC, Rempas wrote:

On Monday, 25 January 2021 at 10:33:14 UTC, Mike Parker wrote:

On Monday, 25 January 2021 at 09:16:11 UTC, Rempas wrote:

[...]


The * has a different meaning for scanf than for printf ([1] 
vs [2]).


There's also the issue that a string is immutable(char)[].

If you really, really, really, must use scanf:

```
char[bufSize] buf;
scanf("%s", buf.ptr);
```

But please don't. This is D, not 1990s C.

[1] https://www.cplusplus.com/reference/cstdio/scanf/
[2] https://www.cplusplus.com/reference/cstdio/printf/


Thanks! Actually for some reason. It won't accept a char[size]. 
I created a heap allocated (with pureFree and pureMalloc) 
chrar*, then used fgets() and created an empty string and 
looped through the result adding one by one character until the 
'\n' which is not included.


char[buffsize] works if buffsize is a compile time constant. Or 
just char[1024]. İt is a static array, and it's size must be 
defined at compile time.


Re: How define accepted types in a template parameter?

2021-01-16 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 16 January 2021 at 18:39:03 UTC, Marcone wrote:
For example, I want my function template to only accept integer 
or string;


There are different ways of doing that. I'd say this one is easy 
to follow:


import std.stdio;

void print(T)(T entry) if(is(T==string) || is(T==int))
{
writeln(entry);

}

void main(){
int i = 5;
string foo = "foo";

double j = 0.6;

print(i);
print(foo);
print(j); // compilation error
}


Re: Directory recursive walking

2021-01-14 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 15 January 2021 at 07:16:21 UTC, Daniel Kozak wrote:
On Fri, Jan 15, 2021 at 8:00 AM dog2002 via Digitalmars-d-learn 
< digitalmars-d-learn@puremagic.com> wrote:



On Friday, 15 January 2021 at 06:33:55 UTC, Paul Backus wrote:
> On Friday, 15 January 2021 at 06:31:18 UTC, Paul Backus 
> wrote:

>>
>> You can save a little bit of memory here by allocating 
>> tempBuffer on the stack:

>>
>> ubyte[512] tempBuffer;
>> _inputFile.rawRead(tempBuffer[]); // note the explicit 
>> []

>
> I made a mistake; this should be:
>
> ubyte[512] tempArray;
> ubyte[] tempBuffer = _inputFile.rawRead(tempArray[]);
>
> ...with the rest the same as your original version.

Thank you so much! It saves a lot of memory!

And one last question: why the application crashes, if I 
allocate 1 MB array?


>ubyte[1024000] tempBuffer;



Because of stack overflow


A compiler parameter can be used to increase the maximum stack 
size

"dflags": ["-L/STACK:15"]

or recursion can be somehow emulated using heap memory. Here is 
my "fake" recursion:

// wins is a range

auto stack = wins.save;
while(!stack.empty){
immutable n = stack.length - 1;
auto window = stack[n];

doSomeThingforEachRecursiveElement(window)

stack.popBack;
if(window.children.length){
foreach (ref child; window.children)
stack.pushBack(child);
}
}
stack.free;


Re: Collections in D

2021-01-13 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 13 January 2021 at 12:06:05 UTC, Roguish wrote:

On Wednesday, 13 January 2021 at 11:58:11 UTC, Roguish wrote:
I can't find anything about collections in D. All I have found 
are arrays and maps ("associative arrays"). What about lists 
and sets? What if I just want a linked list?


It seems collections are called "containers" in D's standard 
library, which explains why I didn't find anything searching 
for "collections".


As concerns linked lists, I have found

   https://dlang.org/phobos/std_container_dlist.html

which seems perfectly adequate.

What about sets?


I read many posts that rbtree can be a replacement for sets in 
dlang.


see its behaviour is identical.

https://dlang.org/phobos/std_container_rbtree.html


Re: Collections in D

2021-01-13 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 13 January 2021 at 11:58:11 UTC, Roguish wrote:
I can't find anything about collections in D. All I have found 
are arrays and maps ("associative arrays"). What about lists 
and sets? What if I just want a linked list?


You can refer to the docs for them:

https://dlang.org/phobos/std_container.html

https://dlang.org/phobos/std_container_slist.html
https://dlang.org/phobos/std_container_dlist.html

For sets see:
https://forum.dlang.org/thread/vqyxqkcszqfwpgqtj...@forum.dlang.org



Re: Using a betterC dub package in ordinary D

2021-01-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 8 January 2021 at 20:19:59 UTC, Bastiaan Veelo wrote:
On Friday, 8 January 2021 at 18:28:36 UTC, Ferhat Kurtulmuş 
wrote:
On Friday, 8 January 2021 at 15:40:12 UTC, Bastiaan Veelo 
wrote:

Hi,

When I use earcutd [1] in an ordinary D project, I get a link 
error for the __D7earcutd12__ModuleInfoZ symbol.

[...]


Dear Bastiaan,

I am not an expert in dub system, but I have just pushed a 
modification in dub.json. I am not sure if it solves your 
problem. My modification is


"configurations": [
{
"name": "default",
"targetType": "library"
},
{
"name": "betterC",
"targetType": "library",
"dflags": ["-betterC"]
}
]

now client projects must explicitly pass the subConfiguration 
parameter to compile it with betterC.


Much appreciated Ferhat! This works like a charm. I am kind of 
surprised that it does, as I expected dvector to need the same 
treatment. Excellent support by the way, thanks!


Off topick, the original js implementation is documented to not 
generate results that are guaranteed to be correct. I could not 
find information on what the conditions are that cause 
deviations, and how large these then can be. Do you have an 
idea about this or experience with accuracy of the algorithm? I 
am looking into whether earcutd can replace GLU tesselation. We 
use the result for engineering purposes (not only 
visualisation) and correctness is important to us.


Thanks!
Bastiaan.


Sorry, I don't have any information regarding the correctness of 
the algorithm. I just ported it doing cpp to d translations. My 
only usage of it for my hobby game[1]. However, it would be nice 
if you have another usage area to test it. I am using it with a 
similar purpose of glu Tessa lation in the game (I guess it is 
so, I am a beginner with opengl)


1: https://github.com/aferust/drawee



Re: Using a betterC dub package in ordinary D

2021-01-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 8 January 2021 at 18:28:36 UTC, Ferhat Kurtulmuş wrote:

On Friday, 8 January 2021 at 15:40:12 UTC, Bastiaan Veelo wrote:

Hi,

When I use earcutd [1] in an ordinary D project, I get a link 
error for the __D7earcutd12__ModuleInfoZ symbol. This is 
because the earcutd dub.json has `"dflags": ["-betterC"]`. I 
think this is in error, my understanding of betterC code is 
that it can be compiled with "-betterC", but does not need to 
(and must not when used in D context).


Am I right? What are the best practices for betterC dub 
packages?


Thanks,
Bastiaan.


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


Dear Bastiaaan,

I am not an expert in dub system, but I have just pushed a 
modification in dub.json. I am not sure if it solves your 
problem. My modification is


"configurations": [
{
"name": "default",
"targetType": "library"
},
{
"name": "betterC",
"targetType": "library",
"dflags": ["-betterC"]
}
]

now client projects must explicitly pass the subConfiguration 
parameter to compile it with betterC.


I also added this:

version(LDC){
version(D_BetterC){
pragma(LDC_no_moduleinfo);
}
}

Docs say

LDC_no_moduleinfo
This pragma disables the generation of the ModuleInfo metadata to 
register the current module with druntime. Note that this, among 
other things, leads to any static constructors not being run, and 
should only be used in very specific circumstances.


I used that pragma against an error, but I cannot remember what 
was that.


Re: Using a betterC dub package in ordinary D

2021-01-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 8 January 2021 at 15:40:12 UTC, Bastiaan Veelo wrote:

Hi,

When I use earcutd [1] in an ordinary D project, I get a link 
error for the __D7earcutd12__ModuleInfoZ symbol. This is 
because the earcutd dub.json has `"dflags": ["-betterC"]`. I 
think this is in error, my understanding of betterC code is 
that it can be compiled with "-betterC", but does not need to 
(and must not when used in D context).


Am I right? What are the best practices for betterC dub 
packages?


Thanks,
Bastiaan.


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


Dear Bastiaaan,

I am not an expert in dub system, but I have just pushed a 
modification in dub.json. I am not sure if it solves your 
problem. My modification is


"configurations": [
{
"name": "default",
"targetType": "library"
},
{
"name": "betterC",
"targetType": "library",
"dflags": ["-betterC"]
}
]

now client projects must explicitly pass the subConfiguration 
parameter to compile it with betterC.


Re: How to resize an image ? 樂

2020-12-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 25 December 2020 at 20:59:03 UTC, vnr wrote:

Hello 

For a small "script" that generates printable files, I would 
need to change the size of an image (which is loaded into 
memory as an array of bytes) to shrink it to scale if it 
exceeds the A4 page size.


To load the images into memory and generate a PDF, I use the 
"printed" package. It is not very provided but is sufficient 
for my use, I just need the resize option... Is there a 
relatively simple way to do this?


Thank you.


Check this out:
https://github.com/adamdruppe/arsd/blob/master/image.d#L434


Re: Can I output strings using core.stdc.stdio?

2020-12-23 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Wednesday, 23 December 2020 at 09:40:27 UTC, Ferhat Kurtulmuş 
wrote:

On Wednesday, 23 December 2020 at 09:06:02 UTC, Godnyx wrote:

[...]


I didn't dive into your use case, but you should use static 
foreach in this case:


void put(A...)(string prompt, A args) {
static foreach (ulong i; 0..args.length) {
if (typeof(args[i]).stringof == "string")
printf("%s\n", args[i].toStringz);
}
}


and better:
void put(A...)(string prompt, A args) {
static foreach (ulong i; 0..args.length) {
if (is(typeof(args[i]) == string))
printf("%s\n", args[i].toStringz);
}
}


Re: Can I output strings using core.stdc.stdio?

2020-12-23 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 23 December 2020 at 09:06:02 UTC, Godnyx wrote:
On Wednesday, 23 December 2020 at 08:50:50 UTC, Mike Parker 
wrote:

On Wednesday, 23 December 2020 at 08:45:15 UTC, Godnyx wrote:

Yep and I find it out! It won't work with templates and/or 
variadic function parameters. It says that the variable can't 
be read at compile time (so I can't cast it) or it will work 
but it will give me a segmentation fault (lol hello C). Any 
idea why this is happening in those cases?


Please show the code that's causing the error. Without it, all 
anyone can do is keep making suggestions that *might* be the 
problem. With the code, someone can point to it exactly.


Yep that's the best thing I can do! Code:

import core.stdc.stdio : printf;
import std.string : toStringz;

void put(A...)(string prompt, A args) {
for (ulong i = 0; i < args.length; i++) {
if (typeof(args[i]).stringof == "string")
printf("%s\n", args[i].toStringz);
}
}

void main() {
string h = "World!";
string w = "World!";
put(h, w);
}

I'm getting two errors. First that i can't be read at compile 
time and second that I don't initialize the function right. So 
I know I'm doing something wrong but I don't know why... Any 
ideas?


I didn't dive into your use case, but you should use static 
foreach in this case:


void put(A...)(string prompt, A args) {
static foreach (ulong i; 0..args.length) {
if (typeof(args[i]).stringof == "string")
printf("%s\n", args[i].toStringz);
}
}


Re: Simple BeamUI project won't link

2020-12-18 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 18 December 2020 at 19:15:16 UTC, Daren Scot Wilson 
wrote:
On Wednesday, 16 December 2020 at 07:45:50 UTC, Ferhat 
Kurtulmuş wrote:
On Wednesday, 16 December 2020 at 07:40:45 UTC, Ferhat 
Kurtulmuş wrote:


This may be not your issue, but I could manage it to work by 
adding this line:


subPackage "examples/myproject"

to the dub.sdl of the beamui. I simply put my project in 
examples/ folder.


And compile and run using:

dub run :myproject


The thought crossed my mind to try putting my source under 
examples/ but that's not a good way to organize a real project. 
I'd like it be under ~/projects/, naturally. What I want to 
make will involve a lot more than just a GUI.


İf you don't need a fancy look and can live with simple widgets, 
Adam D. Ruppe's arsd repository has minigui. On windows it uses 
native Win32 API, so it doesn't need any dependency. 
https://github.com/adamdruppe/arsd




Re: Simple BeamUI project won't link

2020-12-15 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Wednesday, 16 December 2020 at 07:40:45 UTC, Ferhat Kurtulmuş 
wrote:
On Wednesday, 16 December 2020 at 07:02:11 UTC, Daren Scot 
Wilson wrote:
Trying out the beamui GUI package, obtained by git clone from 
github.  The "basic" example builds and runs.


I'm working on an Arch Linux machine with lots of RAM, but a 
user with not enough practice at D yet.


I have a little experience with beamui but only on windows. It 
is under WIP. You'd better open an issue with an error report 
on GitHub as I did before 
https://github.com/dayllenger/beamui/issues/16. You may get 
some help from the maintainer.


This may be not your issue, but I could manage it to work by 
adding this line:


subPackage "examples/myproject"

to the dub.sdl of the beamui. I simply put my project in 
examples/ folder.


And compile and run using:

dub run :myproject


Re: Simple BeamUI project won't link

2020-12-15 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Wednesday, 16 December 2020 at 07:02:11 UTC, Daren Scot Wilson 
wrote:
Trying out the beamui GUI package, obtained by git clone from 
github.  The "basic" example builds and runs.


I'm working on an Arch Linux machine with lots of RAM, but a 
user with not enough practice at D yet.


I have a little experience with beamui but only on windows. It is 
under WIP. You'd better open an issue with an error report on 
GitHub as I did before 
https://github.com/dayllenger/beamui/issues/16. You may get some 
help from the maintainer.


Re: A strange charArray.ptr behavior

2020-12-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 2 December 2020 at 21:01:22 UTC, Ali Çehreli wrote:

On 12/2/20 12:20 PM, Ferhat Kurtulmuş wrote:

given the function:

export void ceaser_enc(char* input, ref char* output);

this compiles:
     char* sezar = (new char[65]).ptr;
     ceaser_enc(key, sezar);

this does not compile:

     char[] sezar = new char[65];
     ceaser_enc(key, sezar.ptr);

by yielding: "cannot pass rvalue argument cast(char*)sezar of 
type char* to parameter ref char* output"


Why is sezar an rvalue in the second case?


Not 'sezar' but sezar.ptr is an rvalue. Imagine ptr() being a 
function that returns a value:


T* ptr() {
  // ...
}

That pointer is an rvalue and D disallows binding them to 'ref' 
parameters.


In the first case, 'sezar' is a local variable, which is an 
lvalue.


Ali


That makes sense. Thank you.


Re: How to build dll?

2020-12-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 2 December 2020 at 20:08:29 UTC, Jack wrote:

On Wednesday, 2 December 2020 at 19:42:37 UTC, Jack wrote:

D code:


[...]


compiled with:

[...]


called from:


   [...]



but hinstLib is NULL and GetLastError() = 193:


[...]


What am I missing?


for same reason, the dll build with ldc2 works fine, compiled 
with:



ldc2 -shared dll.d -ofmydll.dll


what am I missing?


Just out of curiosity, are you sure that you compile both your c 
and d codes for the same arc?


A strange charArray.ptr behavior

2020-12-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

given the function:

export void ceaser_enc(char* input, ref char* output);

this compiles:
char* sezar = (new char[65]).ptr;
ceaser_enc(key, sezar);

this does not compile:

char[] sezar = new char[65];
ceaser_enc(key, sezar.ptr);

by yielding: "cannot pass rvalue argument cast(char*)sezar of 
type char* to parameter ref char* output"


Why is sezar an rvalue in the second case?


Re: How to bundle a GtkD application for Windows

2020-11-30 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 29 November 2020 at 20:08:33 UTC, adnan449 wrote:
Hello, I would be greatly thankful if I was given an easy guide 
on how to produce windows executables for GtkD applications. I 
do not have an access to a windows machine but I need to be 
able to produce installers/exe files for the windows users.


Users should not have to install any dependency manually to be 
able to install my program.

Thank you.


A useful tip.

Assuming one has a list of dependent dlls.

https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer

The subfolder gtk-nsis-pack contains a required folder structure 
if you want to use theme support etc. Simply put your gtkd exe in 
the bin folder. You can remove redundant dlls from the bin folder 
to obtain a minimal bundle for your program. The NSIS project 
structure may also help to create an installer for your program.


Re: How to connect to SQLITE?

2020-11-28 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 28 November 2020 at 17:50:43 UTC, kdevel wrote:
On Saturday, 28 November 2020 at 13:29:50 UTC, Ferhat Kurtulmuş 
wrote:

On Saturday, 28 November 2020 at 12:01:59 UTC, Alex NL wrote:

Is there libs for SQLITE?
How to use it? thanks.


https://github.com/aferust/GtkD-examples-for-TreeView-and-ListBox


IMNSHO the code in example1.d

   string sql = format("UPDATE User SET %s = '%s' WHERE id = 
%s;", field, text, curId);

   db.query(sql);

and that in example2.d

   string sql = format("UPDATE User SET %s = '%s' WHERE id = 
%d;", field, value, cid);

   db.query(sql);

is prone to SQL injection attacks. Why don't you use ? as 
placeholder as in the example


   db.query("INSERT INTO people (id, name) VALUES (?, ?)", 5, 
"Adam");


of

   http://dpldocs.info/experimental-docs/arsd.database.html

If your database is compromised you can blame the arsd.database 
author(s) for publishing a buggy db.escape function ;-)


I just didn't care about security vulnerability there. My focus 
was on GtkD functions. But you are right. It may mislead newbies. 
Library functions must have been used, not format, so that auto 
escape can work. I am too lazy to fix it :)


Re: How to connect to SQLITE?

2020-11-28 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 28 November 2020 at 12:01:59 UTC, Alex NL wrote:

Is there libs for SQLITE?
How to use it? thanks.


https://github.com/aferust/GtkD-examples-for-TreeView-and-ListBox



Re: d++: Error: Could not execute `dmd c.o .\foo.d -offoo.exe`:

2020-11-21 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 21 November 2020 at 17:25:46 UTC, Jack wrote:
I'm trying to get d++ to work on Windows 10/64-bit machine but 
it doesn't work. I'm using the very same code samples c.c, c.h 
and foo.dpp from here 
https://github.com/atilaneves/dpp/tree/master/bash but when I 
went to run:



d++ foo.dpp c.o


I got the error:


Error: Could not execute `dmd c.o .\foo.d -offoo.exe`:
Error: unrecognized file extension o


dmd version:

DMD32 D Compiler v2.094.1-dirty


gcc version:

gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)


d++ the least one, build from sources

my OS is windows 10/64-bit. What am I missing?


I have never used dpp, but the github page says you should use 
LDC, not DMD. And I could not find anything implying gcc is 
supported.





Re: Extract sub string from a string

2020-11-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 9 November 2020 at 18:55:44 UTC, Ali Çehreli wrote:

On 11/9/20 9:53 AM, k2aj wrote:

> string text = "welcome2worldinfo";
> string hg = toUpper(text[0..7] ~ "-" ~ text[7..8] ~ "-" ~
text[8..13]);

If those concatenations with the ~ operators prove to be costly 
at runtime, the following range expression may be faster 
because it does not allocate any memory:


import std.string;
import std.range;
import std.algorithm;
import std.stdio;

void main() {

  string text = "welcome2worldinfo";
  auto hg = chain(text[0..7], only('-'), text[7..8], only('-'), 
text[8..13]).map!toUpper;

  writeln(hg);
}

Ali


I am responding to this just for my personal records. I wish we 
could've a "add to favorites" option here.


Re: Return values from auto function

2020-11-06 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 6 November 2020 at 10:51:20 UTC, Andrey Zherikov wrote:
I have auto function 'f' that might return either an error 
(with some text) or a result (with some value). The problem is 
that the type of the error is not the same as the type of 
result so compilation fails.


[...]


Sounds like Andrei's "Expected". Here is an implementation for d. 
https://github.com/tchaloupka/expected


A GtkD question: Is there an explicit public function to get D Classes from StructCtype*?

2020-11-06 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

For instance,

I have extern (C) int sortList1(GtkListBoxRow* _row1, 
GtkListBoxRow* _row2, void* userData)


I pass it as listbox.setSortFunc(, cast(void*)this, 
&_destroy2);


In the sortList1 function I want to access derived members of my 
ListBoxRowWithData such as:


auto row1 = 
cast(ListBoxRowWithData)getMyDObject!ListBoxRow(_row1);
auto row2 = 
cast(ListBoxRowWithData)getMyDObject!ListBoxRow(_row2);

if(row1.id < row2.id) return 1;

A regular type cast returns null. T opCast(T)() in ObjectG.d 
returns null in this case. I dug into the sources a little, and 
my working solution is like:


template getCType(T)
{
static if ( is(T == class) )
alias getCType = typeof(T.tupleof[0]);
else
alias getCType = void*;
}

T getMyDObject(T, TC = getCType!T)(void* data){

T ret = ObjectG.getDObject!(T)(cast(TC)data);

return ret;
}

Is there an existing implementation for T getMyDObject(T, TC = 
getCType!T)(void* data)?


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

2020-10-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Tuesday, 27 October 2020 at 19:30:06 UTC, Ferhat Kurtulmuş 
wrote:
On Tuesday, 27 October 2020 at 19:23:22 UTC, Ferhat Kurtulmuş 
wrote:

On Tuesday, 27 October 2020 at 15:16:33 UTC, Marcone wrote:

[...]


IMHO, your d program cannot have direct control over a spawned 
process. However, I suggest a road map for you, although I am 
not sure if it works.


[...]


Ohh, spawnShell returns a pid, so you don't need to use expect 
actually [1]


1: https://dlang.org/library/std/process/pid.process_id.html


There is also this: 
https://dlang.org/library/std/process/kill.html


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

2020-10-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Tuesday, 27 October 2020 at 19:23:22 UTC, Ferhat Kurtulmuş 
wrote:

On Tuesday, 27 October 2020 at 15:16:33 UTC, Marcone wrote:

[...]


IMHO, your d program cannot have direct control over a spawned 
process. However, I suggest a road map for you, although I am 
not sure if it works.


[...]


Ohh, spawnShell returns a pid, so you don't need to use expect 
actually [1]


1: https://dlang.org/library/std/process/pid.process_id.html


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

2020-10-27 Thread Ferhat Kurtulmuş 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?


IMHO, your d program cannot have direct control over a spawned 
process. However, I suggest a road map for you, although I am not 
sure if it works.


- I don't know if d has something like C's expect [1] library, 
but you will need a similar thing. Basically, It spawns processes 
and handles their stdout. Maybe you can just wrap libexpect in D.


- Assuming you have "expect" running in D, you can spawn 
"tasklist" [2] and somehow filter out (I recall that it can be 
done with expect using a struct like a regex on stdout) its 
stdout to determine the PID number [2] of the process that you 
want to kill at the end of the program.


- then, in your main:
void main(){
...

scope(exit){ // maybe you should also be aware of 
scope(success) and scope(failure)
killPlink(); // spawn another process: "Taskkill /PID 
26356 /F"

}
...
}
1: 
http://npg.dl.ac.uk/MIDAS/manual/ActiveTcl8.4.9.0-html/expect/libexpect.3.html
2: 
https://tweaks.com/windows/39559/kill-processes-from-command-prompt/


Re: Skipping or Stepping Through an Array?

2020-10-21 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 21 October 2020 at 14:03:54 UTC, DMon wrote:
On Wednesday, 21 October 2020 at 13:04:40 UTC, Ferhat Kurtulmuş 
wrote:

import std.range;
import std.stdio;

void main(){
auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto chunks = chunks(source, 2);

writeln(chunks[0]); // [1, 2]

foreach(c; chunks)
writeln(c[1]);
}


And, thank you Kurtulmuṣ (that's the closest "s" this keyboard 
has).


I've played with std.range but didn't think a control structure 
or import should be necessary.


:) 'sh' sound in English

ş

UTF-8: Å
Numeric: 
Ansi: ÅŸ



Re: Skipping or Stepping Through an Array?

2020-10-21 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Wednesday, 21 October 2020 at 11:55:54 UTC, DMon wrote:
What is the simplest way to output every nth element of an 
array?


I can do it using a for loop:
void main()
{
int[5] a = [1,2,3,4,5];

for (int i = 0 ; i <= 4 ; i += 2)
{
writeln(a[i]);
}
}

Basically, I am wondering if I missed something.


In addition to the drug's solution, this reminds me of the chunks 
of std.range.


import std.range;
import std.stdio;

void main(){
auto source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
auto chunks = chunks(source, 2);

writeln(chunks[0]); // [1, 2]

foreach(c; chunks)
writeln(c[1]);
}

output:
2
4
6
8
10



Re: Compiler is calling `_memset64` in betterC

2020-10-19 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 19 October 2020 at 14:07:38 UTC, matheus wrote:
On Sunday, 18 October 2020 at 19:24:28 UTC, Ferhat Kurtulmuş 
wrote:
I plan to start a project in reasonable size, I wonder if I 
should really use betterC... if I encounter a bug like this, 
will I be stuck at it?


The bug report says, it is a dmd specific problem, and LDC, my 
favorite d compiler, works well (tried it).


So the "first party" compiler has a bug while the "third party" 
one works. That's weird.


I would expect the other way around.

Matheus.


Ldc is used and tested more. An answer to this thread explains 
the situation.


From:

https://stackoverflow.com/questions/62265658/undefined-reference-to-memset64-when-creating-a-struct-array-under-dmd-with?r=SearchResults

"I would highly recommend that you do not use DMD and instead 
stick to either LDC or GDC. They have far more tested and 
performant code generator, and have support for many more 
platforms. The debug info they generate will also be much better, 
and they have support for your use case (bare metal). – Geod24 
Jun 10 at 3:30"




Re: Compiler is calling `_memset64` in betterC

2020-10-18 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 18 October 2020 at 17:05:01 UTC, Neto wrote:

On Sunday, 18 October 2020 at 16:12:59 UTC, Paul Backus wrote:

On Sunday, 18 October 2020 at 16:04:55 UTC, Koro wrote:
I'm writing a 'betterC' program and the compiler is 
generating a call to '_memset64' if I have an array literal 
where the elements are the same.


It's a known bug:

https://issues.dlang.org/show_bug.cgi?id=17778

My guess is that the reason it hasn't been fixed is that (a) 
it's possible to work around it, and (b) the problem is in the 
compiler backend, and few people understand that code well 
enough to fix it.


I plan to start a project in reasonable size, I wonder if I 
should really use betterC... if I encounter a bug like this, 
will I be stuck at it?


The bug report says, it is a dmd specific problem, and LDC, my 
favorite d compiler, works well (tried it).


Re: GtkD CRUD Application

2020-10-17 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 17 October 2020 at 14:53:35 UTC, Alaindevos wrote:

I've written the beginning but dont know how to end.
What is the way to add functionality for the add,edit,delete 
button ?

//==


I put an example[1] here. The fields are not editable. You will 
have to implement it. I think you will get the idea to do that.


My example uses ListBox with a fake header as a bonus. You can 
use TreeView, but it is a complex widget.


[1] 
https://gist.github.com/aferust/47cb782b55cdab1f7775b7755bc50982


Re: How auto convert Variant to required function arguments?

2020-10-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 9 October 2020 at 16:10:03 UTC, Ferhat Kurtulmuş wrote:
On Friday, 9 October 2020 at 15:49:31 UTC, Ferhat Kurtulmuş 
wrote:

On Friday, 9 October 2020 at 00:19:20 UTC, Marcone wrote:

How auto convert Variant to required function arguments?



import std.variant;
import std.stdio;

Variant a;

int mul2(Variant b){
    int c = *b.peek!(int);
    return 2*c;
}

int mul3(int b){
return 3*b;
}

void main()
{
    a = 5;
    writeln(mul2(a));

Variant b = 3;
writeln(mul3(*b.peek!int));
}
Uh, probably this is not what you want. I found this thread: 
https://forum.dlang.org/thread/ebylgcrslkelgrvnt...@forum.dlang.org


You man need to use Algebraic.


may*


Re: How auto convert Variant to required function arguments?

2020-10-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 9 October 2020 at 15:49:31 UTC, Ferhat Kurtulmuş wrote:

On Friday, 9 October 2020 at 00:19:20 UTC, Marcone wrote:

How auto convert Variant to required function arguments?



import std.variant;
import std.stdio;

Variant a;

int mul2(Variant b){
    int c = *b.peek!(int);
    return 2*c;
}

int mul3(int b){
return 3*b;
}

void main()
{
    a = 5;
    writeln(mul2(a));

Variant b = 3;
writeln(mul3(*b.peek!int));
}
Uh, probably this is not what you want. I found this thread: 
https://forum.dlang.org/thread/ebylgcrslkelgrvnt...@forum.dlang.org


You man need to use Algebraic.




Re: How auto convert Variant to required function arguments?

2020-10-09 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 9 October 2020 at 00:19:20 UTC, Marcone wrote:

How auto convert Variant to required function arguments?



import std.variant;
import std.stdio;

Variant a;

int mul2(Variant b){
    int c = *b.peek!(int);
    return 2*c;
}

int mul3(int b){
return 3*b;
}

void main()
{
    a = 5;
    writeln(mul2(a));

Variant b = 3;
writeln(mul3(*b.peek!int));
}



Re: How to spawn a thread within a GtkD button event handler

2020-10-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 8 October 2020 at 19:57:12 UTC, Alaindevos wrote:
The idea looked good but gtk was unhave when 1000 labels where 
updated by another thread.


Are you using Idle? If yes, and still having issues? Sorry, I 
cannot help further.


Re: How to spawn a thread within a GtkD button event handler

2020-10-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 8 October 2020 at 19:53:26 UTC, Alaindevos wrote:
I created blindly a thread and this allowed to do stuff in 
background.
But when i passed the mainwindow as argument and did some stuff 
it resulted in,

[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and 
XInitThreads has not been called

[xcb] Aborting, sorry about that.
Assertion failed: (!xcb_xlib_threads_sequence_lost), function 
poll_for_event, file xcb_io.c, line 263.

Program exited with code -6


I put a minimal example here:
https://gist.github.com/aferust/2b469fad974bf8d80ede4db0d0627645


Re: How to spawn a thread within a GtkD button event handler

2020-10-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 8 October 2020 at 17:02:55 UTC, Alaindevos wrote:
One thing I want to do is in an eventhandler of a button 
released event which takes minutes in duration to change the 
state of the statusbar indicating something is going on.
But the statusbar is not redrawn before the evenhandler 
finishes.


Better would be to start a new thread but D-spwawn-threads can 
not call member functions of the MainWindow calls so some 
plumbing with gtk is needed. This thread would coexist with the 
gtk main eventloop. The GTK docs on this look overwhelmingly 
complicated at first.


I am typing on my mobile phone, so cannot give you a whole 
example. Just copied and pasted some existing code of mine. 
İnherit a Thread class:


module downloadservice;

import core.thread;

import std.stdio;

import appwindow;// your window class

class DownloadService : Thread {

	@property bool workingProperty() { return is_working; } // read 
property
@property bool workingProperty(bool value) { return 
is_working = value; } // write property


AppWindow ctx;// access all members of your appwindow
string itag, path, uuid;

this(AppWindow _ctx, string _itag, string _path, string 
_uuid){

ctx = _ctx;
itag = _itag;
path = _path;
uuid = _uuid;
workingProperty = false;
super();
}

private:
bool is_working;

public: 
void run(){

if(this.workingProperty == false){
this.workingProperty = true;

this.ctx.yvid.downloadItem(itag, path, uuid);

this.workingProperty = false;   
}
}
}

...
// İn your app window class
// You don't have to use a thread pool
pool = new ThreadPool((wkr, ctx){
auto worker = cast(DownloadService)wkr;
worker.run();
}, cast(void*)this, 50, false);



Re: How to spawn a thread within a GtkD button event handler

2020-10-08 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 8 October 2020 at 15:59:15 UTC, Alaindevos wrote:
Because when the eventhandler takes to much time the 
application is no longer responsive.
And even a simple redraw request is not performed before ending 
of the thread.
A small and short demo app would nice. Or guideline and 
direction.


If I understand your situation, you want to modify widgets from a 
spawned thread. You cannot do that, but you should send a 
widget-state-change request to the main thread using Idle class.


import glib.Idle;

void aThreadFun(){
new Idle(delegate bool(){

// Modify your widget here. Redraw etc.


return false;
});


}


Re: Trying to create a trivial 64 bit D Lang DLL on a Windows 10 machine and cant get past linking.

2020-10-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 2 October 2020 at 08:33:25 UTC, Imperatorn wrote:
On Friday, 2 October 2020 at 08:07:33 UTC, Ferhat Kurtulmuş 
wrote:

On Friday, 2 October 2020 at 07:34:03 UTC, WhatMeWorry wrote:
On Thursday, 1 October 2020 at 21:56:46 UTC, Ferhat Kurtulmuş 
wrote:

[...]


Yes, I've been doing that.


[...]


The only msvcrt.lib I can find on my Windows 10 machine is:

"C:\Windows Kits\10\Lib\10.0.19041.0\um\x64\ntstc_msvcrt.lib"

Also on Microsoft's docs
https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-library-features?view=vs-2019
 it talks about a ucrt.lib?


Here are the steps I used with success:

in a VCx64 cmd ->
set PATH=%PATH%;D:\dlang\dmd.2.094.0.windows\dmd2\windows\bin64


Did you create a D-partition just for D. Pro


Haha. Yes my c compiler is also located at c:\c


Re: Trying to create a trivial 64 bit D Lang DLL on a Windows 10 machine and cant get past linking.

2020-10-02 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 2 October 2020 at 07:34:03 UTC, WhatMeWorry wrote:
On Thursday, 1 October 2020 at 21:56:46 UTC, Ferhat Kurtulmuş 
wrote:

On Thursday, 1 October 2020 at 21:35:42 UTC, WhatMeWorry wrote:

On Thursday, 1 October 2020 at 20:28:58 UTC, kinke wrote:

[...]



Thanks all. I've gotten it to work with:


[...]



[...]



[...]

total = 12

[...]


1) try running your commands in Visual Studio Native x64 CMD.


Yes, I've been doing that.


2) try link with msvcrt.lib


The only msvcrt.lib I can find on my Windows 10 machine is:

"C:\Windows Kits\10\Lib\10.0.19041.0\um\x64\ntstc_msvcrt.lib"

Also on Microsoft's docs
https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-library-features?view=vs-2019
 it talks about a ucrt.lib?


Here are the steps I used with success:

in a VCx64 cmd ->
set PATH=%PATH%;D:\dlang\dmd.2.094.0.windows\dmd2\windows\bin64

module user;


import std.stdio;

import mydll; // Yes, I imported the dll here

//export { int myAddSeven(int a, int b); }

void main()
{
int total = mydll.myAddSeven(2, 3);
writeln(total);
}
-
module mydll;

export extern(D) {
int myAddSeven(int a, int b) { return a+b+7; }  /* <-- 
function body */

}

---

dmd -m64 -ofmydll.dll  mydll.d  -L/NOENTRY -L/DLL
dmd -m64 user.d mydll.lib



Re: Trying to create a trivial 64 bit D Lang DLL on a Windows 10 machine and cant get past linking.

2020-10-01 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 1 October 2020 at 21:35:42 UTC, WhatMeWorry wrote:

On Thursday, 1 October 2020 at 20:28:58 UTC, kinke wrote:

[...]



Thanks all. I've gotten it to work with:


[...]



[...]



[...]

total = 12

[...]


1) try running your commands in Visual Studio Native x64 CMD.
2) try link with msvcrt.lib


Re: Trying to create a trivial 64 bit D Lang DLL on a Windows 10 machine and cant get past linking.

2020-09-30 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 29 September 2020 at 21:22:21 UTC, WhatMeWorry wrote:

module user;

export { int myAddSeven(int a, int b); }

[...]


it is better to use this template 
https://github.com/dlang/dmd/tree/master/samples/mydll


You don't have a DllMain.


Re: AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 19:37:10 UTC, Per Nordlöw wrote:

On Sunday, 27 September 2020 at 18:39:10 UTC, Per Nordlöw wrote:
How do I defined an AA with class as key where keys are 
compared using `is` instead of `opEquals`? Do I have to store 
the key as a `void*`?


I got a good answer at 
https://dlang.slack.com/archives/C1ZDHBB2S/p1601234030016700


Sorry I did not understand what you meant. It would be better if 
you share the answer here. I found this also 
https://dlang.org/library/std/traits/key_type.html, but I dont 
know if it is related.


Re: AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 18:39:10 UTC, Per Nordlöw wrote:
How do I defined an AA with class as key where keys are 
compared using `is` instead of `opEquals`? Do I have to store 
the key as a `void*`?


By looking at object.d and aaA.d of druntime, I d say you don't 
need to use void*. Object class has required infrastructure ready 
for using classes aa keys (have not tried though). Object class 
has both toHash and opEquals already implemented.





Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 16:39:45 UTC, Ali Çehreli wrote:

On 9/27/20 6:33 AM, Ferhat Kurtulmuş wrote:

> [...]
Kurtulmuş wrote:
>> [...]
wrote:
> [...]
processing
>  [...]

How many flame threads do you need? I thought one image 
processor and one flame thrower, no? Even if you have a dozen 
of each, main can start only the image processing threads and 
then each image processor can start its own flame thrower. 
Then, each pair will have an owner and a worker.


[...]


Thank you Ali (Bey). I will take those into account when 
finalizing my code. Your comments helped a lot!


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Sunday, 27 September 2020 at 12:05:13 UTC, Ferhat Kurtulmuş 
wrote:

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:


Oh, It will work fine if I imitate my time-consuming image 
processing like this.

I think it is Ok now.

import std.stdio;
import std.concurrency;
import core.thread;

void main() {
foreach (v; 0..10){
auto childTid = spawn(, thisTid);
Thread.sleep(10.msecs); // imitate image processing
send(childTid, v);

}
writeln("main is done.");
}

static void spawnedFunc(Tid ownerTid)
{
receive((int v){
Thread.sleep(1500.msecs);
writeln(v);
});
}


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:

> __gshared DList!Entry queue;
> __gshared bool shouldRun = true;

Have you considered passing messages with 
std.concurrency.send() and std.concurrency.receive() and 
friends? You wouldn't need 'queue' because all of your threads 
already have mail boxes to send messages to each other.


> void worker() {
>  while(shouldRun){
>  auto r = queue[];
>  if(!r.empty && queue.back.st < Clock.currTime){
>  writeln(queue.back); // consume the value
> sendPWMSignalToValfe(pwmval)
>  queue.popLastOf(r);
>  }
>  }
> }

It's not clear whether it's only in your test code but 
busy-waiting like that will make your CPU very warm. :) Since 
requests cannot pass each other, your worker thread should have 
something like the following in that loop:


import core.thread;

  Thread.sleep(duration);

Depending on how accurate the operating system honors your 
sleep requests (e.g. is it real-time?), you may want to sleep 
less than 'duration' and then busy-wait the rest of the 
duration. Similar to the difference between spinForce() and 
yieldForce() of std.parallelism (I understand that your 
solution should not involve std.parallelism):


  https://dlang.org/phobos/std_parallelism.html#.Task.spinForce

As an improvement when defining durations, you don't need to 
"hide" units in comments:


// enum afterNmilliseconds = 1500;

// Instead:
enum after = 1500.msecs;

msecs and friends are defined in core.time:

  https://dlang.org/phobos/core_time.html#.dur

Ali


Yes, this solution requires less code and obviously less system 
resources.


void main() {

while (true) {
int v;

"type your value: ".write;
readf(" %d", );

if(v==0){
break;
}

auto childTid = spawn(, thisTid);
send(childTid, v);
}

writeln("main is done.");
}

static void spawnedFunc(Tid ownerTid)
{
receive((int v){
Thread.sleep(1500.msecs);
writeln(v);
});
}

However, there is a big problem now. If I change my main like 
below, numbers are not written at the correct order after 1.5 
seconds?


void main() {
foreach (v; 0..10){
auto childTid = spawn(, thisTid);
send(childTid, v);
}
writeln("main is done.");
}



Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:


Have you considered passing messages with 
std.concurrency.send() and std.concurrency.receive() and 
friends? You wouldn't need 'queue' because all of your threads 
already have mail boxes to send messages to each other.


I remember that your book covers passing messages with send(). 
Probably I will rewrite it using that mechanism, you are right, I 
noticed that when I run the code I can hear the boosted noise of 
my desktop fan.


As an improvement when defining durations, you don't need to 
"hide" units in comments:


// enum afterNmilliseconds = 1500;

// Instead:
enum after = 1500.msecs;

msecs and friends are defined in core.time:

  https://dlang.org/phobos/core_time.html#.dur


Thank you for the tip. That was just a preudo-code to explain my 
situation.


Thanks a lot.
Ferhat




Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 25 September 2020 at 13:37:09 UTC, Steven 
Schveighoffer wrote:


Given the rate and the number of concurrent tasks, I'd say 
threads.


-Steve


Here is my testable and minimal code using 1 extra thread. Thank 
you all!


import core.thread;

import std.stdio;
import std.concurrency;
import std.container.dlist;
import std.datetime;
import std.datetime.systime;

__gshared DList!Entry queue;
__gshared bool shouldRun = true;

struct Entry {
SysTime st;
int val;
}

void main() {

spawn();

while (true) {
int v;

"enter your value: ".write; // 
getFlameIntensityViaImageProcessing()

readf(" %d", );

if(v==0){
shouldRun = false;
break;
}


queue.insertFront(Entry(Clock.currTime + 1500.msecs, v));
}

writeln("main is done.");
}

void worker() {
while(shouldRun){
auto r = queue[];
if(!r.empty && queue.back.st < Clock.currTime){
writeln(queue.back); // consume the value 
sendPWMSignalToValfe(pwmval)

queue.popLastOf(r);
}
}
}


Re: A scheduled control signal with fibers?

2020-09-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 25 September 2020 at 13:13:50 UTC, Sebastiaan Koppe 
wrote:
On Friday, 25 September 2020 at 13:08:16 UTC, Sebastiaan Koppe 
wrote:

On Friday, 25 September 2020 at 11:58:53 UTC, Ferhat Kurtulmuş
How can I implement schedulePWMSignalToValve(pwmval, 
afterNmilliseconds ) using fibers?


No need for fibers per se.


Can also use https://code.dlang.org/packages/timingwheels


I will take a look at that also, thanks.


Re: A scheduled control signal with fibers?

2020-09-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 25 September 2020 at 13:08:16 UTC, Sebastiaan Koppe 
wrote:
On Friday, 25 September 2020 at 11:58:53 UTC, Ferhat Kurtulmuş 
wrote:

[...]


No need for fibers per se.

You can run 2 threads. One that produces {time: now + 
1500.msecs, value: getFlameIntensityViaImageProcessing} objects 
and one that consumes those and basically waits until each's 
msg.time < now and then sendPWMSignalToValfe(msg.value). You 
would basically rely on std.concurrency's MessageBox to do the 
queuing. Although you could do that manually as well.


Could also run it on 1 thread if you don't mind there being a 
jitter of however long getFlameIntensityViaImageProcessing 
takes, but you will need a queue.


That was the first thing I thought. A FIFO queue. I just wanted 
to not reinvent the wheel. So, you guys say go for regular 
threads not fibers. Thank you.


Re: A scheduled control signal with fibers?

2020-09-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Friday, 25 September 2020 at 12:43:41 UTC, Imperatorn wrote:
On Friday, 25 September 2020 at 11:58:53 UTC, Ferhat Kurtulmuş 
wrote:

[...]


A naive implementation would be to store 1500 ms worth of data 
with the pwm values, like a buffer. I guess memory is not a 
problem if you're using a RP3? Then just loop through and yield 
depending on your sample rate (you didn't say what it was)


I didn't measure the entire sample rate yet, but I can say image 
processing (the most costly process) can be done with ~15 FPS.


Re: what's the best way to convert a sysTime to local machine's time (zone)?

2020-09-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Thursday, 24 September 2020 at 22:22:13 UTC, mw wrote:

Hi,

I'm just wondering what's the best way to convert sysTime to 
local machine's time (zone)?


Is there any library function does this already?


https://dlang.org/phobos/std_datetime_systime.html#SysTime

(The time in SysTime is kept internally in hnsecs from 
midnight, January 1st, 1 A.D. UTC.)


Thanks.


This library may help:
https://code.dlang.org/packages/hunt-time


A scheduled control signal with fibers?

2020-09-25 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

Hi,

I have a problem to solve that may be solved using fibers. I have 
no previous experience with fibers. We are working on a 
variable-rate weeder. A camera is installed in front of a 
tractor. A flame weeder is connected to the behind of a tractor. 
Doing image processing (on RP3), we determine a weed density rate 
and send a PWM signal to the LPG valve to adjust the intensity of 
the flame. It is working well under lab conditions so far. 
However, my control signal has to be continuous with a delayed 
time shift. Because the tractor is moving with a ground-speed, 
and the flame applicator will reach the scene seen by the camera 
after about 1.5 seconds (I cannot change the location of the 
camera for some bad and mandatory design decisions). My 
pseudo-code is like:


int main(){
...

while(true){

int pwmval = getFlameIntensityViaImageProcessing();

sendPWMSignalToValfe(pwmval); // I need this streamed 
ctrl signal to the valfe with a delayed time shift


// a possible solution:
// enum afterNmilliseconds = 1500;

// schedulePWMSignalToValve(pwmval, afterNmilliseconds );

...
}
...
}

How can I implement schedulePWMSignalToValve(pwmval, 
afterNmilliseconds ) using fibers?


Thanks in advance.


Re: Neater "not version (...)" ?

2020-09-16 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Wednesday, 16 September 2020 at 17:53:31 UTC, Vladimirs 
Nordholm wrote:

Hello.

I wonder if there is a better way to compile something if the 
current operating system is _not_ a specific platform.


For example, I only want some code to compile if the operating 
system is not Windows. Currently I do this:


version (Windows)
{
}
else
{
// ... my code
}

Is there a neater version of this, like `!version (Windows) { 
/+ ... my code +/ }` ?


Not what you may want, but a dub solution is available.
"excludeSourceFiles-windows" : ["source/someunixcode.d"]


Re: BetterC + WASM Update

2020-09-03 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 1 September 2020 at 20:39:58 UTC, Mike Brown wrote:
Is there an alternative that works with BetterC for dynamic 
arrays?


You may give these a try:
https://github.com/aferust/dvector

For associative arrays: https://github.com/aferust/bcaa



Re: bindbc OpenGL ES

2020-08-31 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 31 August 2020 at 16:56:45 UTC, Danny Arends wrote:
On Monday, 31 August 2020 at 15:16:40 UTC, Ferhat Kurtulmuş 
wrote:

On Monday, 31 August 2020 at 14:04:19 UTC, Danny Arends wrote:

[...]


I have never tried, but this repo may help. I know that it 
supports d.


https://github.com/Dav1dde/glad

You can create your modules online too.
https://glad.dav1d.de/


Thanks, it seems to generate most of the bindings, even though 
the D branch of the repo is 5 years stale.


It doesn't provide an example on how to load them (only c and 
c++), and since the (generated) loader isn't implemented, but 
just an alias to some unknown function:


alias Loader = void* delegate(const(char)*);

I really love to have the bindings in bindbc, due to their nogc 
and nothrow attributes.


It might be a useful addition to make D more compatible with 
the android eco-system


Danny


If you have some super boring time to spent, you can convert 
derelict one to bind-bc. Once I did it for a relatively small 
library (derelict-nanovg -> bindbc-nanovg).




Re: bindbc OpenGL ES

2020-08-31 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 31 August 2020 at 14:04:19 UTC, Danny Arends wrote:
Don't know exactly where to post this, so I hope the bindbc 
team will see the post here in learn.


I was wondering if it would be possible to have bindbc OpenGL 
ES bindings ?


I'm working on porting my 3D Engine to Android, and well 
Android doesn't support anything else but OpenGL ES... I saw 
that derelict has OpenGL ES bindings, but would rather not 
migrate back to using derelict (since it took me a couple of 
hours to migrating everything to bindbc)


Thanks for all your solid bindings and hard work!

Kind regards,
Danny


I have never tried, but this repo may help. I know that it 
supports d.


https://github.com/Dav1dde/glad

You can create your modules online too.
https://glad.dav1d.de/



Re: How do I statically build a project using DUB?

2020-08-29 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 29 August 2020 at 11:27:28 UTC, Kirill wrote:
I need a stand-alone executable that does not require the user 
to install any libraries on their computer. Everything should 
be packed into the executable.


I understand that I need to statically link all of the 
libraries I use in my project, but how do I do this? What do I 
need to add to dub.json file? What compiler flags do I need to 
use?


Thanks in advance.


In dub.json:

"libs": ["exlib1", "exlib2"],

For any libexlib1.a or exlib2.lib, omit the extensions.

You can also do it like:
"lflags": ["-lstdc++"],



Re: I need an Easy example to understand Alias This

2020-07-07 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Tuesday, 7 July 2020 at 00:35:38 UTC, Marcone wrote:
Hi, I study Dlang for one year, and I can't understand alias 
this. I need an Easy example to understand Alias This.


I used it for widget inheritance in my experimental code here,

https://github.com/aferust/noobgui/blob/master/source/widget.d


Re: Postblit segfault.

2020-06-01 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Monday, 1 June 2020 at 06:35:36 UTC, MaoKo wrote:
Hello, I don't understand why this code segfault on 
Linux/FreeBSD:


import std.stdio;
struct _Poc {
  this(this) { writeln("_Poc.this(this)"); }
}
void main() {
  _Poc[1] valueArray = [ _Poc() ];
  writeln(valueArray);
}

I've just defined the postblit function in _Poc to see how much 
it's invoked.

In my system, it's invoked 3 time after the segfault.
When the array is allocated on the heap, nothing happen.
So I guess it's because it's located on the stack but why?

regard.


I cannot help much, but I can say that problem is not about 
postblit. I tried running the code on https://run.dlang.io/. It 
works with LDC but not with DMD. Even though postblit is removed, 
it crashes because there may be a bug with DMD's writeln or there 
is something more that I missed too.


Re: No implicit opOpAssign for structs with basic types?

2020-04-04 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 4 April 2020 at 12:14:23 UTC, Robert M. Münch wrote:

On 2020-04-04 10:32:32 +, Ferhat Kurtulmuş said:


struct S {
 float a;
 float b;

 S opOpAssign(string op)(ref S rhs) if (op == "+"){
 this.a += rhs.a;
 this.b += rhs.b;
 return this;
 }
}


If the struct is from some 3rd party source, how can I add such 
an operator overloading to it? Is it possible to "extend" a 
struct later?


Oh I see what you mean now. In JavaScript you can for instance 
extend Array with an user defined method like;


Array.prototype.insert = function(index) {
...
return this;
};

Of course in d CTFE helps for similar cases. But I am afraid 
operator overloading outside struct/class body is not available 
in D. It would be nice feature though.




Re: No implicit opOpAssign for structs with basic types?

2020-04-04 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Saturday, 4 April 2020 at 10:22:29 UTC, Robert M. Münch wrote:

D doesn't have implicit operators for structs?

struct S {float a, float b};
S a = {1, 5};
S b = {2, 5);

a += b;
Error: a is not a scalar, it is a S

So I really have to write an overloaded operator for such cases?


Probably I didn't understand what you mean. Sorry if this is not 
the case, but this one is easy.

...
struct S {
float a;
float b;

S opOpAssign(string op)(ref S rhs) if (op == "+"){
this.a += rhs.a;
this.b += rhs.b;
return this;
}
}


void main()
{
S a = {1, 5};
S b = {2, 5};

a += b;

writeln(a);
}
...


  1   2   >