I want to transmit the class name and the member name in the method

2018-01-04 Thread Brian via Digitalmars-d-learn

I think code style like:
~~

struct User
{
int id;
string name;
string email;
}

class ORM
{
}

auto db = new ORM;
auto users = 
db.select(User).where(email.like("*@hotmail.com")).limit(10);


foreach(user; users)
{
writeln("user: " + user.name + "\n");
}

~~

this rust code is support it:
https://github.com/diesel-rs/diesel/blob/master/examples/postgres/all_about_updates/src/lib.rs


Re: I want to transmit the class name and the member name in the method

2018-01-05 Thread Brian via Digitalmars-d-learn

On Friday, 5 January 2018 at 12:19:11 UTC, thedeemon wrote:

On Friday, 5 January 2018 at 07:40:14 UTC, Brian wrote:

I think code style like:
db.select(User).where(email.like("*@hotmail.com")).limit(10);


You need to read about templates in D, here's a good guide:
https://github.com/PhilippeSigaud/D-templates-tutorial

Basically you can write a function like
auto select(Class, string fieldName)(Class value) {
 ...

and call it later as
select!(User, "name")(u);

Here User and "name" are compile-time arguments, you can pass 
there types, values and more exotic stuff like other templates.


And inside the function you can use
__traits(getMember, u, fieldName)
to get field by its name from the passed value.
See: https://dlang.org/spec/traits.html


I can try it?:

auto users = 
db.select!(User).where(User.email.like("*@hotmail.com")).limit(10);


Re: I want to transmit the class name and the member name in the method

2018-01-05 Thread Brian via Digitalmars-d-learn

On Friday, 5 January 2018 at 15:38:17 UTC, Binghoo Dang wrote:

On Friday, 5 January 2018 at 07:40:14 UTC, Brian wrote:

I think code style like:
~~

struct User
{
int id;
string name;
string email;
}

class ORM
{
}

auto db = new ORM;
auto users = 
db.select(User).where(email.like("*@hotmail.com")).limit(10);


foreach(user; users)
{
writeln("user: " + user.name + "\n");
}

~~

this rust code is support it:
https://github.com/diesel-rs/diesel/blob/master/examples/postgres/all_about_updates/src/lib.rs


there's entity library exist in D Dub, which is an ORM 
framework, you may read the code for reference:


https://code.dlang.org/packages/entity


Yes, [entity] is my team's project, I want it to be simpler :)


How to use annotation get key name?

2018-03-26 Thread Brian via Digitalmars-d-learn

Rust sample code:

#[cfg(name = "users")]

PHP sample code:

/*
@Table(name = "users")
*/

Java sample code:

@Table(name = "users")

How to use dlang get key name?


Re: How to use annotation get key name?

2018-03-27 Thread Brian via Digitalmars-d-learn

On Monday, 26 March 2018 at 08:50:31 UTC, Simen Kjærås wrote:

On Monday, 26 March 2018 at 08:29:31 UTC, Brian wrote:

Rust sample code:

#[cfg(name = "users")]

PHP sample code:

/*
@Table(name = "users")
*/

Java sample code:

@Table(name = "users")

How to use dlang get key name?


If I understand your question correctly:

struct Table {
string name;
}

struct Foo {
@Table("foo")
int n;
}

unittest {
import std.traits;

string name = getUDAs!(Foo.n, Table)[0].name;
}

--
  Simen


Thanks.
but you don't understand my means, I want have keys with multiple 
indeterminate names.


Rust sample code:

#[cfg(name1 = "users", name2 = "users111")]

PHP sample code:

/*
@Table(name2 = "users", name2 = "users111")
*/

Java sample code:

@Table(name2 = "users111", name1 = "users")

How to use dlang get key name?

Don't have support get key function?

How to do?


Re: Is HibernateD dead?

2018-05-05 Thread Brian via Digitalmars-d-learn

On Thursday, 3 May 2018 at 10:27:47 UTC, Pasqui23 wrote:

Last commit on https://github.com/buggins/hibernated
was almost a year ago

So what is the status of HibernateD?Should I use it if I need 
an ORM? Or would I risk unpatched security risks?


You can use Entity & Database library:

https://github.com/huntlabs/entity
https://github.com/huntlabs/database



I want delete or change class's member name on compile-time

2018-06-08 Thread Brian via Digitalmars-d-learn

Like:

class A
{
string b;
string c;
}

compile-time to:

class A
{
string _b;
string c;
}

or:

class A
{
string c;
}



How to define class type array?

2018-12-15 Thread Brian via Digitalmars-d-learn

Java code:

```java

class A extends Node {}
class B extends Node {}
class C extends Node {}

@Override public Set> getNodes() {
return new HashSet<>(Arrays.asList(
A.class,
B.class,
C.class
));
}

```

For dlang like this?

```D

class A : Node {}
class B : Node {}
class C : Node {}

override public Set!Node getNodes() {
return new HashSet!Node([
typeid(A),
typeid(B),
typeid(C)
]);
}

```



Password Storage

2015-11-26 Thread brian via Digitalmars-d-learn
I'm starting to build a small web-based application where I would 
like to authenticate users, and hence need to store passwords.


After reading this:
http://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
and many other posts that I zombie-surfed to from that page, I'm 
now fearful of doing this badly. :(


My reading of that post was that I should be storing things as:

hash = md5('salty-' + password)

So when a user tries to authenticate, I need to:
1) validate the user id
2) find the unique "salt" I generated for that user when they 
registered
3) pre- or post-pend the salt to the password entered (apparently 
there is a difference??)

4) md5 the lot
5) check this md5(salt+password) against what I have stored.

So for each user, I need to store in my database:
UserName/UserID
Salt
Hashed_Password

Can the developers in the room confirm if this is the correct 
approach?

Are there examples of betters ways of doing this?

Regards
Brian


Re: Password Storage

2015-11-26 Thread brian via Digitalmars-d-learn

On Friday, 27 November 2015 at 00:42:09 UTC, Alex Parrill wrote:

On Friday, 27 November 2015 at 00:17:34 UTC, brian wrote:
I'm starting to build a small web-based application where I 
would like to authenticate users, and hence need to store 
passwords.


After reading this:
http://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
and many other posts that I zombie-surfed to from that page, 
I'm now fearful of doing this badly. :(


My reading of that post was that I should be storing things as:

hash = md5('salty-' + password)

So when a user tries to authenticate, I need to:
1) validate the user id
2) find the unique "salt" I generated for that user when they 
registered
3) pre- or post-pend the salt to the password entered 
(apparently there is a difference??)

4) md5 the lot
5) check this md5(salt+password) against what I have stored.

So for each user, I need to store in my database:
UserName/UserID
Salt
Hashed_Password

Can the developers in the room confirm if this is the correct 
approach?

Are there examples of betters ways of doing this?

Regards
Brian


Do not use MD5 or SHA for hashing passwords. Use PBKDF2, 
bcrypt, or maybe scrypt. There should be C libraries available 
for those algorithms; use them.


More info: 
http://security.stackexchange.com/questions/211/how-to-securely-hash-passwords/31846#31846


Thanks for the blatant faux pas.
I wasn't going to use MD5, I just meant "hash it somehow", which 
was not apparent from my question. My bad.


Algorithm aside, the rest of that approach seems sensible then?

The hash implementation was probably going to be a part 2 of this 
question.
I'd use dcrypt (https://github.com/puzzlehawk/dcrypt) to keep all 
the d-goodness, but according to the author, that's not 
"production ready" yet.
In lieu of that, I'll have a gander at those libraries you 
mentioned.





Re: Password Storage

2015-11-26 Thread brian via Digitalmars-d-learn

On Friday, 27 November 2015 at 02:05:49 UTC, H. S. Teoh wrote:
...
At no time is the password ever sent over the network, 
encrypted or not.


--T
So, I understand what you are trying to say, but I'm stuck on the 
specifics of implementation, if you'll bear with me.


For authentication, the password shouldn't even be sent over 
the wire. Instead, the server (which knows the correct 
password) should send a challenge to the client


So my app is web based, so I don't really have a "client-server" 
model you are suggesting.
I'm building it using Vibe.d with a mongodb backend, so hopefully 
the "client" will be a web-browser (or in future iterations, a 
mobile device - let's ignore that for now).


random number produced by a good RNG -- which is different each 
time the user authenticates)
I'm not sure why I need this, so I'm going to break down and 
example.


Bob comes in with password "Password01"

Once he enters "Password01" I want to:
Add a string to it:
"StaticRandomString~Password01"

Then hash it:
hash("StaticRandomString~Password01")

which gives me
"I#$%am%^&Random(*&LOL*&"

Then to verify Bob is Bob I need to verify 
"I#$%am%^&Random(*&LOL*&" against something in the database?

So in my DB I need to store :
"I#$%am%^&Random(*&LOL*&"

If *this* is the scenario, then the "StaticRandomString" needs to 
be the same all the time, so I need to store that in the DB too, 
no?

So now my DB contains:
"StaticRandomString"
"I#$%am%^&Random(*&LOL*&"

Your solution was to random generate the random string at 
verification time.

If I do that I have:
"RunTimeRandomString~Password01"

Then hash that to get
"I#$%Too$%456^(am(*$&Random(*&LOL*&"

However I can't store that in the DB, because the
"RunTimeRandomString"

which will produce a different hashed value. Sooo, I need to 
change this scenario to:
Get the Password from the client/user and hash it. Then add on 
the randomness:

"RunTimeRandomString~hashed(clientEntered-Password01)"

Get that answer back.
Get the password from the server/database and hash it. Add on the 
same randomness.

"RunTimeRandomString~hashed(actualPassword-Password01)"

Thus in my db I only need to stored
hashed(Password01)

Compare results.
...
Profit.

Am I correct in these descriptions?
Which is better?

I know this is pedantic and not very language specific, but this 
is the crux of what I want to know.
Doing it is easy. The "making sure I'm doing it right" bit is 
hard...


Storing and Searching large text lists

2015-12-31 Thread brian via Digitalmars-d-learn
I have a large list, B, of string items. For each item in that 
large list, I need to see if it is in the smaller list, A.


I have been using a simple string array for the storage of A

string[] A

and then using foreach to go through all the items of B and check 
they are in A


foreach(string;B)
/* this looks hacky but wasn't working without the !=0 bit )
if(find(A,string) != 0)
writeln("Found a line: ", string);

While this works for small datasets, but when either A or B get 
large (A could be up to 150k records, B in the millions) it takes 
quite a while to run.


I'd like to know what is the best way to store lists of text for 
searching? Is there a better container than a simply array? 
Neither A nor B need to be ordered for my purpose, but would 
sorting help the search? Would it help enough to be worth the CPU 
expense?


Regards
B


Getting the body of a HTTP Request

2016-01-27 Thread brian via Digitalmars-d-learn

Hello forumites

I am using vibe to connect to an (internal) API however, an am 
expecting to get back an authorization token with the body of a 
HTTP POST response.


/* start code snippet */
shared static this()
{

requestHTTP("http://mywebsite.website.com/thelogonthing/oauth/authorize/login.do";,

(scope req) {
req.method = HTTPMethod.POST;
req.headers["grant_type"] = "password";
req.headers["response_type"] = "token";
req.headers["client_id"] = "app";
req.headers["scope"] = "read";
req.writeJsonBody(["username":"usern...@blah.com"
, "password":"mySecretPassword"]);
},
(scope res) {
logInfo("Status Code: %s", res.statusCode);
logInfo("Status Phrase: %s", res.statusPhrase);
logInfo("http Version: %s", res.httpVersion);
foreach(k,v; res.headers)
logInfo("Header: %s %s", k, v);

logInfo("Content Type: %s", res.contentType);
logInfo("Body: %s", res.bodyReader());

logInfo("Body to String: %s", 
res.bodyReader.readAllUTF8);

logInfo("Body to String: %s", res.toString());

logInfo("Response Length: %s", res.readJson);
string resJson = null;
}
);
...
/* end code snippet */

However the response I get is empty.
The response I get for the above code is a whole lot of headers 
(excellent) followed by:


/* start log snippet */
...
Header: Connection Keep-Alive
Content Type: text/plain; charset=utf-8
Body: vibe.stream.counting.EndCallbackInputStream
Body to String:
Body to String: HTTP/1.1 302 Found

core.exception.AssertError@..\..\..\..\AppData\Roaming\dub\packages\vibe-d-0.7.2
6\source\vibe\core\log.d(128): (1): Error: JSON string is empty.
Program exited with code 1
/* end log snippet */

I'm a little fuzzy as to how exactly I should be parsing and then 
outputting the body of the response. I've tried a few different 
combinations of trying to loop through and/or convert to string 
whatever is in `res.bodyReader` but honestly, I'm not sure I'm 
doing it right.


Anyone able to shed some light on what the structure of the 
response is, and how I can read/output it all?


Regards
Brian


Re: Getting the body of a HTTP Request

2016-01-27 Thread brian via Digitalmars-d-learn

On Wednesday, 27 January 2016 at 23:50:34 UTC, Chris Wright wrote:

On Wed, 27 Jan 2016 23:42:54 +, brian wrote:
Body: vibe.stream.counting.EndCallbackInputStream Body to 
String: Body to String: HTTP/1.1 302 Found


You got an HTTP redirect as a response. There should be a 
header called Location containing a URL. Redo the request with 
that URL.


Yup there was. However using that URL in place of the original 
just returns the html for a login page in the response.


I wouldn't call myself an expert on all things API related so I'm 
not sure if the error is my side or not. Do API authentications 
usually access the same url as a normal login?


Most HTTP libraries give you an option to automatically follow 
redirects, but vibe.d appears not to.





Creating an array of user-defined structs

2016-08-21 Thread brian via Digitalmars-d-learn

So I have the below program:

import std.stdio;

/* defines my awesome struct */
struct testStruct
{
string aa;
string bb;
}

/* creates(?) an empty array of structs */
testStruct[int] testStructArray;

void main()
{   
string a = "a";
string b = "b";

/*make a new struct */
auto newStruct = new testStruct;
/* populate the values for the struct */
newStruct.aa = a.dup;
newStruct.bb = b.dup;

writeln(newStruct.aa);
/* oddly if I remove the write to "bb" line, the aa line gives an 
error above user access */

writeln(newStruct.bb);

/* this errors, claiming something about a pointer?? */
testStructArray[1] = newStruct;
}

Running this my output says:
Error: cannot implicitly convert expression (newStruct) of type 
testStruct* to testStruct


So I have a couple of questions:
1) I'm assuming by the error that line 23 defines a pointer 
rather than a ... not-pointer thing. I'm not sure why it is doing 
that, and would like some explanation please. :)
2) Is this the best way to do what I am trying to do, which is 
dynamically grow an array of user defined structs?


TIA
Brian


Re: Creating an array of user-defined structs

2016-08-21 Thread brian via Digitalmars-d-learn

Thanks Adam.

Couple of follow up questions, if you don't mind:

On Sunday, 21 August 2016 at 23:37:38 UTC, Adam D. Ruppe wrote:

testStruct[int] testStructArray;
That's not actually an array per se, that is a key/value map 
where the keys are ints.
I understand it's a map, but does my syntax not define an 
Associative Array?? https://dlang.org/spec/hash-map.html
That's kinda what I wanted because I want to be able to look up 
the Structs by the value of int.


Either do a traditional array and copy struct values onto it or 
do an array of pointers and new them. Which option is bsed 
depends on the details of what you're doing.


This was a simple example of what I wanted to illustrate the 
problem. What I probably want for my future program state is some 
sort of hash map, as I'll be using this "array" as a lookup table.

So conceptually something like:

userid | username | structs

0001   | brian| structAboutBrian
0002   | john | structAboutJohn

I probably want to be able to look up info using either userid, 
or username, but I can settle for one of them
I'm creating the entries during execution of the program, so I 
have no idea how big the structure is going to be. So I wanted 
something dynamic.


I'm a bit of a novice in terms of theoretical comp sci, so I'm 
not sure what data structure would be best suited to something 
like that, or how to implement. Happy to take advice. :)


Re: Creating an array of user-defined structs

2016-08-22 Thread brian via Digitalmars-d-learn

On Monday, 22 August 2016 at 06:19:00 UTC, Mike Parker wrote:
Terminology wise, we distinguish between associative arrays 
(AA) and arrays. The former should never simply be called 
'array', otherwise people will assume you are referring to 
either or both of foo[] (dynamic array/slice) or foo[N] (where 
N is an integer constant, a static array). Change your title to 
'Creating an AA of user-defined structs' and the 
misunderstanding goes away.


That's a terribly confusing naming convention for beginners then! 
:P
Is this D-specific terminology, or is this a more general 
convention that AA are not actually arrays?
This might help my understanding of when to use or not use one or 
the other. :)


Simple Function Parameter question...

2016-10-04 Thread brian via Digitalmars-d-learn

Howdy folks

This might be a really stupid question, but ya know, if you don't 
ask ...


So, anytime I am calling a function, I have to include everything 
that the function needs all the time. My simplistic example is:



#!/usr/bin/rdmd
import std.stdio;

void test(string firstinput, string secondinput)
{
   if(secondinput=="world")
   printoutput(firstinput, secondinput);
}

void printoutput(string thisIsJustGreeting, string secondinput)
{
   writeln(thisIsJustGreeting, " ", secondinput);
}

void main()
{
   string greeting = "hello";  // I really don't want to bring 
this through every function

   string thisthing = "world";
   test(greeting, thisthing);
}


For this, I don't really want to keep bringing "greeting" around 
with me. Now, I know if I call `printoutput` from somewhere where 
that variable hasn't been declared it'll go nuts, but at the 
moment my code is ugly because I have to keep carrying variables 
around everywhere ...


But when I have a whole heap of things which are quasi-global I 
don't want to keep having to include the same things over and 
over again, especially functions within functions. For a tedious 
example:


Maybe my program design just needs rethinking (I'm not from a CS 
background, so I struggle with the easy stuff sometimes), but a 
simple/better way of doing this would really help. :)


TIA


Re: Simple Function Parameter question...

2016-10-04 Thread brian via Digitalmars-d-learn

On Tuesday, 4 October 2016 at 13:16:35 UTC, Adam D. Ruppe wrote:
I'd put your repeated variables together in a struct, then pass 
it around to the functions. At least then you pass just one 
param at a time, without losing the info.


That's not a bad idea.
I have been creating "ids" to point to my structs and passing 
that around where needed, but in places it's still getting ugly, 
as they are sometimes more complicated than single vars, but it 
does the trick.
I might just get it to work the ugly way, and try pretty it up 
later. :P


Re: template library like Jinja

2016-12-08 Thread Brian via Digitalmars-d-learn
On Wednesday, 21 November 2012 at 20:56:04 UTC, Masahiro Nakagawa 
wrote:
On Tuesday, 20 November 2012 at 11:38:46 UTC, Tobias Pankrath 
wrote:

Is there any template library like Jinja? (jinja.pocoo.org).

I'm pretty sure we can do even better by leveraging CTFE and a 
precompiler, but speed is no concern for me.


I'm not familiar with Jinja.
So I may not meet your expectation,
but I have the D version of Mustache template engine.

https://github.com/repeatedly/mustache4d
http://mustache.github.com/


Masahiro


jinja2 or twig better to use!


WebCam or Video in D

2017-08-13 Thread brian via Digitalmars-d-learn

Howdy folks.

Has anyone gotten an example of using D as mechanism to read in 
video files, specifically from a webcam?


I don't see any OpenCV libraries, and the example in the DCV 
library that uses FFMPEG, I can't get to work (I've raised an 
issue in Github here https://github.com/libmir/dcv/issues/119 if 
anyone has suggestions).


If anyone has a working example of something that reads in some 
video, that'd be a start for a project I'm looking to undertake.


TIA
Brian


Re: WebCam or Video in D

2017-08-15 Thread brian via Digitalmars-d-learn

On Monday, 14 August 2017 at 13:19:30 UTC, Guillaume Piolat wrote:


It wouldn't be very hard to write a minimal OpenCV loader (for 
example based on DerelictUtil) with only the few functions you 
need in OpenCV.


Do you know of any simple examples that I could try mimic?
I've looked through some of the Derelict code before and it 
doesn't seem exceptionally straight-forward, but maybe I haven't 
spent enough time on it.




Simplest multithreading example

2017-08-31 Thread Brian via Digitalmars-d-learn
Hello, I am trying to get the most trivial example of 
multithreading working, but can't seem to figure it out.
I want to split a task across threads, and wait for all those 
tasks to finish before moving to the next line of code.


The following 2 attempts have failed :

-
Trial 1 :
-

auto I = std.range.iota(0,500);
int [] X; // output
foreach (i; parallel(I) )
X ~= i;
core.thread.thread_joinAll(); // Apparently no applicable here ?
writeln(X); // some random subset of indices


Trial 2 : (closer to Java)

class DerivedThread : Thread
{
int [] X;
int i;
this(int [] X, int i){
this.X = X;
this.i = i;
super(&run);
}

private:
void run(){
X ~= i;
}
}

void main(){
auto I = std.range.iota(0,500);
int [] X; // output
Thread [] threads;
foreach (i; I )
threads ~= new DerivedThread( X,i);
foreach( thread; threads)
thread.start();
foreach( thread; threads)
thread.join(); // does not seem to do anything
core.thread.thread_joinAll(); // also not doing anything

writeln(X); // X contains nothing at all
}

How can I get the program to wait until all threads have finished 
before moving to the next line of code ?


Thank you !



Re: Simplest multithreading example

2017-08-31 Thread Brian via Digitalmars-d-learn

On Friday, 1 September 2017 at 04:43:29 UTC, Ali Çehreli wrote:

On 08/31/2017 06:59 PM, Brian wrote:
> Hello, I am trying to get the most trivial example of
multithreading
> working, but can't seem to figure it out.
> I want to split a task across threads, and wait for all those
tasks to
> finish before moving to the next line of code.
>
> The following 2 attempts have failed :
>
> -
> Trial 1 :
> -
>
> auto I = std.range.iota(0,500);
> int [] X; // output
> foreach (i; parallel(I) )
> X ~= i;
> core.thread.thread_joinAll(); // Apparently no applicable
here ?

As Michael Coulombe said, parallel() does that implicitly.

If the problem is to generate numbers in parallel, I 
restructured the code by letting each thread touch only its 
element of a results array that has already been resized for 
all the results (so that there is no race condition):


import std.stdio;
import std.parallelism;
import std.range;

void main() {
auto arrs = new int[][](totalCPUs);
const perWorker = 10;
foreach (i, arr; parallel(arrs)) {
const beg = cast(int)i * perWorker;
const end = beg + perWorker;
arrs[i] = std.range.iota(beg,end).array;
}

writeln(arrs);
}

If needed, std.algorithm.joiner can be used to make it a single 
sequence of ints:


import std.algorithm;
writeln(arrs.joiner);

Ali


Hello, thank you very much for your quick replies !

I was trying to make a trivial example, but the 'real' problem is 
trying to split a huge calculation to different threads.


Schematically :

double [] hugeCalc(int i){
// Code that takes a long time
}

so if I do


double[][int] _hugeCalcCache;
foreach(i ; I)
   _hugeCalcCache[i] = hugeCalc(i);

of course the required time is I.length * (a long time), so I 
wanted to shorten this by splitting to different threads :


foreach(i ; parallel(I) )
   _hugeCalcCache[i] = hugeCalc(i);

but as you can guess, it doesn't work that easily.

Very interesting approach about letting only the thread touch a 
particular element, I will try that.


FYI I did manage to make the following work, but not sure if this 
is really still multi-threaded ?



int [] I;
foreach (i; 0 .. 500) I ~= i;
int [] X; // output
class DerivedThread : Thread {
private int [] i;
this(int [] i){
this.i = i;
super(&run);
}
private void run(){
synchronized{ // Need synchronization here !
foreach( i0; i)
X ~= i0;
}
}
}
Thread [] threads;
foreach (i; std.range.chunks( I, 50 ) )
threads ~= new DerivedThread( i);
foreach( thread; threads)
thread.start();

	core.thread.thread_joinAll(); // Does in fact seem to 'join all' 
threads

writeln(X);


Re: Simplest multithreading example

2017-09-04 Thread Brian via Digitalmars-d-learn

On Friday, 1 September 2017 at 20:02:23 UTC, ag0aep6g wrote:

On 09/01/2017 07:27 AM, Brian wrote:

double [] hugeCalc(int i){
 // Code that takes a long time
}

so if I do


double[][int] _hugeCalcCache;
foreach(i ; I)
_hugeCalcCache[i] = hugeCalc(i);

of course the required time is I.length * (a long time), so I 
wanted to shorten this by splitting to different threads :


foreach(i ; parallel(I) )
_hugeCalcCache[i] = hugeCalc(i);

but as you can guess, it doesn't work that easily.


Works pretty well for me:


double [] hugeCalc(int i)
{
// Code that takes a long time
import core.thread: Thread;
import std.datetime: seconds;
Thread.sleep(1.seconds);
return [i];
}

void main()
{
static import std.range;
import std.parallelism: parallel;
auto I = std.range.iota(0, 10);
double[][int] _hugeCalcCache;
foreach(i ; parallel(I))
_hugeCalcCache[i] = hugeCalc(i);
}


That runs in about 3 seconds here. The serial version would of 
course take about 10 seconds. So, parallelism achieved!


Though I don't know if it's safe to access an associative array 
concurrently like that. I'd use a normal dynamic array instead 
and initialize it before going parallel:



auto _hugeCalcCache = new double[][](10);



Thanks very much for your help, I finally had time to try your 
suggestions. The initial example you showed does indeed have the 
same problem of not iterating over all values :



double [] hugeCalc(int i){
// Code that takes a long time
import core.thread: Thread;
import std.datetime: seconds;
Thread.sleep(1.seconds);
return [i];
}

static import std.range;
import std.parallelism: parallel;
auto I = std.range.iota(0, 100);
double[][int] _hugeCalcCache;
foreach(i ; parallel(I))
_hugeCalcCache[i] = hugeCalc(i);


 writeln( _hugeCalcCache.keys ); // this is some random 
subset of (0,100)


but this does seem to work using your other method of 
initialization :



auto _hugeCalcCache = new double[][](100);
foreach(i ; parallel(I))
_hugeCalcCache[i] = hugeCalc(i);

foreach( double[] x ; _hugeCalcCache)
writeln( x ); // this now contains all values


so I guess initializing the whole array at compile time makes it 
thread safe ?

(The second case runs in 16 seconds on my computer.)
Anyways it seems to work, thanks again !



OpenXR library bindings etc

2022-09-08 Thread brian via Digitalmars-d-learn
I'd like to use D for some visualisation in XR, but without 
OpenXR, I'm stuck before I even start.


I have tried before to write the library bindings 
(https://github.com/infinityplusb/OpenXR-D), but got stuck and 
honestly don't know enough about what needs doing to fix it.
Apparently it is beyond my capability to do alone, regardless of 
how "easy" library bindings apparently are in D.


Is anyone interested in writing/collaborating on writing a 
library binding to OpenXR, before I resort to C++/C#/Python?





Forbidden file names?

2021-03-14 Thread Brian via Digitalmars-d-learn

Hello --

Apologies if this is answered somewhere in the documentation.
I was trying out the sample code on the dlang.org home page.

When I got to the "Sort an Array at Compile-Time" example, I 
saved it on my machine as sort.d. When I tried to build sort.d, 
the compile failed. But when I renamed sort.d to anything else 
(e.g., array.d), the compilation was fine.


I am wondering if this is expected.

Thanks! Terminal output below explaining the above.

~Brian

/home/brian/d $ cat sort.d
void main()
{
import std.algorithm, std.conv, std.stdio;

"Starting program".writeln;

// Sort a constant declaration at Compile-Time
enum a = [ 3, 1, 2, 4, 0 ];
static immutable b = sort(a);

// Print the result _during_ compilation
pragma(msg, text("Finished compilation: ", b));
}
/home/brian/d $ dmd sort.d
sort.d(9): Error: function expected before `()`, not `module 
sort` of type `void`
sort.d(12):while evaluating `pragma(msg, text(T...)(T 
args) if (T.length > 0)("Finished compilation: ", b))`

/home/brian/d $ mv sort.d array.d
/home/brian/d $ dmd array.d
Finished compilation: immutable(SortedRange!(int[], "a < b", 
SortedRangeOptions.assumeSorted))([0, 1, 2, 3, 4])


Re: Forbidden file names?

2021-03-14 Thread Brian via Digitalmars-d-learn

On Sunday, 14 March 2021 at 20:57:39 UTC, Paul Backus wrote:


This is the error you get when you try to call a function that 
has the same name as the current module. The best way to fix it 
is to rename the module, but if you can't, you can use an alias 
to disambiguate:


alias sort = std.algorithm.sort;


Thanks.


code.dlang.org package search subtly broken?

2021-03-27 Thread Brian via Digitalmars-d-learn

Hello --

When I go to https://code.dlang.org and use the search function 
on the top right corner, it usually works fine. However, there 
was one package I knew I specifically wanted (png-d) but when I 
typed png-d into the search bar, I was greeted with an error 
page, reproduced at the bottom of this message. I get this error 
whenever a hyphen is in the search query. I have not tested other 
special characters for this error.


Thanks!

~Brian

500 - Internal Server Error

Internal Server Error

Internal error information:
vibe.db.mongo.connection.MongoDriverException@../../vibe.d/mongodb/vibe/db/mongo/cursor.d(304):
 Query failed. Does the database exist?

??:? [0x562f5f97e175]
??:? [0x562f5f9a62b6]
??:? [0x562f5f98912d]
/root/ldc2-1.24.0-linux-x86_64/bin/../import/std/exception.d:517 
[0x562f5f3ee1c5]
/root/ldc2-1.24.0-linux-x86_64/bin/../import/std/exception.d:437 
[0x562f5f3e0625]

/mnt/c/Users/soenke/develop/0-dlang/dub-registry/../../vibe.d/mongodb/vibe/db/mongo/cursor.d:304
 [0x562f5f44820d]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/source/app.d:462 
[0x562f5f448cb0]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/source/app.d:322 
[0x562f5f448ad7]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/source/app.d:367 
[0x562f5f470f96]

/mnt/c/Users/soenke/develop/0-dlang/dub-registry/../../vibe.d/mongodb/vibe/db/mongo/cursor.d:233
 [0x562f5f447cfd]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/../../vibe.d/mongodb/vibe/db/mongo/cursor.d:60
 [0x562f5f36ba6d]
/root/ldc2-1.24.0-linux-x86_64/bin/../import/std/algorithm/iteration.d:615 
[0x562f5f470088]
/root/ldc2-1.24.0-linux-x86_64/bin/../import/std/array.d:140 
[0x562f5f366182]

/mnt/c/Users/soenke/develop/0-dlang/dub-registry/source/dubregistry/dbcontroller.d:333
 [0x562f5f31dee0]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/source/dubregistry/registry.d:103
 [0x562f5f2eba03]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/source/dubregistry/web.d:476 
[0x562f5f2eb967]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/../../vibe.d/web/vibe/web/web.d:1043
 [0x562f5f39947a]
/mnt/c/Users/soenke/develop/0-dlang/dub-registry/../../vibe.d/web/vibe/web/web.d:214
 [0x562f5f399083]
router.d:218 [0x562f5f7f0024]
router.d:674 [0x562f5f7f2856]
router.d:607 [0x562f5f7efcf6]
router.d:211 [0x562f5f7efaae]
server.d:2292 [0x562f5f7f80cb]
server.d:253 [0x562f5f7f64fe]
server.d:245 [0x562f5f7f5dbd]
server.d:2048 [0x562f5f80047e]
task.d:712 [0x562f5f8ea4b5]
task.d:730 [0x562f5f8e7091]
task.d:439 [0x562f5f8e67db]
??:? [0x562f5f97f5ba]


Re: code.dlang.org package search subtly broken?

2021-03-27 Thread Brian via Digitalmars-d-learn

On Saturday, 27 March 2021 at 14:53:52 UTC, Imperatorn wrote:
Yeah, the search is broken sadly. I made a PR about it some 
time ago. Partial searches doesn't work


Good to know. Thank you.


Struct assignment fails, why?

2021-06-16 Thread Brian via Digitalmars-d-learn

Hello all --

I have a question about assigning to structs.

I want to be able to create an array of structs that may contain 
different contents depending on user input. I have reduced the 
test case down.


The following fails to compile:

```d
import std.stdio;

struct item
{
string name;
int type;
};

item[] items;

void main(string[] args)
{
item new_item;

for (int i = 0; i < args.length; i++) {
if (args[i] == "item1") {
new_item = { "item1", 1 };
} else if (args[i] == "item2") {
new_item = { "item2", 2 };
} else {
new_item = { "item3", 3 };
}

items ~= new_item;
}

for (int i = 0; i < items.length; i++)
writeln(items[i].name);
}
```

This fails (dmd 2.097) with the following:
```d
struct_bad.d(17): Error: found `}` when expecting `;` following 
statement
struct_bad.d(17): Deprecation: use `{ }` for an empty statement, 
not `;`
struct_bad.d(18): Error: found `else` when expecting `;` 
following statement
struct_bad.d(19): Error: found `}` when expecting `;` following 
statement
struct_bad.d(19): Deprecation: use `{ }` for an empty statement, 
not `;`
struct_bad.d(20): Error: found `else` when expecting `;` 
following statement
struct_bad.d(21): Error: found `}` when expecting `;` following 
statement
struct_bad.d(21): Deprecation: use `{ }` for an empty statement, 
not `;`
struct_bad.d(24): Error: found `items` when expecting `;` 
following statement

struct_bad.d(24): Error: found `~=` instead of statement
struct_bad.d(30): Error: found `End of File` when expecting `}` 
following compound statement
struct_bad.d(30): Error: found `End of File` when expecting `}` 
following compound statement
struct_bad.d(30): Error: found `End of File` when expecting `}` 
following compound statement

```

However, a slight tweak allows the code to compile and work 
correctly.

```d
import std.stdio;

struct item
{
string name;
int type;
};

item[] items;

void main(string[] args)
{
for (int i = 0; i < args.length; i++) {
if (args[i] == "item1") {
item new_item = { "item1", 1 };
items ~= new_item;
} else if (args[i] == "item2") {
item new_item = { "item2", 2 };
items ~= new_item;
} else {
item new_item = { "item3", 3 };
items ~= new_item;
}
}

for (int i = 0; i < items.length; i++)
writeln(items[i].name);
}
```

I guess I am unclear as to why the first fails and the second 
succeeds.


TIA.

~Brian


Re: Struct assignment fails, why?

2021-06-16 Thread Brian via Digitalmars-d-learn

On Wednesday, 16 June 2021 at 20:54:07 UTC, H. S. Teoh wrote:
On Wed, Jun 16, 2021 at 08:44:46PM +, Brian via 
Digitalmars-d-learn wrote: [...]

struct item
{
string name;
int type;
};

[...]

new_item = { "item1", 1 };


The {...} initializer syntax is only available in variable 
declarations, e.g.:


item i = { "item1", 1 };

You cannot use this syntax in assignment statements.

A simple alternative is to use constructor syntax for 
constructing an instance of the struct:


new_item = item("item", 1);


T


Gotcha. Thanks.

~Brian


I want to implement operation feasible?

2014-12-15 Thread Brian via Digitalmars-d-learn


package com.kerisy.mod.base

interface BaseMod
{
auto getInstance();
}

package com.kerisy.mod.a

class A : BaseMod
{
A getInstance()
{
return (new A);
}

void hello()
{
// in A
writeln("in A");
}
}

package com.kerisy.mod.b

class B : BaseMod
{
B getInstance()
{
return (new B);
}

void hello()
{
// in B
writeln("in B");
}
}

import std.stdio;
import com.kerisy.mod.a;
import com.kerisy.mod.b;

int main(string[] argv)
{
string packageClass;

packageClass packageClass = "mod.forum.controller.forum.A";
BaseMod modObje = cast(BaseMod)Object.factory(packageClass);
auto a = modObj::getInstance();
Object.callMethod(a, "hello");

packageClass packageClass = "mod.forum.controller.forum.A";
BaseMod modObje = cast(BaseMod)Object.factory(packageClass);
auto a = modObj::getInstance();
Object.callMethod(a, "hello");

return 0;
}