How to check whether an empty array variable is null?

2015-10-10 Thread tcak via Digitalmars-d-learn

[code]
int[] list;

list = new int[0];

std.stdio.writeln("Is Null ? ", (list is null));
[/code]

Result is "Is Null? true".

Is this the correct behaviour? I would expect compiler to point 
to an address in the heap, but set the length as 0. So, it 
wouldn't return null, but the length would be 0 only.


Re: How to check whether an empty array variable is null?

2015-10-10 Thread rumbu via Digitalmars-d-learn

On Saturday, 10 October 2015 at 15:20:04 UTC, tcak wrote:

[code]
int[] list;

list = new int[0];

std.stdio.writeln("Is Null ? ", (list is null));
[/code]

Result is "Is Null? true".

Is this the correct behaviour? I would expect compiler to point 
to an address in the heap, but set the length as 0. So, it 
wouldn't return null, but the length would be 0 only.



Long discussion: 
http://forum.dlang.org/thread/rrrtkfosfnfuybble...@forum.dlang.org




Re: How to check whether an empty array variable is null?

2015-10-10 Thread Meta via Digitalmars-d-learn

On Saturday, 10 October 2015 at 15:20:04 UTC, tcak wrote:

[code]
int[] list;

list = new int[0];

std.stdio.writeln("Is Null ? ", (list is null));
[/code]

Result is "Is Null? true".

Is this the correct behaviour? I would expect compiler to point 
to an address in the heap, but set the length as 0. So, it 
wouldn't return null, but the length would be 0 only.


Yes, it's correct behaviour. `array is null` checks whether 
array.ptr is null, which is the case for a 0-length array.


void main()
{
auto a = new int[0];
writeln(a.ptr);  //a.ptr is null

auto a2 = new int[1];
writeln(a2.ptr); //a2.ptr is not null
a2 = a[0..$];//Slice off the only element of a2
writeln(a2.ptr); //Now a2.ptr is null
}


Hash-Table-Based Multiple Arguments Replacement

2015-10-10 Thread Nordlöw via Digitalmars-d-learn
Is there an algorithm somewhere in Phobos which performs when 
possible a replacement/substitution based on a variadic 
definition of replacements using hash-table search similar to


string replaceWhole(string a)
{
switch (x)
{
case "a": return "1";
case "b": return "2";
default:  return x;
}
}

?

Desired interface

y = x.replaceWhole!("a","x",
"b","y",
"c","z")

or perhaps

y = x.replaceWhole!(tuple("a","x"),
tuple("b","y"),
tuple("c","z"))


kind of like

"a".among!("a", "b", "c")

but for replacements.


Re: Hash-Table-Based Multiple Arguments Replacement

2015-10-10 Thread Nordlöw via Digitalmars-d-learn

On Saturday, 10 October 2015 at 16:19:53 UTC, Nordlöw wrote:
Is there an algorithm somewhere in Phobos which performs when 
possible a replacement/substitution based on a variadic 
definition of replacements using hash-table search similar to


Found it:

http://dlang.org/phobos/std_algorithm_comparison.html#predSwitch

An alias would be perhaps be motivated to make newcomers easier 
grap that this can be used for whole replacements.


Re: Hash-Table-Based Multiple Arguments Replacement

2015-10-10 Thread Nordlöw via Digitalmars-d-learn

On Saturday, 10 October 2015 at 16:42:52 UTC, Nordlöw wrote:

Found it:

http://dlang.org/phobos/std_algorithm_comparison.html#predSwitch

An alias would be perhaps be motivated to make newcomers easier 
grap that this can be used for whole replacements.


Ahh, but this doesn't use a hash-table because it doesn't support 
taking its arguments as CT-params...so that doesn't qualify.


Maybe we should add a new CT-param-only overload for `predSwitch` 
similar to `among`?


Destroy!


Re: AWS API Dlang, hmac sha256 function.

2015-10-10 Thread holo via Digitalmars-d-learn

On Friday, 9 October 2015 at 16:30:26 UTC, holo wrote:
OK i find out error, in addRequestHeader i was using ":" after 
header name what casing problem. I removed it and now im 
getting "unauthorized". Here is how it looks right now:


 HTTP/1.1 401 Unauthorized\r\n
[Expert Info (Chat/Sequence): HTTP/1.1 401 
Unauthorized\r\n]

Request Version: HTTP/1.1
Status Code: 401
Response Phrase: Unauthorized
Transfer-Encoding: chunked\r\n
Date: Fri, 09 Oct 2015 16:22:47 GMT\r\n
Server: AmazonEC2\r\n
\r\n
[HTTP response 1/2]
[Next request in frame: 8371]
HTTP chunked response
Data chunk (254 octets)
Chunk size: 254 octets
Data (254 bytes)

In data field i can read:

"AWS was not able to validate provided access credentials" Is 
my signing process incorrect?


Maybe i will put my present code again:

#!/usr/bin/rdmd -L-lcurl

import std.stdio;
import std.string;
import std.file;
import std.datetime;
import std.process;
import std.digest.sha;
import std.net.curl;
import std.uri;
import sigv4;


auto zone = "us-east-1";
auto service = "ec2";


void main()
{
auto accKey = environment["AWS_ACCESS_KEY"];
auto secKey = environment["AWS_SECRET_KEY"];

auto currentClock = Clock.currTime;

auto currentDate = cast(Date)currentClock;
auto curDateStr = currentDate.toISOString;

auto currentTime = cast(TimeOfDay)currentClock;
auto curTimeStr = currentTime.toISOString;

auto xamztime = curDateStr ~ "T" ~ curTimeStr ~ "Z";

string[string] empty;

SignableRequest r;
r.dateString = curDateStr;
r.timeStringUTC = curTimeStr;
r.region = zone;
r.service = service;
r.canonicalRequest = CanonicalRequest(
"POST",
"/",
["action" : "DescribeInstances", "version" : 
"2013-10-15"],
//  ["accept" : "*/*",
			["content-type" : "application/x-www-form-urlencoded; 
charset=utf-8",

 "host" : service ~ ".amazonaws.com",
 "x-amz-date" : xamztime],
			 cast(ubyte[])"");  
//cast(ubyte[])"Action=DescribeInstances&Version=2013-10-15");


	auto qParm = 
canonicalQueryString(r.canonicalRequest.queryParameters);


auto sigHead = canonicalHeaders(r.canonicalRequest.headers);

auto sigStr = signableString(r);

auto sigKey = signingKey(secKey, curDateStr, zone, service);

	auto signature = sign(sigKey, 
cast(ubyte[])sigStr).toHexString().toLower();


writeln();  
writeln(qParm);
writeln();
writeln(sigHead);
writeln();
writeln(sigStr);
writeln();
writeln(signature);
writeln();
auto client = HTTP();
//  client.clearRequestHeaders;
	client.addRequestHeader("content-type", 
"application/x-www-form-urlencoded; charset=utf-8");

client.addRequestHeader("host", service ~ ".amazonaws.com");
client.addRequestHeader("x-amz-date", xamztime);
	client.addRequestHeader("authorization", "AWS4-HMAC-SHA256" ~ " 
" ~ "Credential=" ~ accKey ~ "/" ~ xamztime ~ "/" ~ zone ~ "/" ~ 
service ~ "/" ~ "aws4_request" ~ ", " ~ "SignedHeaders=" ~ 
"content-type;host;x-amz-date" ~ ", " ~ "Signature=" ~ signature);


	auto url = "ec2.amazonaws.com/?" ~ 
"Action=DescribeInstances&Version=2013-10-15";

auto urlenc = encode(url);
writeln(url);
auto content = get(urlenc, client);
writeln(content);
}

Is my signing process correct?


Compile time and runtime grammars

2015-10-10 Thread DLangLearner via Digitalmars-d-learn
Only now I found that most of my confusions are with D's compile 
time grammar or features. As an excuse, my confusions can be 
partially attributed to the way D is presented:


1. There are confusing keywords:
For example, there is a "if", there is also a "static if", there 
is a "if", and there is an "is()". For new learners like me, they 
cause confusion at least uneasiness.


2. Compile time grammar spreads among runtime grammar
Most documents present D's compile time grammar and runtime 
grammar in the same time. It made me feel that D's grammar is not 
consistent because compile time grammar seem to be exceptions 
from runtime grammar. If a document talks exclusively about 
runtime grammar first, and
introduces compile time grammar late, I think this will make 
readers accept those seemingly conflicting grammar. In fact 
without introducing compile time grammar, D is much similar to 
other languages, in this way the readers from other languages can 
find D more friendly.


With the understanding of D's compile time grammar, I can read D 
codes from other projects such as std packages, but I am still 
not easy about the way that D's compile time codes are not 
clearly distinguished from runtime codes. I am wondering if it is 
a good idea to clearly indicate those compile time codes with a 
special identifier say "@ct", or prefix "__" as in __traints, if 
so then those "inconsistencies" can be resolved as follows:


static if -> @ct if
static assert" -> @ct assert
enum fileName = "list.txt" -> @ct  fileName = "list.txt"
is (string[void]) -> @ct is (string[void])
mixin(`writeln("Hello World!");`) -> @ct `writeln("Hello 
World!");`


So this post is not quite a question, just a thought in my mind 
after I am able to differentiate compile time codes from runtime 
codes.


Re: Compile time and runtime grammars

2015-10-10 Thread H. S. Teoh via Digitalmars-d-learn
On Sat, Oct 10, 2015 at 06:52:29PM +, DLangLearner via Digitalmars-d-learn 
wrote:
> Only now I found that most of my confusions are with D's compile time
> grammar or features. As an excuse, my confusions can be partially
> attributed to the way D is presented:
> 
> 1. There are confusing keywords:
> For example, there is a "if", there is also a "static if", there is a
> "if", and there is an "is()". For new learners like me, they cause
> confusion at least uneasiness.

I assume by the second "if" you meant "is".  It's well-known that the
syntax of is() could be better. Unfortunately, the ship has long since
sailed, and there's not much point in breaking existing code just to
make some cosmetic changes.

The "static" in "static if" is clear indication that this isn't a
regular if-statement, but a branch that's taken at compile-time. I'm not
sure how else it can be made clearer.


> 2. Compile time grammar spreads among runtime grammar
> Most documents present D's compile time grammar and runtime grammar in
> the same time. It made me feel that D's grammar is not consistent
> because compile time grammar seem to be exceptions from runtime
> grammar. If a document talks exclusively about runtime grammar first,
> and introduces compile time grammar late, I think this will make
> readers accept those seemingly conflicting grammar. In fact without
> introducing compile time grammar, D is much similar to other
> languages, in this way the readers from other languages can find D
> more friendly.
> 
> With the understanding of D's compile time grammar, I can read D codes
> from other projects such as std packages, but I am still not easy
> about the way that D's compile time codes are not clearly
> distinguished from runtime codes. I am wondering if it is a good idea
> to clearly indicate those compile time codes with a special identifier
> say "@ct", or prefix "__" as in __traints, if so then those
> "inconsistencies" can be resolved as follows:
> 
> static if -> @ct if
> static assert" -> @ct assert
> enum fileName = "list.txt" -> @ct  fileName = "list.txt"
> is (string[void]) -> @ct is (string[void])
> mixin(`writeln("Hello World!");`) -> @ct `writeln("Hello World!");`
> 
> So this post is not quite a question, just a thought in my mind after
> I am able to differentiate compile time codes from runtime codes.

Actually, this shows a misunderstanding of what D's compile-time
features actually do, and also shows that the terminology "compile-time"
itself is a bit misleading. This is likely the fault of the way these
features are described in the documentation.

In D, there are actually (at least) two (very!) distinct categories of
compile-time features:

There's the template system, which is mainly concerned with manipulating
the syntax tree of the code.  This provides the meta-programming
features of D, and runs quite early on in the compilation process.

There's also the CTFE system (compile-time function evaluation), which
is mainly concerned with *executing code* inside the compiler, at
runtime, after the syntax tree has been generated, which is later in the
compilation process. Obviously, this can only be done after the syntax
tree has been fixed, otherwise the semantics of the code would be
undefined or inconsistent.

The two are closely-related, and the difference may seem to be subtle,
but this is extremely important to understand in order to understand how
to use these features effectively.

For example, "static if" is a feature belonging to the template system,
and is concerned with manipulating the syntax tree of the program before
the compiler runs its semantic passes over it.  The branch is evaluated
*before* CTFE even sees the code; and that's why the following code does
*not* work:

int func(bool x) {
static if (x)
return 1;
else
return 2;
}
enum y = func(1);

The first problem is that the static-if is asking the compiler to
evaluate x. Theoretically speaking, this should work, since x is known
at "compile-time", but when the static-if is being processed, the syntax
tree of func() isn't even completed yet, so the compiler has no way of
knowing what x might be referring to.

The second problem is that the value of the enum is processed by CTFE,
but since the static-if is processed before CTFE even sees the code, by
the time CTFE runs it's already too late for the static-if to decide
which branch should be taken. Static-if means that the branch of code
that isn't taken, doesn't even exist in the syntax tree of the program;
it's as if the programmer deleted those lines from the source file.

So you see, the term "compile-time" is actually ambiguous, because there
are actually two distinct phases of compilation here, and intermixing
them doesn't make sense.

The correct version of the above code is:

int func(bool x) {
if (x)  // <--- N.B. no "static"

Re: How to check whether an empty array variable is null?

2015-10-10 Thread Jonathan M Davis via Digitalmars-d-learn
On Saturday, October 10, 2015 15:20:02 tcak via Digitalmars-d-learn wrote:
> [code]
>   int[] list;
>
>   list = new int[0];
>
>   std.stdio.writeln("Is Null ? ", (list is null));
> [/code]
>
> Result is "Is Null? true".
>
> Is this the correct behaviour? I would expect compiler to point
> to an address in the heap, but set the length as 0. So, it
> wouldn't return null, but the length would be 0 only.

It basically didn't bother to allocate an array on the heap, because you
asked for one with a length of zero. Efficiency-wise, it makes no sense to
allocate anything. You wouldn't be doing anything with the memory anyway.
The only way that you're going to get an array of length 0 which doesn't
have a null ptr is to slice an array down to a length of 0.

- Jonathan M Davis



Re: Compile time and runtime grammars

2015-10-10 Thread Ali Çehreli via Digitalmars-d-learn

On 10/10/2015 12:43 PM, H. S. Teoh via Digitalmars-d-learn wrote:
> On Sat, Oct 10, 2015 at 06:52:29PM +, DLangLearner via 
Digitalmars-d-learn wrote:


>> 1. There are confusing keywords:

To OP: I am glad that you are not bothered with compile-time foreach. ;)

> The "static" in "static if" is clear indication that this isn't a
> regular if-statement, but a branch that's taken at compile-time. I'm not
> sure how else it can be made clearer.

I would make curly brackets mandatory for the static if block and its 
else block. The following is almost always wrong:


static if (cond) {
// ...
} else if {// Oops! Inserting a run-time if
// ...
}

If that was really intended, they would have to use curly brackets:

} else {// <-- could be required
if {
// ...
}
}

Ali



Re: Hash-Table-Based Multiple Arguments Replacement

2015-10-10 Thread Meta via Digitalmars-d-learn

On Saturday, 10 October 2015 at 16:19:53 UTC, Nordlöw wrote:
Is there an algorithm somewhere in Phobos which performs when 
possible a replacement/substitution based on a variadic 
definition of replacements using hash-table search similar to


string replaceWhole(string a)
{
switch (x)
{
case "a": return "1";
case "b": return "2";
default:  return x;
}
}

?

Desired interface

y = x.replaceWhole!("a","x",
"b","y",
"c","z")

or perhaps

y = x.replaceWhole!(tuple("a","x"),
tuple("b","y"),
tuple("c","z"))


kind of like

"a".among!("a", "b", "c")

but for replacements.


There was something like this proposed quite awhile ago (can't 
remember what it was, might've been extending unary/binaryFun to 
accept an AA), but it was rejected.


Re: How to check whether an empty array variable is null?

2015-10-10 Thread Meta via Digitalmars-d-learn

On Sunday, 11 October 2015 at 00:18:54 UTC, Meta wrote:
On Saturday, 10 October 2015 at 20:07:11 UTC, Jonathan M Davis 
wrote:
It basically didn't bother to allocate an array on the heap, 
because you asked for one with a length of zero. 
Efficiency-wise, it makes no sense to allocate anything. You 
wouldn't be doing anything with the memory anyway. The only 
way that you're going to get an array of length 0 which 
doesn't have a null ptr is to slice an array down to a length 
of 0.


- Jonathan M Davis


Look at my second example.


Sorry, I thought you were responding to me.


Re: How to check whether an empty array variable is null?

2015-10-10 Thread Meta via Digitalmars-d-learn
On Saturday, 10 October 2015 at 20:07:11 UTC, Jonathan M Davis 
wrote:
It basically didn't bother to allocate an array on the heap, 
because you asked for one with a length of zero. 
Efficiency-wise, it makes no sense to allocate anything. You 
wouldn't be doing anything with the memory anyway. The only way 
that you're going to get an array of length 0 which doesn't 
have a null ptr is to slice an array down to a length of 0.


- Jonathan M Davis


Look at my second example.


Re: Hash-Table-Based Multiple Arguments Replacement

2015-10-10 Thread Nordlöw via Digitalmars-d-learn

On Sunday, 11 October 2015 at 00:16:44 UTC, Meta wrote:
There was something like this proposed quite awhile ago (can't 
remember what it was, might've been extending unary/binaryFun 
to accept an AA), but it was rejected.


With static foreach in a switch we can do better. I'll put 
together a solution.


Re: How to check whether an empty array variable is null?

2015-10-10 Thread tcak via Digitalmars-d-learn
On Saturday, 10 October 2015 at 20:07:11 UTC, Jonathan M Davis 
wrote:
On Saturday, October 10, 2015 15:20:02 tcak via 
Digitalmars-d-learn wrote:

[code]
  int[] list;

  list = new int[0];

  std.stdio.writeln("Is Null ? ", (list is null));
[/code]

Result is "Is Null? true".

Is this the correct behaviour? I would expect compiler to 
point to an address in the heap, but set the length as 0. So, 
it wouldn't return null, but the length would be 0 only.


It basically didn't bother to allocate an array on the heap, 
because you asked for one with a length of zero. 
Efficiency-wise, it makes no sense to allocate anything. You 
wouldn't be doing anything with the memory anyway. The only way 
that you're going to get an array of length 0 which doesn't 
have a null ptr is to slice an array down to a length of 0.


- Jonathan M Davis


The situation is that the "length" parameter comes from user. 
Also the item values come from user as well. I create the array 
with "length" parameter. At another part of code, I check firstly 
whether the array is created [code] if( array is null ) [/code], 
then the items are checked for validation.