Re: ElementType!string

2013-08-26 Thread monarch_dodra

On Sunday, 25 August 2013 at 19:51:50 UTC, qznc wrote:

Thanks, somewhat unintuitive.


Yes, but un-intuitive... to the un-initiated. By default, it's 
also safer. A string *is* conceptually, a sequence of unicode 
codepoints. The fact that it is made of UTF-8 codepoints is 
really just low level implementation detail.


Thanks to this behavior, things like:
string s = 日本語
//search for '本';
for ( ; s.front != '本' ; s.popFront())
{}

Well, they *just work* (TM).

Now... If you *know* what you are doing, then by all means, 
iterate on the UTF8 code units. But be warned, you must really 
know what you are doing.


Back to your original subject, you can use:
ElementEncodingType!S

ElementEncodingType works just like ElementType, but for strings, 
*really* takes the array's element's type. This is usually *not* 
the default you want.


Also related, foreach naturally iterates on codeunits by default 
(for some weird reason). I recommend to try to iterate on dchars.


Limited Semi-PolyMorphic (LSP) structs?

2013-08-26 Thread Era Scarecrow
 Been a while and out of the loop, I need to get my hands dirty 
in the code again (soon). Anyways, let's get to the matter at 
hand as I'm thinking about it. I'm working on some code (or will 
work on code again) that could use a polymorphic type, but at the 
end it will never be shared externally and can never extend 
beyond 'Known' types. (and the 'types' are behavior 95% of the 
time)



 True polymorphism will let me compile a code to work with say 
'Object' and you can plug in any code and pass it an object and 
it will be happy, or inherit and work with it. These are great as 
classes. But I want to throw a wrench in the gears, I want to use 
structs.



 I know you're asking, Why? Well the data structure I'll be 
working with have records in the hundreds of thousands, but most 
of the time looking at/sorting them I don't necessarily need to 
allocate memory (or really even interact with them beyond 
sorting). Most of the time the OO aspect is just behavior and the 
data between them never changes (behave this way because you're a 
type XXX). It can take a very long time to unpack everything 
(when you never needed to unpack in the first place, or allocate 
and then de-allocate immediately, probably without recycling).



 Alright, structs can't inherit because they don't have an object 
pointer to go to their parent structures that they are connected 
to. If we eliminate the pointer and the overhead on some of that, 
we bring it down to the following:


 To be fully polymorphic you need to:
 * Be able to tell what type it is (Probably enum identifier)
 * Extended types cannot be larger than the base/original (or the 
base has to hold extra data in reserve for it's other types).



 When can this LSP be applicable?
 * When a type can be changed on the fly with no side effects 
other than intended (This 'text' struct is now 'left aligned text 
object')
 * When allocations/pointers aren't needed (why fully build the 
object at all?)
 * When it won't be extended beyond the current type... (only a 
few fixed subtypes)
 * When teardown/deallocation/~this() isn't needed (never 
allocates? Never deallocates! Just throw it all away! POD's are 
perfect!)
 * When you have no extra 'data' to append to a class/struct and 
only override methods/behavior (Encryption type switch from DES 
to BlowFish! Same API/methods, otherwise nothing really changed)
 * When you need a half step up from structs but don't need full 
classes/objects


 Limitations: Hmmm..
 * LSP's cannot be a template or mixin (they can call on them)
 * Known at compile-time
 * Only one of them can handle setup/teardown.


 Now, I wonder. What if we make it so it CAN inherit? We need 3 
examples, where something is in A, AB, and B. We will get to 
that. iA and iB are the class/structs and A/B/C are the 
methods/functions. So...


//original based on...
class iA {
  void A();
  void C();
}
class iB : iA {
  void A();
  void B();
}

 Breaking them down for structs we have:

struct base_AB { //the 'manager' that does redirection and known 
size

  char type = 'A'; //polymorphic type identifier, for simplicity
  //shared 'parent' baggage ie - iA
  //baggage space for iB

  //Exists in both iA  iB
  void A() {
switch(type) {
  case 'A': (cast(iA) this).A(); break;
  case 'B': (cast(iB) this).B(); break;
  default: throw new Exception(method A() invalid for struct 
type: ~ type);

}
  }

  //B only exists in inherited
  void B() {
if (type == 'B') (cast(iB) this).B();
else throw new Exception();
  }

  //C exists everywhere
  void C() { (cast(iA) this).C(); }
}


 So far the base is easy to make, now however as for how iA and 
iB interact with eachother... Ignoring infinite loops problems:


struct iA {
  char type;
  //baggage - Size must be identical to base_AB

  void A() {
A();
//B(); /*iA doesn't really know about B so can't call it from 
here... not safely anyways*/

C();
  };
}

  Now, C() can be called regardless of the type (no checks 
needed). iB.B() can also be called anywhere in iB with no 
problems, but it would be simpler if all calls regardless went to 
the base and let the base handle it. (Optimizations would 
probably remove unneeded checks later).


struct iB {
  char type;  //and other baggage

  void A() {
A(); // actually: (cast(base_AB) this).A();
B(); // actually: (cast(base_AB) this).B();
C(); // actually: (cast(base_AB) this).C();
  }
  void B() {
//ditto as A()'s
  }
}


 This can probably be easily done having a different naming set 
which handles the redirection, but the names and boiler-plate 
seems unnecessarily large and verbose for a simple task; 
Optimization will likely remove the excess unneeded portions in 
final binary form anyways.


//different name examples:
 struct base_AB {
  char type;  //and other baggage

  void A() {
switch(type) {
  case 'A': (cast(iA) this).realA(); break;
  case 'B': (cast(iB) this).realB(); break;
  default: throw 

Re: Limited Semi-PolyMorphic (LSP) structs?

2013-08-26 Thread qznc

On Monday, 26 August 2013 at 11:20:17 UTC, Era Scarecrow wrote:
 Been a while and out of the loop, I need to get my hands dirty 
in the code again (soon). Anyways, let's get to the matter at 
hand as I'm thinking about it. I'm working on some code (or 
will work on code again) that could use a polymorphic type, but 
at the end it will never be shared externally and can never 
extend beyond 'Known' types. (and the 'types' are behavior 95% 
of the time)



 True polymorphism will let me compile a code to work with say 
'Object' and you can plug in any code and pass it an object and 
it will be happy, or inherit and work with it. These are great 
as classes. But I want to throw a wrench in the gears, I want 
to use structs.



 I know you're asking, Why? Well the data structure I'll be 
working with have records in the hundreds of thousands, but 
most of the time looking at/sorting them I don't necessarily 
need to allocate memory (or really even interact with them 
beyond sorting). Most of the time the OO aspect is just 
behavior and the data between them never changes (behave this 
way because you're a type XXX). It can take a very long time to 
unpack everything (when you never needed to unpack in the first 
place, or allocate and then de-allocate immediately, probably 
without recycling).



 Alright, structs can't inherit because they don't have an 
object pointer to go to their parent structures that they are 
connected to. If we eliminate the pointer and the overhead on 
some of that, we bring it down to the following:


 To be fully polymorphic you need to:
 * Be able to tell what type it is (Probably enum identifier)
 * Extended types cannot be larger than the base/original (or 
the base has to hold extra data in reserve for it's other 
types).



 When can this LSP be applicable?
 * When a type can be changed on the fly with no side effects 
other than intended (This 'text' struct is now 'left aligned 
text object')
 * When allocations/pointers aren't needed (why fully build the 
object at all?)
 * When it won't be extended beyond the current type... (only a 
few fixed subtypes)
 * When teardown/deallocation/~this() isn't needed (never 
allocates? Never deallocates! Just throw it all away! POD's are 
perfect!)
 * When you have no extra 'data' to append to a class/struct 
and only override methods/behavior (Encryption type switch from 
DES to BlowFish! Same API/methods, otherwise nothing really 
changed)
 * When you need a half step up from structs but don't need 
full classes/objects


 Limitations: Hmmm..
 * LSP's cannot be a template or mixin (they can call on them)
 * Known at compile-time
 * Only one of them can handle setup/teardown.


 Now, I wonder. What if we make it so it CAN inherit? We need 3 
examples, where something is in A, AB, and B. We will get to 
that. iA and iB are the class/structs and A/B/C are the 
methods/functions. So...


//original based on...
class iA {
  void A();
  void C();
}
class iB : iA {
  void A();
  void B();
}


Hm, my try would be alias this for inheritance and function 
pointers for virtual methods.


struct iA {
  void function(iA) A;
  void C();
}

struct iB {
  iA _a;
  alias this = _a;
  void B();
}

If you have multiple subclasses for iA, you can use a 
tagged-union from std.variant.


Re: Limited Semi-PolyMorphic (LSP) structs?

2013-08-26 Thread Era Scarecrow

On Monday, 26 August 2013 at 12:42:43 UTC, qznc wrote:
Hm, my try would be alias this for inheritance and function 
pointers for virtual methods.


struct iA {
  void function(iA) A;
  void C();
}

struct iB {
  iA _a;
  alias this = _a;
  void B();
}

If you have multiple subclasses for iA, you can use a 
tagged-union from std.variant.



 Hmmm. I haven't considered std.variant, and glancing at it 
(although I'll have to be more in depth later) it doesn't look 
like what I'm really going for.


 Besides the iA and iB are far too simplistic compared to what I 
really need to do. For the subclasses there's at least 10, some 
of it's just for comparison/ordering, but some of it is for 
pre/post operations. Let's see...


 HEDR (Header information)
 NAME (raw text)
 DATA (raw, or location x,y,z, or a mapping, etc)
 SCPT (text Script data)
 ENAM (data...)
 FLAG (data, search/handling different)
 NPCO (string, of item)
 NPCS (string, of spell)
 FRMR (Object id)
 INAM (ID for dialog)
 PNAM (linked list, previous dialog)
 NNAM (linked list, next dialog)

 These are just a few of them, Data actually has like 15+ entries 
although only a few of them require special cases. multiple alias 
this's won't work. There's also multiple cases where the 
override/subclass is merely to generate the NAME (or ID entry) 
differently ( partially for sorting but mostly informational 
purposes) so it may reference the original object but I don't 
want to have to do a bunch of forced casts (and clutter up code).


RePost: Help to convert a code to D

2013-08-26 Thread Alexandre

Hi :)

I'm starting with D language... and, I try to convert a C# code
to D...
So, my C# code, I get file informations, and, I create folders
with all days of month of specific year...

So, that is my C# code...

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace Organizador
{
 class Organiza
 {
 private string[] MesesDoAno =
 {
   Janeiro, Fevereiro,
   Marco, Abril,
   Maio, Junho,
   Julho, Agosto,
   Setembro, Outubro,
   Novembro, Dezembro
 };

 private string DirReceb = string.Empty;

 public Organiza()
 {
 CriaDiretorios();
 MoveArquivos();
 }

 private void CriaDiretorios()
 {
 DirReceb = RECEBIDOS\\ +
DateTime.Now.Year.ToString() + \\;
 // Cria o diretorio root
 if (!Directory.Exists(DirReceb))
 Directory.CreateDirectory(DirReceb);

 // cria os diretorios dos meses do ano
 for (int i = 0; i  12; i++)
 if (!Directory.Exists(DirReceb + MesesDoAno))
 Directory.CreateDirectory(DirReceb +
MesesDoAno[i]);

 // cria os diretorios com os dias dos meses e ano
 for (int i = 1; i = 12; i++)
 {
 string dia;
 string mes;
 var ano = DateTime.Now.Year;
 var DiasDoMes =
DateTime.DaysInMonth(DateTime.Now.Year, i);

 if (i  10)
 mes = 0 + i.ToString();
 else
 mes = i.ToString();

 for (int j = 1; j = DiasDoMes; j++)
 {
 if (j  10)
 dia = 0 + j.ToString();
 else
 dia = j.ToString();

 string StrDia = string.Format({0}-{1}-{2},
dia, mes, ano);
 string StrData = DirReceb + MesesDoAno[i-1] +
\\ + StrDia;

 if (!Directory.Exists(StrData))
 Directory.CreateDirectory(StrData);
 }
 }
 }

 private void MoveArquivos()
 {
 string[] filters = new[] { *.REM, *.RET };

 for (int i = 0; i  2; i++)
 {
 DirectoryInfo di = new
DirectoryInfo(Directory.GetCurrentDirectory());
 var files = di.GetFiles(filters[i]);

 foreach (var fi in files)
 {
 var mes = fi.CreationTime.Month;
 var strdt =
fi.CreationTime.ToString(dd-MM-);

 string DestDir = DirReceb + MesesDoAno[mes -
1] + \\ + strdt + \\ + fi.Name;

 File.Move(fi.Name, DestDir);
 }
 }
 }
 }

 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 new Organiza();
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 }
 }
 }
}


So, to create directory and move files... I get the documentation
on that page: http://dlang.org/phobos/std_file.html

But, I don't know, How I can get the file information and what is
the best way to create the directory's, so, I need some help :)

I appreciate the help :)


Re: RePost: Help to convert a code to D

2013-08-26 Thread bearophile

Alexandre:


So, that is my C# code...


If you don't receive answers, then I suggest you to cut your 
program in perpendicular slices, and try to translate them in D, 
one after the other, and to show them here, hoping for comments. 
In a technical forum people are usually happier when you do some 
work yourself.


Bye,
bearophile


improve concurrent queue

2013-08-26 Thread luminousone
I have been working on a project and needed a good concurrent 
queue, so I wrote one, is their anyone more familiar with the 
atomic arts that could tell me if their is anyway i can further 
improve it.


module container.concurrentqueue;

import std.typetuple;
import core.atomic;

class ConcurrentQueue( items...  ) {

align(64) class nodeType {
align(1):
		this( ) { atomicStore( this.next, cast(shared nodeType) null ); 
}

this( TypeTuple!items value ) {
foreach( k, v ; value ) {
this.value[k] = v;
}
this();
}

TypeTuple!items value;
shared nodeType next;
}

class ConsumerResult {
TypeTuple!items value;

alias value this;
}

public this() {
shared nodeType temp = cast(shared)new nodeType( );

atomicStore( first, temp );
atomicStore( last , temp );
atomicStore( producerLock, false );
atomicStore( consumerLock, false );
}   

public void Produce( items item ) {

TypeTuple!items t = item;
shared nodeType temp = cast(shared)new nodeType ( t );

while( !cas(producerLock, false, true ) ) { }

atomicStore( last.next   , temp );
atomicStore( last, temp );
atomicStore( producerLock, false );
}

public ConsumerResult Consume( ) {
while( !cas(consumerLock, false, true ) ) { }

shared nodeType temp = cast(shared)atomicLoad( first );
shared nodeType next = cast(shared)atomicLoad( temp.next );

ConsumerResult result = new ConsumerResult();

if( next !is null ) {
foreach( k, v ; items ) {
result[k] = cast(v)next.value[k];
}
first = next;
atomicStore( consumerLock, false );
return result;
}
atomicStore( consumerLock, false );
return null;
}

private shared nodeType first;

private byte padd1[64];

private shared nodeType last;

private byte padd2[64];

private shared bool consumerLock;

private byte padd3[64];

private shared bool producerLock;
}


Re: RePost: Help to convert a code to D

2013-08-26 Thread Andre Artus

On Monday, 26 August 2013 at 13:30:38 UTC, Alexandre wrote:

Hi :)

I'm starting with D language... and, I try to convert a C# code
to D...
So, my C# code, I get file informations, and, I create folders
with all days of month of specific year...

So, that is my C# code...

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace Organizador
{
 class Organiza
 {
 private string[] MesesDoAno =
 {
   Janeiro, Fevereiro,
   Marco, Abril,
   Maio, Junho,
   Julho, Agosto,
   Setembro, Outubro,
   Novembro, Dezembro
 };

 private string DirReceb = string.Empty;

 public Organiza()
 {
 CriaDiretorios();
 MoveArquivos();
 }

 private void CriaDiretorios()
 {
 DirReceb = RECEBIDOS\\ +
DateTime.Now.Year.ToString() + \\;
 // Cria o diretorio root
 if (!Directory.Exists(DirReceb))
 Directory.CreateDirectory(DirReceb);

 // cria os diretorios dos meses do ano
 for (int i = 0; i  12; i++)
 if (!Directory.Exists(DirReceb + MesesDoAno))
 Directory.CreateDirectory(DirReceb +
MesesDoAno[i]);

 // cria os diretorios com os dias dos meses e ano
 for (int i = 1; i = 12; i++)
 {
 string dia;
 string mes;
 var ano = DateTime.Now.Year;
 var DiasDoMes =
DateTime.DaysInMonth(DateTime.Now.Year, i);

 if (i  10)
 mes = 0 + i.ToString();
 else
 mes = i.ToString();

 for (int j = 1; j = DiasDoMes; j++)
 {
 if (j  10)
 dia = 0 + j.ToString();
 else
 dia = j.ToString();

 string StrDia = 
string.Format({0}-{1}-{2},

dia, mes, ano);
 string StrData = DirReceb + 
MesesDoAno[i-1] +

\\ + StrDia;

 if (!Directory.Exists(StrData))
 Directory.CreateDirectory(StrData);
 }
 }
 }

 private void MoveArquivos()
 {
 string[] filters = new[] { *.REM, *.RET };

 for (int i = 0; i  2; i++)
 {
 DirectoryInfo di = new
DirectoryInfo(Directory.GetCurrentDirectory());
 var files = di.GetFiles(filters[i]);

 foreach (var fi in files)
 {
 var mes = fi.CreationTime.Month;
 var strdt =
fi.CreationTime.ToString(dd-MM-);

 string DestDir = DirReceb + MesesDoAno[mes 
-

1] + \\ + strdt + \\ + fi.Name;

 File.Move(fi.Name, DestDir);
 }
 }
 }
 }

 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 new Organiza();
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 }
 }
 }
}


So, to create directory and move files... I get the 
documentation

on that page: http://dlang.org/phobos/std_file.html

But, I don't know, How I can get the file information and what 
is

the best way to create the directory's, so, I need some help :)

I appreciate the help :)


Hi Alexandre,

Would you mind explaining in English what it is that you would 
like to achieve. I cannot read [what I assume is] Portuguese, but 
if you can explain what you wan't I will try my best to help.


Re: RePost: Help to convert a code to D

2013-08-26 Thread Era Scarecrow
 I wonder if any of this would make any more sense if you threw 
it through Google translate.. (maybe the comments and months?)




On Monday, 26 August 2013 at 20:14:34 UTC, Andre Artus wrote:

Hi Alexandre,

Would you mind explaining in English what it is that you would 
like to achieve. I cannot read [what I assume is] Portuguese, 
but if you can explain what you want I will try my best to help.


 From what I can tell he's making a directory either per day of 
the month, or per month, then moving all files last 
created/modified to those directories.




On Monday, 26 August 2013 at 13:30:38 UTC, Alexandre wrote:

 foreach (var fi in files)
 {
 var mes = fi.CreationTime.Month;
 var strdt =
fi.CreationTime.ToString(dd-MM-);

 string DestDir = DirReceb + MesesDoAno[mes 
-

1] + \\ + strdt + \\ + fi.Name;

 File.Move(fi.Name, DestDir);
 }
 }
 }
 }




Using C/C++-DLL in D

2013-08-26 Thread S0urc3C0de

Hello guys,

I'm trying to use a C++-DLL in D.
I compiled it via GCC, created a .lib-File with implib, but dmd 
keeps telling me that the symbol was undefined.
For test purposes, I created a Test-DLL with just one simple 
function that should output a simple text to the console.


#define TEST_DLL __declspec(dllexport)

#include iostream

void TEST_DLL printCpp()
{
std::cout  Hello from Cpp-DLL :)  std::endl;
}

I compiled everything and then tried to call this function from 
inside D.


pragma(lib,C:\\Path\\to\\Dll\\Test.lib);

extern(C++) void printCpp();

printCpp();

Everything works fine until I try to call the function. dmd says:
Error 42: Symbol Undefined _printCpp

The problem is more or less obvious but I'm not able to solve it.
By the way: this error also occurs when I'm creating the 
.lib-File with a self-written .def-File.
I've searched for hours but didn't find anything that could help 
me solving this, so I hope you guys can help :)


Re: Using C/C++-DLL in D

2013-08-26 Thread Adam D. Ruppe
When you run implib, did you use the /s option? implib /s either 
adds or removes the leading underscore from the name (I don't 
remember which)... so if you didn't use it, try adding that and 
see what happens, and if you did, see what happens if you remove 
that option.


Re: Using C/C++-DLL in D

2013-08-26 Thread S0urc3C0de

On Monday, 26 August 2013 at 22:17:07 UTC, Adam D. Ruppe wrote:
When you run implib, did you use the /s option? implib /s 
either adds or removes the leading underscore from the name (I 
don't remember which)... so if you didn't use it, try adding 
that and see what happens, and if you did, see what happens if 
you remove that option.


Hmm nope I did not but tried it now: same error.
By the way: I should correct the error message from above. The 
correct error from dmd is:
Error 42: Symbol Undefined ?printCpp@@YAXXZ (void cdecl 
printCpp(void ))


The error message from above occurs when I write extern(C) 
instead of extern(C++) but due to the fact that it is C++-DLL, 
extern(C++) should be correct, shouldn't it?


Maybe, someone here already wrote a program that uses a C/C++-Lib 
and may tell me what he exactly did?


bug or feature? shared objects and tuples

2013-08-26 Thread Jack Applegame
It is impossible to pack a structure with shared object into 
tuple.


```
import std.concurrency;
import std.typecons;

class Foo {}

struct A {
shared Foo foo;
}

void main() {
auto a = tuple(new shared Foo); // ОК
 	auto b = tuple(A());// Error: static assert unable 
to format shared objects

}
```


Re: bug or feature? shared objects and tuples

2013-08-26 Thread Andrej Mitrovic
On 8/27/13, Jack Applegame jappleg...@gmail.com wrote:
 It is impossible to pack a structure with shared object into
 tuple.

Bug. Please file it to bugzilla:
http://d.puremagic.com/issues/enter_bug.cgi?product=D

Thanks!


Re: bug or feature? shared objects and tuples

2013-08-26 Thread Jack Applegame

On Monday, 26 August 2013 at 23:04:24 UTC, Andrej Mitrovic wrote:

Bug. Please file it to bugzilla:
http://d.puremagic.com/issues/enter_bug.cgi?product=D

Thanks!

http://d.puremagic.com/issues/show_bug.cgi?id=10907


Re: RePost: Help to convert a code to D

2013-08-26 Thread Andre Artus

On Monday, 26 August 2013 at 13:30:38 UTC, Alexandre wrote:

Hi :)

I'm starting with D language... and, I try to convert a C# code
to D...
So, my C# code, I get file informations, and, I create folders
with all days of month of specific year...

So, that is my C# code...


-- SNIP --

So, to create directory and move files... I get the 
documentation

on that page: http://dlang.org/phobos/std_file.html

But, I don't know, How I can get the file information and what 
is

the best way to create the directory's, so, I need some help :)

I appreciate the help :)


Okay, I banged together something that may be close to what you 
want. I'm not a D expert, so someone is sure to point out some 
areas for improvement.


There does not seem to be any reason to use objects/classes for 
what you want. In fact if I was to write it in C# I would make 
the methods static.


As an aside: it's not generally considered good practice to do 
expensive computations or IO in a constructor (BOCTAOE).


I did not split building the archive directory structure from the 
file moving part. I prefer to only create a directory if there is 
going to be a file in it. This may have a impact on performance, 
but I suspect it is negligible. If it's an issue measure, 
measure, measure.



module main;

import std.stdio, std.algorithm, std.conv;
import std.array, std.random, std.datetime;
import std.file, std.path, std.utf, std.string;


int main(string[] argv)
{
  // string prefixed with 'r' similar to '@' in C#
  auto searchPath = rG:\archivetest\search;
  auto archivePath = rG:\archivetest\archive;

  moveToArchive(searchPath, archivePath);

  return 0;
}

void moveToArchive(string searchPath, string archivePath)
{
  // This ought to be a library thing.
  immutable string[12] MesesDoAno =
  [
Janeiro, Fevereiro,
Marco, Abril,
Maio, Junho,
Julho, Agosto,
Setembro, Outubro,
Novembro, Dezembro
  ];

  // http://dlang.org/phobos/std_file.html#.dirEntries
  auto de = dirEntries(searchPath,*.RE{M,T}, SpanMode.shallow, 
false);


  // Sorting not required, just a personal preference
  auto sortedFiles =
de.array.sort!((DirEntry x, DirEntry y)
  = x.timeLastModified  y.timeLastModified);

  foreach(DirEntry e; sortedFiles) {
// I'm being extra verbose here so that it's easy to follow 
in a debugger


auto tlm = e.timeLastModified;

auto _year = tlm.year;
auto _month = tlm.month;
auto _day = tlm.day;

auto yearString = to!(string)(_year);
auto monthString = MesesDoAno[tlm.month - Month.jan];

// there ought to be a date formatting function. I can't find 
it.
auto dayString = format(%04d-%02d-%02d, _year, _month, 
_day);


string movePath = buildPath(archivePath, yearString, 
monthString);


bool makeDir = !(movePath.exists  movePath.isDir);

if(makeDir)
  mkdirRecurse(movePath);

auto renamedFile = buildPath(movePath, e.name.baseName);

writefln(%s - %s, e.name, renamedFile);

//rename(e.name, renamedFile );
//uncomment above line if all looks good.
  }
}


Re: Using C/C++-DLL in D

2013-08-26 Thread Andrej Mitrovic
On 8/27/13, S0urc3C0de s0urc3c0de@d.learn wrote:
 Hello guys,

 I'm trying to use a C++-DLL in D.
 I compiled it via GCC, created a .lib-File with implib

I don't think you'll be able to match the name mangling, GCC might use
one convention, DMD another.

There was a pragma(mangle) feature introduced in git-head recently,
but it seems to be screwed up because if you set the calling
convention it will end up double-mangling the function. For example:

extern(C++) pragma(mangle, _Z8printCppv) void printCpp();

This will still not link. The following will link, but it is not correct:

pragma(mangle, _Z8printCppv) void printCpp();

The function is missing the calling convention, so you can't call it
without causing memory corruption.

I don't understand why this mangle feature was implemented this way.
The mangle pragma should be the last say on what the mangled name of a
symbol is, without adding additional mangling due to a calling
convention.

Anyway, the safest bet is to use C functions to interface with C++.


Re: RePost: Help to convert a code to D

2013-08-26 Thread Andre Artus

On Monday, 26 August 2013 at 21:43:20 UTC, Era Scarecrow wrote:
 I wonder if any of this would make any more sense if you threw 
it through Google translate.. (maybe the comments and months?)


I did just that :)


On Monday, 26 August 2013 at 20:14:34 UTC, Andre Artus wrote:

Hi Alexandre,

Would you mind explaining in English what it is that you would 
like to achieve. I cannot read [what I assume is] Portuguese, 
but if you can explain what you want I will try my best to 
help.


 From what I can tell he's making a directory either per day of 
the month, or per month, then moving all files last 
created/modified to those directories.


I always try to understand the person's intention. The obvious 
answer isn't always the best solution. Someone may be asking 
what route should I take to sail my lilo [inflatable raft] to 
Perth?


Re: RePost: Help to convert a code to D

2013-08-26 Thread Andre Artus

On Monday, 26 August 2013 at 23:32:26 UTC, Andre Artus wrote:

On Monday, 26 August 2013 at 13:30:38 UTC, Alexandre wrote:

Hi :)

I'm starting with D language... and, I try to convert a C# code
to D...
So, my C# code, I get file informations, and, I create folders
with all days of month of specific year...

So, that is my C# code...


-- SNIP --

So, to create directory and move files... I get the 
documentation

on that page: http://dlang.org/phobos/std_file.html

But, I don't know, How I can get the file information and what 
is

the best way to create the directory's, so, I need some help :)

I appreciate the help :)


Okay, I banged together something that may be close to what you 
want. I'm not a D expert, so someone is sure to point out some 
areas for improvement.


There does not seem to be any reason to use objects/classes for 
what you want. In fact if I was to write it in C# I would make 
the methods static.


As an aside: it's not generally considered good practice to do 
expensive computations or IO in a constructor (BOCTAOE).


I did not split building the archive directory structure from 
the file moving part. I prefer to only create a directory if 
there is going to be a file in it. This may have a impact on 
performance, but I suspect it is negligible. If it's an issue 
measure, measure, measure.



module main;

import std.stdio, std.algorithm, std.conv;
import std.array, std.random, std.datetime;
import std.file, std.path, std.utf, std.string;


int main(string[] argv)
{
  // string prefixed with 'r' similar to '@' in C#
  auto searchPath = rG:\archivetest\search;
  auto archivePath = rG:\archivetest\archive;

  moveToArchive(searchPath, archivePath);

  return 0;
}

void moveToArchive(string searchPath, string archivePath)
{
  // This ought to be a library thing.
  immutable string[12] MesesDoAno =
  [
Janeiro, Fevereiro,
Marco, Abril,
Maio, Junho,
Julho, Agosto,
Setembro, Outubro,
Novembro, Dezembro
  ];

  // http://dlang.org/phobos/std_file.html#.dirEntries
  auto de = dirEntries(searchPath,*.RE{M,T}, 
SpanMode.shallow, false);


  // Sorting not required, just a personal preference
  auto sortedFiles =
de.array.sort!((DirEntry x, DirEntry y)
  = x.timeLastModified  y.timeLastModified);

  foreach(DirEntry e; sortedFiles) {
// I'm being extra verbose here so that it's easy to follow 
in a debugger


auto tlm = e.timeLastModified;


When testing I used timeLastModified as that created the greatest 
variability with the files I had at my disposal. If you need to 
use the file creation time then replace with timeCreated, as 
follows:


auto sortedFiles = de.array.sort!((x, y) = x.timeCreated  
y.timeCreated);

foreach(DirEntry e; sortedFiles) {
  auto tlm = e.timeCreated;



Re: Using C/C++-DLL in D

2013-08-26 Thread S0urc3C0de

On Monday, 26 August 2013 at 23:33:52 UTC, Andrej Mitrovic wrote:
Anyway, the safest bet is to use C functions to interface with 
C++.


Okay, thank you, using C and compiling with gcc now works, but 
isn't there really any way to directly use a C++-Lib? Cause 
wrapping everything seems to be a hell of a lot work...


Actually, I was trying to use ffmpeg and isn't this a C-Lib? 
Because when I tried to call a simple function 
(av_register_all()), I got the same error as described above 
though only with the leading underscore in the error message.


Re: Using C/C++-DLL in D

2013-08-26 Thread Andrej Mitrovic
On 8/27/13, S0urc3C0de s0urc3c0de@d.learn wrote:
 Actually, I was trying to use ffmpeg and isn't this a C-Lib?

Seems so.

 Because when I tried to call a simple function
 (av_register_all()), I got the same error as described above
 though only with the leading underscore in the error message.

Try calling implib with the /s switch.


Re: Using C/C++-DLL in D

2013-08-26 Thread S0urc3C0de

On Tuesday, 27 August 2013 at 00:14:47 UTC, Andrej Mitrovic wrote:

Try calling implib with the /s switch.


Okay thanks, works now.

Hopefully, there will be a safe way to use C++-Libs soon...


Re: Variant[Variant]

2013-08-26 Thread Ali Çehreli

On 08/24/2013 04:12 AM, Jason den Dulk wrote:
 Hi

 Straight off, I should ask if Variant[Variant] is a feasable idea.

It looks like it:

import std.variant;

void main()
{
Variant[Variant] aa;
aa[Variant(42)] = Variant(forty two);

assert(Variant(42) in aa);
assert(aa == [ Variant(42) : Variant(forty two) ]);
}

 This is the function

I spent 15 minutes trying to complete the code but failed. Could you 
please provide a minimal program that almost compiles.


Ali



How to cleanup after Socket.bind on Linux?

2013-08-26 Thread Ali Çehreli
The following simple socket example is trying to cleanup after itself, 
except the bind() call. As I repeat in the QUESTION comment below, I 
have read the man page of bind and I know that I need to unlink a path. 
How can I get that path?


The program waits on localhost:8080, receives N number of data and 
responds with Hello World!.


The problem is, currently the program apparently leakes some resources. 
It cannot be started a second time for 8080 still being in use, unless 
you wait for several seconds, presumably until the OS does the cleanup.


import std.stdio;
import std.socket;
import std.string;

enum port = 8080;

void main()
{
server();
}

void server()
{
// Prepare the socket
auto listener = new TcpSocket();
scope (exit) {
writefln(Shutting down and closing the listener);
listener.shutdown(SocketShutdown.BOTH);
listener.close();
}

/*
 * The port to listen to
 *
 * Note that the following perhaps naive code does not work on OSX. Try
 * the following line instead:
 *
 *   listener.bind(new InternetAddress(port));
 */
Address[] addresses = getAddress(localhost, port);
writefln(Addresses: %s, addresses);
auto address = addresses[0];
writefln(Address: %s, address);
listener.bind(address);
scope (exit) {
/*
 * QUESTION: What to do here?
 *
 * According to 'man bind', the path that represents the 
address must
 * be unlink'ed. However, the path seems to be available only 
through
 * UnixAddress.path but UnixAddress is not available by default 
and it
 * is not convenient to use (e.g. it does not have a 
constructor that

 * takes the port value).
 */
}

// Wait for the client
listener.listen(1);
writeln(Waiting for the client);

// Accept the connection
Socket connection = listener.accept();
scope (exit) {
writefln(Shutting down and closing the client connection %s,
 connection.remoteAddress());
connection.shutdown(SocketShutdown.BOTH);
connection.close();
}

ubyte[1000] buffer;
bool isAllReceived = false;

while (!isAllReceived) {
const received = connection.receive(buffer);

if (received == Socket.ERROR) {
writeln(READ ERROR);
break;

} else {
writefln(Received %s bytes; as string: %s,
 received, cast(string)buffer[0..received]);
}

isAllReceived = (received  buffer.length);
}

if (isAllReceived) {
enum header =
HTTP/1.0 200 OK\nContent-Type: text/html; charset=utf-8\n\n;

string response = header ~ Hello World!\n;
connection.send(response);
}
}

Thank you,
Ali


why no to!bool(0) or to!bool(1) ?

2013-08-26 Thread growler

Is there any reason why the following code fails to compile?

---
auto bfalse = to!bool(0);
auto btrue = to!bool(1);
---
dmd2/src/phobos/std/conv.d(329): Error: template std.conv.toImpl
cannot deduce template function from argument types !(bool)(int)


I can use a string, like so:
---
auto bfalse = to!bool(false);
auto btrue = to!bool(true);
---
...but usually the database column is an INTEGER type.

I can cast(bool)(0) or cast(bool)(1) no problem but I much prefer
to!bool.

Thanks,
G.


Re: How to cleanup after Socket.bind on Linux?

2013-08-26 Thread dnewbie

On Tuesday, 27 August 2013 at 03:30:11 UTC, Ali Çehreli wrote:
It cannot be started a second time for 8080 still being in use, 
unless you wait for several seconds


It works on Windows7, no need to wait.


Freshly Compiled DMD + Visual Studio

2013-08-26 Thread Meta

I decided to compile D from Github for the first time, and
everything seemed to be working. I can build and run stuff fine
from the command line. However, then I tried to make Visual
Studio use my newly compiled DMD, and things blew up. I'm using
VisualD 0.3.37. When I try to compile a small project (which
compiles correctly when doing it from the command line) it gets
as far as linking, and then spits out a bunch of errors:

Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std3uni42__T11Uint24ArrayTS3std3uni13ReallocPolicyZ11Uint24Array5emptyMxFNaNbNdNeZb
(const(pure nothrow @property @trusted bool function())
std.uni.Uint24Array!(std.uni.ReallocPolicy).Uint24Array.empty)
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std3uni42__T11Uint24ArrayTS3std3uni13ReallocPolicyZ11Uint24Array6__dtorMFNbNeZv
(nothrow @trusted void
std.uni.Uint24Array!(std.uni.ReallocPolicy).Uint24Array.__dtor())
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std3uni36__T11Uint24ArrayTS3std3uni8GcPolicyZ11Uint24Array6__dtorMFNaNbNeZv
(pure nothrow @trusted void
std.uni.Uint24Array!(std.uni.GcPolicy).Uint24Array.__dtor())
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std3uni36__T11Uint24ArrayTS3std3uni8GcPolicyZ11Uint24Array5emptyMxFNaNbNdNeZb
(const(pure nothrow @property @trusted bool function())
std.uni.Uint24Array!(std.uni.GcPolicy).Uint24Array.empty)
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D4core4time13TimeException6__ctorMFNaNbNfAyaAyakC6object9ThrowableZC4core4time13TimeException
(pure nothrow @safe core.time.TimeException
core.time.TimeException.__ctor(immutable(char)[],
immutable(char)[], uint, object.Throwable))
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std3utf12UTFException6__ctorMFNaNfAyakAyakC6object9ThrowableZC3std3utf12UTFException
(pure @safe std.utf.UTFException
std.utf.UTFException.__ctor(immutable(char)[], uint,
immutable(char)[], uint, object.Throwable))
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std6format15FormatException6__ctorMFNaNbNfAyaAyakC6object9ThrowableZC3std6format15FormatException
(pure nothrow @safe std.format.FormatException
std.format.FormatException.__ctor(immutable(char)[],
immutable(char)[], uint, object.Throwable))
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std4conv21ConvOverflowException6__ctorMFNaNbNfAyaAyakZC3std4conv21ConvOverflowException
(pure nothrow @safe std.conv.ConvOverflowException
std.conv.ConvOverflowException.__ctor(immutable(char)[],
immutable(char)[], uint))
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std4conv13ConvException6__ctorMFNaNbNfAyaAyakZC3std4conv13ConvException
(pure nothrow @safe std.conv.ConvException
std.conv.ConvException.__ctor(immutable(char)[],
immutable(char)[], uint))
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std4conv10parseErrorFNaNfLAyaAyakZC3std4conv13ConvException
(pure @safe std.conv.ConvException std.conv.parseError(lazy
immutable(char)[], immutable(char)[], uint))
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined
_D3std7variant17__T8VariantNVk20Z8VariantN5opCmpMxFNeKxS3std7variant17__T8VariantNVk20Z8VariantNZi
(const(@trusted int function(ref
const(std.variant.VariantN!(20u).VariantN)))
std.variant.VariantN!(20u).VariantN.opCmp)
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined __aaRange
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined __aaRangeEmpty
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined __aaRangeFrontKey
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined __aaRangePopFront
Debug\Algorithms.obj(Algorithms)
  Error 42: Symbol Undefined __aaRangeFrontValue

 From what I can tell, it looks like it cannot link in druntime
correctly... But I'm not really an expert.


Re: why no to!bool(0) or to!bool(1) ?

2013-08-26 Thread Jesse Phillips

On Tuesday, 27 August 2013 at 04:08:47 UTC, growler wrote:

Is there any reason why the following code fails to compile?

---
auto bfalse = to!bool(0);
auto btrue = to!bool(1);
---
dmd2/src/phobos/std/conv.d(329): Error: template std.conv.toImpl
cannot deduce template function from argument types !(bool)(int)


No one implemented probably. BTW:

void main() {
 bool a = 0;
 bool b = 1;

 assert(!a);
 assert(b);
}


Re: why no to!bool(0) or to!bool(1) ?

2013-08-26 Thread H. S. Teoh
On Tue, Aug 27, 2013 at 07:12:56AM +0200, Jesse Phillips wrote:
 On Tuesday, 27 August 2013 at 04:08:47 UTC, growler wrote:
 Is there any reason why the following code fails to compile?
 
 ---
 auto bfalse = to!bool(0);
 auto btrue = to!bool(1);
 ---
 dmd2/src/phobos/std/conv.d(329): Error: template std.conv.toImpl
 cannot deduce template function from argument types !(bool)(int)
 
 No one implemented probably. BTW:
 
 void main() {
  bool a = 0;
  bool b = 1;
 
  assert(!a);
  assert(b);
 }

Hmm. Maybe file an enhancement request here:

http://d.puremagic.com/issues


T

-- 
I'm not childish; I'm just in touch with the child within! - RL


Re: why no to!bool(0) or to!bool(1) ?

2013-08-26 Thread growler

On Tuesday, 27 August 2013 at 05:13:01 UTC, Jesse Phillips wrote:

On Tuesday, 27 August 2013 at 04:08:47 UTC, growler wrote:

Is there any reason why the following code fails to compile?

---
auto bfalse = to!bool(0);
auto btrue = to!bool(1);
---
dmd2/src/phobos/std/conv.d(329): Error: template 
std.conv.toImpl
cannot deduce template function from argument types 
!(bool)(int)


No one implemented probably. BTW:


No worries, thanks for the info.



void main() {
 bool a = 0;
 bool b = 1;

 assert(!a);
 assert(b);
}


The implicit conversion is only for literals and besides, I have
this sort of hackiness happening:

alias typeof(s.tueplof[ii]) FieldType;
s.tupleof[ii] = value.to!FieldType;

I just stick in a static-if(isBoolean!FieldType) and all is well.

Thanks,
G


Re: why no to!bool(0) or to!bool(1) ?

2013-08-26 Thread growler

On Tuesday, 27 August 2013 at 05:22:00 UTC, H. S. Teoh wrote:

On Tue, Aug 27, 2013 at 07:12:56AM +0200, Jesse Phillips wrote:

On Tuesday, 27 August 2013 at 04:08:47 UTC, growler wrote:
Is there any reason why the following code fails to compile?

---
auto bfalse = to!bool(0);
auto btrue = to!bool(1);
---
dmd2/src/phobos/std/conv.d(329): Error: template 
std.conv.toImpl
cannot deduce template function from argument types 
!(bool)(int)


No one implemented probably. BTW:

void main() {
 bool a = 0;
 bool b = 1;

 assert(!a);
 assert(b);
}


Hmm. Maybe file an enhancement request here:

http://d.puremagic.com/issues


T


Done.

http://d.puremagic.com/issues/show_bug.cgi?id=10909

Thanks,
G.