Re: Crosscompile to Windows
On Monday, 8 November 2021 at 01:16:25 UTC, rikki cattermole wrote: On 08/11/2021 11:34 AM, Imperatorn wrote: On Sunday, 7 November 2021 at 22:19:08 UTC, russhy wrote: If i remember correctly, all you have to do is: dub build --arch=x86_64-pc-windows-msvc --compiler=ldc2 Is this information on dub.pm? If not, we should add it. This is compiler specific. The arch triple is only supported for ldc. If you tried that with gdc it would error out. It should work with the last version of DMD : https://dlang.org/changelog/2.098.0.html#target
Re: Crosscompile to Windows
On Friday, 5 November 2021 at 18:13:03 UTC, Imperatorn wrote: On Friday, 5 November 2021 at 18:11:35 UTC, Luis wrote: There is a obvious way to crosscompile a dub project to Windows from a Linux dev machine ? Wine Ideally should be something like `dub build -target=x64-windows` or something like. But the dub documentation not say nothing about this.
Crosscompile to Windows
There is a obvious way to crosscompile a dub project to Windows from a Linux dev machine ?
Re: anonymous functions and scope(exit)
On Sunday, 4 July 2021 at 10:07:08 UTC, jfondren wrote: On Sunday, 4 July 2021 at 08:24:36 UTC, Luis wrote: Dennis's explanation makes the most sense: writeln can throw an Exception, so its presence prevents nothrow inference, which otherwise permits the (not intended to be catchable) RangeError to exit without properly unwinding the stack. By that, what you're running into is an unpleasant interaction between 1. scope(exit)s that you're writing 2. Errors being thrown rather than Exceptions 3. anonymous functions getting inferred as nothrow I did https://issues.dlang.org/show_bug.cgi?id=22099
Re: anonymous functions and scope(exit)
On Saturday, 3 July 2021 at 22:52:39 UTC, frame wrote: On Saturday, 3 July 2021 at 22:04:04 UTC, Luis wrote: scope(exit) it's syntactic sugar for a classic `try {} finally {}` . The documentation says that must be executed. It works if you replace printf() with writeln() or use writeln() after. There must be some buffer issue. Not works as you expected. Yes, replacing by writeln (better said, putting a writeln) makes it to work. More weird, if I replace the printf(...) by a fprintf(stderr, ...), I don't get anything. To discard depening on checking if it works by the side effect of writing something on the console, now i using malloc/free and checking with valgrind for a lost memory : ```d #!/usr/bin/env dub /+ dub.sdl: dependency "pijamas" version="~>1.1" +/ import core.exception; import core.stdc.stdio; import core.stdc.stdlib; import std.stdio : writeln; void main() { import pijamas; should(() { int* ptr = cast(int*) malloc(int.sizeof * 1000); try { fprintf(stderr, "Hello\n"); throw new RangeError("bla bla"); } finally { // writeln("Bye 1"); fprintf(stderr, "Bye\n"); free(ptr); } }).Throw!RangeError; } ``` Outputs this : ``` $ f.d Hello ``` And valgrind outputs (using the temporal executable generated by dub on /tmp/.dub/...) : ``` $ valgrind --leak-check=full /tmp/.dub/build/f-\~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f ==18356== Memcheck, a memory error detector ==18356== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==18356== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info ==18356== Command: /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f ==18356== --18356-- WARNING: Serious error when reading debug info --18356-- When reading debug info from /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f: --18356-- DWARF line info appears to be corrupt - the section is too small --18356-- WARNING: Serious error when reading debug info --18356-- When reading debug info from /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f: --18356-- read_filename_table: .debug_line is missing? Hello ==18356== ==18356== HEAP SUMMARY: ==18356== in use at exit: 4,056 bytes in 3 blocks ==18356== total heap usage: 231 allocs, 228 frees, 76,436 bytes allocated ==18356== ==18356== 32 bytes in 1 blocks are possibly lost in loss record 2 of 3 ==18356==at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind ==18356== 4,000 bytes in 1 blocks are definitely lost in loss record 3 of 3 ==18356==at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so) ==18356==by 0x16873D: _D1f4mainFZ9__lambda1FNbZv (f.d:15) ==18356==by 0x168B2F: _D7pijamas9assertion__T9AssertionTPFNbZvZQs__T5ThrowHTC4core9exception10RangeErrorZQBlMFNeAyamZv (assertion.d:602) ==18356==by 0x168724: _Dmain (assertion.d:598) ==18356==by 0x18C962: _D2rt6dmain212_d_run_main2UAAamPUQgZiZ6runAllMFZ9__lambda2MFZv (in /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f) ==18356==by 0x18C804: _D2rt6dmain212_d_run_main2UAAamPUQgZiZ7tryExecMFMDFZvZv (in /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f) ==18356==by 0x18C8DE: _D2rt6dmain212_d_run_main2UAAamPUQgZiZ6runAllMFZv (in /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f) ==18356==by 0x18C804: _D2rt6dmain212_d_run_main2UAAamPUQgZiZ7tryExecMFMDFZvZv (in /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f) ==18356==by 0x18C765: _d_run_main2 (in /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f) ==18356==by 0x18C4C1: _d_run_main (in /tmp/.dub/build/f-~master/application-debug-linux.posix-x86_64-dmd_2097-FB7AFBA927D99FA3DDD7307BACA865DA/f) ==18356==by 0x1687B9: main (entrypoint.d:29) ==18356== ==18356== LEAK SUMMARY: ==18356==definitely lost: 4,000 bytes in 1 blocks ==18356==indirectly lost: 0 bytes in 0 blocks ==18356== possibly lost: 32 bytes in 1 blocks ==18356==still reachable: 24 bytes in 1 blocks ==18356== suppressed: 0 bytes in 0 blocks ==18356== Reachable blocks (those to which a pointer was found) are not shown. ==18356== To see them, rerun with: --leak-check=full --show-leak-kinds=all ==18356== ==18356== For lists of detected and suppressed errors, rerun with: -s ==18356== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0) ``` But the most funny thing, it's that if I remove the comment on the writeln, then just works and the memory leak
Re: anonymous functions and scope(exit)
On Saturday, 3 July 2021 at 20:46:00 UTC, Steven Schveighoffer wrote: On 7/3/21 4:08 PM, frame wrote: On Saturday, 3 July 2021 at 17:39:18 UTC, Steven Schveighoffer wrote: But in practice, the compiler does not have to clean up anything when an `Error` is thrown. Whether it does or not is defined by the implementation. This should be really mentionend in the docs? "Guard", yeah... Yeah, there isn't a good discussion of the differences between Error and Exception on that page. -Steve On [The D Error Handling Solution](https://dlang.org/spec/errors.html#the_d_error_handling_solution), says : If code detects an error like "out of memory," then an Error is thrown with a message saying "Out of memory". The function call stack is unwound, looking for a handler for the Error. Finally blocks are executed as the stack is unwound. If an error handler is found, execution resumes there. If not, the default Error handler is run, which displays the message and terminates the program. scope(exit) it's syntactic sugar for a classic `try {} finally {}` . The documentation says that must be executed.
Re: anonymous functions and scope(exit)
On Saturday, 3 July 2021 at 17:47:47 UTC, Dennis wrote: On Saturday, 3 July 2021 at 17:20:47 UTC, Luis wrote: scope(exit) inside of a anonymous functions, it's never called. I think the compiler infers the function `nothrow` since you don't throw any `Exception`, only an `Error`. Errors represent unrecoverable bugs, after which the program is in an invalid state, so the compiler is free to exit immediately without caring about destructors or `scope(exit)`. Use `Exception` instead of `Error` if you want the stack to properly unwind. Indeed, this is happening. I can reproduce with this : ```d #!/usr/bin/env dub /+ dub.sdl: dependency "pijamas" version="~>1.1" +/ import core.exception; void main() { import core.stdc.stdio; import pijamas; should(() { printf("Hello\n"); scope(exit) printf("Bye\n"); throw new RangeError("bla bla"); }).Throw!RangeError; auto f = () { printf("Hello\n"); scope(exit) printf("Bye\n"); throw new RangeError("bla bla"); }; f(); } ``` Outputs this : ``` $ f.d Hello Hello core.exception.RangeError@bla bla(20): Range violation source/f.d:20 nothrow void f.main().__lambda2() [0x5647d46a17db] source/f.d:22 _Dmain [0x5647d46a1732] Program exited with code 1 ``` If I change the RangeError, by a Exception, then the scope(exit) it's executed.
anonymous functions and scope(exit)
This is intentional ? ``` should(function void() { auto emptyStack = SimpleStack!int(); scope(exit) emptyStack.free; // <= This is never called emptyStack.reserve(16); emptyStack.top; }).Throw!RangeError; ``` scope(exit) inside of a anonymous functions, it's never called.
Re: unit test that show more than one failure
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 understand that where the trivial test code is placed, must be something more complex being tested. @("dummy test 1"); unittest { /// Some test code that runs fine } @("dummy test 2"); unittest { /// Some test code that fails } @("dummy test 3"); unittest { /// Some test code that runs fine } Does (with Silly) : ✓ app dummy test 1 ✗ app dummy test 2 ✓ app dummy test 3 Summary: 2 passed, 1 failed in XX ms If you literary expects that some test runner do what you write... sorry but you will never find it on ANY language (that I know).
Re: Finding the file and unittest that triggers an ICE during dub project build only when unittests are enabled
On Friday, 12 June 2020 at 18:18:25 UTC, Per Nordlöw wrote: When I build my project as dub run --compiler=dmd --build=unittest it crashes as Performing "unittest" build using dmd for x86_64. phobos-next ~master: building configuration "library"... Segmentation fault (core dumped) dmd failed with exit code 139. whereas dub run --compiler=dmd --build=debug passes. How do I most easily track down which unittest in which file that causes the crash? Fails with dub test ?
Re: How debugg unittest with visual code + code-d
On Saturday, 6 June 2020 at 08:42:22 UTC, WebFreak001 wrote: On Saturday, 6 June 2020 at 08:06:02 UTC, Luis wrote: On Friday, 5 June 2020 at 18:13:52 UTC, WebFreak001 wrote: [...] It isn't working correctly on my case : I get this error : Performing "unittest" build using dmd for x86_64. ddiv ~sparseSet: building configuration "unittest"... ../../../.dub/packages/silly-1.0.2/silly/silly.d(15,2): Error: static assert: "Couldn't find 'dub_test_root'. Make sure you are running tests with dub test" dmd failed with exit code 1. The terminal process terminated with exit code: 2 And this works fine if I run a dub test from console. You can change it to { "label": "dub build", // <-- add a good name here "type": "dub", "test": true, "problemMatcher": [ "$dmd" ], "group": "build" } but it will run the unittests then too (not just build them), which will increase the task running time It works! Now, I would try these "natvis"
Re: How debugg unittest with visual code + code-d
On Friday, 5 June 2020 at 18:13:52 UTC, WebFreak001 wrote: To build before running the debugger, add the following task to your task definitions file (Ctrl-Shift-B): { "label": "dub build", // <-- add a good name here "type": "dub", "run": false, "buildType": "unittest", // <-- this makes it build the unittests "problemMatcher": [ "$dmd" ], "group": "build" } It isn't working correctly on my case : I get this error : Performing "unittest" build using dmd for x86_64. ddiv ~sparseSet: building configuration "unittest"... ../../../.dub/packages/silly-1.0.2/silly/silly.d(15,2): Error: static assert: "Couldn't find 'dub_test_root'. Make sure you are running tests with dub test" dmd failed with exit code 1. The terminal process terminated with exit code: 2 And this works fine if I run a dub test from console.
How debugg unittest with visual code + code-d
So I actually managed to "debug" my unittests but It requires that I run previsuly "dub test" on console, so the executable is update. As I understand, I need to setup a task to be prelaunched by debug to generate the unittest executable, but I don't know how setup it correctly. I only manage to build the library, but not the unittest executable. Also, how hell I can see the content of a array on the debugger? I only see the length and "pointer" property. I try to add a watch expression to these pointer with the "@" but the show content, don't matches the real stuff on the array... This it's forcing me to use the old classic "debug with printfs" with it's annoying if you have pure @nogc nothrow annotated code. I have the impression that debugging D has get worse in this last years. I remember debuging with "ddd" with zero issues like five years ago, and now I keep hitting all kind of troubles with anything that I try.
Re: What's the best way to find out which exceptions may be thrown ?
On Wednesday, 27 May 2020 at 10:30:36 UTC, wjoe wrote: Could you please elaborate why checked exceptions are more annoying? Have like 3 functions : A calls B, B calls C . Imagine that now you need to throw a checked exception on C, that before wasn't necessary. You need to add the annoying "throws X" to A and B. And A and B could be on another module or on a different project. Perhaps, the guy that wrote B, was previsor, and putted "throws Exception" (or another generic Exception derived class) on B to avoid problems, but now you have loss the information about the specific Exception that C throws. So again, the compiler can't know what kind of exception could be throwed by A beyond of a generic "Exception" (or another generic exception class). Another workaround, could be wrapping the C throwed exception by a generic exception on B. I work daily with Java, and it's pretty annoying. That the IDE helps you auto putting the throws or suggesting a try/catch, helps. But we ended making some generic exceptions RuntimeExceptions to avoiding the noise and problems that could give checked exceptions.
Re: How to efficiently resolve Associative Arrays not being sorted?
On Tuesday, 2 June 2020 at 07:32:56 UTC, BoQsc wrote: I want to read a file, put it into an array, make some search and replace on the content and output the modified text. However Associative Arrays seem to be unsorted by default. Should I drop the Associative Arrays and use something else? What are the ways to resolve this randomness in Associative Arrays? ReadfileAndCopyContentIntoArray.d import std.stdio; int lineNumber = 0; char[][int] fileInArray; void main(){ File exampleFile = File("exampleText.txt"); foreach(line; exampleFile.byLine){ lineNumber++; fileInArray[lineNumber] ~= line; } writeln(fileInArray); } exampleText.txt The quick brown fox jumps over the lazy dog Sphinx of black quartz, judge my vow. How vexingly quick daft zebras jump! The five boxing wizards jump quickly Maecenas consectetur risus a lacus sodales iaculis. Morbi sed tortor sollicitudin, pharetra massa egestas, congue massa. Sed sit amet nisi at ligula ultrices posuere quis nec est. Mauris vel purus viverra, pellentesque elit id, consequat felis. The Command Prompt Output [6:"Morbi sed tortor sollicitudin, pharetra massa egestas, congue massa.\r", 7:"Sed sit amet nisi at ligula ultrices pos uere quis nec est.\r", 2:"Sphinx of black quartz, judge my vow.\r", 3:"How vexingly quick daft zebras jump!\r", 1:"The q uick brown fox jumps over the lazy dog\r", 8:"Mauris vel purus viverra, pellentesque elit id, consequat felis.", 5:"Maec enas consectetur risus a lacus sodales iaculis.\r", 4:"The five boxing wizards jump quickly\r"] As can be seen in the Command Prompt Output, the array is not ordered correctly. It goes: 6: 7: 2: 3: 1: 8: 5: 4: Instead of 1: 2: 3: 4: 5: 6: 7: 8: Associative arrays looks that uses internally a hash map. Hash maps are unordered. The ouput order, looks that is the result of where the hash algorithm it's inserting the key/value pair in the hashmap. If you need order, you need to use a TreeMap (D std lib, emsi_containers and containersd have TreeMap implementations) or something like Java LinkedHashMap if order by insertion it's enough.
Re: Logging best practices
On Sunday, 31 May 2020 at 20:04:11 UTC, mw wrote: Thanks. For the colored console logger, I'm using this one: https://code.dlang.org/packages/colored-logger so far so good. (I prefer to use library, instead of reinvent my own wheels :-). I dind't know that exists.
Re: Logging best practices
On Saturday, 30 May 2020 at 18:17:21 UTC, mw wrote: A related question: how to log to multiple destinations? e.g. both console & log file? any examples? Thanks. ```D auto multiLogger = new MultiLogger(); multiLogger.insertLogger("console", new FileLogger(stdout, LogLevel.all)); multiLogger.insertLogger("file", new FileLogger(outputFile, LogLevel.all)); sharedLog = multiLogger; ``` If you are missing color output for log level , you can use this ConsoleLogger ```D import std.experimental.logger; /// Extends FileLogger to log only to stdout and colorize log level class ConsoleLogger : FileLogger { import std.concurrency : Tid; import std.datetime.systime : SysTime; import std.format : formattedWrite; this(const LogLevel lv = LogLevel.all) { import std.stdio : stdout; super(stdout, lv); } /* This method overrides the base class method in order to log to a file without requiring heap allocated memory. Additionally, the `FileLogger` local mutex is logged to serialize the log calls. */ override protected void beginLogMsg(string file, int line, string funcName, string prettyFuncName, string moduleName, LogLevel logLevel, Tid threadId, SysTime timestamp, Logger logger) @safe { import std.string : lastIndexOf; ptrdiff_t fnIdx = file.lastIndexOf('/') + 1; ptrdiff_t funIdx = funcName.lastIndexOf('.') + 1; auto lt = this.file_.lockingTextWriter(); systimeToISOString(lt, timestamp); colorizeLogLevel(lt, logLevel); formattedWrite(lt, " %s:%u:%s ", file[fnIdx .. $], line, funcName[funIdx .. $]); } private void colorizeLogLevel(Writer)(auto ref Writer lt, LogLevel logLevel) @safe { import std.conv : to; auto logLevelStr = logLevel.to!string; switch (logLevel) { case LogLevel.all: formattedWrite(lt, " [\033[1;37;40m%s\033[0m] ", logLevelStr); break; case LogLevel.trace: formattedWrite(lt, " [\033[1;37;40m%s\033[0m] ", logLevelStr); break; case LogLevel.info: formattedWrite(lt, " [\033[1;32;40m%s\033[0m]", logLevelStr); break; case LogLevel.warning: formattedWrite(lt, " [\033[1;33;40m%s\033[0m] ", logLevelStr); break; case LogLevel.error: formattedWrite(lt, " [\033[1;31;40m%s\033[0m] ", logLevelStr); break; case LogLevel.critical: formattedWrite(lt, " [\033[1;37;41m%s\033[0m]", logLevelStr); break; case LogLevel.fatal: formattedWrite(lt, " [\033[1;25;37;41m%s\033[0m] ", logLevelStr); break; default: formattedWrite(lt, " [\033[1;37;40m%s\033[0m] ", logLevelStr); } } } ```
opEquals @safe is ignored
Lets take this example code (https://run.dlang.io/is/Vkpx9j) : ´´´D import std; void main() { } class ExampleC { int x; this (int x) @safe { this.x = x; } override bool opEquals(Object o) const @trusted { if (ExampleC rhs = cast(ExampleC)o) { return this.x == rhs.x; } return false; } } @safe unittest { auto c = new ExampleC(1); assert(c != new ExampleC(23)); } ´´´ dmd ignores @trusted or @safe on opEquals, throwing this error : onlineapp.d(27): Error: @safe function onlineapp.__unittest_L24_C7 cannot call @system function object.opEquals An override @system or @trusted function can't be @safe, or I it a bug ? Also, how will this be affected by DIP1028 ?
Re: Storing a reference to the calling object
On Saturday, 23 May 2020 at 09:27:46 UTC, Tim wrote: Hi all, I'm a little new to D and I'm wondering how I can store a reference to the calling object. I want to create a reference to an object's parent so that each time I go to update the sprite, it is able to grab its position from the parent. So if I have: class Sprite{ /// Postional components of the sprite int* x, y; SDL_Surface* image_surface; auto parent; this(const char* path, auto parent){ writeln(*x); this.parent = parent; } void update(){ // Copy loaded image to window surface writeln("Sprites x: ", *x); SDL_Rect dstRect; dstRect.x = parent.x; dstRect.y = parent.y; SDL_BlitSurface(image_surface, null, g_surface, ); } } And call it like so: sprite = new Sprite(path, this); How can I make this sort of thing work? Thanks a lot in advance for the help! For example using a interface or a base class ```D interface IBaseInterface { int x(); void x(int newX); int y() void y(int newY); ... } class Parent : IBaseInterface { private int x, y; int x() { return this.x; } void x(int newX) { this.x = newX; } int y() { return this.y; } void y(int newY) { this. y = newY; } ... void f() { auto sprite = new Sprite("foo/bar/sprite.png", this); ... } } class Sprite{ IBaseInterface parent; ... this(const char* path, IBaseInterface parent){ writeln(*x); this.parent = parent; } void update(){ // Copy loaded image to window surface writeln("Sprites x: ", *x); SDL_Rect dstRect; dstRect.x = parent.x; dstRect.y = parent.y; SDL_BlitSurface(image_surface, null, g_surface, ); } } ```
Why emsi containers have @disabled this(this) ?
So, I'm writing my own implementation of sparse sets, and I take as reference emsi_containers for allocator usage. I saw that they have disabled 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 ) Taking a look to std.container.array, I see that it have postblit disabled, but here the range interface isn't implemented. Instead it's recommended to do a slice, where apply range algorithms. I should take this way (ie. forgot to implement front and popFront)? I actually have postblit disabled and implemented InputForward, but as I say, this make it useless as range. I need, like std.container.array, to use slice for do a foreach or any range algorithm.
Re: D, Unit_Threaded, and GtkD
On Sunday, 17 May 2020 at 10:19:38 UTC, Russel Winder wrote: I am experimenting with using manual control of the Glib event loop using the pending and iteration methods on the default MainContext within each unit- threaded test. The alternative of running a GTK application and then putting the tests in as an asynchronous sequence only works with Rust and Python since D has no coroutines of any sort. A Fiber can't be used for this ? D Fibers don't have a scheduler. Yielding returns to the caller context. https://dlang.org/phobos/core_thread_fiber.html
DUB Registry
There is a way to make to ignore some branchs and tags? Actually it's pretty annoying when someone publish a fork, and spams with "does not match the original package name" on older tags.
Re: Optional type parameter on a template
On Tuesday, 12 May 2020 at 20:40:35 UTC, Adam D. Ruppe wrote: A default argument of void is a common way to do it template foo(T = void) { static if(is(T == void)) { not given } else { use T } } Perfect! Works as I desired.
Optional type parameter on a template
I'm trying to make a SparseSet that on function of a optional type parameter, could alongside the index set, store other data. So I need a way to declare a optional type template parameter. I prototyped this stuff on run.dlang, but I like know if there is a better way : https://run.dlang.io/is/Uhy5IT import std; struct S { int x = 0; string toString() { return "S(x="~ x.to!string ~")"; } } struct ZeroOrMore(T = uint, Types...) if (__traits(isUnsigned, T)) { static assert (Types.length == 0 || Types.length == 1); T[] _t; static if (Types.length > 0) { alias V = Types[0]; V[] _values; void ins(T t, V val) { this._t ~= t; this._values ~= val; } } else { void ins(T t) { this._t ~= t; } } } void main() { auto s = ZeroOrMore!()(); // trying to use ZeroOrMore() gives error : struct onlineapp.ZeroOrMore cannot deduce function from argument types !()(), candidates are: onlineapp.d(12): ZeroOrMore(T = uint, Types...) s.ins(456); auto s2 = ZeroOrMore!(uint, S)(); s2.ins(123, S(666)); writeln(s); // ZeroOrMore!uint([456]) writeln(s2); // ZeroOrMore!(uint, S)([123], [S(x=666)]) }
Re: Optional type parameter on a template
Sorry ... wrong link. This is the correct : https://run.dlang.io/is/D2iCP0
Re: Integration tests
On Wednesday, 22 April 2020 at 10:32:48 UTC, Russel Winder wrote: I ended up creating the following project structure: . ├── dub.sdl ├── dub.selections.json ├── source │ ├── arcam_protocol.d │ └── main.d ├── tests │ └── integration_tests.d └── test_support └── mock_avr850 └── main.d with the following Dub control file: name "arcamclient" description "arcamclient is a Rust/gtk-rs/GTK+ desktop application to control an Arcam amplifier over the Ethernet connection." authors "Russel Winder" copyright "Copyright © 2020 Russel Winder." license "GPL-3.0" targetType "executable" targetPath "bin" configuration "application" { } configuration "unittest" { targetName "arcamclient_test" dependency "unit-threaded" version="*" mainSourceFile "bin/ut.d" excludedSourceFiles "source/main.d" preBuildCommands "$DUB run --compiler=$$DC unit-threaded -c gen_ut_main -- -f bin/ut.d -d $DUB" preBuildCommands "$DUB build arcamclient:mock_avr850" importPaths "tests" sourcePaths "tests" } subPackage { name "mock_avr850" targetName "mock_avr850" targetType "executable" targetPath "bin" sourcePaths "source" "test_support/mock_avr850" importPaths "source" "test_support/mock_avr850" excludedSourceFiles "source/main.d" } This seems a bit more sensible that what I have been able to achieve with Rust, but is still second rate compared to how easy things are using Python. Have you try Silly? I found far more straightforward to use, that unit-threaded. On my pet game engine, I got it working with this : "configurations": [ ... { "dependencies": { "beep": "~>0.0.2", "silly": "~>1.0.2" }, "name": "unittest", "targetType": "library" } ], Sadly, Silly only is the test runner (and one far prettier that unit-threaded). I need to add separated dub module to make assertion more easy and fluent. Beep go on the correct path with a API like this : @("My test") unittest { myFunc(1, 2, 3).expect!equals(42); auto a = [1, 2 ,3]; a.expect!contains(2); a.lenght.expect!great(0); true.expect!true(); } And the output on case of fail, shows a human friendly message with the expected value and the real value. Another assertion module that not depends on unit-threaded and have better API, is pyjamas . But actually is abandoned. I did a try to get it working again, but depends on another dead dub module... another test runner called "bed" (that I did a PR to fix it to get it working against the actual DMD version). Finally... What I really miss are two things : - A test/integration framework like Spock (Yeah, I professionally work on Java world :( ) - Test runners had a common output format that make IDE/tools work far more easy. See https://github.com/nomad-software/dunit/issues/19#issuecomment-435209223 Offtopic: Should be a way to mark a dub module dead on dub register. This last weeks I don't stop of finding dead/not working stuff and given a really bad image of the state of D.
Re: Force usage of double (instead of higher precision)
On Thursday, 29 June 2017 at 12:00:53 UTC, Simon Bürger wrote: Thanks a lot for your comments. On Wednesday, 28 June 2017 at 23:56:42 UTC, Stefan Koch wrote: [...] This is only happening on CTFE ? Enforcing to use the old 8086 FPU for any float/double operation would give a lot performance penalty on any modern CPU.
Re: Speed up `dub`.
On Tuesday, 8 March 2016 at 15:43:28 UTC, rcorre wrote: On Monday, 7 March 2016 at 22:47:13 UTC, Luis wrote: I try to grab dstep with dub fetch step (dub version 0.9.24, built on Aug 19 2015, on Ubuntu), and try to run dub build step. I can confirm that on my machine takes around 5 seconds to check if the dependencies are update. I had this same experience. Thought dub would be a convenient way to install dstep, but dub run took so long I ended up just creating an alias to run the binary directly. dub not should have something to install executables without the need of using dub run to execute it ? Like pip install does a true install of the package.
Re: Speed up `dub`.
On Monday, 7 March 2016 at 18:58:55 UTC, ciechowoj wrote: dub --version DUB version 0.9.24+161-gb9ce700, built on Feb 23 2016 `dub.json` is `dub.json` of dstep `dub test --skip-registry=all` Do not helps. I try to grab dstep with dub fetch step (dub version 0.9.24, built on Aug 19 2015, on Ubuntu), and try to run dub build step. I can confirm that on my machine takes around 5 seconds to check if the dependencies are update.
Re: Speed up `dub`.
On Monday, 7 March 2016 at 09:18:37 UTC, ciechowoj wrote: I'm using `dub` to build project. And every time I run `dub` it seems to check if dependencies are up to date, which takes some time. Is there a way to switch of that checking? Or any other way to speed up building process? It really slows down my modify-compile-check iteration time. On my case, I don't see taking too long. Could you check what version of dub are you using, and what OS & D compiler and version ? And better, if you can past here your dub.sdl/dub.json .
Re: Formatting a string on a variadic parameter function without using GC
On Wednesday, 2 March 2016 at 04:12:13 UTC, Mike Parker wrote: On Wednesday, 2 March 2016 at 01:39:13 UTC, David G. Maziero wrote: Consider the following function: void RenderText( FontBMP font, int x, int y, const char* text ) { for( int r=0; text[r]!='\0'; ++r ) { You're asking for trouble here. There's no guarantee that any D string is going to be null terminated. String literals are, but beyond that, all bets are off. char[256] text; sprintf( [0], "Player: pos:%.3f - speed:%.3f", player.position, player.speed ); Instead of sprintf, look into using std.format.sformat [1] (see below). It's equivalent to std.format.format, but allows you to provide a buffer. RenderText( font, 0, 0, cast(char*)text ); It's considered bad form to cast an array to a pointer like this. If you need a pointer to an array, just use the ptr property: text.ptr. Always be aware of the null terminator situation, though, when passing to C. I could simply do "RenderText(font,0,0,"FPS: "~to!string(fps));" Won't compile without using the .ptr property (or casting, which again, you shouldn't do). Moreover, you run into the null terminator problem. "FPS :" will be null terminated because it's a literal, but the string produced by concatentating it with the result of to!string would not be. Read https://dlang.org/spec/arrays.html#strings and try to use std.string.toStringz (http://dlang.org/phobos/std_string.html#.toStringz)
Re: How to better organize dub project to get 3 exe from same codebase?
On Thursday, 25 February 2016 at 20:55:33 UTC, Suliman wrote: On Thursday, 25 February 2016 at 19:09:59 UTC, Suliman wrote: Where to store shared classes? { "name": "123", "authors": [ "Suliman" ], "description": "A minimal D application.", "copyright": "Copyright © 2016, Suliman", "license": "proprietary", "subPackages": [ { "name": "App1", "description": "App1", "targetType": "executable", "sourcePaths": ["source/App1"] }, { "name": "App2", "description": "App2", "targetType": "executable", "sourcePaths": ["source/App2"] }, { "name": "App3", "description": "App3", "targetType": "executable", "sourcePaths": ["source/App3"] } } Should I link from subPackages to general source/ folder ? I don't link nothing. I have some shared D source code files between the 3 files (on src/dcpu). So each subpackage generates a executable file, excluding the not common files of the other subpackages. It isn't the best way of doing this, but just works for my case. Eventually i would change this. I think that alphaPhobos does what you are asking : https://github.com/rikkimax/alphaPhobos/blob/master/dub.sdl
Re: Dynamic pitch shift
On Wednesday, 24 February 2016 at 11:17:27 UTC, Tanel Tagaväli wrote: Sorry for the confusing state of the codebase. Only the saw wave generator is currently functional, the `saw` and `sine` functions are not used and should be left out of analysis. Also, audio output is only to ALSA. Be careful with naive wave generators. You could get very funny artefacts from aliasing. You should try one of this approximations : - Correct naive wave generator : Use furrier composition to build the wave (ie, sum i=1->n An*sin(Wn*t + phase)), On this case, should drop of the sumatory the sin that generate armonics >= (Niquist freq)/2 This way, at least should be enough for sound testing, but isn't very efficient. See for example (C++) this Square wave generator against OpenAL (It needed some tweaks about just what you asked on the first post. The phase wasn't correct, but was enough for me on these moment) : https://github.com/Zardoz89/trillek-vcomputer-module/blob/78c9dd7bf0ead23cb9a8ccf29fd30c9d0ed7e2e5/tools/src/AlEngine.cpp#L210 - Wavetables - band-limited resampling algorithm aka BLIP or BLEP algorithms (See http://www.cs.cmu.edu/~eli/L/icmc01/hardsync.html and http://slack.net/~ant/libs/audio.html#Blip_Buffer )
Re: Why this code can't take advantage from CTFE?
On Friday, 5 February 2016 at 09:36:37 UTC, Andrea Fontana wrote: On Wednesday, 3 February 2016 at 22:45:47 UTC, Timon Gehr wrote: I would use enum forceCTFE(alias expr)=expr; though. With alias it won't force compile-time evaluation of expressions that can be interpreted as symbols. I've a code that build a JSON object using a wrapper over std.json. This code: enum forceCTFE(alias expr)=expr; auto j = forceCTFE!( JSOB ( "hello", JSOB("world", 3), "arr", JSAB("hello", JSOB("world", 1)) ) ); j.put("/hello/world", "!"); j.put("/hello/blah", 42); // Here j == {"arr":["hello",{"world":1}],"hello":{"blah":42,"world":"!"}} Reading/parsing a JSON or a XML using std.json / std.xml could be done on CTFE ?
Re: DUB, Platform specifications and dependencies
On Monday, 30 November 2015 at 20:27:51 UTC, Zardoz wrote: On Monday, 30 November 2015 at 16:54:43 UTC, Sönke Ludwig wrote: Am 24.11.2015 um 19:51 schrieb Zardoz: Platform specifications are currently not supported for dependencies due to the way the dependency resolver works. However, it is possible to use platform specific configurations for this purpose: Thanks!! I ended doing some minor change to get it working : subPackage { name "lem1802" description "Visual LEM1802 font editor" excludedSourceFiles "src/bconv.d" excludedSourceFiles "src/ddis.d" configuration "nogtk" { targetType "executable" targetName "lem1802" platform "windows" libs "gtkd" } configuration "gtk" { targetType "executable" targetName "lem1802" platform "posix" dependency "gtk-d:gtkd" version="~>3.2.0" } } I just updated dmd / dub from the APT repository . This is doing something very weird now. Every time that I do a "dub build dedcpu:lem1802" on Ubuntu 15.10 , dub try to execute the "nogtk" configuration that is Windows only!
Re: why the sort result is different with C#
On Friday, 22 January 2016 at 06:53:29 UTC, mzf wrote: D code: auto arr = ["b1=1", "b=2","a1=1", "a=2"]; writeln(arr.sort()); output:["a1=1", "a=2", "b1=1", "b=2"] C# code: var arr = new string[]{ "b1=1", "b=2", "a1=1", "a=2" }; Array.Sort(arr); output:["a=2","a1=1","b=2","b1=1"] I don't what string sorting criteria is using C#, but '9' < '=', so should be ["a1=1", "a=2", "b1=1", "b=2"]
Re: cairo(D) / x64 / unresolved externals / don't know why
On Monday, 11 January 2016 at 06:53:51 UTC, Benjamin Thaut wrote: Out of curiosity, why do you pass "-m64" 6 times to dmd? Once would be enough. I saw VisualD (dub generated project file) doing that with the latest version of Visual Studio comunnity, when I change to 64 bit building.
Re: issue porting C++/glm/openGL to D/gl3n/openGL
On Sunday, 10 January 2016 at 06:35:34 UTC, rsw0x wrote: On Sunday, 10 January 2016 at 02:51:57 UTC, WhatMeWorry wrote: Just translating some simple C++/glm/opengl tutorial code to D/gl3n/opengl and I'm coming across more friction than I expected. I've got a square centered at my window which is rotated by 45 degrees (counter clockwise) and then moved to the lower right quadrant. [...] iirc, gl3n uses row major and glm uses column major ordering just pass GL_TRUE to the transpose argument in glUniformMatrix4fv If you like to check an D lib for vector/matrix/quaterntion operations that uses column major ordering (ie, not need to transpose), see this : https://github.com/Zardoz89/zmath Was just my D2 learning pet project... I never checked if it was math correct, and I don't updated in a lot of time (5 years ago), plus there isn't documentation beyond comments and a few unit-tests, so use at your risk. But at least I know that was working correctly with Derelict2 when I wrote it. Perhaps I should retake this...
Re: issue porting C++/glm/openGL to D/gl3n/openGL
On Monday, 11 January 2016 at 10:04:29 UTC, Luis wrote: On Sunday, 10 January 2016 at 06:35:34 UTC, rsw0x wrote: On Sunday, 10 January 2016 at 02:51:57 UTC, WhatMeWorry wrote: Just translating some simple C++/glm/opengl tutorial code to D/gl3n/opengl and I'm coming across more friction than I expected. I've got a square centered at my window which is rotated by 45 degrees (counter clockwise) and then moved to the lower right quadrant. [...] iirc, gl3n uses row major and glm uses column major ordering just pass GL_TRUE to the transpose argument in glUniformMatrix4fv If you like to check an D lib for vector/matrix/quaterntion operations that uses column major ordering (ie, not need to transpose), see this : https://github.com/Zardoz89/zmath Was just my D2 learning pet project... I never checked if it was math correct, and I don't updated in a lot of time (5 years ago), plus there isn't documentation beyond comments and a few unit-tests, so use at your risk. But at least I know that was working correctly with Derelict2 when I wrote it. Perhaps I should retake this... I just remember why I never retake this ... Use gl3n, row-major math operations outperforms a lot, if you are doing any matrix multiplication on CPU side ( http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/ )
Re: CMake support for D
On Sunday, 3 January 2016 at 17:30:15 UTC, Dibyendu Majumdar wrote: Does CMake recognise D in the enable_language command? If not is there a workaround? Thanks and Regards Dibyendu I suggest use dub instead of cmake. I did a try to use cmake some time ago (a few years ago, before dub), and was a nightmare to get ir working on GNU/Linux and Windows. With dub , simply works fine with a simple json file.
Re: Threading to prevent GUI Freeze
On Monday, 4 January 2016 at 14:31:04 UTC, TheDGuy wrote: Hello, i use GTKD to draw some stuff on a DrawingArea. Because it needs some time to calculate i want to outsource those calculation so that the GUI doesn't freeze. I tried it with "std.concurrency" like this: bool drawCallback(Scoped!Context cr, Widget widget){ writeln("init"); spawn(, cr, widget); return true; } void render(Context cr, Widget widget){ Renderer renderer = new Renderer(new Vector3D(0,0,0), cr, widget); int i = 0; while(i < 4){ renderer.renderOneStep(); i++; } renderer.DisplayResult(); } But i get: "std.concurrency.spawn(F, T...)(F fn, T args) if(isSpawnable!(F,T))" "Error: template std.concurrency.spawn cannot deduce function from argument types!()(void delegate(Context cr, Widget widget), Scoped Widget), candidates are:" Before doing anything with threads and GTK, you should read this : http://blogs.operationaldynamics.com/andrew/software/gnome-desktop/gtk-thread-awareness
Re: Set color to a single point in Cairo
On Sunday, 20 December 2015 at 01:17:50 UTC, Basile B. wrote: On Saturday, 19 December 2015 at 14:16:23 UTC, TheDGuy wrote: is it possible to set the color of a single pixel with Cairo? Not like you would do with a classic canvas (2d grid), because colors are applied with `cairo_fill()` and `cairo_stroke()` on a particular path. but you can define a path that represents a single pixel and fill it: ``` cairo_rectangle (cr, x, y, 1, 1); // 1 pix rectangle cairo_set_source_rgba (cr, 0, 0, 0, 1); // color cairo_fill (cr); // fill the rectangle with source rgba ``` However cairo is node made to be used like this. The workflow is usually more based on stacked layers (1 layer = 1 path) with different filling, different transparency. I did something similar here : https://github.com/Zardoz89/DEDCPU-16/blob/master/src/lem1802_fontview.d#L287 I need to clean these code...
Re: optlink windows warning 178
On Thursday, 26 November 2015 at 11:00:28 UTC, SpacenJasset wrote: Hello, I am trying to build against the version 3.2.1 of gtk bindings in the dub repository. The build system has built the gtkd-3.lib library file, but doesn't not appear to want to link it to anything else. It gets stuck forever linking, but issues this warning: ..\..\Users\J.Spashett\AppData\Roaming\dub\packages\gtk-d-3.2.1\gtkd-3.lib Warning 178: .LIB pagesize exceeds 512 I had the same issue a few weeks ago : https://github.com/gtkd-developers/GtkD/issues/133 On my case optlink crashes instead of getting stuck. What I end doing is following the "Windows instructions" of his wiki, and build by hand with dmd . I try instruct to dub, on windows, to not grab gtkd from dub repository and use directly gtkd-3.lib that I precompiled, but I don't have any success (And I asked how fix this on this forum, here : http://forum.dlang.org/thread/begtftarmwztbiqfu...@forum.dlang.org )