Re: I like dlang but i don't like dub
On Friday, 18 March 2022 at 04:13:36 UTC, Alain De Vos wrote: Dlang includes some good ideas. But dub pulls in so much stuff. Too much for me. I like things which are clean,lean,little,small. But when i use dub it links with so many libraries. Are they really needed ? And how do you compare to pythons pip. Feel free to elaborate. Long story short, dub isn't needed. If you prefer pulling dependencies and compiling them by hand nothing is stopping you. As for comparison to pip, I'd say that dub compares favourably actually. Yes, it does do more than pip, and that used to annoy me. But if you look at it from the stance of a user it makes sense: when you pull dependencies or a package using pip you expect to be able to run them immediately. Python isn't a compiled language, but D is and to get these packages and dependencies to be run immediately it needs to do more than pip: download dependencies, manages their version and compile them. This last part is the reason for most of the added complexity to dub IMHO.
Re: I need an Easy example to understand Alias This
On Tuesday, 7 July 2020 at 00:44:32 UTC, Marcone wrote: On Tuesday, 7 July 2020 at 00:42:40 UTC, Ali Çehreli wrote: On 7/6/20 5:35 PM, 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. Is the following example useful? http://ddili.org/ders/d.en/alias_this.html Ali I can't undestand it. I need a simple example. This only scrapes the surface, but it should give an idea of the core mechanics and why it's regarded as an important concept. import std.stdio; struct Fruit { string name; } struct ColoredFruit { Fruit _fruit; alias _fruit this; string color; } void printColoredFruit(ColoredFruit f) { writeln(f.color, " ", f.name); } void printGeneralFruit(Fruit f) { writeln(f.name); } void main(string[] args) { ColoredFruit banana; banana.color = "yellow"; // It's a normal struct for its non-alias members banana.name = "banana"; // We can interact with internal fields directly // This function accepts a ColoredFruit so the whole banana is passed. printColoredFruit(banana); // > yellow banana // This function only doesn't accept a ColoredFruit, but it does accept a // Fruit and we have a Fruit alias this so the internal _fruit is passed. printGeneralFruit(banana); // > banana }
Re: Program exited with code -11 when calling
On Wednesday, 1 July 2020 at 05:04:28 UTC, Anthony wrote: I'm trying to convert this c function: bson_t *bson_new_from_json (const uint8_t *data, ssize_t len, bson_error_t *error); Into a D function. This is my attempt: extern(C) { struct bson_t; struct bson_error_t; bson_t* bson_new_from_json(const uint8_t* data, long len, bson_error_t* error); } However when I try it, for example: auto str_utf8 = str.toUTF8(); bson_error_t error auto bson = bson_new_from_json(cast(const uint8_t*)str_utf8.ptr, -1, &error); I get a "Program exited with code -11" message. Does anyone know what I'm doing wrong? Thanks I don't know the exact function you are trying to use, but -11 means "segmentation fault" on linux. This means that your program is trying to read or write a memory location that it is not supposed to. This typically happens during buffer overflows and similar memory corruption bugs. One thing that jumps to me is the -1 in your call instead of the length. Without knowing the C function's implementation I would expect it to mean either "read before the array" which would be a buffer overflow or to have the special meaning of "deduce the string size yourself". In that last case I would expect bson_new_from_json to expect a NUL-terminated array, but I don't know if your UTF8 array is NUL-terminated.
Re: weekly news?
On Wednesday, 22 January 2020 at 18:53:49 UTC, mark wrote: Is there a "D weekly news" I could do an email subscription to? Or at least a way to get notified by email when a new item appears on https://dlang.org/blog/ ? There's http://dpldocs.info/this-week-in-d/Blog.html which is unofficial but interesting and weekly. AFAIK there's no newsletter but it provides a RSS feed. Otherwise I think the easiest is to use the fact that this forum isn't a forum but a newsgroup (hence available by mail) to subscribe to Announce. Blog entries in particular are announced there.
Re: Speed of Random Numbers
On Saturday, 3 August 2019 at 16:35:34 UTC, Giovanni Di Maria wrote: Hi to everybody I am doing some experiments about random numbers. I need "extreme speed" for the generation for numbers from 1 to 8. Generating 500_000_000 numbers with this code: - import std.stdio, std.array, std.random; void main() { byte c; writeln("Start"); for(int k=1;k<=500_000_000;k++) c=uniform!ubyte() % 8 +1; //<<< === RANDOM writeln("Stop"); } - I get these results: c=uniform!ubyte() % 8 +1; ==>>> Execution time: 15.563 s c=cast(byte)uniform(1, 9); ==>>> Execution time: 24.218 s Do you know other faster functions or methods to generate random numbers? For me the "goodness of random" is NOT important. Thank you very much GIovanni Di Maria To what extent isn't the quality of randomness important to you? Your posts reminds me of the way Doom (the original) did it for things like enemy behaviour and shot dispersion: they generated a static table of 256 random numbers once and any time they needed a random byte they just picked the next in the table. They didn't have any security or sciency concern and just wanted to provide a different game each time so that worked well for them. You won't find anything faster than that I think.
Re: Question on Password Encryption, using stdlib or third party lib
On Monday, 29 July 2019 at 14:37:54 UTC, 0x wrote: On a project I was asked to a- Compute SHA-256 of a password b- Do a BigInteger, convert to Hex String c- Encrypt the key using a public key with the following parameters Entropy: I'm given some numbers Modulus: also given long numbers [encrypt using RSA algorithm] So far I'm familiar with a and b in Dlang. how do I go about c) In Dlang ? Thanks I hope it's for a school project since I wouldn't recommend doing that in production. However you can do c) either by implementing RSA (it's rather easy to badly implement RSA which could be enough at school level) or by using a library (I recommend the library). There are several cryptographic libraries on https://code.dlang.org that implement RSA, botan and crypto for example. I'd trust botan more at the moment though I don't think any D library has received a proper cryptographic audit at the moment.
Re: To learn D
On Friday, 5 July 2019 at 12:00:15 UTC, Binarydepth wrote: I've considering learning full D. I remembered that D is not recommended as a first language, So I read time ago. So my question, is learning C and Python a good intro before learning D? TY Both C and Python provide valuable and complementary experience no matter what you want to do. If your goal is specifically to learn D then I'd learn C up to structures. That way you'll have basic tools and vocabulary that you can reuse in D and you can learn the rest as you go. The things that will be hard if you want to learn D directly: - not as many examples and tutorials on the internet (although there are some very good ones) - lots of concepts and vocabulary (always remember that you *don't* have to know every detail of the language, learn what you need to solve the problem at hand, one thing at a time) - not as many libraries, which means that it can be harder to solve a problem that not many people have had yet (popular things like web applications will be alright) I think D isn't that bad of a first language. Once you've passed the vocabulary barrier you'll get the benefit of having a language that'll fit most of your tasks from little scripting or web applications to low-level programming and big projects. You will be confronted to many concepts and ideas without having to learn a new language each time and this knowledge is useful even if you decide to use another language later on.
Re: Closures and memory allocation
On Saturday, 22 June 2019 at 19:26:13 UTC, Cym13 wrote: On Saturday, 22 June 2019 at 16:52:07 UTC, Anonymouse wrote: [...] Clearly this is a good time for you to learn about the tools D offers to profile allocations. There is the --profile=gc DMD argument that you can use but here there's something better: DMD's GC has a few hooks that are directly inside druntime and therefore available to any D program. [...] Ooops, sorry I went a bit fast there, --DRT-gcopt gives you the number of collections, not allocations.
Re: Closures and memory allocation
On Saturday, 22 June 2019 at 16:52:07 UTC, Anonymouse wrote: I'm looking into why my thing does so many memory allocations. Profiling with kcachegrind shows _d_allocmemory being called upon entering a certain function, lots and lots of times. It's a function that receives concurrency messages, so it contains nested functions that close over local variables. Think receiveTimeout(0.seconds, &nested1, &nested2, &nested3, ...) with 13 pointers to nested functions passed. When entering the following function, does it allocate: 1. 0 times, because while there are closures defined, none is ever called? 2. 2 times, because there are closures over two variables? 3. 20 times, because there are 20 unique closures? Clearly this is a good time for you to learn about the tools D offers to profile allocations. There is the --profile=gc DMD argument that you can use but here there's something better: DMD's GC has a few hooks that are directly inside druntime and therefore available to any D program. Putting your above code in test.d you can then do: $ dmd test.d $ ./test --DRT-gcopt=profile:1 Number of collections: 2 Total GC prep time: 0 milliseconds Total mark time: 0 milliseconds Total sweep time: 0 milliseconds Max Pause Time: 0 milliseconds Grand total GC time: 0 milliseconds GC summary:1 MB,2 GC0 ms, Pauses0 ms <0 ms And here is your answer: two allocations. More information about --DRT-gcopt there: https://dlang.org/spec/garbage.html
Re: make C is scriptable like D
On Thursday, 20 June 2019 at 06:20:17 UTC, dangbinghoo wrote: hi there, a funny thing: $ cat rgcc #!/bin/sh cf=$@ mycf=__`echo $cf|xargs basename` cat $cf | sed '1d' > ${mycf} gcc ${mycf} -o a.out rm ${mycf} ./a.out $ cat test.c #!/home/user/rgcc #include int main() { printf("hello\n"); } And then, chmod +x test.c ./test.c output hello. is rdmd implemented similarly? thanks! binghoo Basically, yeah.
Re: Where can find fix length array memory layout document
On Wednesday, 19 June 2019 at 05:27:12 UTC, lili wrote: On Tuesday, 18 June 2019 at 17:29:49 UTC, Cym13 wrote: On Tuesday, 18 June 2019 at 17:25:42 UTC, Cym13 wrote: On Tuesday, 18 June 2019 at 13:05:03 UTC, lili wrote: On Tuesday, 18 June 2019 at 12:39:45 UTC, Dennis wrote: [...] Thanks a lot, where is a core.stdcpp.array , How to user it? I test but get a error ``` auto aa = array!(int, 4); //error ``` Please don't shorten your code or errors to the point where there's hardly any information left: it's hard to help you if we can't know what you did and what went wrong. Forgot to say that it's probably because you don't actually build an array here, try adding parentheses: ``` auto aa = array!(int, 4)(); ``` array!(int,4)(); compile occurs a error say: no overload matches for array Did you import it properly? ``` void main() { import core.stdcpp.array; auto a = array!(int, 4)(); } ``` compiles and runs without issue for me. You'll have to show your code if you want people to help you there.
Re: Where can find fix length array memory layout document
On Tuesday, 18 June 2019 at 17:25:42 UTC, Cym13 wrote: On Tuesday, 18 June 2019 at 13:05:03 UTC, lili wrote: On Tuesday, 18 June 2019 at 12:39:45 UTC, Dennis wrote: [...] Thanks a lot, where is a core.stdcpp.array , How to user it? I test but get a error ``` auto aa = array!(int, 4); //error ``` Please don't shorten your code or errors to the point where there's hardly any information left: it's hard to help you if we can't know what you did and what went wrong. Forgot to say that it's probably because you don't actually build an array here, try adding parentheses: ``` auto aa = array!(int, 4)(); ```
Re: Where can find fix length array memory layout document
On Tuesday, 18 June 2019 at 13:05:03 UTC, lili wrote: On Tuesday, 18 June 2019 at 12:39:45 UTC, Dennis wrote: On Tuesday, 18 June 2019 at 12:26:14 UTC, lili wrote: [...] I'm assuming you mean writeln([1].sizeof). An array literal is a slice of a dynamic array (which is length + pointer, so 2*size_t size). A fixed size array has to be declared as a local / member variable, and then the content is on the stack: ``` int[10] a; writeln(a.sizeof); // 40 writeln(a[].sizeof); // 16 on 64-bit or 8 on 32-bit ``` To get a static array literal, you can use the library function staticArray: ``` import std.array; writeln([1, 2, 3].staticArray.sizeof); // 12 ``` Thanks a lot, where is a core.stdcpp.array , How to user it? I test but get a error ``` auto aa = array!(int, 4); //error ``` Please don't shorten your code or errors to the point where there's hardly any information left: it's hard to help you if we can't know what you did and what went wrong.
Re: What does ! Stand for in map! and filter! function calls?
On Sunday, 2 June 2019 at 15:48:54 UTC, Rnd wrote: I have recently started using Dlang, hence this basic question. Thanks for your insight. To know more about D you should take the time to do the D tour [1] which provides you with general knowledge of most of D's functionalities and vocabulary. To know more about templates specifically, check out this tutorial [2]. [1]: https://tour.dlang.org/ [2]: http://nomad.uk.net/articles/templates-in-d-explained.html
Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?
On Thursday, 23 May 2019 at 09:09:05 UTC, BoQsc wrote: This code of D creates a dummy 47,6 MB text file filled with Nul characters in about 9 seconds import std.stdio, std.process; void main() { writeln("Creating a dummy file"); File file = File("test.txt", "w"); for (int i = 0; i < 5000; i++) { file.write("\x00"); } file.close(); } While GNU coreutils dd can create 500mb dummy Nul file in a second. https://github.com/coreutils/coreutils/blob/master/src/dd.c What are the explanations for this? If you're talking about benchmarking it's important to provide both source code and how you use/compile them. However in that case I think I can point you in the right direction already: I'll suppose that you used something like that: dd if=/dev/zero of=testfile bs=1M count=500 Note in particular the blocksize argument. I set it to 1M but by default it's 512 bytes. If you use strace with the command above you'll see a series of write() calls, each writting 1M of null bytes to testfile. That's the main difference between your code and what dd does: it doesn't write 1 byte at a time. This results in way less system calls and system calls are very expensive. To go fast, read/write bigger chunks. I may be wrong though, maybe you tested with a bs of 1 byte, so test for yourself and if necessary provide all informations and not just pieces so that we are able to reproduce your test :)
Re: is there a way to embed python 3.7 code in D program?
On Sunday, 12 May 2019 at 20:06:34 UTC, torea wrote: Hi, I'd like to use D for the "brain" of a small robot (Anki vector) whose API is coded in Python 3.6+. I had a look at Pyd but it's limited to python 2.7... Would there be other ways to call python functions and retrieve the python objects (including camera image) inside a D program? Best regards If pyd doesn't work you still have the option to use python's C interfaces (it has many). Write your D program normally, provide extern(C) functions as an interface and have python call those. There are some caveats but lots of resources exist on calling C from python and calling D from C. I haven't checked but it's also probable that this is how pyd does it, have a look if you want to reproduce its functionalities. Pyd is easier to use, but it's not the only way.
Re: [windows] Can't delete a closed file?
On Friday, 10 May 2019 at 15:06:46 UTC, Temtaime wrote: Lol, you don't have to load and unload the curl dll. std.net.curl have its own lazy libcurl loader. But i'm not sure if it tries to find the dll in the temp directory. If it is the case, then it simply doesn't unload the dll when you have called some function from it. As I said it's more about the general idea of bundling DLLs in than libcurl itself, but even in that case it doesn't search the temp directory for it. Besides, if it did, it would be a pretty important vulnerability.
Re: In what situation can new Struct() return null?
On Friday, 10 May 2019 at 10:11:51 UTC, faissaloo wrote: My program contains the following statement: auto newChildNode = new Node(); In debugging I have found that this pointer evaluates to null, what could cause this? I should have plenty of memory, my only other idea is some sort of heap corruption. Could you share a complete, concise, compilable example demonstrating that bug? One line is rather short to understand what's happening.
Re: [windows] Can't delete a closed file?
On Friday, 10 May 2019 at 07:09:45 UTC, Seb wrote: On Thursday, 9 May 2019 at 13:18:44 UTC, Cym13 wrote: On Thursday, 9 May 2019 at 13:02:51 UTC, Rene Zwanenburg wrote: On Thursday, 9 May 2019 at 12:33:37 UTC, Cym13 wrote: [...] You could try to use the find handle function in Process Explorer to figure out what process has the file open: https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer I did just that and my test program truly is the only process on the system having that file open. Unless I'm missing something that process-explorer doesn't see and is even true in wine's ultra light environment comprised of a single process, this is definitely not the issue. Which C runtime are you using? The old and buggy DigitalMars one or the official MS one? I really don't know, how can I find out? I litterally just used dmd on the script above with no special options then ran the resulting exe.
Re: [windows] Can't delete a closed file?
On Thursday, 9 May 2019 at 15:05:10 UTC, Andre Pany wrote: Can you reproduce the issue with other Dlls or is it only reproducible with curl dll? Does the issue with curl dll also exists if you do not call the curl function? Kind regards Andre I didn't have the time to test with another dll just yet but in that specific case the issue disappears if I don't call its functions. That's interesting.
Re: [windows] Can't delete a closed file?
On Thursday, 9 May 2019 at 13:02:51 UTC, Rene Zwanenburg wrote: On Thursday, 9 May 2019 at 12:33:37 UTC, Cym13 wrote: On Thursday, 9 May 2019 at 11:31:20 UTC, Cym13 wrote: ... To dismiss any doubt about AV or other processes coming into play I took the binary and ran it with wine on linux with the exact same end result. For reference my windows system is a 64b windows 10. You could try to use the find handle function in Process Explorer to figure out what process has the file open: https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer I did just that and my test program truly is the only process on the system having that file open. Unless I'm missing something that process-explorer doesn't see and is even true in wine's ultra light environment comprised of a single process, this is definitely not the issue.
Re: [windows] Can't delete a closed file?
On Thursday, 9 May 2019 at 11:31:20 UTC, Cym13 wrote: ... To dismiss any doubt about AV or other processes coming into play I took the binary and ran it with wine on linux with the exact same end result. For reference my windows system is a 64b windows 10.
Re: [windows] Can't delete a closed file?
On Thursday, 9 May 2019 at 11:07:53 UTC, Andre Pany wrote: On Thursday, 9 May 2019 at 10:09:23 UTC, Cym13 wrote: Hi, this is likely not related to D itself but hopefully someone can help me with this since I'm rather new to windows programming, I mainly work on linux. I'm trying to bundle a DLL in a binary, write it in a temp folder, use it and remove the dangling file. [...] I can't explain the behaviour, but you could store the temp file name in a string array and remove these file in the module destructor. That's the way how dub handles temp files/folders. https://github.com/dlang/dub/blob/master/source/dub/internal/utils.d#L98 Kind regards Andre No luck there.
Re: [windows] Can't delete a closed file?
On Thursday, 9 May 2019 at 11:11:56 UTC, Rumbu wrote: Since deploying a dll is a suspect behaviour outside a normal installation process, most probably you have a lock on the file put by windows defender or an antivirus if installed. Thanks for your input but I'm absolutely certain that it's not related to AV since I made sure to test in an AV-free environment (and I'd expect AV to kick in before loading the DLL, but I may be wrong on that). FreeLibrary doesn't guarantee that the dll file is closed, maybe other windows processes are accessing it (like prefetch). Anyway, you are deploying a dll just to read a file, It's over engineering, use WinAPI UrlDownloadToFile instead or any other winapi functions. Well, that's just a test script, it's feature or DLL doesn't matter.
[windows] Can't delete a closed file?
Hi, this is likely not related to D itself but hopefully someone can help me with this since I'm rather new to windows programming, I mainly work on linux. I'm trying to bundle a DLL in a binary, write it in a temp folder, use it and remove the dangling file. So far I have the following file: import std; void main(string[] args) { import core.runtime; static immutable libcurl = import("libcurl.dll"); import std.file: write; auto libpath = tempDir.buildPath("libcurl.dll"); libpath.write(libcurl); auto libcurlMem = rt_loadLibrary(libpath.toStringz); import std.net.curl; "https://dlang.org/".byLine.count.writeln; rt_unloadLibrary(libcurlMem); remove(libpath); } Compiled with: dmd.exe -Jlibdir test.d It almost work, I can write, load and use the library, but when it comes to removing it nothing works. std.file.FileException@std\file.d(1045): C:\users\cym13\Temp\libcurl.dll: Access denied. 0x00402377 in EntryPoint 0x00413BC7 in EntryPoint 0x00413B49 in EntryPoint 0x004139E3 in EntryPoint 0x0040B77F in EntryPoint 0x7B4754C2 in call_process_entry 0x7B477FC6 in ExitProcess 0x7B4754CE in call_process_entry I tried using an explicit File handle to explicitely close the file after writing to it but that doesn't change anything. I'm pretty sure I'm missing something basic about the way windows handles open files but I don't know what, could someone explain why this doesn't work the way I expect it to?
Re: Erasing passwords from ram?
On Monday, 6 May 2019 at 09:34:22 UTC, Dukc wrote: Oops, I forgot to check back this theard. But yes, just the info I was looking for. On Wednesday, 1 May 2019 at 22:14:52 UTC, Cym13 wrote: There are very few relevant threat models where removing a password from RAM is an adequate solution. Not an adequate solution... What else is usually needed? You can't mean hashing, because by definition one would not want to delete the password in the first place, if there weren't hashes made of it. I'd rather focus on mitigating that threat by keeping boundchecking on, writing @safe code etc. I do. I was just curious if doing this trick brings any practical extra safety. (By what I understood from your reply, yes with operating systems or password managers but not generally with servers, unless trying to guard it from it's maintainers) And I'm also going to try to follow Walter's safety tip number 1: never assuming the server won't crash. I'm going to make an automatic restarter process for it. The thing is, the most important concept in security is the threat model: what are you protecting against? There is no security without a threat model, protecting your data without first knowing from what makes absolutely no sense, so that question is paramount. Then we compare the cost of a successful attack and the benefit one gets from that attack: if the attacker can make a profit it's not secure. If the defense cost is greatly superior to the value of your asset it's not well spent and those resources should most likely be spent protecting against something else. From what I understand your threat model is that of a remote attacker finding a vulnerability leaking memory in a heartbleed fashion then finding credentials in that leaked memory providing access to sensitive resources. That's a rather constrained scenario which is good, but it's also a very rare scenario. Very few memory issues lead to memory leakage, especially while providing a way to control what is leaked. Memory corruption vulnerabilities (I include out-of-bound reading) generally either result in a crash or can be exploited for code execution. If an attacker has code execution on your server the impact is bigger than that of memory disclosure and erasing credentials from memory doesn't mitigate that. But those bugs are way more common than controlled memory disclosure. However the solutions to memory corruptions are the same whether you're trying to protect against code execution or memory disclosure. So what I'm trying to say is that, given your threat model, it does not seem relevant to protect against memory disclosure specifically: you want to protect against the larger and more common threat of memory corruptions and that happens to cover your current threat model. Unless what you want to protect is very very sensitive erasing passwords from memory would most likely be wasted time. But that's something that only you can assess.
Re: Erasing passwords from ram?
On Tuesday, 30 April 2019 at 08:15:15 UTC, Dukc wrote: I am currently programming a server. So I got the idea that after I've generated all the hashes I need from a password, I want to erase it from RAM before discarding it, just to be sure it won't float around if the server memory is exposed to spyware by some buffer overflow. Is this wise caution, or just being too paranoid? And if it is worthwhile, do I have to do this: ``` foreach(ref part; cast(ubyte[]) rootPassword) volatileStore(&part, 0); ``` Or, can I rely on that the compiler won't optimize this out? ``` rootPassword[] = '\0' ``` `rootPassword` is allocated on the heap, but only locally referred to. There are very few relevant threat models where removing a password from RAM is an adequate solution, I'm not sure it's worth the trouble. For comparison one case where it's considered important is removing the master password from a password manager from RAM to prevent another person finding the computer unlocked to recover it by memory inspection (which it would have the rigth to do since the process would be from the same user). That's quite specific and a server isn't nearly as exposed. That said, if you want to remove it, make sure to audit all functions that use it from the moment it enters memory to check that they don't make a copy for some reason (or use a type that doesn't allow copies). It's no use removing it at one place if it's still at another. In particular a pattern I see often is that you have a function that reads the password from a file/stdin/whatever onto the stack and sets on the heap the object you'll use throughout the program then returns. You will think of checking the use of that object, but may forget to clear the setter's buffer before returning leaving it in a stack's frame. You should also make sure that your compiler isn't recognizing that this part of memory isn't used later and optimizing away the overwrite call. This is lots of work for a vulnerability that should not be there and may not lead to memory disclosure even if it is present. I'd rather focus on mitigating that threat by keeping boundchecking on, writing @safe code etc.
Re: Does D have a tool like pySnooper?
On Monday, 22 April 2019 at 16:24:53 UTC, Taylor Hillegeist wrote: Saw this tool and thought D could probably do something like this pretty easily. Is there such a tool out there already? https://github.com/cool-RR/pysnooper Or would this not be easy at all with D? First line of that link: "PySnooper is a poor-man's debugger". I don't think it is possible to do what PySnooper does at runtime without significantly changing the code you write to accomodate it, D and Python are just structured too differently. However I see no advantage in having something like PySnooper either because D has real debuggers. Using gdb you can do everything that pysnooper does, dynamically and with the corresponding lines of code. You also get much much more such as memory inspection, memory modification, disassembly or the magical ability to rewind time from a crash. PySnooper is nice for python, but I fail to see any advantage over a real debugger in D.
Re: Chat using Socket and Thread
On Tuesday, 23 April 2019 at 22:02:59 UTC, Allison wrote: How to make a chat for several users chat? Using socket and thread. First of all, there are many tutorials on the internet covering that exact topic for different languages. I don't think there are many tutorials for D, but you should definitely be able to understand the concepts and translate them, the vocabulary and strategy is the same. It's possible to guide you through the creation of such a chat but it sounds like a school exercise and if so you'll only benefit by trying them yourself as much as possible. So what did you try? What is your strategy? What didn't work? Where are you blocked? Why are you trying to do that in the first place?
Re: Future of D language
On Wednesday, 24 April 2019 at 05:22:35 UTC, Arjunkumar wrote: I am title bit confuse about learning D Lang and is it well good for future point of view. Currently in a market many of language is present, so why people learn D Lang and any site which provide best tutorials for D Lang? The reason I use D is because I like having one language that I can use for most tasks without having to worry that I might have to switch to another language later. If I need something low level I can do C-like programming and interface easily with C libraries. If I need something high level I can do that, if I want more safety guarantees that I'm not writing bugs D can help with that, if I need to port a program from another language D is likely to support its style already so porting is easier, producing executables for linux or windows is very easy, etc. Is it the best at something? I don't know, probably not, but it's good enough at everything that I can use it without worrying too much about the futur of my project. It's not all perfect though, the language itself is quite big and growing, bugs exists (well, what project doesn't have bugs?) and library support is not as extensive as some other langages. But it served me well so far.
DRuntime arguments
Where can I find a list of all druntime arguments supported? Things like --DRT-covopt='merge:1' or --DRT-gcopt='gc:profile=1' are not easy to guess and I can't find any centralized documentation.
Re: Iterate/sort associative array by value?
On Sunday, 7 April 2019 at 15:41:51 UTC, Robert M. Münch wrote: I have an AA int[ulong] and would like to traverse the AA from biggest to smallest by value. Is there an elegant way to do this? The only way I can imagine is to create an "reverse" AA of the form ulong[int] and than sort by keys. Traverse this AA and use the value as the lookup key in the orginial array. But this feels all a bit wired... You could use sort to gather the indexes in order then traverse from there: aa.byKey.array.sort!((a, b) => aa[a]With a wrapper caching that order and making it transparent as well as update on insertion (which should be in log(n) since you know have an ordered list of indexes, you can use dichotomy to update the indexes without walking all your AA again) I think you could have a nice little container. However if double entry is necessary maybe a simpler 2D array would be easier to work with?
Re: Why does D language do not support BigDecimal type?
On Monday, 11 March 2019 at 15:23:34 UTC, BoQsc wrote: There is Money datatype that can be provided by using a third party package: https://code.dlang.org/packages/money But that's only for money, what about math? Why such fundamental as BigDecimal is still not included into the D language itself? There is BigInt. If it is unavoidable to use Floating point, how can I quickly and simply understand the rules of using float to make the least error, or should I just find a third party package for that as well? There is an article on that, but it is not that straight forward: https://dlang.org/articles/d-floating-point.html Basically any thing that I find on Google, that include explaining floating point are badly written and hard to understand for the outsider lacking ability to understand advanced concepts. How much precision is enough in your use case? There's always a limit to how precise you need to be and how precise you can be, be it only because our memory is finite. I've never had a use case for BigDecimal myself, so forgive my ignorance, but wouldn't you get the exact same result by using BigInt? For example, if you need 20 decimals of precisions then any value times 10^20 will be a BigInt on which you can work, it's just a matter of displaying it correctly when outputing the result but it doesn't change the operations you have to perform. Is there anything that can't be done with BigInt really?
Re: Executing a D script without an [extension in the filename] leads to an error
On Friday, 1 March 2019 at 11:38:51 UTC, BoQsc wrote: On Friday, 1 March 2019 at 09:27:33 UTC, Cym13 wrote: On Friday, 1 March 2019 at 09:00:43 UTC, BoQsc wrote: I've installed D compiler, and when i try to run a D script with filename without an extension/file type named: program via: ./program I'm getting and error: vaidas@SATELLITE-L855:~/Desktop$ ./program Error: module `program` is in file './program.d' which cannot be read import path[0] = . import path[1] = /snap/dmd/49/bin/../import/druntime import path[2] = /snap/dmd/49/bin/../import/phobos Failed: ["/snap/dmd/49/bin/dmd", "-v", "-o-", "./program.d", "-I."] Now, when I rename my scirpt file : program To: program.d and execute it by: ./program.d I no longer have an error. Is this an intended behaviour? In such questions it's important to show your shebang since that's what runs your script. Given your symptoms I guess you're using the following: #!/bin/env rdmd And indeed rdmd won't call your script if it doesn't have the proper extension. Try using this instead: #!/bin/dmd -run The shebang I used: #!/usr/bin/env rdmd I was visiting Dlang Tour and that's where I've got an example of shebang usage, directly from there: https://tour.dlang.org/tour/en/welcome/run-d-program-locally#/on-the-fly-compilation-with-rdmd The shebang you suggested actually works perfectly: #!/bin/dmd -run "And indeed rdmd won't call your script if it doesn't have the proper extension." Then why does Dlang Tour includes shebang: #!/usr/bin/env rdmd Instead of the one you mentioned, that is fool proof. (#!/bin/dmd -run) Is that an error/mistake in Dlang Tour guide? Frankly using rdmd is closer to being fool-proof, you just haven't hit the corner cases yet :) I'd either get used to having scripts with a .d extension or make an alias or a quick wrapper in shell and call it "program": #!/bin/sh exec rdmd /path/to/program.d "$@" It's not exactly a mistake, it's just not that important to most people I guess. And as your program grows you're likely to take the habit to compile it and work with the binary directly anyway.
Re: Executing a D script without an [extension in the filename] leads to an error
On Friday, 1 March 2019 at 14:50:45 UTC, Jesse Phillips wrote: On Friday, 1 March 2019 at 11:38:51 UTC, BoQsc wrote: "And indeed rdmd won't call your script if it doesn't have the proper extension." Then why does Dlang Tour includes shebang: #!/usr/bin/env rdmd Instead of the one you mentioned, that is fool proof. (#!/bin/dmd -run) Is that an error/mistake in Dlang Tour guide? You may want to change that too: #!/bin/dmd -i -run DMD doesn't automatically compile imported files (at least not until -i came along), rdmd existed to solve that problem... I don't know what value it brings with the -i switch existing. All systems I know only accept one argument in shebang so sadly it's not that simple :)
Re: Executing a D script without an [extension in the filename] leads to an error
On Friday, 1 March 2019 at 09:00:43 UTC, BoQsc wrote: I've installed D compiler, and when i try to run a D script with filename without an extension/file type named: program via: ./program I'm getting and error: vaidas@SATELLITE-L855:~/Desktop$ ./program Error: module `program` is in file './program.d' which cannot be read import path[0] = . import path[1] = /snap/dmd/49/bin/../import/druntime import path[2] = /snap/dmd/49/bin/../import/phobos Failed: ["/snap/dmd/49/bin/dmd", "-v", "-o-", "./program.d", "-I."] Now, when I rename my scirpt file : program To: program.d and execute it by: ./program.d I no longer have an error. Is this an intended behaviour? In such questions it's important to show your shebang since that's what runs your script. Given your symptoms I guess you're using the following: #!/bin/env rdmd And indeed rdmd won't call your script if it doesn't have the proper extension. Try using this instead: #!/bin/dmd -run
Re: Process Information
On Saturday, 23 February 2019 at 20:49:49 UTC, r-const-dev wrote: Is there a way to get information about the current process? Memory usage, CPU usage, PID. The PID is easy, from std.process it's a standard function call away: https://dlang.org/phobos/std_process.html#.thisProcessID I don't think there is anything in phobos about memory or cpu usage. If you're on GNU/Linux you can probe /proc/self/stat and /proc/self/status to get that information, I don't know about windows.
Re: Should D file end with newline?
On Sunday, 10 February 2019 at 02:12:43 UTC, Jonathan M Davis wrote: On Saturday, February 9, 2019 2:19:27 PM MST Victor Porton via Digitalmars- d-learn wrote: ISO C++ specifies that the C++ file must end with a newline. Should D file end with newline, too? No, there is no need to end D files with a newline. I would guess that the vast majority of D files end with a closing brace. I just looked at a bunch of files in the standard library for the heck of it, and almost all of the ones I looked at ended with a closing brace. And those that didn't ended with something like an enum declaration and not a newline. Personally, I don't leave newlines at the end of files, because it looks messy. I don't even recall doing that in C++, though I do recall that there supposedly be a rule about it. It seems like a pretty bizarre requirement to me, but regardless, I'm quite sure that D does not have that requirement. - Jonathan M Davis If you used a text editor or IDE to write that final closing brace then I'm pretty confident it does add the newline character at the end. That won't result in an empty line on display. Try using an hex editor to check if you're curious.
Re: Prime number
On Thursday, 2 August 2018 at 14:37:56 UTC, Greatsam4sure wrote: On Thursday, 2 August 2018 at 09:35:20 UTC, Cym13 wrote: On Thursday, 2 August 2018 at 08:30:05 UTC, Greatsam4sure wrote: I know D is very powerful from my little experience. What is the idiomatic way to get prime numbers say from 1-30 without using loops(outer and inner loop). Can map, filter, fold etc in algorithm be use. Pls show some code with chain call. I can easily achieve even numberd and odd numbers using filter. But prime numbers I have to use 2loops. I will appreciate any help,just a newbie in D Denis' answer is good but I'd like to add that the idiomatic D solution is to use whatever tool is the most adequate to solve the issue. If two loops is more natural it wouldn't make much sense to force yourself to use range functions (even though I'd obviously understand that stand to learn to use them). Thanks, I like the idea of using helper function from algorithm module to do the magic instead of loops. I want to know How To optimize it to efficient. I will appreciate any help. Computing prime numbers efficiently would require something more complex like an Atkin sieve which I doubt will be very easy to implement without loop. That said, to start optimizing without changing the algorithm you can profile your code with -profile to see where you're spending time that you can shave off and rewrite the code to accelerate those parts. You should really start by changing the algorithm though. I will also appreciate a link to a comprehensive tutorial on the algorithm module. The documentation did not give me all the help I needed Not specifically on the algorithm module but I'd recommend reading [1] for a good intro to D from basics to advanced topics. For algorithms especially, I'd recommend reading on templates [2] and ranges [3]. Especially one thing you should know to understand the concepts behind most range-based functions is that most of them try to work on infinite sequences of things and therefore make assumptions only about the first items and never about the last ones. That's why functions like std.algorithm.find don't just return the element or its position but the sub-sequence starting at that element. There are exceptions though, and this comment may not make much sense at first so feel free to ignore it for the moment, but hopefully it'll come back to you when you need it. [1]: https://ddili.org/ders/d.en/index.html [2]: https://ddili.org/ders/d.en/templates.html [3]: https://ddili.org/ders/d.en/ranges.html
Re: Prime number
On Thursday, 2 August 2018 at 08:30:05 UTC, Greatsam4sure wrote: I know D is very powerful from my little experience. What is the idiomatic way to get prime numbers say from 1-30 without using loops(outer and inner loop). Can map, filter, fold etc in algorithm be use. Pls show some code with chain call. I can easily achieve even numberd and odd numbers using filter. But prime numbers I have to use 2loops. I will appreciate any help,just a newbie in D Denis' answer is good but I'd like to add that the idiomatic D solution is to use whatever tool is the most adequate to solve the issue. If two loops is more natural it wouldn't make much sense to force yourself to use range functions (even though I'd obviously understand that stand to learn to use them).
Re: Dynamic arrays / ~= giving an exception...
On Sunday, 1 July 2018 at 20:55:16 UTC, Robert M. Münch wrote: I'm a bit puzzled because I think this is pretty straight forward but doesn't work... struct mystruct { myPtr* root; opApply(...){ myPtr*[] childs; childs ~= root; ... } } foreach(node; mystruct(myRoot)){ ... } It compiles but the line with ~= gives the nice "bing" under Windows and the application hangs... What doesn't this work? Could you maybe provide a compilable example?
Re: Zip vs Enumerate
On Wednesday, 20 June 2018 at 04:40:42 UTC, Cym13 wrote: On Wednesday, 20 June 2018 at 03:44:58 UTC, Jordan Wilson wrote: [...] This sounds like a very limited case: if you're not zipping against a iota(foo) then there's no comparing with enumerate, they simply don't do the same thing at all, and if you are then it sounds like enumerate expresses the purpose of using an index way better than a zipped iota IMHO. Is there anything about your true use case that would be worth mentionning to better understand your situation? My bad, I didn't read your example thoroughly enough.
Re: Zip vs Enumerate
On Wednesday, 20 June 2018 at 03:44:58 UTC, Jordan Wilson wrote: Hello, Idiomatically, I make use of zip, however, when looking to speed up my program, notice that using enumerate leads to a 20-30% improvement: void main(){ auto x = iota(1_000).array; auto y = iota(1_000).array; auto func1() { return zip(x,y).map!(a => a[0]+a[1]) .array; } auto func2() { return x.enumerate .map!(a => a.value + y[a.index]) .array; } assert(func1.equal(func2)); import std.datetime.stopwatch; auto r = benchmark!(func1, func2)(10_000); // r[0] approx 1794 ms // r[1] approx 1295 ms } Is there anything I can do to improve zip, before I go ahead and change to the faster but slightly less readable enumerate? In my particular case, all ranges that I zip are of the same length, but not sure how I can leverage that information. Thanks, Jordan This sounds like a very limited case: if you're not zipping against a iota(foo) then there's no comparing with enumerate, they simply don't do the same thing at all, and if you are then it sounds like enumerate expresses the purpose of using an index way better than a zipped iota IMHO. Is there anything about your true use case that would be worth mentionning to better understand your situation?
Re: Create a List or Dictionary.
On Tuesday, 19 June 2018 at 05:52:00 UTC, Sunny wrote: On Monday, 18 June 2018 at 13:23:37 UTC, Cym13 wrote: Yes, this is what need, thank you very much for your help. :-) [...] I recommend that you take the D tour if you can, it explains all those fundamental features quite well I think. https://tour.dlang.org/
Re: Create a List or Dictionary.
On Monday, 18 June 2018 at 11:44:43 UTC, Sunny wrote: Hello, I'm having a problem, how can I create a List or Dictionary in D? In C #, I can create a tuple list, example: var musicList = new List <(string URL, string Artist, string Title, string Cover, string Duration)> (); In Google did not find anything, tell me please how to get out of this situation? If I read you well it seems the simplest equivalent code would be: struct MusicItem { string URL; string Artist; string Title; string Cover; string Duration; } MusicItem[] musicList; You could technically use tuples to get to the same point but I don't really see a point, structs fit that purpose very well. Then you can: musicList ~= MusicItem(url, artist, title, cover, duration); musicList = [musicItem1, musicItem2]; or for dictionnaries: MusicItem[string] musicDictionnary = [ "shortID1": MusicItem(foo, bar, baz, bak, biz, sub), "shortID2": MusicItem(foo, bar, baz, bak, biz, sub), ]; etc.
Re: WTF! new in class is static?!?!
On Thursday, 7 June 2018 at 21:07:26 UTC, DigitalDesigns wrote: class A; class B { A a = new A(); } auto b1 = new B(); auto b2 = new B(); assert(b1.a == b2.a)!! I'm glad I finally found this out! This is not typical behavior in most languages is it? I'd expect it to be translated to something like class B { A a; this() { a = new A(); } } In C# it is different, can't remember if it is different in C++. This has caused bugs in my code because the fields are all pointing to the same data when I expected them to each have unique data ;/ This method is error prone and the behavior should be reversed, it should not break the majority of code. If one wants the current behavior then static new could be used or something else. The spec looks pretty clear to me on that point https://dlang.org/spec/class.html#field-init Besides, defining behaviour at construction is what constructors are for, I wouldn't expect anything outside a constructor to happen when an object is constructed. So while I understand that other languages may (successfully for them) do things differently I don't think I'd like a breaking change for that.
Re: dynamically allocating on the stack
On Sunday, 22 April 2018 at 05:29:30 UTC, Mike Franklin wrote: On Sunday, 22 April 2018 at 00:41:34 UTC, Nicholas Wilson wrote: You're not using the C library version of it, the compiler does the stack space reservation inline for you. There is no way around this. I'm not convinced. I did some no-runtime testing and eventually found the implementation in druntime here: https://github.com/dlang/druntime/blob/master/src/rt/alloca.d Mike The first assertion ("the C library isn't called") is easily apperent from that assembly dump. The second is interesting but not so evident. It might be clearer looking at actual assembly. The doSomething function starts as such: ; sym._D4test11doSomethingFmZv (int arg_1h); ; prologue, puts the old stack pointer on the stack 0x563d809095ec 55 push rbp 0x563d809095ed 488bec mov rbp, rsp ; allocate stack memory 0x563d809095f0 4883ec20 sub rsp, 0x20 ; setup arguments for the alloca call ; that 0x20 in rcx is actually the size of the current stack allocation 0x563d809095f4 48c745e82000. mov qword [local_18h], 0x20 ; 32 0x563d809095fc 48ffc7 inc rdi 0x563d809095ff 48897de0 mov qword [local_20h], rdi 0x563d80909603 488d4de8 lea rcx, [local_18h] ; calls alloca 0x563d80909607 e83001 call sym.__alloca The alloca function works as such: ;-- __alloca: ; Note how we don't create a stack frame by "push rbp;mov rbp,rsp" ; Those instructions could be inlined, it's not a function per se ; ; At that point rcx holds the size of the calling functions's stack frame ; and eax how much we want to add 0x563d8090973c 4889ca mov rdx, rcx 0x563d8090973f 4889f8 mov rax, rdi ; Round rax up to 16 bytes 0x563d80909742 4883c00f add rax, 0xf 0x563d80909746 24f0 and al, 0xf0 0x563d80909748 4885c0 test rax, rax ,=< 0x563d8090974b 7505 jne 0x563d80909752 | 0x563d8090974d b81000 mov eax, 0x10 `-> 0x563d80909752 4889c6 mov rsi, rax ; Do the substraction in rax which holds the new address 0x563d80909755 48f7d8 neg rax 0x563d80909758 4801e0 add rax, rsp ; Check for overflows ,=< 0x563d8090975b 7321 jae 0x563d8090977e | ; Replace the old stack pointer by the new one | 0x563d8090975d 4889e9 mov rcx, rbp | 0x563d80909760 4829e1 sub rcx, rsp | 0x563d80909763 482b0a sub rcx, qword [rdx] | 0x563d80909766 480132 add qword [rdx], rsi | 0x563d80909769 4889c4 mov rsp, rax | 0x563d8090976c 4801c8 add rax, rcx | 0x563d8090976f 4889e7 mov rdi, rsp | 0x563d80909772 4801e6 add rsi, rsp | 0x563d80909775 48c1e903 shr rcx, 3 | 0x563d80909779 f348a5 rep movsq qword [rdi], qword ptr [rsi] ,==< 0x563d8090977c eb02 jmp 0x563d80909780 |`-> 0x563d8090977e 31c0 xor eax, eax | ; Done! `--> 0x563d80909780 c3 ret So as you can see alloca isn't really a function in that it doesn't create a stack frame. It also needs help from the compiler to setup its arguments since the current allocation size is needed (rcx in the beginning of alloca) which isn't a parameter known by the programmer. The compiler has to detect that __alloca call and setup an additionnal argument by itself. Alloca then just ("just") modifies the calling frame. (I really hope I didn't mess something up)
Re: dynamically allocating on the stack
On Saturday, 21 April 2018 at 13:30:55 UTC, Cym13 wrote: [...] Nevermind, forgot that shared libraries are put between the two.
Re: dynamically allocating on the stack
On Saturday, 21 April 2018 at 13:54:14 UTC, H. S. Teoh wrote: On Sat, Apr 21, 2018 at 01:30:55PM +, Cym13 via Digitalmars-d-learn wrote: On Saturday, 21 April 2018 at 12:08:09 UTC, Dmitry Olshansky wrote: [...] > Unbounded allocation on stack is kind of anti-pattern and a > potential DoS vector. I'm having trouble seeing how unbounded heap allocations aren't equally a potential DoS vector. [...] Generally speaking, the heap is much bigger than the stack (often many times so) and so is less prone to overflow. Though it's true, it still does happen if you just blindly allocate memory based on unsanitized external input. T Wait, why? Don't they share the same address space and grow in opposite directions?
Re: dynamically allocating on the stack
On Saturday, 21 April 2018 at 12:08:09 UTC, Dmitry Olshansky wrote: On Saturday, 21 April 2018 at 07:37:50 UTC, Mike Franklin wrote: Does D have some way to dynamically allocate on the stack? I'm looking for something roughly equivalent to the following C code. int doSomething(size_t len) { char stackBuffer[len + 1]; doSomethingElse(stackBuffer); } Unbounded allocation on stack is kind of anti-pattern and a potential DoS vector. I'm having trouble seeing how unbounded heap allocations aren't equally a potential DoS vector. A separate region allocator is exactly as fast and can easily survive across boundaries of function calls. I guess if OP wants it on the stack it's because it doesn't need to survive across boundaries of function calls so this buys nothing in this case. Also you probably want something like char[X] = void; for efficiency if allocating on stack. Thanks, Mike
Re: Passing directory as compiler argument not finding file
On Friday, 13 April 2018 at 13:39:23 UTC, Tony wrote: On Friday, 13 April 2018 at 12:46:32 UTC, Cym13 wrote: On Friday, 13 April 2018 at 01:27:06 UTC, Tony wrote: I think that the typical model (at least in other languages) is to only compile one D source file at a time. Compile the b.d file with the -c option to create an object file. Then put the object file in a library file (either static (easier) or dynamic). Then you can use the -L compiler option to specify the directory of the library and the -l compiler option to specify the library (library name is shortened - libb.a referenced as -lb). Regardless of whether that would work or not this is the opposite of what's recommended in D. D compilers expect you to compile everything at once, or at least by module. That's where it works best when it comes to optimizations etc. What does "or at least by module" mean? Is it possible to have a module that is made up of more than one source file? Sorry, I really meant "package" here, not module. What information does a D compiler get when you stick a.d and b.d on the command line that it doesn't get if you compile a.d and import b.d ? Hmm. I can't quite remember honnestly. What I do remember is Andrei saying times and times again that D supports compilation by package and not incremental compilation (which is difficult because of CTFE and templates), but on second thought maybe you won't run into issues if compiling each module separately as long as you compile them all. However I'm pretty sure you'll get worse compilation times as the compiler can't make use of symbol cache etc. That may be the main reason why people generally avoid compiling separately each module and just put every file on the command line. AFAIK dmd is designed to be used that way.
Re: Passing directory as compiler argument not finding file
On Friday, 13 April 2018 at 01:27:06 UTC, Tony wrote: I think that the typical model (at least in other languages) is to only compile one D source file at a time. Compile the b.d file with the -c option to create an object file. Then put the object file in a library file (either static (easier) or dynamic). Then you can use the -L compiler option to specify the directory of the library and the -l compiler option to specify the library (library name is shortened - libb.a referenced as -lb). Regardless of whether that would work or not this is the opposite of what's recommended in D. D compilers expect you to compile everything at once, or at least by module. That's where it works best when it comes to optimizations etc.
Re: Range length property
On Tuesday, 10 April 2018 at 20:08:14 UTC, Jonathan M Davis wrote: On Tuesday, April 10, 2018 19:47:10 Nordlöw via Digitalmars-d-learn wrote: On Tuesday, 10 April 2018 at 14:34:40 UTC, Adam D. Ruppe wrote: > On Tuesday, 10 April 2018 at 14:25:52 UTC, Nordlöw wrote: >> Should ranges always provide a length property? > > No. > >> If so, in which cases is a length property an advantage or >> a requirement? > > Just provide it whenever it is cheap to do so. If you need > to do complex calculations or especially loop over contents > to figure out the length, do NOT provide it. > > But if it is as simple as returning some value, provide it > and algorithms can take advantage of it for optimizations > etc. as needed. I'm thinking of my own container Hashmap having its range ByKeyValue requiring one extra word of memory to store the iteration count which, in turn, can be used to calculate the length of the remaining range. Is this motivated? That would depend entirely on what you're trying to do, but in general, if a range has length, then some algorithms will be more efficient, and some algorithms do require length. So, if you can provide length, then the range will be more useful, just like a bidirectional range can be more useful than a forward range or a random-access range can be more useful than either. However, if you're not doing anything that ever benefits from it having length, then it doesn't buy you anything. So, it ultimately depends on what you're doing. In a general purpose library, I'd say that it should have length if it can do so in O(1), but if it's just for you, then it may or may not be worth it. The other thing to consider is what happens when the container is mutated. I don't think that ranges necessarily behave all that well when an underlying container is mutated, but it is something that has to be considered when dealing with a range over a container. Even if mutating the underlying container doesn't necessarily invalidate a range, maintaining the length in the manner that you're suggesting probably makes it so that it would be invalidated in more cases, since if any elements are added or removed in the portion that was already popped off the range, then the iteration count couldn't be used to calculate the length in the same way anymore. Now, with a hash map, the range is probably fully invalidated when anything gets added or removed anyway, since that probably screws with the order of the elements in the range, but how the range is going to behave when the underlying container is mutated and how having the length property does or doesn't affect that is something that you'll need to consider. - Jonathan M Davis I find that discussion very interesting as I had never considered that because of design by introspection having a costly length method would lead to unexpected calls by generic algorithms making it a disadventage if present. On the other hand I don't think the end user should have to scratch his head to find the length of a range, especially if it's not trivial to get (say, O(log n) kind of case). Therefore exposing a method in any case seems the best from an API perspective. But to avoid the performance issues mentionned earlier it means it should bear a different name (get/setLength comes to mind). I believe this is the same kind of issue that lead to having "in" for associative arrays but not regular ones. However this also leads to less coherent APIs in contradiction with the principle of least surprise. In retrospect since only "unexpected" calls to such methods cause the issue I wonder if it wouldn't be best to have an UDA saying "Hey, please, this method is costly, if you're a generic template performing introspection you should probably not call me". And writing that Andrei's work on complexity annotations comes to mind. Anyway, I don't think the user should use different names just to alleviate an issue on the library side but the alternative would be costly to put in place... Any thoughts?
Re: Strange Thread Causing Duplicating `writeln`
On Monday, 9 April 2018 at 22:28:45 UTC, Jonathan wrote: I am totally lost on why this is happening. I stripped the code down to what appears to be the most minimal code that still causes the problem. --- import core.sync.mutex; import core.thread; import std.stdio; __gshared Mutex m;//__gshared just for testing (; void thread1() { foreach (i;0..8) { synchronized(m) { writeln("a1-",i); } writeln("a2-",i); } } void thread2() { foreach (i;0..8) { synchronized(m) { writeln("b1-",i); } writeln("b2-",i); } } void main() { m = new Mutex(); new Thread(&thread1).start; new Thread(&thread2).start; } --- The beginning of the output for this code is: a1-0 a2-0 a2-0 b1-0 b2-0 b2-0 a1-1 a2-1 a2-1 Why is the "a2" and "b2" writeln being repeated?! I don't know, but I can't reproduce either with dmd or ldc. What was your compilation line?
Re: Declare and Define Before Use? [rant]
On Wednesday, 4 April 2018 at 19:51:27 UTC, kdevel wrote: On Wednesday, 4 April 2018 at 19:19:30 UTC, Ali wrote: On Wednesday, 4 April 2018 at 18:57:27 UTC, kdevel wrote: [...] I think the rules should have been the same everywhere and if there was an exception to be made, it could be made for the main function since the main function is special anyway The main function of a program corresponds to the final paragraph of a novel. I never understood why programmers place this function which possibly depends on all other functions in the translation unit at the beginning. BTW: You can't write void main () { x.writeln; int x; } import std.stdio; There is no reason why the declaration of x should not be postponed. I've never seen the main function at the top but I think it would be be nice place for it honnestly. Sounds more like a C legacy than anything. The reason why I place common imports at the top is because I read a *lot* of code as my day job is to audit software. While skimming rapidly through directories looking only at the top of each file I know what they are about and can quickly infer their purpose based solely on imports. This file does IO, this one web stuff, etc (and to debunk quickly a counter argument I've heard before: no, given how convoluted file names quickly get especially in languages like java, directory structure isn't nearly enough). The same is true for the main function. If your code is clean it should the main is the place where you orchestrate the whole program. You should be able to grasp most of the program flow from it. What it setups, information flow, etc. Of course in practice people are often trying to burry useful information deep down in functions (where it's generally too coupled for its own good, but that's another story). Such burrying makes it harder to get useful information from the main function, hence maybe why so many are comfortable putting it at the end (I know I do by habit). On the other hand, if the main effectively describes the programs course then putting it at the beggining makes complete sense: it is what you want to see first to get an idea of what the program is doing. No function could be better suited for that. Some points hinted here make me think of https://www.youtube.com/watch?v=FyCYva9DhsI so maybe it could be of some interest to you.
Re: Fix transposed ranges
On Monday, 2 April 2018 at 19:45:31 UTC, Steven Schveighoffer wrote: On 4/2/18 3:24 PM, Cym13 wrote: [...] Well, it's tough, because you can compose ranges in infinite ways. All you need to generate the warning is some code like this: [...] That makes sense, thanks.
Re: Fix transposed ranges
On Monday, 2 April 2018 at 18:33:25 UTC, Steven Schveighoffer wrote: On 3/30/18 4:45 PM, Cym13 wrote: On Friday, 30 March 2018 at 20:43:09 UTC, Cym13 wrote: Hi, I've got the following code that takes a list of files as argument and xor them together (demo example sufficient for that discussion). [...] Forgot to mention but I'm also quite annoyed at the need for that ".array" because "transposed" requires the RoR to be assignable. That kills the laziness. I'm very much open to suggestions regarding that point. 1. The .save deprecation may not affect you. It's probably being used by map or fold but may not need to be. Once it's removed, you may just see the warning go away, and everything still works just fine. I'm not 100% sure on this, as I don't know where it's being used. That's good to hear, although I don't realy like warnings on which I have no control. 2. The array is necessary, as map is lazy. what you want is a range of the first byte of each file, then a range of the second byte of each file, etc. mapping to a byte array can't possibly do this, because what would happen is that map would re-open the file, re-read it's contents, and then give you the *second* byte. This is horribly inefficient. While I agree that using an array is ugly, and that I want ranges of first byte (which is why I'm using transposed in the first place), transposed just doesn't let me work with the result of map itself. I suppose it's because its signature stipulates hasAssignableElements. I feel like I'm missing something there but I can't see what. But you can probably reduce the memory requirements by streaming each file's bytes as you need it. Unfortunately, I don't see a 'byByte' method on File, so you may have to look elsewhere for that. -Steve
Re: Optional parameters?
On Monday, 2 April 2018 at 09:31:35 UTC, Timoses wrote: On Sunday, 1 April 2018 at 15:54:16 UTC, Steven Schveighoffer wrote: I currently have a situation where I want to have a function that accepts a parameter optionally. I thought maybe Nullable!int might work: void foo(Nullable!int) {} void main() { foo(1); // error int x; foo(x); // error } Can somebody enlighten me what this topic is about? I thought an optional parameter would be as easy as void foo(int i = 0) { writeln(i); } void main() { int x; foo(x); foo(1); foo(); } Is the Nullable!int approach because 'i' would always "optionally" be 0 if not passed with above 'foo'? Same feeling here, this situation really asks for a Null Object pattern, not nullable. It's sad that nullable isn't very good in that situation but trying to force it in place doesn't seem very reasonnable.
Re: Fix transposed ranges
On Friday, 30 March 2018 at 20:43:09 UTC, Cym13 wrote: Hi, I've got the following code that takes a list of files as argument and xor them together (demo example sufficient for that discussion). [...] Forgot to mention but I'm also quite annoyed at the need for that ".array" because "transposed" requires the RoR to be assignable. That kills the laziness. I'm very much open to suggestions regarding that point.
Fix transposed ranges
Hi, I've got the following code that takes a list of files as argument and xor them together (demo example sufficient for that discussion). import std.stdio; import std.array; import std.range; import std.algorithm; auto rawContent(string path) { return File(path).byChunk(16384).joiner; } void main(string[] args) { args[1..$] .map!rawContent .array .transposed .map!(bytes => bytes.fold!((a, b) => a^b)) .writeln; } This works but compiles with deprecations: /usr/include/dlang/dmd/std/algorithm/iteration.d(663): Deprecation: function `std.range.Transposed!(Result[], cast(TransverseOptions)0).Transposed.save` is deprecated - This function is incorrect and will be removed November 2018. See the docs for more details. /usr/include/dlang/dmd/std/algorithm/iteration.d(663): Deprecation: function `std.range.Transposed!(Result[], cast(TransverseOptions)0).Transposed.save` is deprecated - This function is incorrect and will be removed November 2018. See the docs for more details. What do you think the best course of action would be to make that code resilient to the modification of transposed? I'd very *very* much like to keep a straight UFCS line, there's really nothing complicated enough with this operation to warrant writting boilerplate, yet the straightforward solution isn't future-proof... Any idea?
Re: string to hex convert
On Thursday, 29 March 2018 at 20:29:39 UTC, aerto wrote: how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ?? Maybe something like: void main() { // Those look like lots of imports but most of those are very common anyway import std.digest: toHexString; import std.stdio: writeln; string s = "Hello world!"; (cast(ubyte[]) s)// We want raw bytes... .toHexString // ...convert them to hex... .writeln;// ...and print. }
Re: What is the "right" way to create a generic type getter (and setter) ?
On Thursday, 15 March 2018 at 15:48:52 UTC, James Blachly wrote: On Wednesday, 14 March 2018 at 22:58:25 UTC, ag0aep6g wrote: You can probably get around the (manually maintained?) `FIELDS` array with `.tupleof` or something similar: static foreach (i, f; S.tupleof) { case __traits(identifier, f): } Any pointers / design patterns on this particular type of problem class would be greatly appreciated. (Sidenote, I realize I could probably use the witchcraft library, but I am also using this as exercise to learn D beyond the basics). You simply cannot have a method that returns different types based on a run-time value. You could possibly return a std.variant.Variant. But if the goal is just to print the value to the screen, all you need is a string. So the signature would be `string get(string field)`. And for the implementation you could use `.tupleof` to iterate over all fields, and then return `f.to!string`. `set` can be done similarly. Take two `string`s: the field name, and the value. `static foreach` over all fields. On a match, convert the given value string to the type of the field that matched. Thanks - to!string certainly seems to be a good option in this case (CLI) and I was definitely overthinking this part, perhaps because I was trying to write everything as generically / extensibly as possible (for example, to use the same framework but with a GUI or web front end, for example). I would still think an AA mapping (string) field name to a type would be useful and will see if I can construct it as a mixin using typeof(Struct.member) somehow. If you're comming from python you may appreciate that you don't need getter/setters in D either. Just as you have @property in python which allows you to change at any time from a simple attribute to a method (be it reading or writing) you have a property syntax in D: struct S { int a; int _b; auto b() { return _b; } void b(int val) { _b = val; } } void main(string[] args) { S s; s.a = 24; writeln(s.a); s.b = 42; writeln(s.b); }
Re: Equivalent to Python with Statement
On Wednesday, 28 February 2018 at 22:55:19 UTC, Seb wrote: On Wednesday, 28 February 2018 at 21:47:40 UTC, Cym13 wrote: On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote: I know Python's `with` statement can be used to have an automatic close action: ``` with open("x.txt") as file: #do something with file #`file.close()` called automatically ``` I know D's `with` statement does something different but is there some sort of equivalent? Others have discussed that particular case at length, but to provide a more generic answer the correct way to translate a python context manager is to use scope(out): { // Scope restriction similar to with's block auto f = File("x.txt"); scope(out) f.close(); // closes f on scope exit no matter what /* do stuff with f */ } This accurately reproduces the behaviour of python's with although it's less automatic. I know that I am repeating myself, but manually closing the file isn't needed in D. It's refCounted and will be closed automatically once the scope is left. That's why `with(File("AAA","w"))` works in D. As stated, yes that's an accurate answer to that particular problem and it's well understood, I'm just giving a more general answer that will work for every python context manager and not only on the specific case of closing files.
Re: Equivalent to Python with Statement
On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote: I know Python's `with` statement can be used to have an automatic close action: ``` with open("x.txt") as file: #do something with file #`file.close()` called automatically ``` I know D's `with` statement does something different but is there some sort of equivalent? Others have discussed that particular case at length, but to provide a more generic answer the correct way to translate a python context manager is to use scope(out): { // Scope restriction similar to with's block auto f = File("x.txt"); scope(out) f.close(); // closes f on scope exit no matter what /* do stuff with f */ } This accurately reproduces the behaviour of python's with although it's less automatic.
Re: countUntil to print all the index of a given string.
On Sunday, 18 February 2018 at 14:48:59 UTC, Cym13 wrote: [...] Just thought of a much better/simpler solution for that last case that also doesn't force you to read all data (which might be impossible when dealing with infinite ranges): import std.range; import std.algorithm; a[] .enumerate // get tuples (index, value) .filter!(t => t[1] == "Test2") // keep only if value == "Test2" .map!(t => t[0]) // keep only the index part .writeln; Completely lazy.
Re: countUntil to print all the index of a given string.
On Sunday, 18 February 2018 at 11:55:37 UTC, Vino wrote: Hi All, Request your help on printing the all index of an array element , eg; the below code prints the index of the string "Test2" as [1], but the string "Test2" is present 2 times at index 1 and 4, so how do I print all the index of a given string. import std.stdio; import std.container; import std.algorithm; void main () { auto a = Array!string("Test1", "Test2", "Test3", "Test1", "Test2"); writeln(SList!int(a[].countUntil("Test2"))[]); } Output [1] Expected [1, 4] From, Vino.B countUntil is good when you want to avoid having to look at all your data, but in this case I don't think it's the best solution. You could do a loop storing each index and then restart your countUntil from there, but quite frankly it would be easier to just loop over the array at that point: ulong[] result; for (ulong index=0 ; indexHowever, if you want a more streamlined, functionnal solution, you can go all the way and avoid all explicit loops and intermediate variables using fold: import std.range: enumerate; import std.algorithm: fold; a[] .enumerate .fold!((a, b) => b[1] == "Test2" ? a ~ b[0] : a)(cast(ulong[])[]) .writeln;
Re: [Help] programm execution leads to infinity background loop after... what reason?
On Sunday, 11 February 2018 at 17:28:25 UTC, Eld0r wrote: changed my design from extending thread to just using taskPool.parallel. seems like my implementation left to many open threads in background and forcing the operation system to cut them off. thought start() and join() allowed me to use start() again on the same thread object in next loop. But there is some leakage... are they not 'self-closig' after finnishing run() ? works now but you are welcome to leave a statement. For a statement... I'm glad you found your way! However nobody can debug a program they can't read so please always post a small working example in order for others to understand your issue and be able to reproduce it ;)
Re: Caesar Cipher
On Sunday, 11 February 2018 at 18:50:25 UTC, Mario wrote: On Sunday, 11 February 2018 at 18:31:35 UTC, Seb wrote: On Sunday, 11 February 2018 at 18:01:20 UTC, Mario wrote: Hello there! I know deep Java, JavaScript, PHP, etc. but as you all probably know, that's high-level and most of them only use the heap memory. [...] If you want to cheap, have a look at https://github.com/dlang-tour/core/issues/227 Thank you for that, but actually it's using stuff that didn't appear yet (I understand how it works but I'd like to know why XD) I think the less advanced way (in term of features) would be using a foreach loop (which haven't been introduced either yet). But yeah, the example isn't well choosen, and that's why an issue was oppened for it ;)
Re: Caesar Cipher
On Sunday, 11 February 2018 at 18:01:20 UTC, Mario wrote: Hello there! I know deep Java, JavaScript, PHP, etc. but as you all probably know, that's high-level and most of them only use the heap memory. So I'm new to the wonderful world of low-level and the stack-heap. I started a week ago learning D (which by the moment is being easy for me) but I'm facing a big problem: I don't know how to do the exercise of https://tour.dlang.org/tour/en/basics/arrays . I really have been looking on forums and Google but I found this in Java https://stackoverflow.com/questions/10023818/shift-character-in-alphabet which is actually not the best due to Java uses other ways. My code is something like this: char[] encrypt(char[] input, char shift) { auto result = input.dup; result[] += shift; return result; } What's wrong? I mean, I know that z is being converted into a symbol, but how should I fix this? Thanks on forward. Your mistake has little to do with D, and more with Ceasar (which is unfortunate IMHO): this cipher is usually defined only on the 26 letters of the alphabet and seeing the result of the assert at the end of the code it's the case here. So while you're working on a full byte (256 values) you should restrict yourself to the 26 lowercase ascii alpha characters. Give it a try :)
Re: Create D portable binary
On Friday, 8 December 2017 at 06:37:36 UTC, Adam D. Ruppe wrote: On Friday, 8 December 2017 at 05:16:22 UTC, Fra Mecca wrote: Is there a way to compile a project and deploying it as a single statically linked binary? A default build of a D program is *reasonably* compatible. All its dependencies are core operating system components like libc. Now, there can certainly be libc version incompatibilities, but there's a decent chance it will just work. I'm pretty sure this is the exact same situation Go is in; the default Go and D builds link the same way. I was curious so I just tried. Building a hello world with "go build" (I just litterally did what was on https://gobyexample.com/hello-world) produces a file that is not a dynamic executable. There is no dependency. For comparison building a similar hello world with dmd and no options gives the followig dependencies (thanks ldd): linux-vdso.so.1 (0x7fffd02aa000) libpthread.so.0 => /usr/lib/libpthread.so.0 (0x7f45e5e69000) libm.so.6 => /usr/lib/libm.so.6 (0x7f45e5b1d000) librt.so.1 => /usr/lib/librt.so.1 (0x7f45e5915000) libdl.so.2 => /usr/lib/libdl.so.2 (0x7f45e5711000) libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x7f45e54fa000) libc.so.6 => /usr/lib/libc.so.6 (0x7f45e5142000) /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x7f45e6087000) (And using -L-static produces an error because of an incompatibility with -pie... I'm sure it's workable I just didn't take the time to look it up yet)
Re: Binary serialization of a struct
On Saturday, 16 September 2017 at 13:15:54 UTC, Azi Hassan wrote: On Saturday, 16 September 2017 at 03:30:51 UTC, Joseph wrote: Are there any simple direct serialization libraries where I can mark elements of a class or struct that I want serialized with an attribute and it will take care of all the rest(including recursive structures, arrays, etc) then deserialize back in to the structs? I want something straight forward without allot of plumbing on my end. Have you checked Cerealed ? From the looks of it, it supports a @NoCereal attribute which does the opposite of what you're looking for. Not sure how it handles nested structs, but there are examples in the test/directory : https://github.com/atilaneves/cerealed/ Cerealed is definitely my favourite library out there for binary serialization. High quality.
Re: Getting a safe path for a temporary file
On Sunday, 18 January 2015 at 00:51:37 UTC, Laeeth Isharc wrote: On Saturday, 17 January 2015 at 16:55:42 UTC, Marc Schütz wrote: On Saturday, 17 January 2015 at 14:37:00 UTC, Laeeth Isharc wrote: On Saturday, 17 January 2015 at 13:47:39 UTC, Marc Schütz wrote: [...] I agree that it would be useful. This is what I used, although there may be a better option: http://dlang.org/phobos/std_uuid.html Nice idea, but it still allows for intentional collision attacks :-( The only really safe solution is one that generates (probably) unique names, then opens the file with O_EXCL|O_CREAT (or whatever other means the OS provides), and if it fails, retries with a different name. `std.stdio.tmpfile()` already does that (it uses `tmpfile(3)` under the hood), but doesn't allow access to the name. I don't follow why a collision attack is applicable in this case. Your stage 1 of generating unique names: how is this different from using a random uuid? UUIDs are defined to be unique, not unpredictable. UUID that use random number generation (UUID4) should use a cryptographically secure random number generator but are not required to. Therefore it shouldn't be blindly trusted against someone actively trying to get a collision.
Re: Getting a safe path for a temporary file
On Sunday, 18 January 2015 at 16:00:32 UTC, Kagamin wrote: On Sunday, 18 January 2015 at 11:21:52 UTC, Marc Schütz wrote: It's not different, and if you're still doing the O_EXCL open afterwards, it's safe. I just assumed you were going to use the generated filename without a further check. This is then unsafe, no matter how the UUID is generated, and depending on the RNG that's been used, they can be quite predictable. Granted, the risk is low, but still... tmpfile is more predictable: it generates sequential file names. Being predictable is only an issue if the file is wrongly used (ie: no check that it might already exist, or be a symlink or check at the wrong time leaving an exploitable time frame etc). Sequential file names are a good way to provide uniqueness over a single system after all.
Re: Valid File Path
On Thursday, 31 August 2017 at 21:59:22 UTC, vino wrote: Hi All, Can you help me what is wrong in the below program, as the output is empty. import std.stdio, std.path; void main () { version (Windows) { auto Path = `C:\#Users\Admin\Desktop\Script\Test1`; if(!Path.isValidPath) { writeln("Path Not Valid");} } } From, Vino.B It doesn't print anything because the path is valid. Why do you expect otherwise? Note that isValidPath is only used for syntax check, it does not checks that the file or directory exists. If that is what you want use std.file.exists instead.
Re: Why D have two function contains and canFind?
On Monday, 24 July 2017 at 18:31:09 UTC, Ali Çehreli wrote: On 07/24/2017 11:19 AM, Suliman wrote: > [...] only > [...] std.algorithm.canFind and std.range.SortedRange.contains: [...] I'm gessing this predates design by introspection as it would be cleaner to let the compiler do the switch itself.
Re: criando modulos em D para classe pessoa[AJUDA]
On Monday, 24 July 2017 at 19:45:03 UTC, dark777 wrote: pessoal eu tenho umas classes java e estava portando para D e para usar as importaçoes criei os modules nescessarios todos estao dentro da mesma pasta porem ao fazer: $rdmd principal ele retorna o seguinte erro: principal.d(18): Error: octal literals 01023040 are no longer supported, use std.conv.octal!1023040 instead Failed: ["dmd", "-v", "-o-", "principal.d", "-I."] Os codigos sao os que estao abaixo no pastebin https://pastebin.com/CYinHWyQ Sorry, I don't know what language you're talking so I hope I'll get it right anyway ;) D used to have octal numbers. They started with a 0 so 0100 == 64. This was deprecated in favour of std.conv.octal which explains the error message. To fix, remove the 0: e.setCEP(1020304)
Re: How to add authentificaion method to request?
On Wednesday, 12 July 2017 at 07:43:27 UTC, Suliman wrote: Compiler require libssl32.dll for run dlang-request based app. Where I can get it? I installed, OpenSSL, but can't find this lib in C:\OpenSSL-Win64 I don't use windows so it's nothing definitive but I'd bet that the "32" in libssl32.dll stands for 32bits while OpenSSL-Win64 is for 64bits. You need to get the 32bits version.
Re: dmd, vibe.d RAM usage when compiling.
On Tuesday, 11 July 2017 at 16:04:52 UTC, SrMordred wrote: I never notice this before, but i tried to put a basic hello world from vibe.d (like the one that are in the dlang front page examples now), into the most basic instance on google cloud (with 600mb of RAM) and the compilation returned "Killed dmd failed with exit code 137." So I look at the RAM usage and saw that when compiling (with dub) it uses 550mb+. So i´m unable to put hello world to work. Aren´t this number a bit too high for a basic example? They're expected sadly. It's known that D's common style and especially templates quickly leads to huge memory usage. There is work in progress to mitigate the issue such as reducing the size of symbols within the binary but it's not available for the moment.
Re: How to add authentificaion method to request?
On Tuesday, 11 July 2017 at 12:15:39 UTC, Suliman wrote: I am using dlang-requests. I need authentificate on https://scihub.copernicus.eu/dhus/login and than do some data-parsing. MultipartForm form; form.add(formData("login_username", "Suliman")); form.add(formData("login_password", "123")); // changed auto content = postContent("https://scihub.copernicus.eu/dhus/login";, form); writeln("Output:"); writeln(content); Return error about login pass. So it's seems that I need to add BasicAuthentication method type. But how to add it? Browser console show next: https://snag.gy/VXaq2R.jpg Something like: Request req; req.authenticator = new BasicAuthentication("login", "password");
Re: Application settings
On Friday, 7 July 2017 at 19:40:35 UTC, FoxyBrown wrote: What's the "best" way to do this? I want something I can simply load at startup in a convenient and easy way then save when necessary(possibly be efficient at it, but probably doesn't matter). Simply json an array and save and load it, or is there a better way? Ideally, I'd like to store the settings as part of the binary to keep everything together but that poses a few issues I think. I think you're better off with a simple file in a format like JSON or INI yeah. Simpler is better. I don't see any easy way to save the configuration in the binary and would find it more troublesome than anything as an user as having the configuration appart means I can easily compare it between computers and track its changes etc. I don't think you need to worry about performances, after all it's only loaded once and the config would have to be *really* big for it to have a noticable loading time.
Re: How to get uniq to return an array?
On Tuesday, 4 July 2017 at 11:00:05 UTC, PumpkinCake wrote: I'm trying to strip repeated values out of an int array using uniq. It's returning a UniqResult which can't be accessed like an array... how can I get it to return an array, or cast whatever it is returning to be an array? Most functions are lazy in order to allow more centrol over the memory. This means the actual value is computed only when needed. To use an array import std.array and do [1, 1, 2].uniq.array; for example. This will allocate a new array to keep the result.
Re: Advice wanted on garbage collection of sockets for c++ programmer using D
On Tuesday, 27 June 2017 at 12:29:03 UTC, Guillaume Piolat wrote: [...] Hmm... Isn't it possible to just allocate the object/a pool of objects outside the loop and reuse it? Everybody's proposing other means of allocations which is nice, but I wonder why there is such a need for reallocations in the first place. Of course the specifics depend on the implementation, maybe it isn't as straightforward. It's just that no allocation is faster than reallocation no matter what reallocation method is used.
Re: Dealing with the interior pointers bug
On Thursday, 22 June 2017 at 18:38:59 UTC, Boris-Barboris wrote: On Thursday, 22 June 2017 at 13:56:29 UTC, ag0aep6g wrote: For example, the type system guarantees that immutable data never changes. But the compiler allows you to cast from immutable to mutable and change the data. It's an invalid operation, but the compiler is not expected to catch that for you. Casts are part of the type system. Yes, D type system allows invalid operations. It's not the compiler's fault, it's type system's fault. unittest { immutable int a = 4; int* b = cast(int*) &a; *b = 5; assert(*(&a) == 5); assert(a == 4); } Here it's the programmer's fault really. You should never use casts in normal code, cast is the ultimate switch to say "Look, I know what I'm doing, so disable all safety, don't try to make sense of it, and let me do my thing. If I'm telling you it's a cat, then it is dammit.". You can't blame the type system not to do something coherent here, you explicitely went out of your way to lie to that very same type system in the most unsafe way possible.
Re: GDC generate wrong .exe ("not a valid win32 application")
On Thursday, 22 June 2017 at 05:57:59 UTC, bauss wrote: On Wednesday, 21 June 2017 at 15:55:27 UTC, David Nadlinger wrote: On Monday, 19 June 2017 at 14:08:56 UTC, Patric Dexheimer wrote: Fresh install of GDC. (tried with 32x ad 32_64x) Where did you get the GDC executable from? The GDC project doesn't currently offer any official builds that target Windows; the 6.3.0 builds from https://gdcproject.org/downloads in fact generate Linux binaries. — David I see Windows distributions below the Linux ones. They're used for cross-compiling.
Re: Dealing with the interior pointers bug
On Wednesday, 21 June 2017 at 17:11:41 UTC, TheGag96 wrote: On Wednesday, 21 June 2017 at 15:42:22 UTC, Adam D. Ruppe wrote: This comes from the fact that D's GC is conservative - if it sees something that *might* be a pointer, it assumes it *is* a pointer and thus had better not get freed. So is the GC then simply made to be "better-safe-than-sorry" or is this a consequence of how the GC does things? Or rather, does the GC know the type of any references to its memory at all? I suppose I should really ask if there's a document other than druntime's source that describes how the GC really works under the hood haha. You may like reading http://olshansky.me/gc/runtime/dlang/2017/06/14/inside-d-gc.html
Re: libc dependency
On Monday, 19 June 2017 at 21:01:35 UTC, Honey wrote: On Monday, 19 June 2017 at 20:26:43 UTC, Adam D. Ruppe wrote: On Monday, 19 June 2017 at 20:20:23 UTC, Honey wrote: Is it correct that D produces executables that depend on libc? Usually yes, since that makes sense for most programs on operating systems, but you can pull it out if you want to for a specialized task. (Really, same boat C is in.) Thanks, Adam! To elaborate on my second point: if one compares, say, FreeBSD's libc [1] with glibc [2] it is pretty obvious that not all implementations are optimized to the same degree. Does it make sense - at least in cerain cases - to provide and use a D implementation that is fast on all platforms, instead? [1] https://svnweb.freebsd.org/base/head/lib/libc/ [2] https://sourceware.org/git/?p=glibc.git;a=tree;hb=HEAD The issue with that is that you assume: 1) that a complete libc replacement can be created from scratch 2) that a correct libc replacement can be created from scratch 3) that a better libc replacement can be created from scratch 4) that this replacement can be maintained for years to come on all plateforms All those points are certainly theoretically possible, but getting all 4 at once isn't a small task. Point 2 and 3 in particular: whatever your libc is it's been tested, reflected upon and optimized for years by good programmers. There is absolutely no reason to throw away this work. Even if it was practical to do that and that the developper was confident enough that he can do better than libc to start working on it, point 4 would be out of reach given the current state of affairs. So, while replacing specific C functions by D implementations where the gain is clear seems like a good idea to me, dropping the dependency on libc seems more like a risky gamble than anything.
Re: Simple c header => Dlang constants using mixins in compile time
On Saturday, 17 June 2017 at 11:20:53 UTC, Igor Shirkalin wrote: On Saturday, 17 June 2017 at 11:10:47 UTC, Igor wrote: On Saturday, 17 June 2017 at 10:56:52 UTC, Igor Shirkalin wrote: Hello! I have a simple C header file that looks like: #define Name1 101 #define Name2 122 #define NameN 157 It comes from resource compiler and I need all these constants to be available in my Dlang program in compile time. It seems to me it is possible. I know I can simply write external program (in python, for example) that does it, but it means I should constantly run it after every change before D compilation. Please, can anyone help to direct me how to realize it? Thank you in advance! Igor Shirkalin Maybe I am not quite understanding what you are asking but can't you just use: enum Name1 = 101; enum Name2 = 122; ... No, I need the original header file to be used in other applications (say, resource compiler). Therefore this file is primary. I think some pretty short code can be written in D that use such a file to generate constants (enum Name1 = 101) in compile time. I'm sure others will have cleaner solutions as as a quick hack you can read the file at compile time, modify it, and compile the D code on the go: import std.stdio; import std.array; import std.algorithm; // Normal function that takes a list of #define and transforms them in enum // constants textually. string enumify(string header) { return header.split("\n") .filter!(x => x.startsWith("#define Name")) .map!(x => x.split(" ")) .map!(s => "enum " ~ s[1] ~ " = " ~ s[2] ~ ";") .join("\n"); } unittest { string txt = "#define Name1 101\n#define Name2 122"; assert(txt.enumify == "enum Name1 = 101;\nenum Name2 = 122;"); } /* Our file header.h #define Name1 101 #define Name2 122 #define Name3 157 */ // We import the content of the file, enumify it producing D code, and mix it // in place to declare our constants. // // The string import requires compiling with -Jpath/to/dir/with/header.h mixin(enumify(import("header.h"))); void main(string[] args) { writeln(Name3); // 157 // Yep, that works pragma(msg, Name2); // 122 // Yep, that works at compile time too }
Re: byLine(n)?
On Sunday, 11 June 2017 at 12:44:05 UTC, helxi wrote: On Sunday, 11 June 2017 at 06:28:18 UTC, Stanislav Blinov wrote: On Sunday, 11 June 2017 at 05:36:08 UTC, helxi wrote: [...] You need only the nth line? Then you'd need to `drop` the preceding ones: void main(string[] args) { import std.algorithm, std.range, std.stdio, std.conv; stdin.byLine.drop(args[1].to!int-1).front.writeln; } Or if you need every nth line, combine `drop` and `stride`: void main(string[] args) { import std.algorithm, std.range, std.stdio, std.conv; auto step = args[1].to!int; stdin.byLine.drop(step-1).stride(step).each!writeln; } I was actually just looking for ways to read the first n line and then print it ($man head). My current program 1. reads all the lines provided by the stdin (bottleneck) 2. takes the first n lines (bottleneck) 3. prints each line I want to 1. read all the lines 2. when line number n is reached, stop reading the rest of the input 3. print each line byLine doesn't reall all input at once. Using byline and take you are effectively reading only the right amount of lines and not reading the rest. You already have what you want, what makes you think the contrary?
Re: byLine(n)?
On Sunday, 11 June 2017 at 08:33:16 UTC, Cym13 wrote: On Sunday, 11 June 2017 at 05:36:08 UTC, helxi wrote: [...] Ok, if I read you right you are writing to stdin and want first to print the first args[1] lines, then to do other things with the other lines of stdin. [...] Meh... I just noticed my first and second propositions are essentially the same, the main difference is that the range stdin.ByLineCopy is stored so you don't create a new one when reading from stdin again. This is what causes the loss of a line.
Re: byLine(n)?
On Sunday, 11 June 2017 at 05:36:08 UTC, helxi wrote: I was writing a program that reads and prints the first nth lines to the stdout: import std.stdio; void main(string[] args) { import std.algorithm, std.range; import std.conv; stdin.byLine.take(args[1].to!ulong).each!writeln; } As far as I understand the stdin.byLine.take(args[1].to!ulong) part reads all the lines written in stdin. What if I want to make byLine read only and only first nth line? stdin.byLine(args[1].to!ulong).each!writeln; Obviously the code above won't work. Is there any efficient workaround? Ok, if I read you right you are writing to stdin and want first to print the first args[1] lines, then to do other things with the other lines of stdin. If you use byLine you will not read all the lines of stdin, but you will lose a line. From there I see three possibilities: 1) If you control the input, add a limit line (if you want to take 2 then the third line will be lost): import std.conv; import std.stdio; import std.range; import std.algorithm; void main(string[] args) { auto limit = args.length > 1 ? args[1].to!ulong : 2; writefln("First %d lines", limit); stdin.byLineCopy.take(limit).each!writeln; writeln("Next lines"); stdin.byLineCopy.each!writeln; } 2) Read all stdin and separate those you want to print from the others later: import std.conv; import std.stdio; import std.range; import std.algorithm; void main(string[] args) { // I used byLineCopy because of the buffer reuse issue auto input = stdin.byLineCopy; auto limit = args.length > 1 ? args[1].to!ulong : 2; writefln("First %d lines", limit); input.take(limit).each!writeln; writeln("Next lines"); input.each!writeln; } 3) Do not use byLine for the first lines in order to control how much you read. import std.conv; import std.stdio; import std.range; import std.algorithm; void main(string[] args) { auto limit = args.length > 1 ? args[1].to!ulong : 2; writefln("First %d lines", limit); foreach (line ; 0 .. limit) { // I use write here because readln keeps the \n by default stdin.readln.write; } writeln("Next lines"); stdin.byLine.each!writeln; } There are other options but I think these are worth considering first.
Re: How to Compare 2 objects of the same class
On Saturday, 3 June 2017 at 20:02:13 UTC, Mark wrote: On Saturday, 3 June 2017 at 19:57:47 UTC, Mark wrote: Hello again. I'm designing a template version of a BST. Because of this, I want to be able to compare if two objects of the same class type are references to the same anonymous class on the heap somewhere. Example: Not sure what happened there. Anyways, example: auto A = new Box(); auto B = new Box(); if(A.opEquals(B)) {} gives the error test.o:(.data.rel.ro+0x18): undefined reference to `_D5Stack12__ModuleInfoZ' collect2: error: ld returned 1 exit status Error: linker exited with status 1 if(Object.opEquals(A,B) gives test.d(10): Error: function object.Object.opEquals (Object o) is not callable using argument types (Box, Box) How do I got about comparing two objects then?? Thanks. Could you please systematically post compilable code? It is very hard to say anything without even seeing what you're struggling with.
Re: howto count lines - fast
On Wednesday, 31 May 2017 at 17:23:46 UTC, Ali Çehreli wrote: On 05/30/2017 11:50 PM, Daniel Kozak via Digitalmars-d-learn wrote: > How do you compile it? When I use ldc2 -O3 -release -mcpu=bdver1 lc.d > my code is even faster than wc My bad: I'm not familiar with ldc's optimization options. (I used -O3 but not -release) Now I get the same performance as 'wc -l' when I add -release. Ali It seems to me that your initial result is more interesting: you manage to get faster than wc *while keeping bound safety*. At a time where safety is finally getting the importance it should always have had showing that you can write fast code without sacrifiying any of it is important I think.
Re: Finding the index of the maximum value in an associative array
On Tuesday, 30 May 2017 at 17:57:04 UTC, Lyle wrote: Hi, I have an associative array of type int[ulong] and I'm trying to get the index of the maximum value, like this: int[ulong] aa = [1UL: 2000, 2UL: 5000, 5UL: 1000]; writeln(aa.maxIndex); // should print 2 Can anyone help me out? Many thanks, Lyle Simple enough: get all key/values pairs in the AA, and ask for the element which is the maximum relatively to the value, then take its key. auto maxIndex(int[ulong] aa) { import std.algorithm; return aa.byKeyValue .maxElement!(x => x.value) .key; }
Re: As many thanks As possible to who crates D and UFCS feature
On Friday, 12 May 2017 at 11:58:23 UTC, k-five wrote: On Friday, 12 May 2017 at 11:41:57 UTC, cym13 wrote: [...] --- [...] - Thanks and the correct syntax for each! is, passing a lambda. So the: [...] is an error: temp.d(15): Error: found 'item' when expecting ')' following template argument list ... and should be: .each!( ( string item ) => writeln( item ) ); Ah, yeah, my bad, I should have try compiling it instead of answering directly ;)
Re: As many thanks As possible to who crates D and UFCS feature
On Friday, 12 May 2017 at 11:10:01 UTC, k-five wrote: I was waiting for a stable version of C++17 ( standard library ) to add some features of fileSystem in C++17 to my program that wants to iterate through all files in a directory recursively. I was thinking how could I do for implementing that and add it to my program. Now after starting to learn D ( nearby 2 weeks so far ). I can do it in 6 lines! void main( string[] args ){ string[] all_file_name = dirEntries( ".", SpanMode.depth, false ) .filter!( file => !file.name.matchFirst( regex( args[ 1 ] ) ).empty() ) .filter!( file => ( args[ 2 ] == "-f" || args[ 2 ] == "-d" ? ( args[ 2 ] == "-f" ? !file.isDir : !file.isFile ) : ( !file.isSymlink ) ) ) .map!( file => file.name ) .array; foreach( string item; all_file_name ) writeln( item ); } ./bin-file '[A-Z]$' -f ---> print all files that are matched against [A-Z]$ ./bin-file '[A-Z]$' -d ---> print all directory that are matched against [A-Z]$ ./bin-file '[A-Z]$' "anything-else" ---> print both files and directory that are matched against [A-Z]$ I am so happy since after more than one year practicing in C++ and putting a collection more than 2000 examples of C++ on my github, I was not sure I could do it in 6 lines. May it is a Spam but I think it is worth it. Shorter: void main( string[] args ){ dirEntries( ".", SpanMode.depth, false ) .filter!( file => !file.name.matchFirst( regex( args[ 1 ] ) ).empty() ) .filter!( file => ( args[ 2 ] == "-f" || args[ 2 ] == "-d" ? ( args[ 2 ] == "-f" ? !file.isDir : !file.isFile ) : ( !file.isSymlink ) ) ) .map!( file => file.name ) .each!(string item => writeln( item )); } It's more memory efficient too because at no point the actual list is stored.
Re: User input; quick question.
On Saturday, 29 April 2017 at 21:09:13 UTC, fred wrote: import std.stdio; I am somewhat new to D, and I am trying to receive user input, like this, with a prompt: string str; writeln("Enter a string: "); str = readln; writeln(str); However, the prompt appears after I enter the input; any reason why? I've trawled the internet for a good hour, but I can't seem to find an answer. Your code is correct, it's your terminal or whatever you use to see your program's output that doesn't flush stdout. You can force it though: string str; writeln("Enter a string: "); stdout.flush; str = readln; write(str);
Re: Get name of current function
On Sunday, 23 April 2017 at 20:34:12 UTC, Mike B Johnson wrote: I'd like to get the symbolic name of the current function I'm in void foo() { writeln(thisFunc.stringof()); // prints foo } I need something short, elegant and doesn't require modifying preexisting code... I'm sure D has something along those lines? So something like __FUNCTION__ or __PRETTY_FUNCTION__ ? https://dlang.org/spec/traits.html#specialkeywords
Re: Why map return [] ?
On Friday, 14 April 2017 at 15:29:33 UTC, Suliman wrote: auto x = MySQLTablesRange.map!(a=>a); writeln(x); return: [] while next code: MySQLTablesRange.each!(a=>a.writeln); return data line by line. Why? What library is that supposed to be?
Re: exceptions thrown when running app with failed unittests
On Sunday, 19 March 2017 at 22:13:21 UTC, Ervin Bosenbacher wrote: Its my 2nd day into D, I am already in deep love (:D), and I would like to understand whether this is normal behavior or something went terribly wrong, so all help is greatly appreciated. [...] Well, unittests can pass or fail and as the exception states there it failed. Binary search returns true if it found the element in the array, false otherwise. 5 is not an element of [1, 3, 6, 7, 9, 15] so binarySearch returned false. Assert throws an error if its argument is false to it threw. Nothing out of the ordinary except maybe a broken test.
Re: RAII
On Thursday, 23 February 2017 at 09:52:26 UTC, Arun Chandrasekaran wrote: I'm trying to write an RAII wrapper on Linux. I understand struct in D doesn't have default constructor (for .init reasons). I don't want to use `scope`. Is there an elegant way to achieve this in D? ``` import core.sys.posix.pthread; import core.sys.posix.sys.types; /// Makes pthread_mutexattr_t cleanup easy when using exceptions struct mutexattr_wrapper { /// Constructor this(bool _) { if (pthread_mutexattr_init(&m_attr) != 0 || pthread_mutexattr_setpshared(&m_attr, PTHREAD_PROCESS_SHARED)!= 0) // may be I will add few more methods here throw custom_exception("pthread_mutexattr_ failed"); } /// Destructor ~this() { pthread_mutexattr_destroy(&m_attr); } /// This allows using mutexattr_wrapper as pthread_mutexattr_t alias m_attr this; pthread_mutexattr_t m_attr; } ``` It reminds me of https://w0rp.com/blog/post/an-raii-constructor-by-another-name-is-just-as-sweet/ which isn't what you want but may be interesting anyway.