Re: Manipulate slice or specific element of range and return range

2018-03-21 Thread Seb via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 11:30:28 UTC, Timoses wrote:

Hey,

I'm struggling to find a way to achieve this. I've looked 
through std.algorithm but didn't find anything.. Maybe I'm 
blind.


What I would like to do is filter out all spaces in a string 
and change the front letter to lower case:


string m = "My Capital String";
string lower = m
.filter!(c => c != ' ')
.!(0, c => c.toLower) // executeAt does not 
exist

.array.to!string;
assert(lower == "myCapitalString");

or sth like

m.filter!(...)
.map!((element, int index) {
if (index == 0)
return element.toLower;
else
break; // stop since we are done manipulating 
range

});

Anyway to do this?


No need for regular expressions. D is powerful enough without 
them:


```
alias lowercased = (m, n) => 
m.take(n).asLowerCase.chain(m.drop(n));

```

https://run.dlang.io/is/cSL0si


Re: Understanding slide

2018-03-21 Thread Seb via Digitalmars-d-learn

On Thursday, 22 March 2018 at 03:58:35 UTC, Seb wrote:

On Thursday, 22 March 2018 at 03:39:38 UTC, Jordan Wilson wrote:

auto a = iota(5).slide!(Yes.withPartial)(3);
auto b = iota(5).slide!(No.withPartial)(3);
assert (a.equal(b));

The assert passes, but I would expect it to fail? They both 
are:

[[0,1,2],[1,2,3],[2,3,4]]

Thanks,

Jordan


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


PR to improve the docs: https://github.com/dlang/phobos/pull/6322


Re: Understanding slide

2018-03-21 Thread Seb via Digitalmars-d-learn

On Thursday, 22 March 2018 at 03:39:38 UTC, Jordan Wilson wrote:

auto a = iota(5).slide!(Yes.withPartial)(3);
auto b = iota(5).slide!(No.withPartial)(3);
assert (a.equal(b));

The assert passes, but I would expect it to fail? They both are:
[[0,1,2],[1,2,3],[2,3,4]]

Thanks,

Jordan


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


Understanding slide

2018-03-21 Thread Jordan Wilson via Digitalmars-d-learn

auto a = iota(5).slide!(Yes.withPartial)(3);
auto b = iota(5).slide!(No.withPartial)(3);
assert (a.equal(b));

The assert passes, but I would expect it to fail? They both are:
[[0,1,2],[1,2,3],[2,3,4]]

Thanks,

Jordan


Re: recursive template expansion: Why does this not compile?

2018-03-21 Thread Jonathan M Davis via Digitalmars-d-learn
On Wednesday, March 21, 2018 22:50:32 Ontonator via Digitalmars-d-learn 
wrote:
> On Wednesday, 21 March 2018 at 06:39:22 UTC, ag0aep6g wrote:
> > On 03/21/2018 01:47 AM, Ontonator wrote:
> >> The following code does not compile:
> >>> [...]
> >>
> >> It gives the error:
> >>> [...]
> >>
> >> The aliases do not have to be aliases, as long as there is
> >> some reference to the class (e.g. method and variable
> >> declarations also work). What exactly is the reason for this
> >> error?
> >
> > Compiler bug. It works when you move the declaration of `B`
> > before the one of `A`. Order shouldn't matter there.
>
> Is this a known bug, or should I report it?

If you can't find it searching on bugzilla, report it.

- Jonathan M Davis



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

2018-03-21 Thread Jonathan M Davis via Digitalmars-d-learn
On Wednesday, March 21, 2018 20:07:09 tipdbmp via Digitalmars-d-learn 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.

In principle, D types read in more or less the same way as C types. The main
differences are that we simplifed how function pointers are declared (making
them more like function prototypes) and got rid of the types on the
right-hand side of the name. e.g.

int[10] arr;

instead of

int arr[10];

Both read outward from the type, but the D way is then right-to-left in this
case, whereas the C way is left-to-right even though they're both reading
outward from the type. So, this makes it look like D reads right-to-left,
but it'st still reading outward from the type. e.g. if you look at how
dynamic arrays are declared, it's still outward from the type, not
right-to-left. e.g.

auto foo = new int[][](10, 14);
assert(foo.length == 10);
assert(foo[0].length == 14);

vs

int[10][14] foo;
assert(foo.length == 14);
assert(foo[0].length == 10);

The fact that parens are used for const does muck with things a bit though.
In C/C++, you have

const int* p;

which is equivalent to

int const* p;

but for whatever reason, both are allowed. The second one reads outward from
the type, whereas the first one essentially breaks those rules a bit. And D
essentially went with the first one, because the equivalent would be

const(int)* p;

and there's no way to put the const on the right. So, while the pointer
portion of the type does read outward from the type, const doesn't really.

So, overall, D cleaned things up, but it didn't actually make them fully
consistent either.

- Jonathan M Davis



Re: recursive template expansion: Why does this not compile?

2018-03-21 Thread Ontonator via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 06:39:22 UTC, ag0aep6g wrote:

On 03/21/2018 01:47 AM, Ontonator wrote:

The following code does not compile:

[...]


It gives the error:

[...]


The aliases do not have to be aliases, as long as there is 
some reference to the class (e.g. method and variable 
declarations also work). What exactly is the reason for this 
error?


Compiler bug. It works when you move the declaration of `B` 
before the one of `A`. Order shouldn't matter there.


Is this a known bug, or should I report it?


Re: Slow start up time of runtime (correction: Windows real-time protection)

2018-03-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 13:26:48 UTC, HeiHon wrote:
In Windows Security Center Settings (where you can disable 
realtime scan) there is also an entry "Exclusions" (in german 
windows "Ausschlüsse").
I added exclusions for the folder, where I installed dmd and 
ldc and I added an exclusion for the folder, where I compile my 
D programs. Now startup of dmd and freshly compiled programs is 
fast again.


Awesome tip!


Re: Need example of usage DerelictPQ

2018-03-21 Thread number via Digitalmars-d-learn

On Wednesday, 24 December 2014 at 11:56:40 UTC, Suliman wrote:
Could anybody provide any simple examples of usage DerelictPQ. 
I do not have experience of C, and I can't understand how to 
use this driver.


I need just basics like connect, select and insert.

http://code.dlang.org/packages/derelict-pq

thanks!



A bit late, but maybe useful for others, and googling 'dlang 
derelict postgres example' brings you here..


The default ubuntu (16.04) postgres version caused runtime errors 
for me (DerelictPQ.load()), what worked was installation from 
here:

https://www.postgresql.org/download/linux/ubuntu/

the example expects a postgres user/role 'sammy' with password 
'sammypw' and a database 'sammy' with a table as shown in 
comments and set up as here:

https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-16-04

if you don't specify a host at PQconnectdb() then you might get 
an error

'Peer authentication failed for user "sammy"'
when you run the binary as a OS user different from 'sammy', or 
you would have to run the program as the postgres user like

sudo -iu sammy /path/to/prog

 dub.json
{
"name": "prog",
"targetType": "executable",
"sourceFiles": [ "prog.d" ],
"dependencies": {
"derelict-pq": "~>2.2.0"
}
}

 prog.d
import core.stdc.stdlib;
import std.stdio;
import std.conv;
import derelict.pq.pq;

/*
CREATE TABLE playground (
equip_id serial PRIMARY KEY,
type varchar (50) NOT NULL,
color varchar (25) NOT NULL,
	location varchar(25) check (location in ('north', 'south', 
'west', 'east', 'northeast', 'southeast', 'southwest', 
'northwest')),

install_date date
);

	INSERT INTO playground (type, color, location, install_date) 
VALUES ('slide', 'blue', 'south', '2014-04-28');
	INSERT INTO playground (type, color, location, install_date) 
VALUES ('swing', 'yellow', 'northwest', '2010-08-16');


 */

int main(string[] args)
{
int retval = EXIT_SUCCESS;

DerelictPQ.load();

	PGconn* conn = PQconnectdb("user = 'sammy' password = 'sammypw' 
dbname = 'sammy' host = '127.0.0.1'");

if (PQstatus(conn) != CONNECTION_OK)
{
		writefln("ERROR (connection): %s", 
to!string(PQerrorMessage(conn)));

retval = EXIT_FAILURE;
}
else
{
writeln("OK (connection)");

PGresult* result = PQexec(conn, "select * from playground");
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
			writefln("ERROR (result): %s", 
to!string(PQerrorMessage(conn)));

retval = EXIT_FAILURE;

}
else
{
writeln("OK (result)");

int nbFields = PQnfields(result);
writeln("nbFields: ", nbFields);

int nbRows = PQntuples(result);
writeln("nbRows: ", nbRows);

for (int f; f < nbFields; f++)
{
writef("%16s", to!string(PQfname(result, f)));
}
writeln("");

for (int r; r < nbRows; r++)
{
for (int f; f < nbFields; f++)
{
ubyte* ub = 
cast(ubyte*)(PQgetvalue(result, r, f));
int len = PQgetlength(result, r, f);
char[] c = cast(char[])ub[0..len];
string s = to!string(c);
writef("%16s", s);
}
writeln("");
}
}
PQclear(result);
}
PQfinish(conn);

return retval;
}



If someone has a better way to convert the PQgetvalue() to 
string, i'm interested :)

The functions are as follows:
alias da_PQgetvalue = const(ubyte)* 
function(const(PGresult)*,int,int);

alias da_PQgetlength = int function(const(PGresult)*,int,int);

have a nice day


Re: Slow start up time of runtime (correction: Windows real-time protection)

2018-03-21 Thread Dennis via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 13:26:48 UTC, HeiHon wrote:
I added exclusions for the folder, where I installed dmd and 
ldc and I added an exclusion for the folder, where I compile my 
D programs. Now startup of dmd and freshly compiled programs is 
fast again.


I've done this too now, thanks for the tip!


Re: OK, I'm stumped on this one: dstep, struct, mixin, bitfields

2018-03-21 Thread Jacob Carlborg via Digitalmars-d-learn

On 2018-03-21 20:30, Russel Winder wrote:


Thanks to Adam and Ali, it was clear and obvious.


Please report and issue so it's not forgotten.

--
/Jacob Carlborg


Re: Packages and module import

2018-03-21 Thread Jacob Carlborg via Digitalmars-d-learn

On 2018-03-21 17:06, Russel Winder wrote:


No I wasn't. And it works a treat.


Cool :). I recommend having a look at the changelog and the usage 
information (--help).


--
/Jacob Carlborg


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: D's type declarations seem to read right to left.

2018-03-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 20:07:09 UTC, tipdbmp wrote:
I think this is a big improvement over C's "spiral" way of 
reading types:


Yes, D is perfect and has achieved sanity where before there was 
none.


You can read basically anything with little knowledge.

void function()[] array_of_funtions;
int[]*[]*[string] assoctiavive array of pointers to arrays of 
pointers to arrays of ints.


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

2018-03-21 Thread tipdbmp via Digitalmars-d-learn

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.



Re: OK, I'm stumped on this one: dstep, struct, mixin, bitfields

2018-03-21 Thread H. S. Teoh via Digitalmars-d-learn
On Wed, Mar 21, 2018 at 07:30:28PM +, Russel Winder via Digitalmars-d-learn 
wrote:
[...]
> But :-(
> 
> Why does version have to be a keyword?
[...]

version(all) { ... }
version(none) { ... }
version(Posix) { ... }
version(Windows) { ... }

But yeah, using "version" for this purpose makes the very common
identifier "version" unavailable for use.  I've been bitten by this
multiple times.

auto version = getVersion();// NG
auto ver = getVersion();// OK

struct PacketHeader {
ushort version; // NG
ushort ver; // OK
}

:-(


T

-- 
Маленькие детки - маленькие бедки.


Re: OK, I'm stumped on this one: dstep, struct, mixin, bitfields

2018-03-21 Thread Russel Winder via Digitalmars-d-learn
On Wed, 2018-03-21 at 18:11 +, Adam D. Ruppe via Digitalmars-d-
learn wrote:
> On Wednesday, 21 March 2018 at 18:00:38 UTC, Russel Winder wrote:
> > ubyte, "version", 5,
> 
> 
> version is a D keyword, so I would suggest trying "version_" 
> there instead and see if it works. (I'm guessing btw, the error 
> message was way to long and illegible, but this is an easy first 
> guess anyway)

On Wed, 2018-03-21 at 11:14 -0700, Ali Çehreli via Digitalmars-d-learn
wrote:
[…]
> 
> I think it's because 'version' is a D keyword. :)
> 
> Ali
> 

Thanks to Adam and Ali, it was clear and obvious. 

But :-(

Why does version have to be a keyword?

-- 
Russel.
===
Dr Russel Winder  t: +44 20 7585 2200
41 Buckmaster Roadm: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk


signature.asc
Description: This is a digitally signed message part


Re: strip() and formattedRead()

2018-03-21 Thread realhet via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 18:50:18 UTC, Adam D. Ruppe wrote:

On Wednesday, 21 March 2018 at 18:44:12 UTC, realhet wrote:
Compiling this I get an error: "formattedRead: cannot deduce 
arguments from (string, string, float, float, float)"


What compiler version are you using? The newest versions allow 
this code, though the old ones require an intermediate variable 
to satisfy the `ref` requirement on formattedRead (it will want 
to update that variable to advance it past the characters it 
read).


so either update your version, or just give an and use an 
intermediate:


string s = "".strip;
formattedRead(s, )


Thank both of You! You guys are super helpful. (I'm learning from 
Ali's book and after these instant answers I was like: "I'm not 
worthy" :D)


So I had v2077.1 previously, now I've installed 2079.0 and it all 
works great.





Re: why does this compile fine, but dies when you run it.

2018-03-21 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 21 March 2018 at 18:53:39 UTC, steven kladitis 
wrote:

int[] array3;
array3[0]=4;


array3 is empty. You are trying to set a value that doesn't 
exist..


Calling Windows Command

2018-03-21 Thread Vino via Digitalmars-d-learn

Hi All,

 Request your help in calling the windows command to delete all 
file and folders recursively as the D function rmdirRecurse does 
not delete file in the permission of the file is readonly in 
windows 2008 R2


import std.process: execute;
import std.array: empty;
auto RemoveDir () (
auto dFiles = "C:\\Temp\Test1";
auto Step = "run";
if (Step == "run" && !dFiles.empty) {
version(Windows)
 {
  foreach(d; dFiles) {
  execute(["rmdir.exe","-command", "/S /Q", `~d~`]); } } } 
return dFiles;

)

void main () {
writeln(RemoveDir);
}

From,
Vino.N


why does this compile fine, but dies when you run it.

2018-03-21 Thread steven kladitis via Digitalmars-d-learn

import std.stdio;

void main(){
int[3] array1 = [ 10, 20, 30 ];
auto array2 = array1; // array2's elements are different
// from array1's
array2[0] = 11;
int[] array3;
//array4[0]=3;
array3[0]=4;
auto array4 = array3;

writeln(array1,'\n',array2,'\n',array3,'\n',array4);
}


-- windows 7 64 bit ( os ) dmd 2.079.0
-- thanks
-- Steven


Re: strip() and formattedRead()

2018-03-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 18:44:12 UTC, realhet wrote:
Compiling this I get an error: "formattedRead: cannot deduce 
arguments from (string, string, float, float, float)"


What compiler version are you using? The newest versions allow 
this code, though the old ones require an intermediate variable 
to satisfy the `ref` requirement on formattedRead (it will want 
to update that variable to advance it past the characters it 
read).


so either update your version, or just give an and use an 
intermediate:


string s = "".strip;
formattedRead(s, )


Re: strip() and formattedRead()

2018-03-21 Thread Ali Çehreli via Digitalmars-d-learn

On 03/21/2018 11:44 AM, realhet wrote:

   float x,y,z;
   if(formattedRead("    vertex -5.1 2.4 3.666".strip, "vertex %f %f 
%f", x, y, z)){

     writefln("v(%f, %f, %f)", x, y, z);
   }


formattedRead wants to modify the source, so it takes it by reference, 
which rvalues cannot be passed for. Make the source an lvalue (i.e. a 
proper variable):


  auto source = "vertex -5.1 2.4 3.666".strip;
  if(formattedRead(source, "vertex %f %f %f", x, y, z)){

Ali


Re: How to use an associative array with array values.

2018-03-21 Thread Jesse Phillips via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 18:31:29 UTC, tipdbmp wrote:

I see. I guess the other would be:

{
int[8192] bar;
int[8192][string] foo;
foo["a"] = bar;
foo["a"][8191] = -1;
}


https://run.dlang.io/is/AK2X2t

Are you looking to use static arrays or dynamic? You can't use 
the new keyword if it static.


strip() and formattedRead()

2018-03-21 Thread realhet via Digitalmars-d-learn

Hi,

I just got this problem and since an hour can't find answer to it.

  float x,y,z;
  if(formattedRead("vertex -5.1 2.4 3.666".strip, "vertex %f 
%f %f", x, y, z)){

writefln("v(%f, %f, %f)", x, y, z);
  }

Compiling this I get an error: "formattedRead: cannot deduce 
arguments from (string, string, float, float, float)"


When I don't use .strip(), just a string literal or a string 
variable it works good.


(It fails also when I'm using UFCS)

What did I do wrong?


Re: #import mapi.h

2018-03-21 Thread nkm1 via Digitalmars-d-learn
On Wednesday, 21 March 2018 at 16:22:45 UTC, Martin Tschierschke 
wrote:
Is there an step by step introduction how to convert a C header 
of an external lib into the right extern(C){} block?


A blog post or tutorial, or chapter in a D book? (I have those 
from Packt Publishing)


(Especially I am trying to get this used with D:
Montetdb C-API 
https://www.monetdb.org/Documentation/Manuals/SQLreference/Programming/MAPI
With: 
https://github.com/snaga/monetdb/blob/master/clients/mapilib/mapi.h)


The page: https://dlang.org/spec/interfaceToC.html is known, 
but not detailed enough for me.


The easiest thing to do is to write a wrapper in C. The wrapper 
will include all necessary headers and provide some easy to use 
functions that you can call from D. Of course, you'll need to use 
a C compiler to compile it.
Anyway, this header looks very straightforwar, no particular 
tricks with the preprocessor. It should be something like this 
(untested, obviously):


import core.stdc.stdio : FILE;

enum
{
MAPI_AUTO  = 0,  /* automatic type detection */
MAPI_TINY  = 1,
MAPI_UTINY = 2,
MAPI_SHORT = 3,
MAPI_USHORT= 4,
MAPI_INT   = 5,
MAPI_UINT  = 6,
MAPI_LONG  = 7,
MAPI_ULONG = 8,
MAPI_LONGLONG  = 9,
MAPI_ULONGLONG = 10,
MAPI_CHAR  = 11,
MAPI_VARCHAR   = 12,
MAPI_FLOAT = 13,
MAPI_DOUBLE= 14,
MAPI_DATE  = 15,
MAPI_TIME  = 16,
MAPI_DATETIME  = 17,
MAPI_NUMERIC   = 18,
}

enum int PLACEHOLDER = '?';

enum
{
MAPI_SEEK_SET = 0,
MAPI_SEEK_CUR = 1,
MAPI_SEEK_END = 2,
}

enum
{
MAPI_TRACE  = 1,
MAPI_TRACE_LANG = 2,
}

alias MapiMsg = int;

enum
{
MOK =  0,
MERROR  = -1,
MTIMEOUT= -2,
MMORE   = -3,
MSERVER = -4,
}

enum
{
LANG_MAL= 0,
LANG_SQL= 2,
LANG_JAQL   = 3,
}

/* prompts for MAPI protocol */
enum int PROMPTBEG = '\001'; /* start prompt bracket */

 /* prompt: ready for new query */
const(char)* PROMPT1 = "\001\001\n".ptr;

/* prompt: more data needed */
const(char)* PROMTP2 = "\001\002\n".ptr;

/*
 * The table field information is extracted from the table headers
 * obtained from the server. This list may be extended in the 
future.

 * The type of both the 'param' and 'binding'
 * variables refer to their underlying C-type. They are used for
 * automatic type coercion between back-end and application.
 */
struct MapiStruct;
alias Mapi = MapiStruct*;

/* this definition is a straight copy from 
sql/include/sql_query.h */

enum
{
Q_PARSE = 0,
Q_TABLE = 1,
Q_UPDATE= 2,
Q_SCHEMA= 3,
Q_TRANS = 4,
Q_PREPARE   = 5,
Q_BLOCK = 6,
}

struct MapiStatement;
alias MapiHdl = MapiStatement*;

alias mapi_uint64 = ulong;
alias mapi_int64 = long;

/* three structures used for communicating date/time information 
*/
/* these structs are deliberately compatible with the ODBC 
versions

   SQL_DATE_STRUCT, SQL_TIME_STRUCT, and SQL_TIMESTAMP_STRUCT */

/* used by MAPI_DATE */
struct MapiDate
{
short year;
ushort month;
ushort day;
}

/* used by MAPI_TIME */
struct MapiTime
{
ushort hour;
ushort minute;
ushort second;
}

/* used by MAPI_DATETIME */
struct MapiDateTime
{
short year;
ushort month;
ushort day;
ushort hour;
ushort minute;
ushort second;
uint fraction;  /* in 1000 millionths of a second (10e-9) */
}

/* connection-oriented functions */
extern (C)
{
Mapi mapi_mapi(const char *host,
   int port,
   const char *username,
   const char *password,
   const char *lang,
   const char *dbname);


// and so on...
}


Re: How to use an associative array with array values.

2018-03-21 Thread tipdbmp via Digitalmars-d-learn

I see. I guess the other would be:

{
int[8192] bar;
int[8192][string] foo;
foo["a"] = bar;
foo["a"][8191] = -1;
}



Re: Template condition evaluation (shortcircuit)

2018-03-21 Thread H. S. Teoh via Digitalmars-d-learn
On Wed, Mar 21, 2018 at 05:42:34PM +, rumbu via Digitalmars-d-learn wrote:
> I tried to define a template:
> 
> enum isFoo(alias T) =
> T.stringof.length >= 3 && T.stringof[0..3] == "abc";
> 
> int i;
> pragma(msg, isFoo!i);
> 
> Error: string slice [0 .. 3] is out of bounds
> Error: template object.__equals cannot deduce function from argument types
> !()(string, string), candidates are:
> [...]
> 
> Is it normal that the condition is not short circuited at first test?
> Of course, I can throw there a bunch of static ifs in an eponymous
> template, but I don't see the point of this verbosity.
[...]

The reason it's not short-circuited is because T.stringof[0..3] is
processed *before* the && is evaluated.  Basically, this:

enum isFoo(alias T) = T.stringof.length >= 3 && T.stringof[0..3] == 
"abc";

is a shorthand for this:

template isFoo(alias T)
{
enum isFoo = T.stringof.length >= 3 && T.stringof[0..3] == 
"abc";
}

T.stringof[0..3] is actually evaluated during AST expansion time,
because it's slicing a template argument list, but && isn't evaluated
until CTFE-time.

See: https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time


Now, arguably, we *could* make it so that && is also shortcircuited at
AST expansion time, i.e., basically lower && in this context into a
series of nested static if's instead of a CTFE expression.  But that
would probably involve some extensive changes in the compiler.


T

-- 
The trouble with TCP jokes is that it's like hearing the same joke over and 
over.


Re: OK, I'm stumped on this one: dstep, struct, mixin, bitfields

2018-03-21 Thread Ali Çehreli via Digitalmars-d-learn

On 03/21/2018 11:00 AM, Russel Winder wrote:
> The code I am playing with generated by DStep involves lots of lots of
> structs with mixin bitfields. All of them seem to compile file, except
> one. How is it that:
>
>  mixin(bitfields!(
>  ubyte, "current_next", 1,
>  ubyte, "version", 5,
>  ubyte, "one2", 2)); /* TS ID */
>
> can result in the following error. The line for "version" is 141 and
> the one for "one2" is 142.

I think it's because 'version' is a D keyword. :)

Ali



Re: OK, I'm stumped on this one: dstep, struct, mixin, bitfields

2018-03-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 18:00:38 UTC, Russel Winder wrote:

ubyte, "version", 5,



version is a D keyword, so I would suggest trying "version_" 
there instead and see if it works. (I'm guessing btw, the error 
message was way to long and illegible, but this is an easy first 
guess anyway)


OK, I'm stumped on this one: dstep, struct, mixin, bitfields

2018-03-21 Thread Russel Winder via Digitalmars-d-learn
The code I am playing with generated by DStep involves lots of lots of
structs with mixin bitfields. All of them seem to compile file, except
one. How is it that:

mixin(bitfields!(
ubyte, "current_next", 1,
ubyte, "version", 5,
ubyte, "one2", 2)); /* TS ID */

can result in the following error. The line for "version" is 141 and
the one for "one2" is 142.

source/libdvbv5_d/header.d-mixin-139(141): Error: no identifier for declarator 
`ubyte`
source/libdvbv5_d/header.d-mixin-139(141): Error: identifier or integer 
expected inside version(...), not `)`
source/libdvbv5_d/header.d-mixin-139(141): Error: found `@` when expecting `)`
source/libdvbv5_d/header.d-mixin-139(141): Error: no identifier for declarator 
`safe`
source/libdvbv5_d/header.d-mixin-139(141): Error: declaration expected, not 
`return`
source/libdvbv5_d/header.d-mixin-139(142): Error: no identifier for declarator 
`void`
source/libdvbv5_d/header.d-mixin-139(142): Error: identifier or integer 
expected inside version(...), not `ubyte`
source/libdvbv5_d/header.d-mixin-139(142): Error: found `v` when expecting `)`
source/libdvbv5_d/header.d-mixin-139(142): Error: declaration expected, not `)`
source/libdvbv5_d/header.d-mixin-139(142): Error: declaration expected, not 
`assert`
source/libdvbv5_d/header.d-mixin-139(142): Error: no identifier for declarator 
`_current_next_version_one2`
source/libdvbv5_d/header.d-mixin-139(142): Error: declaration expected, not `=`
source/libdvbv5_d/header.d(139): Error: incomplete mixin declaration `"private 
ubyte _current_next_version_one2;@property ubyte current_next() @safe pure 
nothrow @nogc const { auto result = (_current_next_version_one2 & 1U) >>0U; 
return cast(ubyte) result;}\x0a@property void current_next(ubyte v) @safe pure 
nothrow @nogc { assert(v >= current_next_min, \"Value is smaller than the 
minimum value of bitfield 'current_next'\"); assert(v <= current_next_max, 
\"Value is greater than the maximum value of bitfield 'current_next'\"); 
_current_next_version_one2 = cast(typeof(_current_next_version_one2)) 
((_current_next_version_one2 & (-1-cast(typeof(_current_next_version_one2))1U)) 
| ((cast(typeof(_current_next_version_one2)) v << 0U) & 1U));}\x0aenum ubyte 
current_next_min = cast(ubyte)0U;  enum ubyte current_next_max = cast(ubyte)1U; 
@property ubyte version() @safe pure nothrow @nogc const { auto result = 
(_current_next_version_one2 & 62U) >>1U; return cast(ubyte) 
result;}\x0a@property void version(ubyte v) @safe pure nothrow @nogc { assert(v 
>= version_min, \"Value is smaller than the minimum value of bitfield 
'version'\"); assert(v <= version_max, \"Value is greater than the maximum 
value of bitfield 'version'\"); _current_next_version_one2 = 
cast(typeof(_current_next_version_one2)) ((_current_next_version_one2 & 
(-1-cast(typeof(_current_next_version_one2))62U)) | 
((cast(typeof(_current_next_version_one2)) v << 1U) & 62U));}\x0aenum ubyte 
version_min = cast(ubyte)0U;  enum ubyte version_max = cast(ubyte)31U; 
@property ubyte one2() @safe pure nothrow @nogc const { auto result = 
(_current_next_version_one2 & 192U) >>6U; return cast(ubyte) 
result;}\x0a@property void one2(ubyte v) @safe pure nothrow @nogc { assert(v >= 
one2_min, \"Value is smaller than the minimum value of bitfield 'one2'\"); 
assert(v <= one2_max, \"Value is greater than the maximum value of bitfield 
'one2'\"); _current_next_version_one2 = 
cast(typeof(_current_next_version_one2)) ((_current_next_version_one2 & 
(-1-cast(typeof(_current_next_version_one2))192U)) | 
((cast(typeof(_current_next_version_one2)) v << 6U) & 192U));}\x0aenum ubyte 
one2_min = cast(ubyte)0U;  enum ubyte one2_max = cast(ubyte)3U; "`


-- 
Russel.
===
Dr Russel Winder  t: +44 20 7585 2200
41 Buckmaster Roadm: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk


signature.asc
Description: This is a digitally signed message part


Template condition evaluation (shortcircuit)

2018-03-21 Thread rumbu via Digitalmars-d-learn

I tried to define a template:

enum isFoo(alias T) =
T.stringof.length >= 3 && T.stringof[0..3] == "abc";

int i;
pragma(msg, isFoo!i);

Error: string slice [0 .. 3] is out of bounds
Error: template object.__equals cannot deduce function from 
argument types !()(string, string), candidates are:

[...]

Is it normal that the condition is not short circuited at first 
test? Of course, I can throw there a bunch of static ifs in an 
eponymous template, but I don't see the point of this verbosity.






Re: #import mapi.h

2018-03-21 Thread Timoses via Digitalmars-d-learn
On Wednesday, 21 March 2018 at 16:22:45 UTC, Martin Tschierschke 
wrote:
Is there an step by step introduction how to convert a C header 
of an external lib into the right extern(C){} block?


A blog post or tutorial, or chapter in a D book? (I have those 
from Packt Publishing)


While googling I found this:
https://dlang.org/blog/2017/12/05/interfacing-d-with-c-getting-started/

Haven't read it yet, but might give you some more insight.

For automatic conversion I stumbled across Dstep which I so far 
like a lot:

https://github.com/jacob-carlborg/dstep


Re: Manipulate slice or specific element of range and return range

2018-03-21 Thread Timoses via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 12:07:49 UTC, Simen Kjærås wrote:

On Wednesday, 21 March 2018 at 11:30:28 UTC, Timoses wrote:
unittest {
assert("my capitalized string".capitalize == 
"myCapitalizedString");

}

auto capitalize(string s) {
import std.regex, std.uni;

return s.replaceAll!(a => a[1].toUpper)(regex(" (.)"));
}


Ty! This definitely put me on the right track regarding strings.


Re: Manipulate slice or specific element of range and return range

2018-03-21 Thread Timoses via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 12:53:56 UTC, Ali Çehreli wrote:


Here is another one that uses ForwardRange.

import std.range; // empty, take, save, chain, popFrontN;
import std.uni; // asLowerCase;
import std.algorithm; // equal, filter;
import std.conv; // text;

auto initialLowerCased(R)(R str, size_t N = 1) {
if (str.empty) {
N = 0;
}
auto frontPart = str.take(N);
auto rest = str.save;
rest.popFrontN(N);

return chain(frontPart.asLowerCase, rest);
}

unittest {
assert(initialLowerCased("My Test String", 4).equal("my 
test String"));

assert(initialLowerCased("").equal(""));
}

auto foo(R)(R str) {
return str.filter!(c => c != ' ').initialLowerCased;
}

void main() {
auto result = foo("My Capital String");
// result above is a range. std.conv.text can make a string:
string lower = result.text;
assert(lower == "myCapitalString");
}

Ali



I like it! I remember having a similar situation another time 
where it was not about strings. I wonder why there is no method 
for this in the standard library that can execute a predicate on 
specific elements of a range..


Re: #import mapi.h

2018-03-21 Thread ketmar via Digitalmars-d-learn

Martin Tschierschke wrote:


or tutorial


ok, tutorial:

1. learn C.
2. learn D.
3. DO IT!

;-)


#import mapi.h

2018-03-21 Thread Martin Tschierschke via Digitalmars-d-learn
Is there an step by step introduction how to convert a C header 
of an external lib into the right extern(C){} block?


A blog post or tutorial, or chapter in a D book? (I have those 
from Packt Publishing)


(Especially I am trying to get this used with D:
Montetdb C-API 
https://www.monetdb.org/Documentation/Manuals/SQLreference/Programming/MAPI
With: 
https://github.com/snaga/monetdb/blob/master/clients/mapilib/mapi.h)


The page: https://dlang.org/spec/interfaceToC.html is known, but 
not detailed enough for me.


Re: Incomprehensible error message

2018-03-21 Thread Russel Winder via Digitalmars-d-learn
On Tue, 2018-03-20 at 14:18 -0700, H. S. Teoh via Digitalmars-d-learn
wrote:
> […]
> 
> Either way, it will require a lot of effort to pull off.
> 

As Rust has shown appreciating that the quality of the error messages
define the quality of the compiler, the quality of the error message
from rustc are now very good indeed.

On the other hand Rust has a lot of paid staff.

-- 
Russel.
===
Dr Russel Winder  t: +44 20 7585 2200
41 Buckmaster Roadm: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk


signature.asc
Description: This is a digitally signed message part


Re: Packages and module import

2018-03-21 Thread Russel Winder via Digitalmars-d-learn
On Tue, 2018-03-20 at 22:08 +0100, Jacob Carlborg via Digitalmars-d-
learn wrote:
> 
[…]
> Not sure if this will help, but are you aware that DStep can add a 
> package to the module declaration using "--package"?

No I wasn't. And it works a treat.

-- 
Russel.
===
Dr Russel Winder  t: +44 20 7585 2200
41 Buckmaster Roadm: +44 7770 465 077
London SW11 1EN, UK   w: www.russel.org.uk


signature.asc
Description: This is a digitally signed message part


Re: How to use an associative array with array values.

2018-03-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 15:53:32 UTC, tipdbmp wrote:

int[10][string] foo;


One option is to initialize like this

---
void main() {
   int[10][string] foo;

   if("a" !in foo)
	foo["a"] = [0,0,0,0,0,0,0,0,0,0]; // set all to zero to create 
the key


   foo["a"][4] = 4;  // now valid to set individual element
}
---


How to use an associative array with array values.

2018-03-21 Thread tipdbmp via Digitalmars-d-learn

 // foo is an associative array/hashtable with
 // key type: string
 // value type: int[10]
 //
int[10][string] foo;

// foo["a"] = new int[10]; // Range violation at runtime

// foo["a"][0] = 1; // Range violation at runtime



Issue with traits usability

2018-03-21 Thread Márcio Martins via Digitalmars-d-learn

Hi!

How do I get past this?


static struct X {
int x;
private enum T = 1;
private alias M = string;
}

foreach (Member; __traits(allMembers, X)) {
	pragma(msg, __traits(getProtection, __traits(getMember, X, 
Member)));

}


Output:

public
private
c.d(1084): Error: argument string has no protection
c.d(1084):while evaluating pragma(msg, 
__traits(getProtection, string))



What I want to achieve essentially is skip all X's aliases and 
templates, but get everything else, like enums and data members. 
How would I go about this in a robust way?

I actually want to skip aliases, and templates.


How Does Language Interpretation Take Place In United Nations?

2018-03-21 Thread Globibo via Digitalmars-d-learn
You may be wondering whether the United Nations employ an 
interpreter for all dialects across the globe. It does not do so 
as the presenters at the UN should make their dose he's in any 
one of its 6 official languages, These official languages are 
Spanish, French, English, Chinese, Arabic, and Russian. The 
interpreters of the United Nations then translate the speech into 
all other 5 official languages. In case a presenter does not use 
any of these 6 languages either because he or she is unaware of 
these languages or to make a political statement, they need to 
also bring an interpreter of their own.




The said interpreter then has to translate the presentation into 
any of the official languages like French or English. The other 
interpreters then translate from that particular translation. 
There is another alternative before the speaker. They are 
permitted to submit a written translation of the speech being 
made by him or her in any official language provided their speech 
do not deviate from the written text.


The UN makes use of simultaneous interpretation that signifies 
that all translations rake place instantly without any break. It 
is contrary to consecutive interpretation where the translator 
and the speaker speak alternately. The interpretation service of 
the United Nations always has 12.interpreters who work in six 
different booths. Each booth is dedicated to one official 
language. Both the interpreters sitting in its English booth 
translate in English while the French booth interpreters 
translate the presentation into French and so on.


www.language-school.hk
www.language-school.sg


Re: Slow start up time of runtime (correction: Windows real-time protection)

2018-03-21 Thread HeiHon via Digitalmars-d-learn

On Tuesday, 20 March 2018 at 16:56:59 UTC, Dennis wrote:

On Tuesday, 20 March 2018 at 12:18:16 UTC, Adam D. Ruppe wrote:

On Tuesday, 20 March 2018 at 09:44:41 UTC, Dennis wrote:
This now leaves the question what's the best way to mitigate 
this, because I would gladly get rid of the second of delay any 
time I invoke dmd, ldc or dub as well as my own applications.


In Windows Security Center Settings (where you can disable 
realtime scan) there is also an entry "Exclusions" (in german 
windows "Ausschlüsse").
I added exclusions for the folder, where I installed dmd and ldc 
and I added an exclusion for the folder, where I compile my D 
programs. Now startup of dmd and freshly compiled programs is 
fast again.




Re: Manipulate slice or specific element of range and return range

2018-03-21 Thread Ali Çehreli via Digitalmars-d-learn

On 03/21/2018 04:30 AM, Timoses wrote:

Hey,

I'm struggling to find a way to achieve this. I've looked through 
std.algorithm but didn't find anything.. Maybe I'm blind.


What I would like to do is filter out all spaces in a string and change 
the front letter to lower case:


     string m = "My Capital String";
     string lower = m
     .filter!(c => c != ' ')
     .!(0, c => c.toLower) // executeAt does not exist
     .array.to!string;
     assert(lower == "myCapitalString");

or sth like

     m.filter!(...)
     .map!((element, int index) {
     if (index == 0)
     return element.toLower;
     else
     break; // stop since we are done manipulating range
     });

Anyway to do this?


Here is another one that uses ForwardRange.

import std.range; // empty, take, save, chain, popFrontN;
import std.uni; // asLowerCase;
import std.algorithm; // equal, filter;
import std.conv; // text;

auto initialLowerCased(R)(R str, size_t N = 1) {
if (str.empty) {
N = 0;
}
auto frontPart = str.take(N);
auto rest = str.save;
rest.popFrontN(N);

return chain(frontPart.asLowerCase, rest);
}

unittest {
assert(initialLowerCased("My Test String", 4).equal("my test String"));
assert(initialLowerCased("").equal(""));
}

auto foo(R)(R str) {
return str.filter!(c => c != ' ').initialLowerCased;
}

void main() {
auto result = foo("My Capital String");
// result above is a range. std.conv.text can make a string:
string lower = result.text;
assert(lower == "myCapitalString");
}

Ali


Re: Static Arrays: Behaviour of Passing & Returning

2018-03-21 Thread Simen Kjærås via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 12:01:01 UTC, Quantum Nerd wrote:
How is it possible that b in main() and r in the function 
occupy the same memory?

I would expect the same behaviour as with c.

Can somebody with more experience shed some light on this?


I'm pretty sure you're seeing NRVO - Named Return Value 
Optimization. Also called copy elision:

https://en.wikipedia.org/wiki/Copy_elision

The compiler sees that when you return r, it's immediately 
assigned to b. Since it's a waste of cycles to allocate twice and 
copy the values, the function is told where the result will end 
up, and writes it there immediately.


The reason you don't see that with c is that the compiler isn't 
very smart, especially not with optimizations turned off, so it 
doesn't know for sure that it can safely overwrite the values 
already in c at that point.


--
  Simen


Re: Manipulate slice or specific element of range and return range

2018-03-21 Thread Simen Kjærås via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 11:30:28 UTC, Timoses wrote:

Hey,

I'm struggling to find a way to achieve this. I've looked 
through std.algorithm but didn't find anything.. Maybe I'm 
blind.


What I would like to do is filter out all spaces in a string 
and change the front letter to lower case:


https://xkcd.com/208/

unittest {
assert("my capitalized string".capitalize == 
"myCapitalizedString");

}

auto capitalize(string s) {
import std.regex, std.uni;

return s.replaceAll!(a => a[1].toUpper)(regex(" (.)"));
}

--
  Simen


Static Arrays: Behaviour of Passing & Returning

2018-03-21 Thread Quantum Nerd via Digitalmars-d-learn

Hello everybody,

I am fairly new to the D language,
and I've been trying to understand the behaviour
of passing arrays to functions, especially also
static arrays.

There is an example that puzzles me:

import std.stdio;

double[3] sqr( double[3] v ) {
  double[3] r;
  writefln( "v (%20s) : %s", typeof(v).stringof, [0] );
  writefln( "r (%20s) : %s", typeof(r).stringof, [0] );
  r[] = v[] * v[];
  return r;
}

void main() {
  double[3] a = [1.0, 2.0, 3.0 ];
  double[3] b = sqr(a);
  writefln( "a (%20s) : %s", typeof(a).stringof, [0] );
  writefln( "b (%20s) : %s", typeof(b).stringof, [0] );

  double[3] c; c = sqr(a);
  writefln( "c (%20s) : %s", typeof(c).stringof, [0] );
}


with the output:
v (   double[3]) : 7FFD0D3874E0
r (   double[3]) : 7FFD0D387548
a (   double[3]) : 7FFD0D387528
b (   double[3]) : 7FFD0D387548
v (   double[3]) : 7FFD0D3874E0
r (   double[3]) : 7FFD0D387588
c (   double[3]) : 7FFD0D387568


According to the documentation, static arrays are of value type.

How is it possible that b in main() and r in the function occupy 
the same memory?

I would expect the same behaviour as with c.

Can somebody with more experience shed some light on this?


Thanks in advance,

qnerd





Manipulate slice or specific element of range and return range

2018-03-21 Thread Timoses via Digitalmars-d-learn

Hey,

I'm struggling to find a way to achieve this. I've looked through 
std.algorithm but didn't find anything.. Maybe I'm blind.


What I would like to do is filter out all spaces in a string and 
change the front letter to lower case:


string m = "My Capital String";
string lower = m
.filter!(c => c != ' ')
.!(0, c => c.toLower) // executeAt does not 
exist

.array.to!string;
assert(lower == "myCapitalString");

or sth like

m.filter!(...)
.map!((element, int index) {
if (index == 0)
return element.toLower;
else
break; // stop since we are done manipulating 
range

});

Anyway to do this?


Re: Is there a way to pipeline program with random-access ranges in C#?

2018-03-21 Thread Kagamin via Digitalmars-d-learn

On Wednesday, 21 March 2018 at 07:40:01 UTC, Dukc wrote:
...except that IEnumerables cannot popBack(), so can only do 
that by doing an additional copy and reversing that. But I 
quess there's no better alternative, short of doing it 
C-style...


A random access range would be represented as IList, backward 
iteration can be just a part of chunking.


Re: Is there a way to pipeline program with random-access ranges in C#?

2018-03-21 Thread Dukc via Digitalmars-d-learn

On Tuesday, 20 March 2018 at 15:57:16 UTC, Kagamin wrote:

On Tuesday, 20 March 2018 at 15:06:14 UTC, Dukc wrote:

Won't quite do it, because that would not iterate backwards.


Linq has no chunking, so you would need to write it, maybe 
similar to SelectMany, but with the opposite meaning.


...except that IEnumerables cannot popBack(), so can only do that 
by doing an additional copy and reversing that. But I quess 
there's no better alternative, short of doing it C-style...




If you want to have index, there's 
https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx


Wow, didn't know that. Thanks, It'll be useful.


Re: recursive template expansion: Why does this not compile?

2018-03-21 Thread ag0aep6g via Digitalmars-d-learn

On 03/21/2018 01:47 AM, Ontonator wrote:

The following code does not compile:

void main() {}

class SuperClass {}

class TemplatedClass(T : SuperClass) {}

class A : SuperClass {
    alias T = TemplatedClass!B;
}

class B : SuperClass {
    alias T = TemplatedClass!C;
}

class C : SuperClass {}


It gives the error:
test.d(12): Error: class `test.TemplatedClass(T : SuperClass)` 
recursive template expansion

test.d(12):    while looking for match for TemplatedClass!(C)


The aliases do not have to be aliases, as long as there is some 
reference to the class (e.g. method and variable declarations also 
work). What exactly is the reason for this error?


Compiler bug. It works when you move the declaration of `B` before the 
one of `A`. Order shouldn't matter there.