Re: Erasing passwords from ram?

2019-05-09 Thread Nick Sabalausky via Digitalmars-d-learn

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?


I've seen this done, and regardless of likelihoods, it doesn't 
hurt as a precaution.


The memutils lib offers a tool for this, 'SecureMem':
http://code.dlang.org/packages/memutils

In addition to memory-zeroing, it can also prevent it from 
getting "dumped to disk on a crash or during OS 
sleep/hibernation."




Recommendations for best JSON lib?

2019-04-20 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn
I only need to read arbitrary JSON data, no need for 
writing/(de)serialization.


Re: Cross compile windows programs on linux

2018-08-24 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/24/2018 12:30 PM, John Burton wrote:

On Friday, 24 August 2018 at 15:26:30 UTC, kinke wrote:

On Friday, 24 August 2018 at 13:10:40 UTC, John Burton wrote:
Is in the subject. Are there any cross compilers that will run on a 
linux system but compile D code using Win32 into a windows .exe file, 
preferably 64 bit? I can find hints of cross compilers but not really 
seen anything packaged up?


See https://forum.dlang.org/post/acjcrfvxloapdlapz...@forum.dlang.org.


Oh thank you.
I did a search but somehow missed that


You could probably also just run the windows version of the compiler 
under wine. I think I remember hearing of people doing that.


Re: Generically call a function on Variant's payload?

2018-08-21 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/21/2018 03:27 PM, Steven Schveighoffer wrote:


If you examine how the code for variant works, it's quite clever. It 
establishes a "handler" that is generated with full compile-time type 
info available when the value is *assigned*, but then cast to a function 
taking a void pointer and an operation. This way, the user of the 
variant doesn't have to know what is inside, just the handler does. The 
code that sets the payload is the one that establishes how to use it.


The same type of pattern could be used to, for instance, provide all the 
functions that a range uses.


But it's not something that can be tacked on to Variant. You'd have to 
write your own type, because you'd have to handle the different 
functions that you know are common between the types in question (e.g. 
the operations supported on a variant are here: 
https://github.com/dlang/phobos/blob/master/std/variant.d#L163)


Oooh, that's really cool! I might try my hand at something like that.

I bet it actually could be generalized to a certain extent. Variant 
would just have to be templated on the expected interface. Then it could 
compile-time loop over the list of functions expected, and introspect 
each of them enough to build the handler and the forwarders. Doesn't 
exactly sound fun to implement, but I'd bet it could be done.


Re: Generically call a function on Variant's payload?

2018-08-21 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/21/2018 03:03 AM, Nicholas Wilson wrote:
On Monday, 20 August 2018 at 00:27:04 UTC, Nick Sabalausky (Abscissa) 
wrote:
Suppose I've wrapped a Variant in a struct/class which ensures the 
Variant *only* ever contains types which satisfy a particular 
constraint (for example: isInputRange, or hasLength, etc...).


Is there a way to call a function (ex: popFront) on the Variant, 
*without* knowing ahead of time all the possible static types it might 
might contain?


I assume you mean at compile time AoT of development of your library?

Yes, don't use Variant; use https://github.com/s-ludwig/taggedalgebraic



TaggedAlgebraic requires a finite list of every type it can contain. 
That's the deal-breaker for what I had in mind. I need something less 
like Algebraic and more like Variant, which *doesn't* require a finite, 
canonical list of every type it can contain.


The more I think about it though, the more I'm not so sure that the 
extensibility is important enough to warrant all of this, or...more 
importantly...that all of this is even necessary anyway for users to 
accomplish the use-cases I had in mind. I think I may go with an 
entirely different approach.


Re: Generically call a function on Variant's payload?

2018-08-21 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/20/2018 10:57 PM, Jonathan M Davis wrote:


Runtime reflection is theoretically possible in D, but it requires
generating the appropriate stuff for every type involved so that the runtime
stuff has something to work with. Java built all of that into the language
and has the JVM to boot, which fundamentally changes some of what can be
done. With D, we're basically in exactly the same boat as C or C++ except
that we have better compile-time type introspection. In principle, a runtime
reflection facility could be built using that, but even if it were part of
Phobos, it would still have to be opt-in. So, I don't know how useful such a
solution would ever be outside of very specific use cases. Regardless, given
that D's object files, linking, etc. are using the C tools, it was never
going to be the case that Java-style runtime reflection would be built in to
D like it is with Java.


Yea. Not to disagree at all with those reasons, but that is unfortunate. 
I've long been interested in how various features of D (not exclusively 
D, though) combine in ways that, in effect, obsolete much of traditional 
OOP inheritence-based polymorphism - offering the same abilities of OOP 
but without many of the notable downsides. Java-style runtime reflection 
would take us that much further in this regard. (Plus, it would make D 
that much more of a universal-toolbox of a language.) Oh well, dreams vs 
reality ;)




Re: Generically call a function on Variant's payload?

2018-08-20 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/20/2018 04:34 PM, Jonathan M Davis wrote:


 foreach(T; TypesThatVariantHolds)


Yea, that's what I would've just done, but I wanted to support 
user-created types not already known to my library.



You
can't just call functions on completely unknown types, because the compiler
wouldn't know what code to generate or what to link against.



Right. D's templates have really spoiled me. Because of them, I've grown 
accustomed to invoking functions on unknown types ;)


But you're right, that's not going to work for runtime dispatch without 
enumerating each possible type. Even if I try (like I was thinking) to 
provide a templated function to convert any of the concrete types to an 
internal-only supertype, I'd still need something to runtime dispatch to 
the right template instance. Darn.


A lot of times, I really wish I could introspect across *all* linked 
modules, not just specific ones. Ex: "Hey compiler, give me a 
compile-time list of ALL types in this program with UDA @xyz". Then 
things like this could be built out of that. No need to worry about 
unknown types/symbols because they would all be known and a finite list 
could always be constructed.


Although, what would REALLY be nice is if, for every type, the compiler 
built a list of every member and how to access it (which...really it has 
to do anyway), but then uses that info to build a master runtime 
dispatch system. Types such as Variant already have runtime knowledge of 
what type is currently being held, so that info could be passed to the 
compiler-generated "master runtime dispatch" system along with what 
member to invoke/access.


Come to think of it...aren't I just describing standard run-of-the-mill 
runtime reflection? I mean, hasn't Java already been able to do that for 
ages? But then, in Java everything is already part of the class 
hierarchy anyway so maybe that's why it's possible there?




Re: Generically call a function on Variant's payload?

2018-08-20 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/19/2018 11:31 PM, Paul Backus wrote:


You are basically reinventing OOP here.



Yes, I am. Deliberately, in fact. Class inheritance is my backup plan, 
though.


My use-case is actually very, very similar to std.digest:

There are various benefits to using a template-and-constraint based 
interface. But one notable downside is the inability to handle the 
situation where the actual type needed is only known at runtime. In 
std.digest, this dilemma is dealt with by duplicating the entire 
interface in BOTH template/constraint AND class-inheritance varieties.


Additionally, an important thing to note in the case of std.digest is 
that `isDigest!T` returns FALSE for types using the OOP version of the 
interface. I think there is (arguably) a certain merit in that:


The OOP interface obviously uses classes, whereas (in order to obtain 
the full potential benefits of a template-and-constraint approach) the 
template interface uses (and even requires) structs. Because of this, 
instances should be constructed differently ("T instance;" vs "T 
instance = new T();"). Thus, any generic code that wants to handle ANY 
digest type must be very careful to mind this distinction whenever 
creating new instances. Presumably, this may be why std.digest chose to 
NOT let OO digests satisfy the template-oriented isDigest.


And then std.digest also needs WrapperDigest, needed to convert a 
template-style digest to OO-style.


So...while std.digest succeeds at offering the best-of-both-worlds 
between template and OO approaches, it also creates a whole new mess via 
completely duplicated interfaces that aren't 100% compatible.


I want to see if I can do better.

So back to the root of the problem:

We have a bunch of types, including user-defined types we don't have 
advance knowledge of. And we need a type which can hold any of them at 
runtime.


AFAIK, there are two classic ways to do that: One is OOP, the other is 
an unbounded discriminated union (a variant). Unlike class-based 
inheritance, a variant CAN be implemented as a struct. So, at least in 
theory, a variant-based type could potentially be made which implements 
the *true* template-based interface, eliminating the need for duplicate 
APIs and the mess that entails.


There are a bunch of discriminated union types available for D, but the 
only one I'm aware of that *doesn't* require a finite-sized list of 
types known ahead-of-time is Phobos's Variant. The only problem is 
calling a function on a type not already known ahead-of-time. Maybe 
that's unsolvable? If so, then I'll fallback to the std.digest approach. 
But I'd prefer to avoid that, if possible.


Re: Generically call a function on Variant's payload?

2018-08-19 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/19/2018 10:23 PM, Jonathan M Davis wrote:

On Sunday, August 19, 2018 6:33:06 PM MDT Nick Sabalausky (Abscissa) via
Digitalmars-d-learn wrote:


Maybe something involving using Variant.coerce to convert the payload to
a single common type? Not sure how I would do that though.


You could always create a wrapper type. Whatever code you're dealing with is
going to need to statically know what type it's using even that's a base
type in a class hierarchy. So, you need to present a type which actually has
the appropriate API even if internally, it can dynamically handle several
types which have that API, and it's not known ahead of time which type that
is.



I guess the parts I'm unclear on are:

1. What mechanism does Variant.coerce!SomeType use to attempt conversion 
to SomeType?


2. How (if possible) can I provide a way to convert something to type 
SomeType which Variant.coerce!SomeType will then recognize and use?


Re: Generically call a function on Variant's payload?

2018-08-19 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 08/19/2018 08:27 PM, Nick Sabalausky (Abscissa) wrote:
Suppose I've wrapped a Variant in a struct/class which ensures the 
Variant *only* ever contains types which satisfy a particular constraint 
(for example: isInputRange, or hasLength, etc...).


Is there a way to call a function (ex: popFront) on the Variant, 
*without* knowing ahead of time all the possible static types it might 
might contain?


Maybe something involving using Variant.coerce to convert the payload to 
a single common type? Not sure how I would do that though.


Generically call a function on Variant's payload?

2018-08-19 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn
Suppose I've wrapped a Variant in a struct/class which ensures the 
Variant *only* ever contains types which satisfy a particular constraint 
(for example: isInputRange, or hasLength, etc...).


Is there a way to call a function (ex: popFront) on the Variant, 
*without* knowing ahead of time all the possible static types it might 
might contain?


Re: D's type declarations seem to read right to left.

2018-03-21 Thread Nick Sabalausky via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 20:07:09 UTC, tipdbmp wrote:

D's type declarations seem to read right to left.


int an_integer;

int[10] an_array_of_10_integers;
int[10]* a_pointer_to_an_array_of_10_integers = 
_array_of_10_integers;


int*[10] an_array_of_10_pointers_to_integers;
int*[10]* a_pointer_to_an_array_of_10_pointers_to_integers = 
_array_of_10_pointers_to_integers;


int[3][2] an_array_of_2_arrays_of_3_integers;
int[string] a_hashtable_with_string_keys_and_integer_values;

int[3][string][2] 
an_array_of_2_hashtables_with_string_keys_and_array_of_3_integers_values;


int function(float) 
a_pointer_to_a_function_that_takes_a_float_and_returns_an_integer;
int function(float)[10] 
an_array_of_10_functions_that_take_floats_and_return_integers;



I think this is a big improvement over C's "spiral" way of 
reading types: 
http://www.unixwiz.net/techtips/reading-cdecl.html

I guess it could've been left to right, but... it's okay.


The way I see it, English "of" flips its operands backwards 
compared to English's [adjective][noun] syntax:


int an_integer;
int* an_integer_pointer;
int[] an_integer_array;
int[3]* an_integer_array(length 3)_pointer;

But granted, in English, "of" is more scalable than 
[adjective][noun].


Re: docs/definition: !object

2018-03-08 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 03/08/2018 05:31 AM, Steven Schveighoffer wrote:

On 3/8/18 1:00 AM, Nick Sabalausky (Abscissa) wrote:


But are we CERTAIN that's all there is to it? I have a non-reduced 
situation right now where outputting the address of a class reveals a 
non-null address, and yet assert(!!theObjectInQuestion) is failing. 
(this is occurring during stack unwinding, if that makes a difference)


Turns out it wasn't a class at all: As Jacob pointed out in my other 
thread, it *used* to be a class/interface in a previous lib version 
(vibe's TCPConnection) but got changed to a struct without my noticing. 
Hence the seemingly weird behaviours.




One thing to keep in mind, assert(someObject) does more than just check 
if it's not null, it also runs the object's invariant to see if it's valid.




Ahh, right! *That's* the part I knew I'd heard about and was trying to 
remember.


Re: Can't "is null" an interface?!?! Incompatible types???

2018-03-08 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 03/08/2018 03:04 AM, Nick Sabalausky (Abscissa) wrote:


Interesting. I was using vibe.d 'v0.8.3-rc.1' (which doesn't appear to 
work on run.dlang.io). But it does seem to work for me if I use 
'v0.8.3-alpha.1'.


I wonder what could have changed to result in this?


https://github.com/vibe-d/vibe.d/issues/2108


Re: Can't "is null" an interface?!?! Incompatible types???

2018-03-08 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 03/08/2018 01:13 AM, Nicholas Wilson wrote:


That does seem odd.
---
/+dub.sdl:
dependency "vibe-d" version="~>0.8.3-alpha.1"
+/
import vibe.core.net;
import std.stdio;
TCPConnection mySocket;

void main() {
     auto b = mySocket is null;
     writeln(b);
}
---
works fine on run.dlang.io


Interesting. I was using vibe.d 'v0.8.3-rc.1' (which doesn't appear to 
work on run.dlang.io). But it does seem to work for me if I use 
'v0.8.3-alpha.1'.


I wonder what could have changed to result in this?


Re: docs/definition: !object

2018-03-07 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 03/08/2018 12:05 AM, ketmar wrote:

Nick Sabalausky (Abscissa) wrote:

I'm having trouble finding the documentation for what exactly the 
unary "not" operator does when applied to a class/interface object. 
Does this documentation exist somewhere?


I know at least part of it involves "is null", but I seem to remember 
hearing there was more to it than just that.


https://dlang.org/spec/operatoroverloading.html#boolean_operators

"Class references are converted to bool by checking to see if the class 
reference is null or not."


Ah, thanks.

But are we CERTAIN that's all there is to it? I have a non-reduced 
situation right now where outputting the address of a class reveals a 
non-null address, and yet assert(!!theObjectInQuestion) is failing. 
(this is occurring during stack unwinding, if that makes a difference)


(Or does  return the address of the *reference* to the object 
rather than the address of the object?...You can see just how often I do 
OO in D ;) )


docs/definition: !object

2018-03-07 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn
I'm having trouble finding the documentation for what exactly the unary 
"not" operator does when applied to a class/interface object. Does this 
documentation exist somewhere?


I know at least part of it involves "is null", but I seem to remember 
hearing there was more to it than just that.


Can't "is null" an interface?!?! Incompatible types???

2018-03-07 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

-
import vibe.core.net;
TCPConnection mySocket;

void main() {
auto b = mySocket is null;
}
-

That's giving me:

-
Error: incompatible types for (mySocket) is (null): TCPConnection and 
typeof(null)

-

WTF?!?!

The type in question (vibe.core.net.TCPConnection) is an interface:
http://vibed.org/api/vibe.core.net/TCPConnection
https://github.com/vibe-d/vibe.d/blob/master/core/vibe/core/net.d#L344

The following works just fine:
-
interface IFoo {}

void main() {
IFoo i;
auto b = i is null;
}
-



Spawning a process: Can I "have my cake and eat it too"?

2018-03-01 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn
I'd like to include this functionality in Scriptlike, but I don't know 
if it's even possible:


Launch a process (spawnProcess, pipeShell, etc) so the child's 
stdout/stderr go to the parent's stdout/stderr *without* the possibility 
of them getting inadvertently reordered/reinterleaved when viewed on the 
terminal, *and* still allow the parent to read the child's stdout and 
stderr?


How could this be accomplished? Is it even possible?


Tuts/Aritcles: Incrementasl C++-to-D conversion?

2018-02-21 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn
Are there any tutorials or articles out there for "getting started with 
converting a C++ codebase to D one module at a time?" Or at the very 
least: tips, tricks, lessions learned, from those who have come before.


Re: No line numbers in stack trace (again)

2017-12-12 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 12/05/2017 08:43 AM, Nordlöw wrote:
If I get the following stack trace ___without line numbers___ (instead 
??:?) what's missing?




Linux stack trace line numbers have disappeard for me, too. Used to 
work. Very frustrating, and a royal PITA when dealing with unittests. 
Help would be appreciated. Could it be a PIC thing?


Re: git workflow for D

2017-12-04 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 12/03/2017 03:05 PM, bitwise wrote:
I've finally started learning git, due to our team expanding beyond one 
person - awesome, right? 


PROTIP: Version control systems (no matter whether you use git, 
subversion, or whatever), are VERY helpful on single-person projects, 
too! Highly recommended! (Or even any time you have a directory tree 
where you might want to enable undo/redo/magic-time-machine on!)



Anyways, I've got things more or less figured 
out, which is nice, because being clueless about git is a big blocker 
for me trying to do any real work on dmd/phobos/druntime. As far as 
working on a single master branch works, I can commit, rebase, merge, 
squash, push, reset, etc, like the best of em.


Congrats! Like Arun mentioned, git's CLI can be a royal mess. I've heard 
it be compared to driving a car by crawling under the hood and pulling 
on wires - and I agree.


But it's VERY helpful stuff to know, and the closer you get to 
understanding it inside and out, the better off you are. (And I admit, I 
still have a long ways to go myself.)


What I'm confused about 
is how all this stuff will interact when working on a forked repo and 
trying to maintain pull requests while everyone else's commits flood in.


Yea. It's fundamental stuff, but it can be frustratingly convoluted for 
the uninitiated. TBH, I really wish we had widespread tools that cater 
to what have emerged as the most common best-practice workflows and the 
basic primitives of those workflows. I even went so far as to get 
started on such a tool (I call it "wit"), but it's been kind of on the 
back burner lately, and it's still far too embryonic for any kind of 
release. (I am still using a git repo for it locally though! Again, 
highly recommeded. At the very least, just because there's nothing worse 
than accidentally loosing a bunch of important code, or finding you need 
to undo a bunch of changes that didn't work out.)


One thing to keep in mind: Any time you're talking about moving anything 
from one repo to another, there's exactly two basic primitives there: 
push and pull. Both of them are basically the same simple thing: All 
they're about is copying the latest new commits (or tags) from WW branch 
on XX repo, to YY branch on ZZ repo. All other git commands that move 
anything bewteen repos start out with this basic "push" or "pull" 
primitive. (Engh, technically "fetch" is even more of a primitive than 
those, but I find it more helpful to think in terms of "push/pull" for 
the most typical daily tasks.)


How does one keep their fork up to date? For example, if I fork dmd, and 
wait a month, do I just fetch using dmd's master as a remote, and then 
rebase?


Yes. "pull" from the official ~master to your local repo's ~master, if 
necessary rebasing your changes on top of the new ~master. Although 
generally, you shouldn't have much (or any) changes in your own ~master 
branch, so typically the rebase part really shouldn't be needed at all, 
since you shouldnt have any local changes on ~master which would need to 
be rebased (this ideal is a situation git refers to as "fast-forward").


Unless, of course, you happen to be futzing around making some changes 
and making your commits to your ~master (which you're not *supposed* to 
be doing anyway - standard best practice is to do all your work within a 
branch). In this case you probably will need to rebase. (The other 
alternative to rebasing is always a merge, but in the specific situation 
you're describing, rebase is definitely cleaner and will lead to less 
problems).



Will that actually work,


Yes.

or is that impossible across separate 
forks/branches?


Totally possible. In fact, that's exactly the sort of stuff git is 
designed to handle.


What if I have committed and pushed to my remote fork 
and still want to merge in the latest changes from dlang's master branch?




You pretty much already got this right. First, you do just as you said 
above:


1. Pull from the official repo's ~master to your local repo's ~master 
(rebasing, if necessary, any commits you may have on your local ~master. 
Although, like Bastile said, if you're making local commits to ~master 
then *technically* "you're doing it wrong").


2. And then, after you've pulled (and maybe rebased) the lastest 
official updates to your local machine...maybe then you added some more 
commits of your own...then you can push it all from your local machine's 
clone to your remote fork.


Think of your remote github fork as the "published" copy of your local 
repo. It should exactly mirror your local repo (minus whatever 
branches/commits you're not yet ready to unleash upon the world): You do 
your work locally, and whenever you want to "publish" or "make public" 
your local work, you push it from your local repo to your remote github 
fork. That's all your remote github fork is: A copy of your whatever 
parts of your local repo that you've chosen to publish.



And how does a pull request 

Re: Struct inside a class: How to get outer?

2017-12-03 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 12/03/2017 03:46 AM, bauss wrote:

On Sunday, 3 December 2017 at 07:38:47 UTC, Jonathan M Davis wrote:
As I understand it, there is no outer for nested structs, only nested 
classes. So, you'll either have to use a nested class or explicitly 
pass a reference to the outer class to the nested struct.



It wouldn't make much sense either, if a struct  was able to do it.



Why is that?


Struct inside a class: How to get outer?

2017-12-02 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

Is this even possible? My attempts:

class Outer {
struct Inner {
void foo() {
// Error: no property 'outer' for type 'Inner'
Outer o = this.outer;

// Error: cannot implicitly convert expression
// this of type Inner to testNested.Outer
Outer o = this;
}
}
}


gdc-6.3.0 on travis borked?

2017-11-30 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn
When using gdc-6.3.0 on travis-ci, travis is reporting that it can't 
download the compiler:


--
$ source "$(CURL_USER_AGENT="$CURL_USER_AGENT" bash install.sh gdc-6.3.0 
--activate)"


curl: (22) The requested URL returned error: 404 Not Found

curl: (22) The requested URL returned error: 404 Not Found

curl: (22) The requested URL returned error: 404 Not Found

curl: (22) The requested URL returned error: 404 Not Found

curl: (22) The requested URL returned error: 404 Not Found

Failed to download 
'http://gdcproject.org/downloads/binaries/x86_64-linux-gnu/gdc-6.3.0.tar.xz'


/home/travis/.travis/job_stages: line 57: : No such file or directory

The command "source "$(CURL_USER_AGENT="$CURL_USER_AGENT" bash 
install.sh gdc-6.3.0 --activate)"" failed and exited with 1 during .

--

Anyone know anything about this? Where (and to whom) should this be 
reported?


Re: Range tee()?

2017-10-16 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 10/16/2017 03:30 AM, lobo wrote:
On Monday, 16 October 2017 at 07:28:03 UTC, Nick Sabalausky (Abscissa) 
wrote:

Does Phobos have a way to "tee" a range?

For example, suppose you had something like this:

[...]


https://dlang.org/phobos/std_range.html#tee ?


Ahh, thanks, I was only looking in std.algorithm. Didn't expect it to be 
in std.range.


Range tee()?

2017-10-16 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

Does Phobos have a way to "tee" a range?

For example, suppose you had something like this:

-
// Do something with each file in a dir
dirEntries(selectedDir, SpanMode.shallow)
.filter!someFilterCriteria
.doSomethingWithFile;
-

It would be really nice to be able to "wiretap" that, to trace/debug/etc 
by nothing more than ADDING a single statement at any desired wiretap point:


-
// Do something with each file in a dir
dirEntries(selectedDir, SpanMode.shallow)
//.tee(a => writeln("FOUND: ", a))  // DEBUG: TRACE ALL FILES FOUND!
.filter!someFilterCriteria
//.tee(a => writeln("SELECTED: ", a))  // DEBUG: TRACE RESULT OF 
FILTER!

.doSomethingWithFile;
-

Does something like this already exist Phobos? I tried looking for a 
"tee" in st.algorithm but came up nothing. If not, it seems like a 
pretty glaring omission.


Re: problem with std.variant rounding

2017-05-02 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 05/02/2017 04:02 AM, Suliman wrote:


I need co concatenate string with variant type (I am doing SQL query).

What is the best way to put it? It's seems that if I am doing simple
`replace`

string sql = "..."
sql.replace(`37.72308`, to!string(cargpspoint.lon)).replace(`55.47957`,
to!string(cargpspoint.lat))

I am loosing accuracy. Is there any better way?


Building SQL strings manually isn't really good practice these days, for 
both that and other reasons. It's better to use prepared statements, 
which will fix that issue for you and will also ensure your code is not 
susceptible to SQL-injection attacks:



// Raw SQL strings (old, ugly, unsafe way):
auto name = "Fred";
auto num = 1.23;
auto sql = text(
  "INSERT INTO `myTable` (`field1`, `field2`) VALUES ('",
  mysqlEscape(name), "', ", num, ")"
);
exec(conn, sql);


// Prepared statement (good, modern, safe way):
auto name = "Fred";
auto num = 1.23;
Prepared insertSomeFields = prepare(conn,
  "INSERT INTO `myTable` (`field1`, `field2`) VALUES (?, ?)"
);
insertSomeFields.setArgs(name, num);
insertSomeFields.exec();




Re: GC: Understanding potential sources of false pointers

2017-04-24 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 04/22/2017 08:56 AM, Kagamin wrote:

.rdata is fine, but afaik you have only strings there, the rest - .data,
.bss, .tls will suffer the same issue.


I don't know anything about the various object file sections. :/


Re: GC: Understanding potential sources of false pointers

2017-04-20 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 04/20/2017 09:00 AM, Kagamin wrote:

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


Hmm, so apparently embedded data (even if it's from a C lib) can also be 
a source of false pointers. Thanks, good to know.


Re: Can we disallow appending integer to string?

2017-04-20 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 04/19/2017 01:34 PM, Jonathan M Davis via Digitalmars-d-learn wrote:


Yeah, which reduces the number of casts required when doing arithmetic on
characters and thus reduces bugs there,


Ugh, because apparently doing arithmetic on characters is such a common, 
important use-case in this modern unicode world... :/




GC: Understanding potential sources of false pointers

2017-04-19 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

According to :

"Registers, the stack, and any other memory locations added through the 
GC.addRange function are always scanned conservatively."


1. Can that be safely assumed to be a canonical list of all possible 
sources of false pointers?


2. What about memory allocated through language constructs such as 
"new", append ("~"/"~="), closures, or any others I may be forgetting? 
Is this memory always/never/sometimes set to NO_SCAN? (I assume not 
"always", as that would be silly.) If "sometimes", what are the conditions?


A couple specific examples:

3. Are there any situations where a (for example) int[] or long[] that 
is stored on the GC heap could lead to false pointers?


4. Same question as #3, but if it's an array of structs, and the struct 
type contains no members that are statically-typed as pointers.


Re: ddoc: Can I escape a colon?

2017-02-23 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 02/23/2017 10:36 PM, Adam D. Ruppe wrote:

On Friday, 24 February 2017 at 02:50:27 UTC, Nick Sabalausky (Abscissa)
wrote:

What I'd kinda like to do is put together a D doc generator that uses,
uhh, probably markdown.


My dpldocs.info generator continues to progress and I'm almost ready to
call it beta and let other people use it.

It's syntax is a hybrid of ddoc and markdown. Take a look at the sample
page: http://dpldocs.info/experimental-docs/test.html


Oh, nice. The $(MATH stuff is especially cool (although unlikely to be 
useful in my libs - damn! I wanna put that to use!).


Looking forward to seeing that hit beta (and beyond) and trying that out.



Re: Big Oversight with readln?

2017-02-23 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 02/23/2017 09:43 PM, Jonathan Marler wrote:

I can't figure out how to make use of the full capacity of buffers that
are allocated by readln.  Take the example code from the documentation:

 // Read lines from $(D stdin) and count words

 void main()
 {
 char[] buf;
 size_t words = 0;

 while (!stdin.eof)
 {
 char[] line = buf;
 stdin.readln(line);
 if (line.length > buf.length)
 buf = line;

 words += line.split.length;
 }

 writeln(words);
 }

When buf is not large enough to hold the line, readln will allocate a
new buffer to accomodate and this example shows how you can save that
new buffer to reuse the next time.  The problem is that the capacity of
the new buffer is nowhere to be found. readln only returns the line that
was read which is only a slice of the buffer that was allocated.  The
next time that readln is called, it will not read past the slice even if
the capacity of the buffer it allocated was larger.  This will cause a
new allocation/copy every time you read a line that was larger than all
the previous lines, even if a previous allocation was already large
enough. This seems like a big oversight to me, I must be missing
something right?


I don't think that problem is actually occurring:

Let's step through the code, and suppose you're reading the following 
four lines of text:


12345
123456789
123
1234567

Starting out, buf.length is 0. When reading the first line, the buffer 
isn't big enough for 5, so readln allocates returns new buffer of length 
5. That is more than buf.length (0), so the new buffer becomes the new buf.


Second line, again, buf (length 5) isn't big enough for 9, so readln 
allocates a new buffer length 9. That's more than the old one (5), so 
again your code sets buf to the larger new buffer (length 9).


Third line: buf (length 9) can definitely hold length 3, so readln does 
not allocate. The new slice returned (length 3) is NOT longer than buf 
(still length 9), so buf is NOT set to the slice returned by readln. So 
buf REMAINS length 9.


Fourth line: buf (still length 9) can definitely hold length 7, so 
readln does not allocate.




Re: ddoc: Can I escape a colon?

2017-02-23 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 02/23/2017 04:34 PM, Ali Çehreli wrote:


(None of the following is tested.)

a) Try using the following macro:

 COLON = 

And then use "Note$(COLON) Blah".



Thanks, that works.


c) Another option:

 NOTE = Note $0

Then use "$(NOTE Blah)"


Actually, that's more or less what I was already doing anyway (for a 
changelog):


ENHANCE  = $(LI $(B Enhancement:) $0)
CHANGE   = $(LI $(B Change:) $0)
FIXED= $(LI $(B Fixed:) $0)

But the section interpretation there wasn't playing nice with newer 
versions of ddox. Using that "COLON = " trick fixed it though (and 
does indeed appear to work outside of these macros, too.





Re: ddoc: Can I escape a colon?

2017-02-23 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 02/23/2017 04:49 PM, H. S. Teoh via Digitalmars-d-learn wrote:


I'm becoming more and more convinced that software that tries to be
smart ends up being even dumber than before.


I've been convinced of that for a long time ;) Not just software either. 
Anything. My car does idiotic "smart" junk that irritates the crap out 
of me and makes me wish my 1997 Prizm hadn't finally rusted itself to 
pieces. K.I.S.S.




Re: ddoc: Can I escape a colon?

2017-02-23 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

On 02/23/2017 04:51 PM, Adam D. Ruppe wrote:

On Thursday, 23 February 2017 at 21:39:11 UTC, H. S. Teoh

Apparently COLON is defined to be ':' in the default ddoc macros, so
you needn't define it yourself.


Oh yeah.

Still, barf.


Luckily in my case, the "Word:" part is already generated inside a ddoc 
macro, so it'll be just as well hidden.


What I'd kinda like to do is put together a D doc generator that uses, 
uhh, probably markdown. But still with some sort of basic (but 
better-looking than ddoc) macro system, because link URLs can still 
REALLY clutter up even markdown source and make it unreadable (which is 
why I actually ended up converting the changelog for at least one of my 
projects from markdown to ddox.) Not a high enough priority for me now 
though :(




ddoc: Can I escape a colon?

2017-02-23 Thread Nick Sabalausky (Abscissa) via Digitalmars-d-learn

Suppose I want ddoc output to include this line:

--
Note: Blah blabbety blah
--

But the colon causes "Note" to be considered a section header. Is there 
a way to escape the ":" so that it's displayed as expected, but doesn't 
trigger a section?


Partial arrays reclaimed?

2017-01-27 Thread Nick Sabalausky via Digitalmars-d-learn

Suppose an array is being used like a FIFO:

---
T[] slice;

// Add:
slice ~= T();

// Remove:
slice = slice[1..$];
---

Assuming of course there's no other references to the memory, as this 
gets used, does the any of the memory from the removed elements ever get 
GC'd?


Also, if this is a long-running process, isn't there a potential danger 
in the array just marching through the address space and running out of 
room? (ie either running out of of continuous space, or hitting 0xFFF)


Reflection: Order of fields guaranteed?

2016-10-21 Thread Nick Sabalausky via Digitalmars-d-learn
When using reflection to obtain the fields of a class/struct, is there 
any guarantee that the order is the same as the order the fields are 
defined?


Escaping ref to stack mem sometimes allowed in @safe?

2016-10-16 Thread Nick Sabalausky via Digitalmars-d-learn

This compiles. Is it supposed to?

@safe ubyte[] foo()
{
ubyte[512] buf;
auto slice = buf[0..$];
// Escaping reference to stack memory, right?
return slice;
}

Or is the escaping reference detection not intended to be 100%? Or 
something else I'm missing?


Should I file @ bugzilla?


Re: Phobos func for string -> enum member?

2016-10-13 Thread Nick Sabalausky via Digitalmars-d-learn

On 10/13/2016 07:14 PM, H. S. Teoh via Digitalmars-d-learn wrote:

On Thu, Oct 13, 2016 at 07:11:15PM -0400, Nick Sabalausky via 
Digitalmars-d-learn wrote:

I'm sure it'd be easy enough to write, but does phobos have a simple
way to convert the name of an enum member from a runtime string to the
enum type?

Ie, something like:

enum Foobar { foo=1, bar }
Foobar a = doesThisExistInPhobos!Foobar("foo");

I'm not finding anything like it in the docs, but I'm wondering if I
just missed it somewhere.


import std.conv : to;
Foobar a = "foo".to!Foobar;

:-)


T



Ah. Right. ;)

Thanks all.



Phobos func for string -> enum member?

2016-10-13 Thread Nick Sabalausky via Digitalmars-d-learn
I'm sure it'd be easy enough to write, but does phobos have a simple way 
to convert the name of an enum member from a runtime string to the enum 
type?


Ie, something like:

enum Foobar { foo=1, bar }
Foobar a = doesThisExistInPhobos!Foobar("foo");

I'm not finding anything like it in the docs, but I'm wondering if I 
just missed it somewhere.


Re: Custom test runner

2016-09-21 Thread Nick Sabalausky via Digitalmars-d-learn

On 09/21/2016 02:26 AM, Jacob Carlborg wrote:

On 2016-09-21 07:51, Nick Sabalausky wrote:

IIRC, there is some way to hook in and use a custom unittest-runner. How
does one go about that?


http://dlang.org/phobos/core_runtime.html#.Runtime.moduleUnitTester



Cool, thanks.

I got that to work, and FWIW submitted a PR to add an example to the 
docs for that: https://github.com/dlang/druntime/pull/1656




Re: Fully-qualified symbol disambiguation is deprecated???

2016-09-09 Thread Nick Sabalausky via Digitalmars-d-learn

On 09/09/2016 12:35 PM, pineapple wrote:

On Friday, 9 September 2016 at 11:54:42 UTC, Steven Schveighoffer wrote:

Can you demonstrate the issue? I have never heard of this. imports
should work when done inside a function.

-Steve


Tried and failed to reproduce with a simple example, but any time I've
tried doing it in the code I'm working on I get Symbol Undefined errors
which I had to fix by moving imports out of struct/class methods.


Are those maybe linker errors you're getting? It sounds like maybe the 
build system you're using, rather than the compiler, for some reason is 
rudimentary and isn't using the compiler itself to find dependencies. 
What build tool are you using?


Re: Fully-qualified symbol disambiguation is deprecated???

2016-09-09 Thread Nick Sabalausky via Digitalmars-d-learn

On 09/08/2016 06:22 PM, Nick Sabalausky wrote:

On 09/08/2016 06:13 PM, Steven Schveighoffer wrote:

On 9/8/16 6:02 PM, Nick Sabalausky wrote:

I'm getting deprecation messages ("Package...not accessible here,
perhaps add static import") when simply trying to use fully-qualified
symbol names to disambiguate a symbol. Is this really intended?


Yes.

It's difficult to attribute the message without context, though.


Yea, unfortunately I don't have it narrowed down to a test case, atm.


And
there are still some straggling bugs which cause this message to be
erroneously printed.



I'm pretty sure I've hit one of those :( Can't be certain though until I
examine my specific case further.



Turns out I didn't hit one of those bugs, but one of the problems I was 
hitting was the old problem where package.d completely fucks any and all 
attempts at using a FQN. Worked around with local selective renamed imports.


FQN used to be a real killer feature of D: To deal with name collisions, 
you could *ALWAYS* replace a visible symbol with it's FQN and it would 
*just work*. But now with package.d, UFCS, and 2.071's selective import 
behavior, that benefit's pretty much been shot to hell.




Re: Fully-qualified symbol disambiguation is deprecated???

2016-09-08 Thread Nick Sabalausky via Digitalmars-d-learn

On 09/08/2016 06:22 PM, Nick Sabalausky wrote:

On 09/08/2016 06:13 PM, Steven Schveighoffer wrote:

And
there are still some straggling bugs which cause this message to be
erroneously printed.



I'm pretty sure I've hit one of those :( Can't be certain though until I
examine my specific case further.



Oh, although the whole "selective imports don't import the FQN" is a big 
surprise to me. I think at least some of the messages I hit were from 
that. (Can't say I'm a big fan of that particular one, but meh, whatever...)


Re: Fully-qualified symbol disambiguation is deprecated???

2016-09-08 Thread Nick Sabalausky via Digitalmars-d-learn

On 09/08/2016 06:13 PM, Steven Schveighoffer wrote:

On 9/8/16 6:02 PM, Nick Sabalausky wrote:

I'm getting deprecation messages ("Package...not accessible here,
perhaps add static import") when simply trying to use fully-qualified
symbol names to disambiguate a symbol. Is this really intended?


Yes.

It's difficult to attribute the message without context, though.


Yea, unfortunately I don't have it narrowed down to a test case, atm.


And
there are still some straggling bugs which cause this message to be
erroneously printed.



I'm pretty sure I've hit one of those :( Can't be certain though until I 
examine my specific case further.




Fully-qualified symbol disambiguation is deprecated???

2016-09-08 Thread Nick Sabalausky via Digitalmars-d-learn
I'm getting deprecation messages ("Package...not accessible here, 
perhaps add static import") when simply trying to use fully-qualified 
symbol names to disambiguate a symbol. Is this really intended?


Get third part of front-end version number

2016-04-05 Thread Nick Sabalausky via Digitalmars-d-learn

These days, DMD/DMDFE version numbers are three parts, ex: 2.070.1.

I can get the first two via std.compiler.version_major and 
std.compiler.version_minor. Is there a way to get the third part?


I know I can "dmd --help | grep DMD", but that only works for DMD. GDC's 
"gdc --version" doesn't appear to show the DMDFE version, and I have no 
idea about LDC.


Or is the third part of the DMDFE version completely irrelevant to LDC/GDC?


Varargs and default arguments

2015-10-06 Thread Nick Sabalausky via Digitalmars-d-learn

Ok, D-style varargs can accept a parameter length of zero:

---
void foo(T...)(T args) {
//...
}
foo();
foo(t1, t2);
---

Is there any way to stick a param with a default value before that?

---
void foo(T...)(string str=null, T args=/+what goes here???+/) {
//...
}
foo();
foo(str);
foo(str, t1, t2);
---

Obviously this can be worked around easily enough by splitting it into 
two overloads ("foo(string str=null)" and "foo(string str, T args)"), 
but is there a way to do it in one?


const-correct structs, best practices?

2015-08-21 Thread Nick Sabalausky via Digitalmars-d-learn
Is there a good posting somewhere that summarizes the current best 
practices for making const-correct (ie works for all of 
mutable/const/immutable) structs?


Re: const-correct structs, best practices?

2015-08-21 Thread Nick Sabalausky via Digitalmars-d-learn

On 08/21/2015 12:22 PM, Dicebot wrote:

On Friday, 21 August 2015 at 15:00:04 UTC, Nick Sabalausky wrote:

Is there a good posting somewhere that summarizes the current best
practices for making const-correct (ie works for all of
mutable/const/immutable) structs?


- mark methods const
- avoid reference type fields

;)


What about inout?

I have a struct that supports operator overloading, returning the 
struct's own type. After fiddling with that, I got a good laugh out of 
Meta's comment, and I think he may be right!




Appender at CTFE?

2015-08-21 Thread Nick Sabalausky via Digitalmars-d-learn
Not at a pc, so can't test right now, but does Appender work at 
compile time? If not, does ~= still blow up CTFE memory usage 
like it used to? Any other best practice / trick for building 
strings in CTFE?


Re: Appender at CTFE?

2015-08-21 Thread Nick Sabalausky via Digitalmars-d-learn

Thanks!

I wouldn't have expected that about the 	memory. But I wonder how 
much of that memory usage with Appender was just all the template 
instantiations. I'll have to look into that when I get back.


Bitfield-style enum to strings?

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

Assuming a plain old bitfield-style enum like:

enum Foo {
optionA = 10;
optionB = 11;
optionC = 12;
optionD = 13;
optionE = 14;
}

Does a function already exist somewhere to take an instance of Foo and 
get a list of the switch names as strings?


Something kinda like:

Foo fooVar = Foo.optionB | Foo.optionD;
assert(
DOES_THIS_FUNC_EXIST(fooVar)
.equals([optionB, optionD])
);

Seems entirely feasible, although my traits-fu is a bit rusty.



Re: Moving from Python to D

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn
I'm not really sure exactly what parts are the issue, but I'll point out 
what I can:


On 05/07/2015 11:24 PM, avarisclari wrote:

Hello,

Sorry to bother you with something trivial, but I am having trouble
translating a block of code I wrote in Python over to D. Everything else
I've figured out so far. Could someone help me understand how to get
this right?

Here's the python:

scene = scenes[title]


It looks like scenes is a dictionary that stores dictionaries of 
strings? If so, then in D, scenes would be declared like this:


string[string][string] scenes;

Then the above line would be:

auto scene = scenes[title]



while 1 == 1:


In D, while(true) is probably prefered, but that's just a matter of 
style. 1==1 will work too.



 next_choice = None
 paths = scene[paths]
 description = scene[description]
 lines = string.split(\n)



Phobos (D's standard library) has a split:
http://dlang.org/phobos/std_array.html#split

Also one specifically for splitting lines:
http://dlang.org/phobos/std_string.html#splitLines

They're easier to use than it looks:
auto lines = description.split(\n);

or better yet (also handles mac and win-style properly):
auto lines = description.splitLines();



 for line in lines:


Standard foreach:

for(ref line; lines) {


 if len(line  55):
 w = textwrap.TextWrapper(width=45, break_long_words=False)


Exists in Phobos:
http://dlang.org/phobos/std_string.html#wrap

I've never actually used it myself though.


 line = '\n'.join(w.wrap(line))


Join is easy:
http://dlang.org/phobos/std_array.html#join

result = (whatever array or range you want to join).join(\n)

But really, I don't think you'll need this entire loop at all, though. I 
would just strip all the newlines and feed the result to Phobos's 
wrap(). Probably something like:


auto description =
scene[description].replace(\n,  ).wrap(45);

That should be all you need for the word wrapping.


 decription += line +\n


D uses ~ to concatenate strings instead of +. In D, + is just for 
mathematical addition.



 print description



writeln(description);




 #Shows the choices
 for i in range(0, len(paths)):


foreach(i; 0..paths.length) {


 path = paths[i]
 menu_item = i + 1
 print \t, menu_item, path[phrase]


writeln(\t, menu_item, path[phrase]);


 print \t(0 Quit)

 #Get user selection


// Get user selection



 prompt = Make a selection ( 0 - %i): \n % len(paths)


This is in phobos's std.conv: http://dlang.org/phobos/std_conv.html

So, either:

auto prompt = Make a selection ( 0 -  ~
paths.length.to!string() ~ ): \n;

or:

auto prompt = text(Make a selection ( 0 - ,
paths.length, ~ ): \n)



 while next_choice == None:
 try:
 choice = raw_input(prompt)


The basic equivalent to raw_input would be readln():
http://dlang.org/phobos/std_stdio.html#readln

But, the library Scriptlike would make this super easy, thanks to a 
contributer:

https://github.com/Abscissa/scriptlike

Pardon the complete lack of styling in the docs (my fault):
http://semitwist.com/scriptlike/interact.html

So, it'd be:

import scriptlike.interact;
auto choice = userInput!int(prompt);


 menu_selection = int(choice)

 if menu_selection == 0:
 next_choice = quit
 else:
 index = menu_selection - 1
 next_choice = paths[ index ]

 except(IndexError, ValueError):
 print choice, is not a valid selection

 if next_choice == quit:
 print Thanks for playing.
 sys.exit()


I forget the function to exist a program, but if this is in your main() 
function, then you can just:


return;


 else:
 scene = scenes[ next_choice[go_to] ]
 print You decided to:, next_choice[phrase], \n
 if sys.platform == 'win32':
 os.system(cls)
 else:
 os.system(clear)

I've got the very last piece set up, using consoleD to use
clearScreen(), but The rest I'm not sure how to translate. Sorry for my
incompetence in advance.




Re: Moving from Python to D

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

On 05/08/2015 12:06 AM, Nick Sabalausky wrote:

On 05/07/2015 11:24 PM, avarisclari wrote:


scene = scenes[title]


It looks like scenes is a dictionary that stores dictionaries of
strings? If so, then in D, scenes would be declared like this:

string[string][string] scenes;

Then the above line would be:

auto scene = scenes[title]



BTW, D calls them Associative Arrays or AA, instead of dictionary. 
I *think* dictionary is what Python calls them, but I could be wrong.


Re: Bitfield-style enum to strings?

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

On 05/07/2015 09:17 PM, Meta wrote:

On Thursday, 7 May 2015 at 21:41:06 UTC, Nick Sabalausky wrote:

On 05/07/2015 05:19 PM, Justin Whear wrote:


T[] members = [ EnumMembers!T ];



Doh! Yup, that works.

Still, I would think there should be a way to do it without allocating
an array. But it's not a huge deal right now though.


You could also do `TypeTuple!(EnumMembers!T))` I believe.


filter doesn't seem to like that.



Re: Bitfield-style enum to strings?

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

Gah, missed some imports that time:

On 05/07/2015 05:04 PM, Nick Sabalausky wrote:

Minor fix to work right for none fields. Already worked fine on
combination fields liek all.

-
enum Foo
{
 none = 0,
 optionA = 10,
 optionB = 11,
 optionC = 12,
 optionD = 13,
 all = optionA | optionB | optionC | optionD,
}

import std.traits : isIntegral;
auto bitFieldValues(T)(T value) if(is(T==enum)  isIntegral!T)
{

import std.algorithm : filter, map;
import std.conv : to;
import std.traits : EnumMembers;


 // There's gotta be a better way to convert EnumMembers!T
 // to a range, right? But std.range.only() didn't work,
 // due to a template instantiation error.
 T[] members;
 foreach(m; EnumMembers!(T))
 members ~= m;

 return members
 .filter!(member = member==0? value==0 : (valuemember)==member)
 .map!(member = to!string(member));
}

void main()
{
 import std.range : join;
 import std.stdio : writeln;

 Foo fooVar = Foo.optionB | Foo.optionD;

 // Output:
 // optionB | optionD
 // none
 // optionA | optionB | optionC | optionD | all

 writeln(bitFieldValues(Foo.optionB | Foo.optionD).join( | ));
 writeln(bitFieldValues(Foo.none).join( | ));
 writeln(bitFieldValues(Foo.all).join( | ));
}
-





Re: Bitfield-style enum to strings?

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

On 05/07/2015 01:41 PM, Nick Sabalausky wrote:

Assuming a plain old bitfield-style enum like:

enum Foo {
 optionA = 10;
 optionB = 11;
 optionC = 12;
 optionD = 13;
 optionE = 14;
}

Does a function already exist somewhere to take an instance of Foo and
get a list of the switch names as strings?

Something kinda like:

Foo fooVar = Foo.optionB | Foo.optionD;
assert(
 DOES_THIS_FUNC_EXIST(fooVar)
 .equals([optionB, optionD])
);

Seems entirely feasible, although my traits-fu is a bit rusty.



Wow, D's seriously awesome, that was actually way easier than I expected:


import std.traits : isIntegral;
auto bitFieldValues(T)(T value) if(is(T==enum)  isIntegral!T)
{
import std.algorithm : filter, map;
import std.conv : to;
import std.traits : EnumMembers;

// There's gotta be a better way to convert EnumMembers!T
// to a range, right? But std.range.only() didn't work,
// due to a template instantiation error.
T[] members;
foreach(m; EnumMembers!(T))
members ~= m;

return members
.filter!(member = (value  member) == member)
.map!(member = to!string(member));
}


Sample code to use it:


enum Foo
{
optionA = 10,
optionB = 11,
optionC = 12,
optionD = 13,
optionE = 14,
}

void main()
{
import std.range : join;
import std.stdio : writeln;

Foo fooVar = Foo.optionB | Foo.optionD;

// Output: optionB | optionD
writeln(bitFieldValues(fooVar).join( | ));
}




Re: Bitfield-style enum to strings?

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

On 05/07/2015 05:19 PM, Justin Whear wrote:

On Thu, 07 May 2015 16:55:42 -0400, Nick Sabalausky wrote:


  // There's gotta be a better way to convert EnumMembers!T // to a
  range, right? But std.range.only() didn't work, // due to a
  template instantiation error.
  T[] members;
  foreach(m; EnumMembers!(T))
  members ~= m;


T[] members = [ EnumMembers!T ];



Doh! Yup, that works.

Still, I would think there should be a way to do it without allocating 
an array. But it's not a huge deal right now though.




Re: Bitfield-style enum to strings?

2015-05-07 Thread Nick Sabalausky via Digitalmars-d-learn
Minor fix to work right for none fields. Already worked fine on 
combination fields liek all.


-
enum Foo
{
none = 0,
optionA = 10,
optionB = 11,
optionC = 12,
optionD = 13,
all = optionA | optionB | optionC | optionD,
}

import std.traits : isIntegral;
auto bitFieldValues(T)(T value) if(is(T==enum)  isIntegral!T)
{
// There's gotta be a better way to convert EnumMembers!T
// to a range, right? But std.range.only() didn't work,
// due to a template instantiation error.
T[] members;
foreach(m; EnumMembers!(T))
members ~= m;

return members
.filter!(member = member==0? value==0 : (valuemember)==member)
.map!(member = to!string(member));
}

void main()
{
import std.range : join;
import std.stdio : writeln;

Foo fooVar = Foo.optionB | Foo.optionD;

// Output:
// optionB | optionD
// none
// optionA | optionB | optionC | optionD | all

writeln(bitFieldValues(Foo.optionB | Foo.optionD).join( | ));
writeln(bitFieldValues(Foo.none).join( | ));
writeln(bitFieldValues(Foo.all).join( | ));
}
-



line numbers in linux stack traces?

2014-10-05 Thread Nick Sabalausky via Digitalmars-d-learn
I know this keeps getting asked every year or so, but I couldn't find 
recent info.


Are line numbers in linux stack traces supposed to be working at this 
point? Because I'm not getting any with 2.066.0 with either -g or -gc 
even when running under gdb. Kind of a pain, esp. compared to D dev on 
windows.


Re: Installing LDC on Windows

2014-09-06 Thread Nick Sabalausky via Digitalmars-d-learn

On 9/6/2014 11:09 AM, Kagamin wrote:

SEH was patented, so llvm doesn't support it.


Seriously, if they're worried about infringing a software patent, they 
have no business writing any code at all. Avoiding things covered by 
patents *and* writing code that actually does anything useful is NOT 
REALISTICALLY POSSIBLE. The SEH patent is just a red herring here.


Good/Bad? @disable postblit for struct InputRange

2014-09-05 Thread Nick Sabalausky via Digitalmars-d-learn
One issue with struct-based input ranges: Saving the state of an input 
range is not supported (by definition of input range), and yet, you can 
trivially and accidentally do so with a simple assignment or passing 
into a function. The results may or may not blow up depending on the 
exact situation.


And if the input range happens to hit a poorly-implemented algorithm 
which *should* be statically requiring a ForwardRange and using 
.save() to duplicate state, but instead accepts any range and 
(accidentally?) saves state by simple struct copy...which will work fine 
for most struct-based forward ranges and therefore could go completely 
unnoticed...Then once again, your input range touches it and BOOM.


This *could* be addressed by making the input range a class, but that 
seems a bit overkill in many cases.


So I'm tempted to give my struct-bassed input ranges a @disable'd 
postblit. That would solve the problem, right? Would there be any reason 
NOT to do this?


Re: Good/Bad? @disable postblit for struct InputRange

2014-09-05 Thread Nick Sabalausky via Digitalmars-d-learn

On 9/5/2014 6:14 PM, monarch_dodra wrote:


Ref semantics is one option, yes. Either by class, or by struct. For
example, most IO ranges implemented ref-counted reference semantics.

IMO, disabling postblit is overkill, as almost anything that does
anything with ranges will pass them by value at one point or another.


[...]


*Ideally*, these functions would do a move-return, and you'd
pass-by-move, so you'd be able to effectively disable postblit, but
still pass by move-value. Unfortunately, we aren't quite there yet...



I see. Good points, thanks.



Re: Curl Exception

2014-05-11 Thread Nick Sabalausky via Digitalmars-d-learn

On 5/10/2014 9:02 AM, Jack wrote:

First off a rant:

I use the Code::Blocks IDE and at times it has been proven to a
double-edged source because of various issueslike this one:

http://forum.dlang.org/thread/ndeyzrifseipuebvy...@forum.dlang.org)

and am now itching to search for other IDEs to suit my needs.



I switched from C::B to Programmer's Notepad 2 several years ago, and 
I've been happy with it:


http://www.pnotepad.org/

It's good if you're looking for a light editor rather than a heavy-duty 
IDE. Otherwise, there's VisualD and Mono-D which I hear are good.



Now on to the question:
Anyway, I was using std.net.curl to implement an auto updater for my
program.



Sorry, I haven't really used the curl stuff yet, so I can't be a bigger 
help, but a couple notes below:



Function code is this: http://pastebin.com/i6WnwJF5(links removed due to
it having private content. Original host is https://dropbox.com)

And the overall function was working fine in the IDE except for an
Access Violation that I thought would work itself out when it's (run by
administrator).



Access Violation, despite its wording, isn't usually about user 
permissions. It's the Windows version of a segfault. Usually means a 
null pointer was dereferenced, or a freed pointer was used, or an 
otherwise bad pointer or buffer overflow, etc. If you're really unlucky 
those can be a result of memory corruption, but that's usually not the case.




So I Exported it to a folder with all necessary files, including the
cacert.pem file and run it.

Well this little error popped out : http://pastebin.com/8MmPLg2Q



If you recompile with -g (enable debugging symbols), then those 
annoyingly meaningless addresses will change into a proper stack trace. 
(Or try -gc if -g doesn't work.)


Is that the same error you get if you try to give it a pem file you 
*know* doesn't exist? If so, then maybe it's not looking in the 
directory you expect. Try giving it a full absolute path to the pem 
file. If that works, then it's probably looking in the directory you're 
running from instead of the directory where it actually exists. If so, 
you can use std.file.thisExePath() and build your path relative to that 
(or just stick with an absolute path).


You can also try opening your pem file directly:

auto pemFile = File(cacert.pem);

See what happens if you do that. It won't fix the problem, but seeing 
what it does it should help give you a better idea of what's going on.



Though in the Code:: Blocks IDE there was the object.Error Access
Violation error
And in the actual program(.exe) this : http://pastebin.com/8MmPLg2Q

Though I'm also up for not verifying the link but I still can't figure
out how.

Anyway, can anyone give me an idea what went wrong?




Re: Implicit static-dynamic arr and modifying

2014-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

On 5/6/2014 6:46 PM, Rene Zwanenburg wrote:

On Tuesday, 6 May 2014 at 02:17:06 UTC, Nick Sabalausky wrote:

So all is well, and deliberately so. Pardon the noise.


IMO it's not. I once had a particularly nasty bug because of this:

struct S
{
 @safe:
 string str;

 this(string data)
 {
 import std.digest.md;
 str = md5Of(data).toHexString(); // Oops...
 }
}


That must be a terribly subtle one, I'm not seeing the problem at all.

I get that md5Of returns a static array, and then a slice of it gets 
passed to toHexString, but AIUI toHexString finishes (and returns a 
newly allocated string) before the temporary static array leaves scope.




Re: [Rosettacode] D code line length limit

2014-05-07 Thread Nick Sabalausky via Digitalmars-d-learn

On 5/7/2014 9:25 AM, bearophile wrote:

So far in Rosettacode D entries I've kept a line length limit of 72 or
73 chars.

But now a little larger monitors are common, D UFCS chains are common,
and we also have longer function signatures with pure nothrow @safe
@nogc (that usually I put on a new line), so keeping that line length
limit is becoming a little pain.

So probably I'll increase the maximum line length. Rosettacode rules
forbids too much long lines, and while in my code I use a limit of about
90-100 in my code, this is too much for online wiki pages. So I'll do
some tests, and I think for Rosettacode D entries I'll increase the
limit to about 80 chars.

Bye,
bearophile


72-73 chars would indeed be a pain. In my own code I like to use a soft 
limit of 80, FWIW.


I do find I need to break up lines in D more than I would in other 
languages, especially function signatures.




Implicit static-dynamic arr and modifying

2014-05-05 Thread Nick Sabalausky via Digitalmars-d-learn

Is this kinds stuff a sane thing to do, or does it just work by accident?:

void modify(ubyte[] dynamicArr)
{
dynamicArr[$-1] = 5;
}

void main()
{
ubyte[4] staticArr = [1,1,1,1];
modify(staticArr);
assert(staticArr == [1,1,1,5]);
}


Re: Implicit static-dynamic arr and modifying

2014-05-05 Thread Nick Sabalausky via Digitalmars-d-learn

On 5/5/2014 10:11 PM, Nick Sabalausky wrote:

Is this kinds stuff a sane thing to do, or does it just work by accident?:

void modify(ubyte[] dynamicArr)
{
 dynamicArr[$-1] = 5;
}

void main()
{
 ubyte[4] staticArr = [1,1,1,1];
 modify(staticArr);
 assert(staticArr == [1,1,1,5]);
}


Duh, it's just using a normal slice of the static array...

// Roughly:
dynamicArr.ptr = staticArr;
dynamicArr.length = typeof(staticArr).sizeof;

So all is well, and deliberately so. Pardon the noise.



Extracting Params of Templated Type

2014-04-03 Thread Nick Sabalausky
If you have a templated type, is there a way to get the compile-time 
parameters it was instantiated with?


Ie:

--
struct Foo(T) {}

alias MyFoo = Foo!int;
--

Is there a way to inspect MyFoo to get its T type (in this case, 'int')? 
*Without* actually making any changes to Foo to explicitly support this?


Re: Extracting Params of Templated Type

2014-04-03 Thread Nick Sabalausky

On 4/4/2014 1:02 AM, Meta wrote:


alias TemplateArgs(T: Foo!U, U) = U;

void main()
{
 assert(is(TemplateArgs!MyFoo == int));
}


Ahh thanks.




Re: writeln if not empty

2014-03-10 Thread Nick Sabalausky

On 3/10/2014 9:24 PM, Timothee Cour wrote:

Is there a way to do the following lazily:

writelnIfNotEmpty(T)(T a){
auto b=text(a);
if(b.length)
   writeln(b);
}

ie, without using std.conv.text (which needlessly computes an intermediate
string, which could be quite large) or launching a separate process ?

writelnIfNotEmpty(); //doesn't print new line
writelnIfNotEmpty(a); //prints a\n



Sounds like what you need is a version of to!string() or text() that 
takes an output sink. Taking a look at std.conv, I'm kinda surprised I 
don't see one :/




Re: Converting string to ascii value

2014-03-07 Thread Nick Sabalausky

On 3/7/2014 5:21 PM, Setra wrote:

Hello all! I am having trouble converting a letter in a array of string
to the ascii value. For example:



First of all:


string[] stringarray[3];


This isn't your main problem, but that line is incorrect. Actually, I'm 
kinda surprised that even works. It should be one of these, depending if 
you want a static array or a dynamic one:


string[3] staticStringArray;

string[] dynamicStringArray;
dynamicStringArray.length = 3;

Or you can do it all in one like this:

string[] dynamicStringArray = [blahblahblah, a, 5];


stringarray[0] = blahblahblah;
stringarray[1] = a;
stringarray[3] = 5;

long y = to!long(stringarray[2]); // makes y the value 5
long x = to!long(stringarray[1]); // errors


This is not working properly. I want to get the ascii value of the
characters.
In this case y should equal 97, b should equal 53. How do I do this
properly?
Thanks!


First of all, ASCII is outdated, it's all Unicode now. D's strings are 
UTF-8. See this if you need a primer on Unicode:


http://www.joelonsoftware.com/articles/Unicode.html

That said, the English letters and numeric digits just happen to be the 
same in UTF-8 as ASCII, so in your examples, you can still get the ASCII 
values (as long as you remember it's *really* Unicode's UTF-8). Just 
keep in mind you don't normally want to be dealing with ASCII or even 
individual characters. Usually you want to just stick with with full 
strings.


Back to your code though, your code is trying to convert the *entire* 
string to a long. So that's not going to get you want you want. You want 
the numeric representation of an *individual* character *within* the 
string. In your example, you'd do that like this:


char c2 = stringarray[2][0]; // First 'char' in string #2: '5'
char c1 = stringarray[1][0]; // First 'char' in string #1: 'a'

Again, remember those aren't really characters, they're UTF-8 code 
units. So if your strings have any non-english characters, then that 
won't always work as you expect.


Now, to get the numeric representation of c1 and c2 (ie the UTF-8 code 
unit, which in your example just happens to also be the ASCII code, but 
only by pure chance), you can just cast it to a ubyte:


ubyte y = cast(ubyte)c2;
ubyte x = cast(ubyte)c1;



Re: Converting string to ascii value

2014-03-07 Thread Nick Sabalausky

On 3/7/2014 5:33 PM, H. S. Teoh wrote:


long x = cast(ubyte) stringarray[0];



long x = cast(ubyte) stringarray[0][0];

;)



Re: Converting string to ascii value

2014-03-07 Thread Nick Sabalausky

On 3/7/2014 5:37 PM, Setra wrote:

Thanks! Now I feel kind of dumb.
For some reason I thought it would not be that simple...


In a lot of languages it isn't that simple ;)



Re: Nobody understands templates?

2014-03-04 Thread Nick Sabalausky

On 3/1/2014 1:00 PM, Steve Teale wrote:

I have already dealt
with the yada-yada cases by old-fashioned OOP.



As I see it, a big part of the benefit of templates is that they can 
help you avoid a lot of the downsides of OOP:


- OO Boilerplate.
- Multiple dispatch is ridiculously messy, having to resort to 
contortions like the visitor pattern.

- Upcasting looses compile-time type info.
- Decreased opportunity for compiler optimizations, because a single 
function handles multiple data types at runtime. So the optimizer can't 
generate optimal code for all the data types used.

- Extra indirections at runtime.
- Downcasting has a runtime cost.
- Poor cache behavior.
- Tendency for increased heap activity, which is not cheap at all.
- Lumping all data/functionality for a single object instance into the 
same physical chunk of memory causes problems for parallelization. And 
that's increasingly problematic on modern processors which work best 
when operating as streaming-data processors. (See Entity/Component 
Systems[1] - There are good reasons videogame development has mostly 
switched from OOP to entity/component systems.)


Basically, while OOP certainly has benefits, it also has notable flaws 
that inherently slow down both the programmer and the computer. JVM goes 
to an enormous amount of trouble to mitigate that natural tendency, but 
it still has limits. And most languages (like D) can't expect to 
approach JVM's work on de-slow-ifying OO.


The runtime performance issues of OO aren't *always* a problem, but they 
can easily kill inner-loop/performance-sensitive sections of code. So 
with OO, you have to give up the generic/polymorphic benefits for any 
critical sections. Metaprogramming lets you still be generic even in the 
critical sections. This is demonstrated in sections #1-4 of an article I 
wrote a little while back[2]. It's a very contrived example, but even I 
was still surprised just *how* badly the OO version performed.


There's also this template primer[3] which might help, but I'm guessing 
it may be below your ability level.


[1] Entity/Component Systems: 
http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/


[2] 
http://www.semitwist.com/articles/EfficientAndFlexible/MultiplePages/Page1/


[3] https://semitwist.com/articles/article/view/template-primer-in-d



Re: Nobody understands templates?

2014-03-04 Thread Nick Sabalausky

On 3/4/2014 7:42 PM, bearophile wrote:

Nick Sabalausky:


- Lumping all data/functionality for a single object instance into
the same physical chunk of memory causes problems for parallelization.
And that's increasingly problematic on modern processors which work
best when operating as streaming-data processors. (See
Entity/Component Systems[1] - There are good reasons videogame
development has mostly switched from OOP to entity/component systems.)


Sometimes OOP is handy, for GUIs and other situations, but if today a
more horizontal placement of fields is more efficient when high
performance is needed, then perhaps a creative programmer has to find
the courage to step out of his/her/hir language constraints to invent a
better language. Is it possible to invent a language more fit for this
different kind of data layout?



I don't think it's necessary to go as far as creating a new language. An 
entity-system in a low-level-capable language gives you enough power to 
control layouts however appropriate, and using them is pretty easy.


It seems intimidating at first, but it's really just like a relational 
DB: You have a unique ident for each object (ie, what an OO system 
would call an instantiated object, but in this case called an entity). 
And then all the data associated with the object/entity is stored in 
various tables/structs/whatever (in this case, called components) with 
the entity's unique identifier being the primary key for each 
table/component. Functionality operates on a particular table/component, 
or a set of specific tables/components, either on a row-at-a-time basis 
or as the whole table as an aggregate.


Note that this imposes very little, if any, requirements on in-memory 
layouts, so things can be laid out however desired - possibly even with 
per-platform topologies thanks to the magic of metaprogramming. In any 
case, metaprogramming can help abstract away many of the internal 
memory-layout details.


Playing around with the Unity3D editor, and it's tutorial videos, can 
help grok the usage and modeling power of entities (like any good modern 
game engine, it uses an entity-based design). Although, FWIW, I'm not 
convinced Unity3D's design is able to *fully* take advantage of all the 
potential performance benefits of an entity system (mostly because of 
its CLR-based scripting and black-box closed-source engine).


But, I admit, I have wondered if a language could aid the creation/usage 
of entity systems with some special language features.




Re: Nobody understands templates?

2014-03-04 Thread Nick Sabalausky

On 3/3/2014 5:35 PM, Chris wrote:


Maybe I'm a bit too philosophical about this. But consider the following
(made up) case:

struct MyTemp(T) {
 // ...
 T add(T a, T b) {
 if (a is string  b is string) {
   return a~b;  // or return a~+~b; or whatever
 } else if (a is integer  a is integer) {
   return a+b;
 }
 }
}

I don't know if this can be considered a pure template. It is a
template of sorts, but the type specialization in the function add makes
it a watered-down template,


Any useful template function already works that way. The mere + operator 
is *not* one single operation, but a whole category of opcodes which are 
chosen based on the operand's type. Thus, + can be thought of as a 
built-in template that [roughly] does this:


T opPlus(T a, T b) {
if (T is integer) {
[asm opcode for 32-bit addition] a, b
} else if (T is ubyte) {
[asm opcode for 8-bit addition] a, b
} else if (T is float) {
[asm opcode for floating point addition] a, b
}
}

Specialization is what makes function templates useful. Some of the 
specialization is explicit (static if) and some is implicit (+ 
operator). But without specialization (explicit or implicit), all 
instantiations would be identical. If all instantiations are identical, 
why even have a template in the first place?




Re: Nobody understands templates?

2014-03-04 Thread Nick Sabalausky

On 3/4/2014 1:27 PM, H. S. Teoh wrote:

On Tue, Mar 04, 2014 at 06:19:38PM +, Chris wrote:


Btw, the quote you have in this post:

Never ascribe to malice that which is adequately explained by
incompetence. -- Napoleon Bonaparte

I'm surprised that Napoleon would say something like this. Malice is
often a characteristic of the incompetent. The only way to get the
better of their betters. :-)


I'm not sure if that attribution is accurate. Nick has pointed out to me
that he knows the same quote attributed to someone else, so this may be
a case of internet misattribution (I picked up that quote from somewhere
online, way back when -- no idea if the source was reliable, y'know,
being the internet and everything).



Hanlon's Razor, a tongue-in-cheek corollary (of sorts) to Occam's 
Razor. I'm a huge believer in Hanlon's Razor, BTW, as well as Occam's 
Razor which I see as an axiom (for a loose definition of axiom) that's 
fundamental in making all of science actually work and separating 
science from folklore.


For all I know, Napoleon may have uttered Hanlon's Razor at some point. 
I'm sure he's said a lot of things :) If so, he may have been the first.




Re: Nobody understands templates?

2014-03-04 Thread Nick Sabalausky

On 3/4/2014 9:00 PM, bearophile wrote:

Nick Sabalausky:


But, I admit, I have wondered if a language could aid the
creation/usage of entity systems with some special language features.


I have seen that a good way to learn lazyness and purity is to try to
write some Haskell code. Then you can use the same ideas in other
languages, like D. Similarly I've studied regular expressions in dynamic
languages, and now I am able to use them in Java, C#, D, etc.

So I've seen that it's good to learn a feature/style in a language that
uses it a lot, or even in a language designed around such feature.
Because languages shape your mind, and specialized languages train your
mind to use few specific features. Later in real-world situations often
you can't use such specialized/esoteric/rare language, and you have to
use a common language as Java. And sometimes if people use a feature a
lot in other languages, eventually it gets ported even to the common
languages (like lambdas in Java).

So even if you can't or you don't want to use a new language to use
entity systems, training your mind a bit thinking in a new language
designed for it could help use it in a common language, or could even
suggest you few features to add to a more general purpose language as D.

Wouter van Oortmerssen shows very well that designing many small
specialized languages helps you sharpen your mind and later you apply
those ideas to more general situations:
http://strlen.com/language-design-overview



Yea, all good points. I'm reminded of one of my favorite quotes from 
Joel Spolsky:


I have never met anyone who can do Scheme, Haskell, and C pointers who 
can't pick up Java in two days, and create better Java code than people 
with five years of experience in Java, but try explaining that to the 
average HR drone.

  - http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html



Re: Optimize my code =)

2014-02-17 Thread Nick Sabalausky

On 2/16/2014 6:47 PM, Robin wrote:


@Nick Sabalausky:

Don't be shocked at the bad performance of a beginner D programmer. At
least I am not shocked yet that my D implementation isn't performing as
well as the highly optimized C++11 implementation or the JIT-optimized
Java implementation. In general one can not compare the results of a
native compilation optimization which shall run on different hardwares
and a JIT optimization which is able to pull out every single
optimization routine because it knows the system and all its components
to compile at.



I think you've misunderstood me. I was only explaining D's class vs 
struct system, and why in D (as opposed to Java) structs are better than 
classes in this particular case.




Re: Optimize my code =)

2014-02-17 Thread Nick Sabalausky

On 2/17/2014 4:56 PM, Robin wrote:


And here is the complete and improved code:
http://dpaste.dzfl.pl/7f8610efa82b



You should get rid of the .dup's in the constructors and postblits. You 
don't want big arrays ever getting accidentally allocated and copied 
behind your back when you're only trying to pass things around. Better 
to provide an explicit .dup function in your Matrix class (just like how 
D's dynamic arrays work) for when you *intentionally* want a full duplicate.


Also, unlike classes, when you're copying a struct there's no need to 
copy each field individually. Just copy the struct as a whole. In fact, 
copy constructors and overloading assignments from the same type are 
generally not needed at all: They aren't going to be any faster than 
just using D's default behavior of memory-blitting the struct to the new 
location *if* a copy is actually even needed at all. By providing 
explicit copy constructors and overloading assignments from the same 
type, you're forcing the compiler to use a potentially-slower method 
every time.


Finally, and I could be wrong on this part, but I doubt those move 
constructors are really needed in D. See the top answer here: 
http://stackoverflow.com/questions/4200190/does-d-have-something-akin-to-c0xs-move-semantics




Re: Optimize my code =)

2014-02-14 Thread Nick Sabalausky

On 2/14/2014 11:00 AM, Robin wrote:


class Matrix(T = double) {
 private T[] data;
 private Dimension dim;
}



A matrix is just plain-old-data, so use a struct, you don't need a class.

A struct will be much more lightweight: A struct doesn't normally 
involve memory allocations like a class does, and you'll get better data 
locality and less indirection, even compared to a final class.




I am using opIndex and opIndexAssign in order to access and assign the
matrix values:

T opIndex(size_t row, size_t col) const {
 immutable size_t i = this.dim.offset(row, col);
 if (i = this.dim.size) {
 // TODO - have to learn exception handling in D first. :P
 }
 return this.data[i];
}


No need for the bounds check. D already does bounds checks automatically 
(unless you compile with -noboundscheck, but the whole *point* of that 
flag is to disable bounds checks.)


But that said, I don't know whether the compiler might already be 
optimizing out your bounds check anyway. So try it and profile, see what 
happens.




Another nice thing to know would be if it is possible to initialize an
array before it is default initialized with T.init where T is the type
of the array's fields. In C++ e.g. there is no default initialization
which is nice if you have to initialize every single field anyway. E.g.
in a Matrix.random() method which creates a matrix with random values.
There it is unnecessary that the (sometimes huge) array is completely
initialized with the type's init value.


You can opt-out of the default initialization with a void initializer: 
http://dlang.org/declaration.html#VoidInitializer


Although to be honest I forget how to do that for arrays, and the 
functions other people already suggested for creating/initing your array 
probably already do that anyway.




Re: Custom default exception handler?

2014-02-13 Thread Nick Sabalausky

On 2/12/2014 6:14 PM, Sean Kelly wrote:

On Wednesday, 12 February 2014 at 22:42:45 UTC, Nick Sabalausky
wrote:


Tried on both 2.064.2 and 2.065-b3.

Could it be that the custom toString just doesn't get run for static
exceptions?


It should.  I'm not entirely sure why it isn't working.  For
reference, the relevant code is in rt/dmain2.d (printThrowable)
and object_.d (toString(sink)) in Druntime.


Argh, there seems to be something wonky with the new RDMD in 2.065-b3 
(or hopefully it's just my system):


If I use the RDMD from 2.064.2 to invoke DMD 2.065-b3 then this all 
works fine (thanks!). But if I use the RDMD/DMD *both* from DMD 2.065-b3 
then...I dunno, either the exe doesn't get actually get rebuilt even 
with --force, or maybe it does but then runs an older copy of the exe, 
or something screwy like that. I need to look into that more.


Looks like it's *not* going to work with DMD 2.064.2 though. In that 
version, printThrowable never actually calls Throwable.toString (*any* 
version of toString for that matter), and the sink version of 
Throwable.toString doesn't even exist. That's fine though, at least I 
know it'll work staring with 2.065.




Re: Custom default exception handler?

2014-02-13 Thread Nick Sabalausky

On 2/13/2014 2:55 AM, Nick Sabalausky wrote:

But if I use the RDMD/DMD *both* from DMD 2.065-b3
then...I dunno, either the exe doesn't get actually get rebuilt even
with --force, or maybe it does but then runs an older copy of the exe,
or something screwy like that. I need to look into that more.



RDMD Regression Filed:
https://d.puremagic.com/issues/show_bug.cgi?id=12149



Re: Trouble Compiling DMD, Druntime, Phobos on Windows

2014-02-13 Thread Nick Sabalausky

On 2/13/2014 8:09 PM, Meta wrote:

I'm using Windows 7 x64, but compiling 32-bit DMD. DMD compiles fine,
but the linker warns about a Warning 9: Unknown Option : LA. After
that, when trying to compile Druntime, DMD chokes with this error:



Sounds like you're using an outdated OPTLINK. The /LA flag was added 
relatively recently and the newer DMD buildscripts use it.


Try updating your copy of DMC, maybe a newer one will have the 
up-to-date OPTLINK. Or just replace your DMC's OPTLINK with the one that 
comes with DMD 2.064.2:


http://downloads.dlang.org/releases/2013/dmd.2.064.2.zip



Assertion Failure: 'impl' on line 4930 in file 'mtype.c'.

I looked in the file, but all I could find on line 4930 was:

int TypeAArray::isZeroInit(Loc loc)
{
 return true;
}



Not sure what's up with that one, but I don't have any familiarity with 
mtype. Maybe it's just fallout from the earlier error?




Re: Multiple-OS Header Access

2014-02-12 Thread Nick Sabalausky

On 2/12/2014 12:21 PM, Malkierian wrote:

Alright, so I'm making a little utility, and it looks like I'm going to
need to access OS-specific header functions on each operating system in
order to make it work, because 1) I want to get a list of all active
processes and their names and 2) I want to periodically check which
window currently has focus.  I've already found SetWinEventHook and
GetForegroundWindow (for checking the foreground window and setting an
event hook for focus change), and also EnumProcesses for getting the
list, but these are all Windows specific, not to mention C++ specific on
Windows, and I can't see any way of making one set of functions that
would work on Windows, Mac and Linux.

So anyway, my question is, does D have the capability of interfacing
with Linux and Mac such that those functions are accessible, and/or
would I be better of working in C++ for this particular venture?  How
would I go about accessing those functions, and using the information
they provide in D?


Regarding actually accessing system libraries:
---

The system APIs on Windows and Linux are in C (and sometimes some C++ on 
Windows), and D is perfectly capable of linking with C (and a certain 
subset of C++), so yes this is possible. All you have to do to access 
these system libraries from D is write the extern declarations as 
described here:


http://dlang.org/interfaceToC.html  (C, for most system calls)
http://dlang.org/cpp_interface.html (C++, in case you happen to need it)

All in all, it's actually quite simple.

There's also a really good series of articles out somewhere that 
explains more about it. Unfortunately I don't have a link to it handy 
right now, but you could maybe search for it, or maybe someone else knows.


OSX might be a little trickier since a lot of its libs are in 
Objective-C instead of straight C, but Objective-C is still 
link-compatible with C just like D is, so it's definitely possible.


Also, keep in mind that a lot of OS-specific calls are already available 
through D's standard library. See std.windows, std.linux, std.c.windows, 
std.c.posix, and I think there's some others.


As for dealing with differences between OSes:
---

In C/C++, you'd do this with something like #ifdef. In D you use version().

//One way to do it:
version(Windows) void myOwnWrapperFunction(blah blah blah) {
// Use the Windows API
}

version(linux) void myOwnWrapperFunction(blah blah blah) {
// Use the Linux API
}

version(OSX) void myOwnWrapperFunction(blah blah blah) {
// Use the OSX API
}

//Another way to do it:
void myOwnWrapperFunction(blah blah blah) {
version(windows) {
// Do it the Windows way
}
else version(OSX) {
// Do it the Mac way
}
else version(Posix) {
// Do it the Posix way
}
else
static assert(0, This OS not supported.)
}

Or any combination of the above. This way all the OS-specific 
differences are hidden inside your myOwnWrapperFunction, and you can 
call it from any OS you've supported.


As for knowing what OS-specific functions to use:
---

For that, you'd have to look at the documentation for the OS's API.



Custom default exception handler?

2014-02-11 Thread Nick Sabalausky
I don't suppose there's a way to change the default exception handler 
without using a modified druntime? I'm not seeing one in the docs, but I 
could have overlooked something.


Replacing a druntime function at link-time wouldn't be ideal because 
then druntime's handler couldn't be called as a fallback, at least 
without maintaining a duplicate of druntime's handler and keeping it in 
sync with the version of druntime being used.


Re: Custom default exception handler?

2014-02-11 Thread Nick Sabalausky

On 2/10/2014 10:57 PM, Adam D. Ruppe wrote:

On Tuesday, 11 February 2014 at 03:53:05 UTC, Nick Sabalausky wrote:

I don't suppose there's a way to change the default exception handler
without using a modified druntime


I'm pretty sure there used to be, but not anymore looking at the source.
The d_run_main function has a hardcoded catch block.

Why do you need to change the default though? Can't you just wrap your
own main function in a big try/catch block?


I don't strictly *need* to. But if you're curious, here's the story:

I like to use a little custom exception (Fail) in shell script-like 
stuff to bail out and exit with a given error message in an 
exception-safe way. This is for expected failure conditions, not 
internal errors (so for example: copy src.txt - Error, no 
destination given! or File src.txt doesn't exist!, etc), so the stack 
trace is unnecessary noise and omitted. Only the message is printed, 
maybe with a common prefix like mytool: ERROR: 


This is arguably a slight abuse of the exception system, but in 
script-like stuff the exception performance doesn't really matter, and I 
find it does greatly simply the error logic of D-based scripts. Helps 
keep simple scripts simple.


I'm sticking this Fail stuff into a little utility lib for simple 
script-like programs, and so, if possible, I'd *like* to instruct users 
to just do this:


void main() {
installFailHandler();
...
}

instead of all this boilerplate:

int main() {
try {
...user code...
}
catch(Fail e) {
writeln(e.msg);
return 1;
}

return 0;
}

I'm sure I could also do something like this, but it's rather ugly:

int main() {
mixin(handleFail!(() = {
...user code...
}));
}

So not a real big deal, but it'd be nice if I could swing it.



Re: Custom default exception handler?

2014-02-11 Thread Nick Sabalausky

On 2/11/2014 10:00 AM, Adam D. Ruppe wrote:

So this would work too:

int handleError(void delegate() dg) {
 try dg();
 catch(Throwable t) return 1;
 return 0;
}

int main() {
 return handleError({

 });
}



Oh yea, good point. That's not bad at all;



Re: Custom default exception handler?

2014-02-11 Thread Nick Sabalausky

On 2/11/2014 6:35 PM, Sean Kelly wrote:

Throw a static exception (maybe even derived directly from Throwable),
similar to OutOfMemory, with a custom toString.  That should eliminate
the formatting you don't like and will prevent the trace from occurring
as well (see rt/deh.d in Druntime--the trace isn't run if you throw
typeid(t).init.ptr).


Oh, interesting. Is this something that can be relied on long-term? Ie, 
is a static non-Exception Throwable deliberately *supposed* to not 
include a stack trace, or is it potentially more of a currently-missing 
feature?




Re: Custom default exception handler?

2014-02-11 Thread Nick Sabalausky

On 2/11/2014 6:35 PM, Sean Kelly wrote:

Throw a static exception (maybe even derived directly from Throwable),


I assume then that throwing something directly derived from Throwable 
would still run cleanup code (like scope guards and finally) like 
throwing Exception would? Or is it like throwing an Error, skipping 
cleanup code?




Re: Custom default exception handler?

2014-02-11 Thread Nick Sabalausky

On 2/11/2014 6:35 PM, Sean Kelly wrote:

Throw a static exception (maybe even derived directly from Throwable),
similar to OutOfMemory, with a custom toString.  That should eliminate
the formatting you don't like and will prevent the trace from occurring
as well (see rt/deh.d in Druntime--the trace isn't run if you throw
typeid(t).init.ptr).


Hmm, my custom toString isn't being executed. Am I doing something wrong 
here? Same result if I inherit direct from Throwable instead of Exception.


class Fail : Exception
{
private this()
{
super(null);
}

private static Fail opCall(string msg, string file=__FILE__, int 
line=__LINE__)

{
auto f = cast(Fail) cast(void*) Fail.classinfo.init;

f.msg  = msg;
f.file = file;
f.line = line;

return f;
}

override string toString()
{
writeln(In Fail.toString());
return someapp: ERROR: ~msg;
}

}

void fail(string msg, string file=__FILE__, int line=__LINE__)
{
throw Fail(msg, file, line);
}

void main()
{
fail(Shit/fan collision detected.);
}

Output:
scriptlike.Fail@scriptlike.d(106): Shit/fan collision detected.



Overload sets and templates

2014-02-08 Thread Nick Sabalausky

This works:

--
void foo(T)(T t) if(is(T==char)) {}
void foo(T)(T t) if(is(T==int )) {}

void main() { foo(1); }
--

But if I move the int version to a different module, and try to alias 
it into the current module's overload set (like I can with non-templated 
functions), I just get an error that the char version of foo conflicts 
with the alias:


--
module a;
import b;

alias foo = b.foo;
void foo(T)(T t) if(is(T==char)) {}

void main() { foo(1); }
--
module b;
void foo(T)(T t) if(is(T==int)) {}
--

What's up with that? Is there a way to do it?


Re: Overload sets and templates

2014-02-08 Thread Nick Sabalausky

On 2/8/2014 11:35 AM, Timon Gehr wrote:


What you are trying to do should work. I.e. this is a compiler bug.


Thanks. Filed:
https://d.puremagic.com/issues/show_bug.cgi?id=12111


pure vs writeln debugging

2014-02-08 Thread Nick Sabalausky
Is there some way to poke enough of a hole in pure to get some writeln 
debugging statements in?


Re: pure vs writeln debugging

2014-02-08 Thread Nick Sabalausky

On 2/8/2014 5:30 PM, Adam D. Ruppe wrote:

On Saturday, 8 February 2014 at 22:27:39 UTC, Nick Sabalausky wrote:

Is there some way to poke enough of a hole in pure to get some
writeln debugging statements in?


literally write
debug writeln(..)

abnd it should work in the pure function


Nice!

So I take it purity enforcement is disabled with the -debug flag? Or is 
it some sort of hack with writeln?




  1   2   3   4   5   >