Re: Dub hanging for a long time
I do not use antivirus. It's floated error. I can't reproduce it. But sometime it's appears again.
Re: Issue with template function
On Friday, 6 February 2015 at 17:40:31 UTC, ketmar wrote: On Fri, 06 Feb 2015 17:09:28 +, Charles wrote: readString(toBytes!string(test),0,4).writeln; if you'll take a look into druntime sources, you'll find that string is just an alias to `immutable(char)[]`. so you actually doing thing: readString(toBytes!(immutable(char)[])(test),0,4).writeln; i bet that this is not what you meant. ;-) Thanks!
Re: Dub hanging for a long time
On 7/02/2015 8:55 p.m., Suliman wrote: Several times I encounter problem when DUB is hanging for a long time It's look like that when I tun DUB from folder of current project it's do not show me nothing, just move cursor on next line for a long time. http://img.ctrlv.in/img/15/02/07/54d5c37f6d3c3.png running dub from any other location is fine. If to wait some times (about 1 minutes) it's begin build project. After it next running dub from project dir work mediately. Does anybody encounter such problem? Try disabling anti-virus ext. Something seems to be messing up execution.
Dub hanging for a long time
Several times I encounter problem when DUB is hanging for a long time It's look like that when I tun DUB from folder of current project it's do not show me nothing, just move cursor on next line for a long time. http://img.ctrlv.in/img/15/02/07/54d5c37f6d3c3.png running dub from any other location is fine. If to wait some times (about 1 minutes) it's begin build project. After it next running dub from project dir work mediately. Does anybody encounter such problem?
Using reduce with user types
I can use filter algorithm with my types easily. struct A { string value; int count; } void main( string[] args ) { A[] aArr; aArr ~= A(HTTP, 3); aArr ~= A(HTTPS, 2); aArr ~= A(UNKNOWN_TCP, 4); aArr.filter!( a = a.count == 2); But I couldn't compile when I want to use reduce algorithm. I simply want to get the sum of count variables inside of A[]. auto sum = aArr.reduce!((a,b) = a.count + b.count); The line above gives C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(770): Error: cannot implicitly convert expression (__lambda3(result, front(_param_1))) of type int to A C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(791): Error: template instance app.main.reduce!((a, b) = a.count + b.count).reduce!(A, A[]) error instantiating source\app.d(363):instantiated from here: reduce!(A[]) How can I achieve summing count variables inside A[]? Best Regards Kadir Erdem Demir Ps: The problem caused by my lack of D basics I admit, the reason I can't look up references more before ask question I am in a bit tight schedule. Sorry for my dummy questions.
static alias this
Consider this simple example A)- struct StaticRegister { static private uint _value; @property static uint value() { return _value; } @property static void value(uint v) { _value = v; } } void main(string[] s) { StaticRegister = 1; assert(StaticRegister == 1); } --- This gives two errors for each line in `main` (exactly what I expected). test.d(8): Error: StaticRegister is not an lvalue test.d(9): Error: incompatible types for ((StaticRegister) == (1)): cannot use '==' with types However, if I modify the example by adding an `alias this` ... B)- struct StaticRegister { static private uint _value; @property static uint value() { return _value; } @property static void value(uint v) { _value = v; } alias value this; } void main(string[] s) { StaticRegister = 1; assert(StaticRegister == 1); } --- ... the assignment error is eliminated, but the read is not. test.d(11): Error: incompatible types for ((StaticRegister) == (1)): cannot use '==' with types I argue that either both errors should be eliminated, or neither should be eliminated. One could also argue that some variation of the following should be required... * static alias value this; * alias static value this; * alias value static this; ... to distinguish it from non-static `this` Now, in the example below, `this` is referring to the type itself in a static context C)--- import std.stdio; struct StaticRegister { static string GetType() { return typeof(this).stringof; } } void main(string[] s) { writeln(StaticRegister.GetType()); } --- So, it follows that the example below should work... and it does D)--- struct StaticRegister { static private uint _value = 0; @property static uint value() { return _value; } @property static void value(uint v) { _value= v; } static uint GetValue() { return this.value; } } void main(string[] s) { assert(StaticRegister.GetValue() == 0); } --- So, why does `alias this` in a static context (See example B above) only half-work? Bug? If not, what's the design rationale? Thanks, Mike
Re: strange work of GC
If a destroy method is used together with GC inside of my app,it makes my app unstable. In this case I need to choose how to destroy my objects: 1) always manually by method destroy, but without GC; 2) or always automatically by GC, but without using the destroy method. In the first case I need to know how can I disable the automatic GC in my app? In the second case - how can I disable the destroy method calls inside of my app?
Re: Issue with template function
On Friday, 6 February 2015 at 17:09:29 UTC, Charles wrote: I'm trying to create a template function that can take in any type of array and convert it to a ubyte array. I'm not concerned with endianness at the moment, but I ran into a roadblock when trying to do this with strings. It already works with ints, chars, etc. Here's the relevant test code: module byteReader; public import std.system : Endian; ubyte[] toBytes(T)(T[] arr) { if (arr == null) { return null; } ubyte[] result = new ubyte[arr.length]; foreach (key, val; arr) { result[key] = cast(ubyte) val;// This is line 16 } return result; } string readString(ubyte[] buffer, uint offset, uint length) { assert( buffer.length = offset + length ); char[] chars = new char[length]; foreach(key, val; buffer[offset .. offset + length]) { chars[key] = cast(char) val; } return cast(string)chars; } void main() { import std.stdio; readString(toBytes!char(['t','e','s','t']),0,4).writeln; readString(toBytes!string(test),0,4).writeln;// This is line 39 } Here's the output: byteReader.d(16): Error: cannot cast val of type string to type ubyte byteReader.d(39): Error: template instance byteReader.toBytes!string error instantiating Are you wanting to to convert each element in arr to a byte thus truncating and losing data (when T.sizeof != 1)? as in toBytes([1,2,3, 42, 500 /*this will be truncated to 244 */]);// T == int here or are you wanting to convert each element to a ubyte array and then concatenate it to the result. as is ubyte[] toBytes(T)(T[] arr) { ubyte[T.sizeof] buf; if (arr is null) { return null; } ubyte[] result = new ubyte[arr.length * T.sizeof]; foreach (i, val; arr) { buf[] = cast(ubyte[T.sizeof])(arr[i])[0 .. T.sizeof] result ~= buf; } return result; } ?
Re: strange work of GC
On 2015-02-07 at 12:02, Andrey Derzhavin wrote: If a destroy method is used together with GC inside of my app,it makes my app unstable. In this case I need to choose how to destroy my objects: 1) always manually by method destroy, but without GC; 2) or always automatically by GC, but without using the destroy method. In the first case I need to know how can I disable the automatic GC in my app? In the second case - how can I disable the destroy method calls inside of my app? Why do you want to use destroy? Put GC.collect() after the call to fn1 and GC cleanup will work just fine[1], I've checked. Are you talking about a different program now? [1] Assuming that you compile the program as 64-bit and not 32-bit.
Re: Learning to XML with D
On Friday, 6 February 2015 at 09:15:54 UTC, Derix wrote: So, I set sails to transform a bunch of HTML files with D. This, of course, will happen with the std.xml library. There is this nice example : http://dlang.org/phobos/std_xml.html#.DocumentParser that I put to some use already, however some of the basics seem to escape me, specially in lines like xml.onEndTag[author] = (in Element e) { book.author = e.text(); }; OK, we're doing some event-base parsing, reacting with a lambda function on encountering so-and-do tag, à la SAX. (are we ?) What I don't quite grab is the construct (in Element e) , especially the *in* part. Is it *in* as in http://dlang.org/expression.html#InExpression ? In which case I fail to see what associative array we're considering. It's probably more a way to further qualify the argument e were passing to the λ-function : could someone elaborate on that ? Of course, it is entirely possible that I completely miss the point and that I'm overlooking some fundamentals, if so have mercy and help me find my way back to teh righteous path ;-) Thxxx Maybe, when you're on windows, you could use msxml6 through COM. You have DOM, SAX, Xpath 1.0 and XSLT at your disposal.
Re: Using reduce with user types
On 8/02/2015 1:47 a.m., Kadir Erdem Demir wrote: I can use filter algorithm with my types easily. struct A { string value; int count; } void main( string[] args ) { A[] aArr; aArr ~= A(HTTP, 3); aArr ~= A(HTTPS, 2); aArr ~= A(UNKNOWN_TCP, 4); aArr.filter!( a = a.count == 2); But I couldn't compile when I want to use reduce algorithm. I simply want to get the sum of count variables inside of A[]. auto sum = aArr.reduce!((a,b) = a.count + b.count); The line above gives C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(770): Error: cannot implicitly convert expression (__lambda3(result, front(_param_1))) of type int to A C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(791): Error: template instance app.main.reduce!((a, b) = a.count + b.count).reduce!(A, A[]) error instantiating source\app.d(363):instantiated from here: reduce!(A[]) How can I achieve summing count variables inside A[]? Best Regards Kadir Erdem Demir Ps: The problem caused by my lack of D basics I admit, the reason I can't look up references more before ask question I am in a bit tight schedule. Sorry for my dummy questions. auto sum = aArr.map!`a.count`.reduce!((a,b) = a + b); Not much difference. I tried sum instead of reduce, but it didn't work. Wouldn't matter much as it is the same thing pretty much anyway.
Re: Using reduce with user types
On 2015-02-07 at 13:47, Kadir Erdem Demir wrote: auto sum = aArr.reduce!((a,b) = a.count + b.count); The line above gives C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(770): Error: cannot implicitly convert expression (__lambda3(result, front(_param_1))) of type int to A C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(791): Error: template instance app.main.reduce!((a, b) = a.count + b.count).reduce!(A, A[]) error instantiating source\app.d(363):instantiated from here: reduce!(A[]) // auto sum = aArr.reduce!((a,b) = a.count + b.count); // Wrong auto sum = reduce!((a, b) = a + b.count)(0, aArr); // Good See here: http://dlang.org/phobos/std_algorithm.html#.reduce
Re: static alias this
Another try E)--- struct StaticRegister { static private uint _value; @property static uint value() { return _value; } @property static void value(uint v) { _value = v; } static uint opCall(){return _value;} alias _value this; } void main(string[] s) { StaticRegister = 1; assert(StaticRegister()==1); } Yes you're right, it's a bit strange that the writer works...does the expression 'static this' make sense ?!
Re: Using reduce with user types
auto sum = aArr.map!`a.count`.reduce!((a,b) = a + b); Rikki Thanks a lot. It works. Function map!a.count(aArr) surprises me a little. Because when I read std.algorithm reference: `Implements the homonym function (also known as transform)`. Which reminds me C++ transform and it will never used for returning a element of the struct. I expect transform to modify the elements of the range but in D it seem to me it also used traversing the elements. How can I imagine what map does in my mind, because it doesn't matches with the transform concept in my mind? Regards Kadir Erdem
internal compiler error with immutable
Hi, I'm trying to use immutable class instances and that seems to be really difficult. For example, with the following program I get an internal compiler error: cut- import std.outbuffer : OutBuffer; import std.typecons : Rebindable; enum Attrkey : ubyte { Fgcolor, Bgcolor, } enum MAX_COMPRESSED_ATTRS = 128U; alias Codes = Rebindable!(Attrs)[MAX_COMPRESSED_ATTRS]; static shared Codes codes; private class Attrsp { immutable(Attrsp) next; Attrkey key; ubyte value; private this(Attrkey key, ubyte value, immutable(Attrsp) next) { this.next = next; this.key = key; this.value = value; } // FIXME allow comparing the entire chain for equality. private immutable void print(OutBuffer destination /* destination */) { destination.write(Attrs(); destination.write(cast(ubyte) key); // FIXME .toString() destination.write(, ); destination.write(value); destination.write(, \n); if(this.next is null) destination.write(null); else next.print(destination); destination.write()); } override immutable string toString() { auto destination = new OutBuffer(); print(destination); return destination.toString(); } // TODO add newless static opCall which also does compression? /*doesn't work static immutable immutable(Attrsp) opCall(Attrkey key, ubyte value, immutable(Attrsp) next) { return new immutable Attrsp(key, value, next); }*/ alias Code = ubyte; /* Compresses the given attributes into 1 Byte, if possible. Returns MAX_COMPRESSED if it's not possible. */ static Code compress(immutable(Attrs) node) { // FIXME make thread safe ubyte i; for(i = 0U; i MAX_COMPRESSED_ATTRS; ++i) { if(codes[i] is null) { codes[i] = node; return i; } else if(codes[i] == node) return i; } return i; // tell that it didn't work. } static immutable(Attrs) uncompress(Code value) { assert(value = 0U value MAX_COMPRESSED_ATTRS); return codes[value]; } } alias Attrs = immutable(Attrsp); cut- gdc A.d cc1d: ../../src/gcc/d/dfrontend/statement.c:293: ErrorStatement::ErrorStatement(): Assertion `global.gaggedErrors || global.errors' failed. cc1d: internal compiler error: Aborted Please submit a full bug report, with preprocessed source if appropriate. See file:///usr/share/doc/gcc-4.9/README.Bugs for instructions. gdc (Debian 4.9.1-19) 4.9.1 cut- What I'm trying to do is save space by putting often-used Attrs into an array and just compressing references to those into 1 Byte in the other data structures where it's used (these other data structures are not thread-local). Why do I need Rebindable to begin with? I'm not even trying to modify the contents of the instance, I'm just trying to assign another one to the array slot (actually not even another one - it was null before).
Re: signal handling
On Friday, 6 February 2015 at 19:40:44 UTC, Danny wrote: Hi, if I want to clean up inside a signal handler and then exit the process (as it would have without me handling it), what do I do? Can I exit() inside a signal handler or should I use a more direct quit now function? (after all, it could have been in the middle of relinking the free list when the signal arrived) I'm using a basic C-style sigaction with core.sys.posix.signal and calling std.c.stdlib:exit. For context, I'm performing serial communication with an actual device so the signal may come when my code is blocked in an vendor API call or on an underlying syscall. I have very little state so I'm doing equally little beside freeing extern handles. Setting a global flag and testing it didn't really prove adequate and littered the checks everywhere so I'm thinking now of leveraging std.signals but I'm not sure that will be reliable.
Re: signal handling
Hi rlonstein, I've now read up on the opengroup pages about signal handling (which references POSIX), and apparently it goes like this: A signal can be delivered to a specific thread or to a process. If it's delivered to a process, a random thread of that process will receive it. If it's delivered to a thread, that thread will receive it. sigaction() thus seems to be required per-thread. The handler of a random thread will usually be called. I've now settled on: - per thread, register signal handler using sigaction with a mask that blocks all the cleanup signals while the handler is running. Remember the old handler in TLS variable. - in the signal handler, clean up (just use the write syscall to make it sane), then use sigaction to reinstall the old signal handler, and then call raise(). Seems to work fine so far. Not sure whether it's safe to raise() inside a signal handler. Calling raise() without reinstalling the old signal handler is a very bad idea, I tried. Interesting is that, after reinstalling the old signal handler, I can raise() inside the signal handler even though it's blocked. It probably gets queued in the kernel for the thread. Then the handler returns and it processes the queue, calling the old handler. So win win? See http://svn.nomike.com/playground/trunk/L1/D/TUI/Terminalclient.d, bottom. Note that I don't distinguish between whether I'm in the correct thread or not since for my use case it's not necessary. The FD is always the same and who cares who resets the terminal... I have very little state so I'm doing equally little beside freeing extern handles. Yeah, same for me, really. Setting a global flag and testing it didn't really prove adequate and littered the checks everywhere Yeah,I don't think that EINTR and flag-checking is even safe. What if you check the flag (and see nothing happened) and then go back to the loop and block (in read() or whatever), and right after the flag checking, unbeknowst to you the signal handler sets the flag, returns, and only then you block in read()? You'd block forever. Do you know signalfd() ? I know how it is with external libaries, they always block at the silliest of times. But I've had one (OKAPI) which gave me the FD back, so I could select() on a bunch FDs in my mainloop. In that case, signalfd() was nice since it showed up as a normal read ready in select(), i.e. as a normal event source. Might be worth a try in your case? Like this, in pseudo-code: while (!error) { auto readyfd = select([signalfd, externalfd]); if (readyfd == signalfd) ... signal (would have) happened, handle it else if (readyfd == externalfd) vendor_read_chunk(); else ... } so I'm thinking now of leveraging std.signals but I'm not sure that will be reliable. Hmm, I don't know that one yet.
Re: internal compiler error with immutable
Hi, I've filed it with gdcproject.org before reading your reply. Will it be forwarded to issues.dlang.org or should I file it there as well? Also, it seems there's a new DMD release underway right now, does it still happen with that? (I tried but can't get it to build - doesn't seem to support ARMHF target)
Fun with floating point
Hi, D community! I have this program: import std.stdio; import std.conv; int main(string[] argv) { float eps = 1.0f; float f = 0.0f; while (f + eps != f) f += 1.0f; writeln(eps = ~ to!string(eps) ~ , max_f = ~ to!string(f)); return 0; } According to the languge specification what result would you expect from its execution? When running similar C++ program (VS 2013) the loop terminates and I get t = 2^24 = 16777216. Does D language specifies that loop will be terminated for this program or ? I compiled with DMD and it hungs. Details about assembly generated by DMD can be found here: http://stackoverflow.com/questions/28380651/floating-point-maxing-out-loop-doesnt-terminate-in-d-works-in-c Thanks.
Re: Fun with floating point
And sory for the typos, cannot find edit functionality here..
Re: Using reduce with user types
On Saturday, 7 February 2015 at 13:38:00 UTC, Kadir Erdem Demir wrote: How can I imagine what map does in my mind, because it doesn't matches with the transform concept in my mind? You can think of map as taking a range of something (in this case, an array of A), and calling a user-supplied function on each element in that range. The user-supplied function is a function that describes how to map each value in the range to a result. In your case, the function defines how to map from an A to its `count` member variable (it is a function of type A-int). All aArr.map!`a.count` means is that for each A in aArr, return its `count` member. map!`a.count` is some syntax sugar D has to make function calls shorter; It expands to the following: aArr.map!((A a) { return a.count; }) The main difference between `map` in D and `transform` in C++ is, I believe, twofold. First off, `transform` is eager, meaning it does as much work as possible as son as possible. On the other hand, `map` does as little work as possible as late as possible. For the following code: iota(10).map!(n = writeln(n)).take(5).array Only 0 1 2 3 4 will be printed, as map is lazy and will not do work it doesn't have to. Second of all, map returns a range that is the result of applying the supplied function to each element of aArr. C++'s tranform copies the result to another user-supplied range. If you wanted the equivalent of transform in C++, you could do this: auto result = new int[](10); iota(10).map!(n = n + 1).copy(result) And result will be filled with the results of map.
Re: internal compiler error with immutable
On Sat, Feb 07, 2015 at 02:35:13PM +, Danny via Digitalmars-d-learn wrote: [...] cut- gdc A.d cc1d: ../../src/gcc/d/dfrontend/statement.c:293: ErrorStatement::ErrorStatement(): Assertion `global.gaggedErrors || global.errors' failed. cc1d: internal compiler error: Aborted Please submit a full bug report, with preprocessed source if appropriate. See file:///usr/share/doc/gcc-4.9/README.Bugs for instructions. gdc (Debian 4.9.1-19) 4.9.1 cut- [...] Please file a bug at http://issues.dlang.org/. Compiler internal errors are *always* bugs that need to be fixed. Thanks! T -- English is useful because it is a mess. Since English is a mess, it maps well onto the problem space, which is also a mess, which we call reality. Similarly, Perl was designed to be a mess, though in the nicest of all possible ways. -- Larry Wall
Re: strange work of GC
Why do you want to use destroy? The destroy method always calls a dtor of the objects, where I can destroy some object's variables in that order that I need, I think. And this is very good for me, because I have a full control of the object's destroying stage. But if I use the GC, I have no garanties that the dtors will be called, therefore some of my methods will not be called too. In this case it would be better to disable automatically garbage collection in my D app, elsewise once app will be failed (manual destroying idiom). On another hand if I use only GC (automatically destroying idiom), I have to disable destroy method and all dtors of the objects, so that nobody can call destroy method. Otherwise app will be failed once again. Two idioms are existing in one app at the same time have more possiblities for D programmers to make hard errors in their code, and it is confusing me sometimes. For example, .Net (C#) have no dtors and destroy methods. It is a very good idiom, because no confusions occur.
Re: Issue with template function
On Saturday, 7 February 2015 at 12:04:12 UTC, Nicholas Wilson wrote: Are you wanting to to convert each element in arr to a byte thus truncating and losing data (when T.sizeof != 1)? as in toBytes([1,2,3, 42, 500 /*this will be truncated to 244 */]);// T == int here or are you wanting to convert each element to a ubyte array and then concatenate it to the result. as is ubyte[] toBytes(T)(T[] arr) { ubyte[T.sizeof] buf; if (arr is null) { return null; } ubyte[] result = new ubyte[arr.length * T.sizeof]; foreach (i, val; arr) { buf[] = cast(ubyte[T.sizeof])(arr[i])[0 .. T.sizeof] result ~= buf; } return result; } ? The original code I was using was written in Java, and only had a method for strings. This is closer to what I wanted. My unit tests were just going back and forth with readString function, so I was completely missing this for other types. Nice catch! There were a couple issues with your code so I've included the corrected version: ubyte[] toUbytes(T)(T[] arr) { if (arr is null) { return null; } ubyte[T.sizeof] buffer; ubyte[] result = new ubyte[arr.length * T.sizeof]; foreach (i, val; arr) { buffer[] = cast(ubyte[T.sizeof])((arr[i]))[0 .. T.sizeof]; // Parenthesis and missing semicolon result[i * T.sizeof .. (i * T.sizeof) + T.sizeof] = buffer; // Specify appropriate slice for buffer to be inserted into } return result; }
Re: Better native D 2D graphics library?
On Saturday, 7 February 2015 at 23:29:01 UTC, Namespace wrote: On Saturday, 7 February 2015 at 22:09:03 UTC, Gan wrote: Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists. I once wrote such a library: https://github.com/Dgame/Dgame But since I left D I don't maintain it. Maybe that will change in the next few weeks. But otherwise you are free to use or improve it. That's really cool. Very very similar to SFML. Only thing that makes me concerned is: static immutable string Disk = D; static immutable string Mode = Release; pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\derelict\\lib\\dmd\\DerelictSDL2.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\derelict\\lib\\dmd\\DerelictUtil.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\derelict\\lib\\dmd\\DerelictGL3.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\Dgame\\lib\\ ~ Mode ~ \\DgameInternal.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\Dgame\\lib\\ ~ Mode ~ \\DgameAudio.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\Dgame\\lib\\ ~ Mode ~ \\DgameGraphics.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\Dgame\\lib\\ ~ Mode ~ \\DgameSystem.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\Dgame\\lib\\ ~ Mode ~ \\DgameMath.lib); pragma(lib, Disk ~ :\\D\\dmd2\\src\\ext\\Dgame\\lib\\ ~ Mode ~ \\DgameWindow.lib); I'm not entirely sure what that is or if it's cross-compatible friendly or sharing-with-friends friendly. Though I really hope you re-maintain it.
Re: Fun with floating point
On Saturday, 7 February 2015 at 21:33:51 UTC, Kenny wrote: The above code snippet works correctly when I use LDC compiler (it finds expected 'f' value and prints it to console). I'm wondering is it a bug in DMD? p.s. the final code used by both compilers: import std.stdio; import std.conv; int main(string[] argv) { const float eps = 1.0f; float f = 0.0f; while (f + eps != f) f += 1.0f; writeln(eps = , eps, , max_f = , f); return 0; } Intermediate calculations may be performed at higher precision than the precision of the values themselves. In particular, the f + eps may be performed with 80 bits of precision, even though both values are 32-bit. The comparison will then fail. The reason for the difference between DMD and LDC is that DMD tends to use the FPU more with 80 bits of precision, whereas LDC and GDC will use the SSE2 instructions, which only support 32-bit and 64-bit precision.
Re: Fun with floating point
On Saturday, 7 February 2015 at 23:06:15 UTC, anonymous wrote: On Saturday, 7 February 2015 at 22:46:56 UTC, Ali Çehreli wrote: 1.0 is famously not representable exactly. 1.0 is representable exactly, though. I think he meant 0.1 :-)
Re: Better native D 2D graphics library?
On Saturday, 7 February 2015 at 22:09:03 UTC, Gan wrote: Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists. I once wrote such a library: https://github.com/Dgame/Dgame But since I left D I don't maintain it. Maybe that will change in the next few weeks. But otherwise you are free to use or improve it.
Re: Fun with floating point
On 02/07/2015 01:33 PM, Kenny wrote: The above code snippet works correctly when I use LDC compiler (it finds expected 'f' value and prints it to console). I'm wondering is it a bug in DMD? p.s. the final code used by both compilers: import std.stdio; import std.conv; int main(string[] argv) { const float eps = 1.0f; float f = 0.0f; while (f + eps != f) f += 1.0f; writeln(eps = , eps, , max_f = , f); return 0; } OK, ignore some of my earlier response. :) The code above works with dmd git head 64-bit compilation and prints the following: eps = 1, max_f = 1.67772e+07 You can use the %a format specifier when debugging this issue. It allows you see the bits of the floating point value: writefln(eps: %a, 0.1); double 0.1 on my system: eps: 0x1.ap-4 Ali
Re: Problem with simple Formatted Input example.
On Sunday, 8 February 2015 at 00:47:46 UTC, Ali Çehreli wrote: On 02/07/2015 04:42 PM, Ali Çehreli wrote: readf(%s\n, firstName); I see that readf reads the first line of entry *after* I press two Enters on the console. OK, that is related to the '\n' character that you have in the format string. Also, repeating the space characters has no effect as a single space means zero or more white space anyway. Ali Thankyou, I think it was encoded to be some other character instead of a space. Once I removed the space and re-added it to the string, things seem to work. I am reading your book. It is a great book for newbies. Thanks a lot for the effort.
Re: Fun with floating point
To answer your other question, there is no Edit because this is a newsgroup (see NNTP). The forum interface is supposed to be a convenience but it hides that fact. On 02/07/2015 01:33 PM, Kenny wrote: The above code snippet works correctly There is no right or wrong when you compare floating point values for equality (and inequality) unless those values can be represented exactly in the machine. 1.0 is famously not representable exactly. (It is similar to how 1/3 cannot be represented in the decimal system.) when I use LDC compiler (it finds expected 'f' value and prints it to console). I'm wondering is it a bug in DMD? Not a bug. Ali p.s. the final code used by both compilers: import std.stdio; import std.conv; int main(string[] argv) { const float eps = 1.0f; float f = 0.0f; while (f + eps != f) f += 1.0f; writeln(eps = , eps, , max_f = , f); return 0; }
Re: Fun with floating point
On Saturday, 7 February 2015 at 16:06:14 UTC, Kenny wrote: Hi, D community! I have this program: import std.stdio; import std.conv; int main(string[] argv) { float eps = 1.0f; float f = 0.0f; while (f + eps != f) f += 1.0f; writeln(eps = ~ to!string(eps) ~ , max_f = ~ to!string(f)); return 0; } According to the languge specification what result would you expect from its execution? When running similar C++ program (VS 2013) the loop terminates and I get t = 2^24 = 16777216. Does D language specifies that loop will be terminated for this program or ? I compiled with DMD and it hungs. Details about assembly generated by DMD can be found here: http://stackoverflow.com/questions/28380651/floating-point-maxing-out-loop-doesnt-terminate-in-d-works-in-c Thanks. A point of advice that Walter gives for situations like these is to ensure that your algorithm has a minimum required precision to work correctly but not a maximum. As Peter Alexander mentioned, DMD performs intermediate calculations at higher precision than GDC/LDC and thus your algorithm breaks.
Re: How to write asia characters on console?
On 02/07/2015 09:57 PM, Lave Zhang wrote: Hi, My first D program is like this: --- import std.stdio; void main(string[] args) { dstring s1 = hello你好d; writeln(s1); } --- But the output is not correct(and my console codepage is 936): C:\D\dmd2\samples\ddmd hello.d -offilename hello.exe C:\D\dmd2\samples\dhello.exe hello浣犲ソ thanks. This thread may be useful: http://forum.dlang.org/thread/suzymdzjeifnfirtb...@dfeed.kimsufi.thecybershadow.net#post-suzymdzjeifnfirtbnrc:40dfeed.kimsufi.thecybershadow.net Ali
Better native D 2D graphics library?
Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists.
Re: Fun with floating point
On Saturday, 7 February 2015 at 22:46:56 UTC, Ali Çehreli wrote: 1.0 is famously not representable exactly. 1.0 is representable exactly, though.
Re: strange work of GC
On 2/8/2015 4:32 AM, Andrey Derzhavin wrote: Why do you want to use destroy? The destroy method always calls a dtor of the objects, where I can destroy some object's variables in that order that I need, I think. And this is very good for me, because I have a full control of the object's destroying stage. But if I use the GC, I have no garanties that the dtors will be called, therefore some of my methods will not be called too. In this case it would be better to disable automatically garbage collection in my D app, elsewise once app will be failed (manual destroying idiom). On another hand if I use only GC (automatically destroying idiom), I have to disable destroy method and all dtors of the objects, so that nobody can call destroy method. Otherwise app will be failed once again. Two idioms are existing in one app at the same time have more possiblities for D programmers to make hard errors in their code, and it is confusing me sometimes. For example, .Net (C#) have no dtors and destroy methods. It is a very good idiom, because no confusions occur. You shouldn't think of destructors as they are in C++. They're more akin to finalizers in Java and C#. You should never use them to clean up any GC memory or implement any operations which touch GC memory. In your case, forget destructors and the destroy method. Just implement a common method on all of your objects that need cleanup (perhaps name it 'terminate') and call that. This gives you the deterministic destruction that you want (the same as calling destroy on each object) while avoiding the possibility that the GC can call your cleanup method.
Re: static alias this
On 02/07/2015 04:46 AM, Mike wrote: B)- struct StaticRegister { static private uint _value; @property static uint value() { return _value; } @property static void value(uint v) { _value = v; } alias value this; } void main(string[] s) { StaticRegister = 1; assert(StaticRegister == 1); } --- ... the assignment error is eliminated, but the read is not. I bet it's an unintentional implementation artifact. Assigning to a type doesn't make sense to me. I argue that either both errors should be eliminated, or neither should be eliminated. It is not hard to create strange D code. I recommend the following lightning talk for fun. :) Brian Schott at DConf 2014: http://www.youtube.com/watch?v=oF8K4-bieaw#t=1620 Now, in the example below, `this` is referring to the type itself in a static context Not exactly type itself because you apply typeof() to it later below. I this 'this' means the type of the object if it were not a static function. :/ C)--- import std.stdio; struct StaticRegister { static string GetType() { return typeof(this).stringof; } } void main(string[] s) { writeln(StaticRegister.GetType()); } --- So, it follows that the example below should work... and it does D)--- struct StaticRegister { static private uint _value = 0; @property static uint value() { return _value; } @property static void value(uint v) { _value= v; } static uint GetValue() { return this.value; That works by accident. I am surprised that 'this' works in a static function. In any case, it should better be null. Ok, it's good that 'this' is not available: assert(this is null); Error: 'this' is only defined in non-static member functions, not foo Phew... :) So, 'this.value' works by accident because the compiler reaches for *static* value() without evaluating 'this'. Ali
Re: Issue with template function
The original code I was using was written in Java, and only had a method for strings. This is closer to what I wanted. My unit tests were just going back and forth with readString function, so I was completely missing this for other types. Nice catch! There were a couple issues with your code so I've included the corrected version: That's what I get for replying at 11pm =p ubyte[] toUbytes(T)(T[] arr) { if (arr is null) { return null; } ubyte[T.sizeof] buffer; ubyte[] result = new ubyte[arr.length * T.sizeof]; foreach (i, val; arr) { buffer[] = cast(ubyte[T.sizeof])((arr[i]))[0 .. T.sizeof]; // Parenthesis and missing semicolon result[i * T.sizeof .. (i * T.sizeof) + T.sizeof] = buffer; // Specify appropriate slice for buffer to be inserted into } return result; } thinking about it again this can be done in a single memcpy ubyte[] toUbytes(T)(T[] arr) { if (arr is null) { return null; } ubyte[] result = new ubyte[arr.length * T.sizeof]; memcpy(result.ptr, arr.ptr , arr.length * T.sizeof); return result; } and an asUbytes can be done as a cast ubyte[] toUbytes(T)(T[] arr) { if (arr is null) { return null; } return cast(ubyte[]) arr.ptr [0 .. arr.length * T.sizeof]; }
Re: How to write asia characters on console?
On Sunday, 8 February 2015 at 05:57:31 UTC, Lave Zhang wrote: Hi, My first D program is like this: --- import std.stdio; void main(string[] args) { dstring s1 = hello你好d; writeln(s1); } --- But the output is not correct(and my console codepage is 936): C:\D\dmd2\samples\ddmd hello.d -offilename hello.exe C:\D\dmd2\samples\dhello.exe hello浣犲ソ thanks. Hi, I tried your code and it works fine for me. I think the windows console only supports UTF-16, try using wchar/wstring instead of dchar/dstring.
Re: Problem with simple Formatted Input example.
On 02/07/2015 04:29 PM, Venkat Akkineni wrote: This simple program seems to just hang. I am probably missing something. Any help is appreciated. I am using Linux with DMD. Program compiles fine, but when enter a string press enter, the programs seems to wait forever without returning. import std.stdio; void main() { string firstName; readf(%s\n, firstName); My earlier understanding was that readf was reading till the end of the input. So, you will see that it will terminate when you press Ctrl-D at the console. I explain that understanding here: http://ddili.org/ders/d.en/strings.html#ix_strings.readln However, when I tried your code again with dmd git head, I see that readf reads the first line of entry *after* I press two Enters on the console. Ali
How to write asia characters on console?
Hi, My first D program is like this: --- import std.stdio; void main(string[] args) { dstring s1 = hello你好d; writeln(s1); } --- But the output is not correct(and my console codepage is 936): C:\D\dmd2\samples\ddmd hello.d -offilename hello.exe C:\D\dmd2\samples\dhello.exe hello浣犲ソ thanks.
How to write asia characters on console?
Hi, My first D program is like this: --- import std.stdio; void main(string[] args) { dstring s1 = hello你好d; writeln(s1); } --- But the output is not correct(and my console codepage is 936): C:\D\dmd2\samples\ddmd hello.d -offilename hello.exe C:\D\dmd2\samples\dhello.exe hello浣犲ソ thanks.
Problem with simple Formatted Input example.
This simple program seems to just hang. I am probably missing something. Any help is appreciated. I am using Linux with DMD. Program compiles fine, but when enter a string press enter, the programs seems to wait forever without returning. import std.stdio; void main() { string firstName; readf(%s\n, firstName); writeln(firstName); } Thankyou Venkat
Re: strange work of GC
On 2015-02-08 at 01:20, Mike Parker wrote: In your case, forget destructors and the destroy method. Just implement a common method on all of your objects that need cleanup (perhaps name it 'terminate') and call that. This gives you the deterministic destruction that you want (the same as calling destroy on each object) while avoiding the possibility that the GC can call your cleanup method. What is wrong with doing all that in a destructor? I don't know if it is just an implementation detail, but a destroyed object is either zero-filled or reinitialized to the default, so, if implemented correctly, it knows whether a cleanup is required (and I'm assuming that a model of simple single ownership is used, like in Qt). Therefore it should be safe to use destroy to finalize an object and even to put destroy in its destructor in order to perform a controlled cascade destruction of all the children that require immediate cleanup (ie. releasing expensive non-GC resources, closing connections, etc.). The main difference with C++ being that you would only force finalization, but then let the GC free the memory in its normal fashion.
Re: Better native D 2D graphics library?
On Saturday, 7 February 2015 at 22:09:03 UTC, Gan wrote: Is there a better D graphics library in the works? I'm using SFML(which is very easy and has lots of features) but it seems to use a lot of ram(if you leave it running for a while on a graphic intensive scene) and trying to make it include the dependencies with the compiled executable is complicated. Is there a D 2D graphics library that's just as easy, cross platform, doesn't use X11, allows drawing to off-screen buffers and drawing those to screen? (plus supports nice drawing of shapes, circles, rectangles, lines) I'm probably asking too much- I doubt such a thing exists. Not what you're asking for, but you could always use SDL - I believe it has two or three bindings to D. Check on dub. I doubt you're going to find anything like SFML written in D as it's a lot of work to maintain such a project, and just duplication of effort. It's why most projects in most languages just wrap SDL in some form.
Re: Problem with simple Formatted Input example.
On 02/07/2015 04:42 PM, Ali Çehreli wrote: readf(%s\n, firstName); I see that readf reads the first line of entry *after* I press two Enters on the console. OK, that is related to the '\n' character that you have in the format string. Also, repeating the space characters has no effect as a single space means zero or more white space anyway. Ali
Re: strange work of GC
On 2/8/2015 11:32 AM, FG wrote: On 2015-02-08 at 01:20, Mike Parker wrote: In your case, forget destructors and the destroy method. Just implement a common method on all of your objects that need cleanup (perhaps name it 'terminate') and call that. This gives you the deterministic destruction that you want (the same as calling destroy on each object) while avoiding the possibility that the GC can call your cleanup method. What is wrong with doing all that in a destructor? I don't know if it is just an implementation detail, but a destroyed object is either zero-filled or reinitialized to the default, so, if implemented correctly, it knows whether a cleanup is required (and I'm assuming that a model of simple single ownership is used, like in Qt). Therefore it should be safe to use destroy to finalize an object and even to put destroy in its destructor in order to perform a controlled cascade destruction of all the children that require immediate cleanup (ie. releasing expensive non-GC resources, closing connections, etc.). The main difference with C++ being that you would only force finalization, but then let the GC free the memory in its normal fashion. First, there are no guarantees about when or if a destructor is going to be called. The fact that the current GC calls the destructors of all live objects at application shutdown is an implementation detail. If you want deterministic destruction, you can not rely on destructors. Second, if you are going to call destroy on every object to clean them up, then in principle that's fine. But now you have to be careful that no mistakes slip into the code base, e.g. forgetting to call destroy on an object that touches GC memory in its destructor. By separating resource cleanup from object destruction, you get both deterministic cleanup and more freedom in choosing whether or not to clean up at all. I used to be obsessive about cleaning up everything at app exit (my C background, I suppose). These days, I've come around to the view that it's fine just to let the OS handle it. I put a terminate method in every class that allocates any sort of resource. If I need to free those resources at runtime, I call terminate and let the GC worry about the object when it needs to. At app exit, I only call terminate on objects that absolutely need to do something before the process exits, like writing a final message to a log file, or sending a See You Later packet to a server. Everything else I just let go and leave to the OS to deal with. There's no reason to do otherwise. In essence, resource cleanup only happens when and if I say. That just isn't possible if all cleanup is in destructors. You either have to destroy *every* object yourself, or be vigilant about which objects you let the GC call destructors on.