Re: How to use the Among method with a string array
On Saturday, 16 September 2017 at 12:09:28 UTC, Adam D. Ruppe wrote: On Saturday, 16 September 2017 at 11:18:45 UTC, Andrew Chapman wrote: string[] fruit = ["apple", "pear", "strawberry"]; How do I use "among" to see if "apple" is present. E.g. I want to do this: if ("apple".among(fruit)) among doesn't take an array, but rather a list of arguments: "bar".among("foo", "bar", "baz") For searching in an array, you can use canFind: if(fruit.canFind("apple")) Thanks Adam!
How to use the Among method with a string array
Hi all, sorry for the very simple question, but I'm looking at the "among" function in std.comparison: https://dlang.org/phobos/std_algorithm_comparison.html#among If I have a string array: string[] fruit = ["apple", "pear", "strawberry"]; How do I use "among" to see if "apple" is present. E.g. I want to do this: if ("apple".among(fruit)) However that wont compile - I'm missing something fundamental in my knowledge. It seems fruit has to be a Tuple? Is there a way to use a string array instead?
Re: Web servers in D
On Friday, 25 August 2017 at 05:25:09 UTC, Hasen Judy wrote: What libraries are people using to run webservers other than vibe.d? Don't get me wrong I like the async-io aspect of vibe.d but I don't like the weird template language and the fact that it caters to mongo crowd. I think for D to a have good web story it needs to appeal to serious backend developers, not hipsters who go after fads (mongodb is a fad, jade/haml is a fad). I probably need to combine several libraries, but the features I'm looking for are: - Spawn an HTTP server listening on a port, and routing requests to functions/delegates, without hiding the details of the http request/response objects (headers, cookies, etc). - Support for websockets - Runs delegates in fibers/coroutines - Basic database connectivity (No "orm" needed; just raw sql). - When iterating the result set of a sql query, has the ability to automatically map each row against a struct, and throw if the structure does not match. - More generally, map any arbitrary object (such as json) to a struct. Something like Zewo/Reflection package for swift[0]. [0]: https://github.com/Zewo/Reflection I feel like Vibe.d satisfies my first 3 requirements, but for the rest I will probably have to look for something else. Don't get me wrong I like the async-io aspect of vibe.d but I don't like the weird template language and the fact that it caters to mongo crowd. Don't use these components :-) - Spawn an HTTP server listening on a port, and routing requests to functions/delegates, without hiding the details of the http request/response objects (headers, cookies, etc). Vibe.d does this - just don't use the automatic API generation feature if you don't like it. Note, you can get access to the request/response objects even if you do use the API generation by using an @before method. E.g. in an interface you may have something like this: @method(HTTPMethod.POST) @before!getRequestInfo("requestInfo") @property Token login(LoginRequestMeta login, RequestInfo requestInfo); And then define your getRequestInfo method like this: static RequestInfo getRequestInfo(HTTPServerRequest req, HTTPServerResponse res) { RequestInfo requestInfo; requestInfo.headers = req.headers; requestInfo.ipAddress = req.clientAddress.toAddressString(); requestInfo.userAgent = requestInfo.headers.get("User-Agent", ""); return requestInfo; } In this case I've grabbed the ip address and user agent of the user, but you could also grab cookies etc. - When iterating the result set of a sql query, has the ability to automatically map each row against a struct, and throw if the structure does not match. You can do this with MySQL Native whilst using vibe.d. You might do something like this: Prepared prepared = prepare(this.conn, sql); prepared.setArgs(params); auto row = prepared.queryRow(); if (row.isNull()) { throw new Exception("Query returned an empty row"); } T item; try { row.toStruct!T(item); } catch(Exception e) { } Where T is your struct type that you're trying to convert the row to. As for the template language, you could try: http://code.dlang.org/packages/diamond https://github.com/repeatedly/mustache-d There are probably others.
Re: Confusion over enforce and assert - both are compiled out in release mode
On Sunday, 27 August 2017 at 10:37:50 UTC, Moritz Maxeiner wrote: On Sunday, 27 August 2017 at 10:17:47 UTC, Andrew Chapman wrote: On Sunday, 27 August 2017 at 10:08:15 UTC, ag0aep6g wrote: [...] Thanks, that explains it. I think it's a bit of a shame that the "in" blocks can't be used in release mode as the clarity they provide for precondition logic is wonderful. If you need that, you could compile using ldc in release mode (which you probably want to do anyway): --- test.d --- import std.exception; import std.stdio; void foo(int x) in { enforce(x > 0); } body { } void bar(int x) in { assert(x > 0); } body { } void baz(int x) in { if (!(x > 0)) assert(0); } body { } void main() { (-1).foo.assertThrown; (-1).bar; (-1).baz; } -- $ ldc2 test.d -> failed assert in bar's in contract terminates the program $ ldc2 -release test.d -> failed assertThrown in main terminates the program $ ldc2 -release -enable-contracts test.d -> failed assert in baz's in contract terminates the program $ ldc2 -release -enable-contracts -enable-asserts test.d -> failed assert in bar's in contract terminates the program Oh interesting. Does DUB support passing through the --enable-contracts flag to ldc? Also, if this is an ldc specific thing it's probably not a good idea i'd imagine, since in the future one may want to use a GDC, or DMD?
Re: Confusion over enforce and assert - both are compiled out in release mode
On Sunday, 27 August 2017 at 10:08:15 UTC, ag0aep6g wrote: On 08/27/2017 12:02 PM, Andrew Chapman wrote: However, I am finding that BOTH enforce and assert are compiled out by dmd and ldc in release mode. Is there a standard way of doing what enforce does inside an "in" contract block that will work in release mode? I'm guessing I should write my own function for now. The whole `in` block is ignored in release mode. Doesn't matter what you put in there. Nothing of it will be compiled. Thanks, that explains it. I think it's a bit of a shame that the "in" blocks can't be used in release mode as the clarity they provide for precondition logic is wonderful.
Confusion over enforce and assert - both are compiled out in release mode
In the docs regarding contract programming and the use of enforce / assert: https://dlang.org/library/std/exception/enforce.html it says: "enforce is used to throw exceptions and is therefore intended to aid in error handling. It is not intended for verifying the logic of your program. That is what assert is for. Also, do not use enforce inside of contracts (i.e. inside of in and out blocks and invariants), because they will be compiled out when compiling with -release. Use assert in contracts." However, I am finding that BOTH enforce and assert are compiled out by dmd and ldc in release mode. Is there a standard way of doing what enforce does inside an "in" contract block that will work in release mode? I'm guessing I should write my own function for now.
Re: How to store data when using parallel processing
On Sunday, 27 August 2017 at 01:58:04 UTC, Jonathan M Davis wrote: [...] Thanks Jonathan, that makes sense. As it turns out, the Mutex approach actually makes things slower. In this case I believe trying to use multiple cores isn't worth it. Cheers.
How to store data when using parallel processing
Hi all, just wanting some advice on parallel processing and specifically how to deal with access violations. I am reading a list of words from a file like this: auto fileHandle = File("wordlist.txt", "r"); string word; string[] words; string[ulong] hashMap; while ((word = fileHandle.readln()) !is null) { words ~= word; } Then I'm doing some processing on the words. I want to make this run as quickly as possible so I am doing the processing across the cores of my CPU like this: foreach (thisWord; parallel(words)) { string wordLower = thisWord.strip().toLower(); ulong key = keyMaker.createKeyForWord(wordLower); // hashMap[key] = wordLower; } The question is, in the above loop, how can I make the commented out line work without having an access violation. Do I need to use a different data structure? Or rethink what I'm doing? Thanks in advance. Andrew.
Re: Using templates with interfaces
On Sunday, 25 June 2017 at 17:30:58 UTC, Petar Kirov [ZombineDev] wrote: On Sunday, 25 June 2017 at 13:32:57 UTC, Andrew Chapman wrote: I think you've answered the question with "You cannot have unimplemented templates in interfaces". Thanks for the answer. I'll rethink the way I'm doing this. Cheers. In your case you can probably use something along the lines of: interface RelationalDBInterface { // You can even make this protected Varaint loadUntypedRow(string sql, Variant[] params); final T loadRow(T)(string sql, Variant[] params) { auto row = loadUntypedRow(sql, params); enforce(row.hasValue, this.classID ~ "::loadRow - Query returned an empty row"); return row.toStruct!T; } } Amazing, thank you!
Re: Using templates with interfaces
I think you've answered the question with "You cannot have unimplemented templates in interfaces". Thanks for the answer. I'll rethink the way I'm doing this. Cheers.
Re: Using templates with interfaces
On Sunday, 25 June 2017 at 13:04:32 UTC, Nicholas Wilson wrote: On Sunday, 25 June 2017 at 11:39:27 UTC, Andrew Chapman wrote: Hi guys, I'm a little confused as to whether D supports interfaces with templates. I can compile OK, but linking reports an error like this: Error 42: Symbol Undefined _D12relationaldb10interfaces21RÇëÜDBIÇêÿ35__T7loadRowTS6prefix÷6P¶ZÇêáMFAyaAS3std7variant18Çâ└8VÇåìNVki20ZÇëÅZÇûð Essentially my desired interface looks like this: interface RelationalDBInterface { public T loadRow(T)(string sql, Variant[] params); } An example implementation: public T loadRow(T)(string sql, Variant[] params) { Prepared prepared = prepare(this.conn, sql); prepared.setArgs(params); auto row = prepared.queryRow(); if (row.isNull()) { throw new Exception(this.classID ~ "::loadRow - Query returned an empty row"); } T item; return row.toStruct!T(item); } And I would try to call it like this: auto user = this.loadRow!User(sql, params); Is it possible, or do I need to rethink the solution? The idea is to pass around a RelationalDBInterface so I can later switch from MySQL to Postgres or SQLite or whatever. You cannot have unimplemented templates in interfaces (where would they go in the virtual function table?), just return a variant. Implementations of interfaces must be classes not free functions so class MyDB : IRelationalDB { // implementation ... } which you then need to create a instance of auto mydb = MyDB(...); // connection auto user = mydb.loadRow!User(sql, params); 'this' is only valid inside an aggregate (struct or class). Sorry I wasn't very clear. My "this" was infact inside a class. Here's a more complete example of attempting to use the intertace: class MySQLRelationalDB : RelationalDBInterface { private Connection conn; private const string classID = "MySQLRelationalDB"; this(Connection conn) { this.conn = conn; } public T loadRow(T)(string sql, Variant[] params) { Prepared prepared = prepare(this.conn, sql); prepared.setArgs(params); auto row = prepared.queryRow(); if (row.isNull()) { throw new Exception(this.classID ~ "::loadRow - Query returned an empty row"); } T item; row.toStruct!T(item); return item; } } Then I use it within another class like this: class UserQuery { protected RelationalDBInterface relationalDb; this(RelationalDBInterface relationalDb) { this.relationalDb = relationalDb; } public User getUser(string emailAddress) { string sql = " SELECT * FROM usr WHERE email = ? "; auto user = this.relationalDb.loadRow!User( sql, variantArray(emailAddress) ); } } It compiles, but it wont link. Is it the case that you can't use templates with interfaces?
Using templates with interfaces
Hi guys, I'm a little confused as to whether D supports interfaces with templates. I can compile OK, but linking reports an error like this: Error 42: Symbol Undefined _D12relationaldb10interfaces21RÇëÜDBIÇêÿ35__T7loadRowTS6prefix÷6P¶ZÇêáMFAyaAS3std7variant18Çâ└8VÇåìNVki20ZÇëÅZÇûð Essentially my desired interface looks like this: interface RelationalDBInterface { public T loadRow(T)(string sql, Variant[] params); } An example implementation: public T loadRow(T)(string sql, Variant[] params) { Prepared prepared = prepare(this.conn, sql); prepared.setArgs(params); auto row = prepared.queryRow(); if (row.isNull()) { throw new Exception(this.classID ~ "::loadRow - Query returned an empty row"); } T item; return row.toStruct!T(item); } And I would try to call it like this: auto user = this.loadRow!User(sql, params); Is it possible, or do I need to rethink the solution? The idea is to pass around a RelationalDBInterface so I can later switch from MySQL to Postgres or SQLite or whatever.
Re: Get the address of an object, within the object itself
On Wednesday, 15 February 2017 at 21:37:12 UTC, Jonathan M Davis wrote: On Wednesday, February 15, 2017 13:33:23 Jonathan M Davis via Digitalmars-d- learn wrote: On Wednesday, February 15, 2017 21:27:00 Andrew Chapman via Digitalmars-d- learn wrote: > Hi all, sorry if this question is silly, but is it possible > to get the address of an object within the object itself? > > e.g. > > class Node > { > > this() > { > > writeln(); // Doesn't work > > } > > } > > auto node = new Node(); > writeln(); // Does work This does _not_ give you the address of the Node object. It gives you the address of the reference. IIRC, the only way to get the address of the object itself would be to cast it to void*, but it's not something that I do normally, so I'd have to experiment a bit to be sure. - Jonathan M Davis Thanks Jonathan. Good point about the reference address. I can work around this quite easily, but I was curious. I will try the void* cast and see what happens. Cheers.
Get the address of an object, within the object itself
Hi all, sorry if this question is silly, but is it possible to get the address of an object within the object itself? e.g. class Node { this() { writeln(); // Doesn't work } } auto node = new Node(); writeln(); // Does work Thanks very much, Cheers, Andrew.
Re: How to use a char[] buffer in D
Perfect, thank you! :-) Works like a charm. On Wednesday, 22 June 2016 at 22:41:24 UTC, H. S. Teoh wrote: On Wed, Jun 22, 2016 at 09:57:04PM +, Andrew Chapman via Digitalmars-d-learn wrote: Maybe try: if (buffer[] in myHash) { ... } ? Does that make a difference? T
How to use a char[] buffer in D
Hi everyone, just wanting some help with optimisation if anyone is kind enough :-) I have a loop that iterates potentially millions of times, and inside that loop I have code that appends some strings together, e.g.: string key = s1 ~ "_" ~ s2; I discovered that due to the memory allocation required, this slows the execution significantly. s1 is always a two character string, e.g "AA", and s2 is always a single character. What I want to do is something like this: Outside the loop: char[4] buffer; buffer[2] = '_'; Then inside the loop buffer[0] = s1[0]; buffer[1] = s1[1]; buffer[3] = s2[0]; This works OK, however, I then need to use the buffer value to check for an existing value in a hashmap / associative array. Code such as: if(buffer in myHash) { } throws an access violation. A string value works without error. Is there a way for me to use a buffer AND use it in functions expecting strings? I can use idup() on the char[] to make a string, but again we're allocating memory which I'd rather avoid. Thanks sincerely in advance, Cheers, Andrew.
Re: Dynamically setting struct values from hash map
On Thursday, 12 May 2016 at 21:01:06 UTC, Adam D. Ruppe wrote: foreach(member; __traits(allMembers, YourStruct)) if(member in yourhash) __traits(getMember, your_object, member) = to!right_type(yourhash[member]); basically, it is a bit more complex to filter out inappropriate fields and such, but that's the idea. Check out the sample chapter of my book https://www.packtpub.com/application-development/d-cookbook to see more, you can get the reflection chapter free on that site. That's wonderful Adam, thank you! I actually had your book previously bookmarked - I should probably buy it :-)
Dynamically setting struct values from hash map
Hi guys, apologies for the silly question, but I come from the world of dynamic languages and I'm wondering if it's possible to set struct values basic on dynamic variables? e.g. struct Person { string firstName; string lastName; } void main() { string[string] map; map["firstName"] = "Homer"; map["lastName"] = "Simpson"; } Is it possible to iterate through the hash map and set the struct values using the key/value pairs? Something like this: e.g. Person p1; foreach(key,val; map) { p1[key] = val; } The problem I'm trying to solve is that I'm wanting to write a generic "model" class that can read a record from a database and populate a known struct from the database values. I have seen the "allMembers" method from the traits module that can give me the names of the struct fields, but I am unsure if it's even possible to set the struct values using variable/dynamic names. Any help will be greatly appreciated! Cheers, Andrew.
Re: Most performant way of converting int to string
On Wednesday, 23 December 2015 at 11:46:37 UTC, Jakob Ovrum wrote: On Wednesday, 23 December 2015 at 11:21:32 UTC, Jakob Ovrum wrote: Dynamic memory allocation is expensive. If the string is short-lived, allocate it on the stack: See also std.conv.toChars[1] for stringifying lazily/on-demand. http://dlang.org/phobos/std_conv#toChars Thanks Jakob! I did try toChars but I couldn't quite figure out a syntax of calling it that the compiler was happy with. From memory I tried things along the lines of: string v = toChars!(16,char,LetterCase.lower)(i); to convert an integer to Hex for example, but the compiler wasn't happy with it. How would I convert an int to a string using this? Cheers.
Re: Most performant way of converting int to string
On Tuesday, 22 December 2015 at 18:11:24 UTC, rumbu wrote: On Tuesday, 22 December 2015 at 17:15:27 UTC, Andrew Chapman wrote: Sorry if this is a silly question but is the to! method from the conv library the most efficient way of converting an integer value to a string? e.g. string s = to!string(100); I'm seeing a pretty dramatic slow down in my code when I use a conversion like this (when looped over 10 million iterations for benchmarking). Cheers! Converting numbers to string involves the most expensive known two operations : division and modulus by 10. Cool thanks, so essentially it's unavoidable - I have a background in PHP programming where we don't really get exposed to memory allocation, conversions etc. Good to learn. Cheers.
Re: Most performant way of converting int to string
On Tuesday, 22 December 2015 at 17:43:00 UTC, H. S. Teoh wrote: I wonder if the slowdown is caused by GC collection cycles (because calling to!string will allocate, and here you're making a very large number of small allocations, which is known to cause GC performance issues). Try inserting this before the loop: import core.memory; GC.disable(); Does this make a difference in the running time? T Thanks! Unfortunately that actually makes it run slightly slower :-)
Most performant way of converting int to string
Sorry if this is a silly question but is the to! method from the conv library the most efficient way of converting an integer value to a string? e.g. string s = to!string(100); I'm seeing a pretty dramatic slow down in my code when I use a conversion like this (when looped over 10 million iterations for benchmarking). Cheers!
Re: Most performant way of converting int to string
On Tuesday, 22 December 2015 at 17:18:16 UTC, cym13 wrote: On Tuesday, 22 December 2015 at 17:15:27 UTC, Andrew Chapman wrote: Sorry if this is a silly question but is the to! method from the conv library the most efficient way of converting an integer value to a string? e.g. string s = to!string(100); I'm seeing a pretty dramatic slow down in my code when I use a conversion like this (when looped over 10 million iterations for benchmarking). Cheers! Out of curiosity a slow down compared to what? No conversion at all? Yeah, if I include a simple conversion in my loop: for({int i; i = 0;} i < num; i++) { //string s = to!string(i); Customer c = Customer(i, "Customer", "", i * 2); string result = objS.serialize(c); } If I uncomment the "string s" line I'm seeing a 20% increase in running time, which given what's going on the rest of the code is quite surprising. I've tried compiling with both dmd and ldc2 - it's the same under both. Cheers.