Re: Is there any bettter solution to Windows wide string

2021-05-09 Thread FreeSlave via Digitalmars-d-learn

On Saturday, 8 May 2021 at 20:50:10 UTC, Vinod K Chandran wrote:

Hi all,
I am planning some win32 hobby projects. Now I have this 
function to tackle the LPCWSTR data type in win32.

```d
private import std.utf;
auto toWString(S)(S s) { return toUTFz!(const(wchar)*)(s); }
```
Is there any better way to do this ?


You may try using tempCStringW from std.internal.cstring. It uses 
small string optimization. However the api is internal, so I'm 
not sure how valid it is to use this function. The returned 
struct is a temporary buffer so you must ensure that you don't 
escape dangling pointers.


Remove routes from URLRouter in vibe.d

2021-03-17 Thread FreeSlave via Digitalmars-d-learn
I want to be able to dynamically remove some routes in my Vibe.d 
application.
URLRouter accounts for newly added routes, but I can't find a way 
to clear routes unless I create the new URLRouter object, in 
which case I also need to re-create HTTP listener.

Also, is it safe to replace already existing route handlers?


Re: Getting the source text of an expression

2020-12-17 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 17 December 2020 at 19:45:38 UTC, Dave P. wrote:
In C, you can use a macro to get the source text of an 
expression as a string. For example


#include 
#define PRINT_INT(x) printf(#x " = %d\n", x)

int main(){
// prints "3 = 3"
PRINT_INT(3);
int x = 4;
// prints "x = 4"
PRINT_INT(x);
#define FOO 5
// prints "FOO = 5"
PRINT_INT(FOO);
#define BAR FOO
// prints "BAR = 5"
PRINT_INT(BAR);
return 0;
}

Is there a feature of D that allows you to achieve a similar 
goal? I’ve used this in the past for logging for example.


Something like that?

import  std.stdio;

void print_int(alias n)()
{
writeln(n.stringof~"=", n);
}

void main()
{
int x = 42;
print_int!(x);
print_int!(7);
}


Re: How can I set Timeout of Socket?

2020-11-14 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 15 November 2020 at 00:05:08 UTC, Marcone wrote:

Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.connect(new InternetAddress("domain.com", 80));

I want that program raise an error if reach for example 30 
seconds of timeout.


Perhaps using Socket.select and SocketSet?

import std.socket;
import std.stdio;
import core.time;

void main()
{
Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.blocking = false;
auto set = new SocketSet(1);
set.add(s);
s.connect(new InternetAddress("dlang.org", 80));
scope(exit) s.close();
Socket.select(null, set, null, dur!"seconds"(10));
if (set.isSet(s))
{
writeln("socket is ready");
}
else
{
writeln("could not connect");
}
}


Re: Renaming Flag!"" in API

2020-10-12 Thread FreeSlave via Digitalmars-d-learn

On Monday, 12 October 2020 at 16:44:52 UTC, Ali Çehreli wrote:
It's amazing how things come together before each conference. 
Flag appears among my slides for an upcoming conference as 
well! :)


But I don't think there is any solution to your problem.

On 10/12/20 3:24 AM, FreeSlave wrote:

> Later I realize that 'myflagname' is a bad name and I want to
change it
> to something else. But if I do so, I break the existing code
using this
> API as Flag with different name will be a different type

This is essentially the same as one of the objections to named 
arguments.


Ali


Huh, never thought about named arguments in this way. Yet some 
syntax for parameter name aliasing could be invented to refer to 
the same parameter by different names if D ever gets named 
arguments feature.


Re: Renaming Flag!"" in API

2020-10-12 Thread FreeSlave via Digitalmars-d-learn
On Monday, 12 October 2020 at 11:34:25 UTC, Vladimir Panteleev 
wrote:

On Monday, 12 October 2020 at 10:24:44 UTC, FreeSlave wrote:

Can this issue overcome somehow?


Why not add a deprecated overload for your function which takes 
the old Flag value?


I thought about overloading too. Templatizing the parameter is 
fitting too especially if the function is already templated. I 
think I'll go with the latter.
Yet in general it would be a tedious work to add template 
constraints or overloads (and in case of overloads there's also a 
lot of copy-pasting included) to all functions that use this flag 
as parameter if there were too many of them. Some way to declare 
two flag types as implicitly convertable would be nice.


Renaming Flag!"" in API

2020-10-12 Thread FreeSlave via Digitalmars-d-learn

Let's say I use Flag type named 'myflagname' in API like this:

import std.typecons;

void func(Flag!"myflagname" flag)
{
//...
}

void main()
{
func(Yes.myflagname);
}

Later I realize that 'myflagname' is a bad name and I want to 
change it to something else. But if I do so, I break the existing 
code using this API as Flag with different name will be a 
different type and Yes.myflagname and No.myflagname won't fit in. 
I can't use alias as Yes and No relies on string literal.
Can this issue overcome somehow? Looks like a fundamental flaw 
with std.typecons.Flag.


More complete windows declarations

2020-09-21 Thread FreeSlave via Digitalmars-d-learn
Druntime has a limited set of declarations, lacking some COM 
interfaces, e.g. IShellItem and IFileOperation (the latter is 
understandable though as it was introduced in Vista, and I guess 
druntime declarartions are limited to symbols from XP), and some 
others are declared wrongly (e.g. IShellFolder2 has duplicated 
declarations of methods derived from IShellFolder).

Is there any project on porting missing declarartions to D?


Re: Access violation when using IShellFolder2

2020-09-10 Thread FreeSlave via Digitalmars-d-learn
On Thursday, 10 September 2020 at 15:20:54 UTC, John Chapman 
wrote:

On Thursday, 10 September 2020 at 13:30:15 UTC, FreeSlave wrote:
Thanks. I tried this, but VarDateFromStr does not succeed for 
me.


It turns out the shell embeds some control characters in the 
string, specifically 8206 and 8207. So remove those before 
passing it to VarDateFromStr.


auto temp = strRet.pOleStr[0 .. lstrlenW(strRet.pOleStr)]
  .replace(cast(wchar)8206, "")
  .replace(cast(wchar)8207, "");
DATE date;
VarDateFromStr((temp ~ '\0').ptr, LOCALE_USER_DEFAULT, 0, 
);


Thank you again for consulting. I thought these character are 
part of the date format. This is all working now.


Re: Access violation when using IShellFolder2

2020-09-10 Thread FreeSlave via Digitalmars-d-learn
On Thursday, 10 September 2020 at 06:43:35 UTC, John Chapman 
wrote:

On Wednesday, 9 September 2020 at 22:44:50 UTC, FreeSlave wrote:
Btw do you know how to parse a date returned by GetDetailsOf? 
Couldn't find any examples in C++. I actually can see digits 
representing date and time as a part of the string, but I 
would prefer to use some winapi function to translate it into 
some time type instead of manually parsing the result.


You could look at passing the str.pOleStr field in the 
SHELLDETAILS you got from GetDetailsOf to VarDateFromStr. It 
will give you a DATE value that VariantTimeToSystemTime will 
convert to a SYSTEMTIME from which you can get the years, 
months, days etc.


For example:

SHELLDETAILS details;
GetDetailsOf(pidl, 3, );
DATE date;
VarDateFromStr(details.str.pOleStr, LOCALE_USER_DEFAULT, 0, 
);

SYSTEMTIME st;
VariantTimeToSystemTime(date, );
auto year = st.wYear;
auto month = st.wMonth;

You can convert that into a more D-friendly SysTime object 
using SYSTEMTIMEToSysTime from the std.datetime package.


Thanks. I tried this, but VarDateFromStr does not succeed for me. 
Here's the updated example. Note that I use a column 2 to 
retrieve the date because that's the deletion date column for 
recycle bin folder.


import core.sys.windows.windows;
import core.sys.windows.shlobj;
import core.sys.windows.wtypes;
import core.sys.windows.oaidl;

import std.exception;
import std.datetime;

pragma(lib, "Ole32");
pragma(lib, "OleAut32");

interface IShellFolder2 : IShellFolder {
  HRESULT GetDefaultSearchGUID(GUID*);
  HRESULT EnumSearches(IEnumExtraSearch*);
  HRESULT GetDefaultColumn(DWORD, ULONG*, ULONG*);
  HRESULT GetDefaultColumnState(UINT, SHCOLSTATEF*);
  HRESULT GetDetailsEx(LPCITEMIDLIST, const(SHCOLUMNID)*, 
VARIANT*);

  HRESULT GetDetailsOf(LPCITEMIDLIST, UINT, SHELLDETAILS*);
  HRESULT MapColumnToSCID(UINT, SHCOLUMNID*);
}

import std.stdio;

static @trusted string StrRetToString(ref scope STRRET strRet)
{
import std.string : fromStringz;
switch (strRet.uType)
{
case STRRET_CSTR:
return fromStringz(strRet.cStr.ptr).idup;
case STRRET_OFFSET:
writeln("STRRET_OFFSET!");
return string.init;
case STRRET_WSTR:
char[MAX_PATH] szTemp;
auto len = WideCharToMultiByte (CP_UTF8, 0, 
strRet.pOleStr, -1, szTemp.ptr, szTemp.sizeof, null, null);

scope(exit) CoTaskMemFree(strRet.pOleStr);
if (len)
return szTemp[0..len-1].idup;
else
return string.init;
default:
return string.init;
}
}

static @trusted SysTime StrRetToSysTime(ref scope STRRET strRet)
{
enforce(strRet.uType == STRRET_WSTR, "Expected STRRET_WSTR");
DATE date;
enforce(SUCCEEDED(VarDateFromStr(strRet.pOleStr, 
LOCALE_USER_DEFAULT, 0, )), "Failed to convert string to 
date value");

SYSTEMTIME sysTime;
VariantTimeToSystemTime(date, );
return SYSTEMTIMEToSysTime();
}

void main()
{
OleInitialize(null);
scope(exit) OleUninitialize();
IShellFolder desktop;
LPITEMIDLIST pidlRecycleBin;

enforce(SUCCEEDED(SHGetDesktopFolder()), "Failed to 
get desktop shell folder");

assert(desktop);
scope(exit) desktop.Release();
enforce(SUCCEEDED(SHGetSpecialFolderLocation(null, 
CSIDL_BITBUCKET, )), "Failed to get recycle bin 
location");

assert(pidlRecycleBin);
scope(exit) ILFree(pidlRecycleBin);

IShellFolder2 recycleBin;
enforce(SUCCEEDED(desktop.BindToObject(pidlRecycleBin, null, 
_IShellFolder2, cast(LPVOID *))), "Failed to get 
recycle bin shell folder");

assert(recycleBin);
scope(exit) recycleBin.Release();

IEnumIDList enumFiles;
with(SHCONTF) enforce(SUCCEEDED(recycleBin.EnumObjects(null, 
SHCONTF_FOLDERS | SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, 
)), "Failed to enumerate objects in recycle bin");

scope(exit) enumFiles.Release();

LPITEMIDLIST pidl;
while (enumFiles.Next(1, , null) != S_FALSE) {
string name;
string originalLocation;
SysTime deletionTime;
SHELLDETAILS details;
if(SUCCEEDED(recycleBin.GetDetailsOf(pidl,0,)))
{
name = StrRetToString(details.str);
}
if(SUCCEEDED(recycleBin.GetDetailsOf(pidl,1,)))
{
originalLocation = StrRetToString(details.str);
}
if(SUCCEEDED(recycleBin.GetDetailsOf(pidl,2,)))
{
deletionTime = StrRetToSysTime(details.str);
}
writefln("Name: %s, original location: %s, datetime: %s", 
name, originalLocation, deletionTime);

CoTaskMemFree(pidl);
}
}


Re: Access violation when using IShellFolder2

2020-09-09 Thread FreeSlave via Digitalmars-d-learn
On Wednesday, 9 September 2020 at 07:18:04 UTC, John Chapman 
wrote:

On Tuesday, 8 September 2020 at 22:24:22 UTC, FreeSlave wrote:
However if I change the type of recycleBin variable to 
IShellFolder (not IShellFolder2), the crash does not happen.


Does IShellFolder2 require some special handling?


The issue is caused by druntime's definition of IShellFolder2. 
To fix it temporarily, just redefine it in your module 
somewhere:


interface IShellFolder2 : IShellFolder {
  HRESULT GetDefaultSearchGUID(GUID*);
  HRESULT EnumSearches(IEnumExtraSearch*);
  HRESULT GetDefaultColumn(DWORD, ULONG*, ULONG*);
  HRESULT GetDefaultColumnState(UINT, SHCOLSTATEF*);
  HRESULT GetDetailsEx(LPCITEMIDLIST, const(SHCOLUMNID)*, 
VARIANT*);

  HRESULT GetDetailsOf(LPCITEMIDLIST, UINT, SHELLDETAILS*);
  HRESULT MapColumnToSCID(UINT, SHCOLUMNID*);
}

IShellFolder2 isn't the only culprit - IShellView2 will need 
fixing too if you intend to use it. There are probably others 
as well.


Redefinition did the trick, thank you.

Btw do you know how to parse a date returned by GetDetailsOf? 
Couldn't find any examples in C++. I actually can see digits 
representing date and time as a part of the string, but I would 
prefer to use some winapi function to translate it into some time 
type instead of manually parsing the result.


Access violation when using IShellFolder2

2020-09-08 Thread FreeSlave via Digitalmars-d-learn

Consider the following code:

import core.sys.windows.windows;
import core.sys.windows.shlobj;
import core.sys.windows.wtypes;

import std.exception;

pragma(lib, "Ole32");

void main()
{
OleInitialize(null);
scope(exit) OleUninitialize();
IShellFolder desktop;
LPITEMIDLIST pidlRecycleBin;

enforce(SUCCEEDED(SHGetDesktopFolder()), "Failed to 
get desktop shell folder");

assert(desktop);
scope(exit) desktop.Release();
enforce(SUCCEEDED(SHGetSpecialFolderLocation(null, 
CSIDL_BITBUCKET, )), "Failed to get recycle bin 
location");

assert(pidlRecycleBin);
scope(exit) ILFree(pidlRecycleBin);

IShellFolder2 recycleBin;
enforce(SUCCEEDED(desktop.BindToObject(pidlRecycleBin, null, 
_IShellFolder2, cast(LPVOID *))), "Failed to get 
recycle bin shell folder");

assert(recycleBin);
scope(exit) recycleBin.Release();

IEnumIDList enumFiles;
with(SHCONTF) enforce(SUCCEEDED(recycleBin.EnumObjects(null, 
SHCONTF_FOLDERS | SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, 
)), "Failed to enumerate objects in recycle bin");

enumFiles.Release();
}

For me this code crashes with error:

object.Error@(0): Access Violation

0x75B4EBB8 in SHELL32_CLocationContextMenu_Create
0x004023A9
0x0040493B
0x004048B5
0x0040474E
0x00402C9A
0x0040250B
0x75816359 in BaseThreadInitThunk
0x76F07C24 in RtlGetAppContainerNamedObjectPath
0x76F07BF4 in RtlGetAppContainerNamedObjectPath

However if I change the type of recycleBin variable to 
IShellFolder (not IShellFolder2), the crash does not happen.


Does IShellFolder2 require some special handling?


Re: Vibe.d timer - change callback?

2020-08-27 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 25 August 2020 at 18:42:53 UTC, codic wrote:
I'd like to be able to change the callback of a vibe.d Timer 
(eg created with 
http://vibe-core.dpldocs.info/v1.9.3/vibe.core.core.createTimer.html) after creation, something like:


auto timer = createTimer();
timer.rearm(duration, /*...*/);
timer.callback = delegate {
   // things
}

An alternative method would be to recreate the timer, like so:

auto timer = createTimer();
timer.rearm(duration, /*...*/);
auto timer = createTimer();
timer.rearm(duration - timer.elapsed);

However, I can't find an `elapsed` property or similar in the 
documentation.


I did not try it myself, but you can make an object which is 
accessible from both callback scope and outside scope. Depending 
on the state of the object it will call different functions. So 
if you want to change the callback in the meantime, you just 
change the state of the object.


Re: How to get the element type of an array?

2020-08-25 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 25 August 2020 at 03:41:06 UTC, Jon Degenhardt wrote:
What's the best way to get the element type of an array at 
compile time?


Something like std.range.ElementType except that works on any 
array type. There is std.traits.ForeachType, but it wasn't 
clear if that was the right thing.


--Jon


Why not just use typeof(a[0])

It does not matter if array is empty or not. Typeof does not 
actually evaluate its expression, just the type.


Re: Returning range of inout objects from inout method

2020-07-25 Thread FreeSlave via Digitalmars-d-learn
On Saturday, 25 July 2020 at 14:19:15 UTC, Steven Schveighoffer 
wrote:


The only way to do this without code duplication (but with 
generated code duplication) is to template the byAction 
function on the type of `this`:


auto byAction(this This)() { /* same implementation */ }

Note that this ONLY works if your base range type is an array. 
If you have a custom range type, you need to parameterize that 
based on the constness of `This`.


-Steve


Thanks. I thought this template is useful only in inheritance.
Is constness of member function inferred automatically in this 
case?


Re: Result and Option types

2020-07-25 Thread FreeSlave via Digitalmars-d-learn

On Saturday, 25 July 2020 at 18:06:51 UTC, powerboat9 wrote:

Does dlang have an analog to Result or Option types from rust?


Standard library has std.typecons.Nullable 
https://dlang.org/phobos/std_typecons.html#Nullable


Note that objects are nullable by themselves as classes are 
reference types.


As for Result it's easy to implement using Tuple and writing some 
additional functions.


Returning range of inout objects from inout method

2020-07-25 Thread FreeSlave via Digitalmars-d-learn
I want to be able to return a range of const objects from the 
const object and a range mutable objects from the mutable object.


inout comes to mind, but not applicable in this case, because 
inout must be applied to the return type as whole, which does not 
make much sense for the range. Defining range of inout objects 
does not work too. See the example.


import std.range;
class A
{
string name;
}

class B
{
A[] _actions;
ForwardRange!(inout(A)) byAction() inout { // can't instance 
this type

import std.algorithm : filter;
return inputRangeObject(_actions.filter!(a => a !is null 
&& a.name.length));

}
}

So how can I achieve the intended effect without code 
duplication? (like making separate mutable and const versions of 
the method).


Re: std.process - avoid interaction with parent shell

2020-07-20 Thread FreeSlave via Digitalmars-d-learn
On Monday, 20 July 2020 at 20:55:52 UTC, Steven Schveighoffer 
wrote:


I don't want any user interaction. Occasionally, I get a 
repository that no longer exists (404). Then git comes up and 
asks for a username/password. I want it to just fail. 
Apparently git has no option to be non-interactive, it 
supposedly checks stdin to see if it's a tty, and only errors 
if it's not.



-Steve


Try setting GIT_TERMINAL_PROMPT=0 as an environment variable.


Redundant function calls in filtered joined range

2020-07-18 Thread FreeSlave via Digitalmars-d-learn
Consider the following code. It counts the number of 
subdirectories in directories provided via commandline args.


import std.stdio;
import std.algorithm;
import std.file;
import std.range;
import std.exception;

@trusted bool isDirNothrow(string dir) nothrow
{
bool ok;
collectException(dir.isDir(), ok);
return ok;
}

auto subDirs(Range)(Range searchDirs)
if(is(ElementType!Range : string))
{
return searchDirs
.filter!(isDirNothrow).map!(function(dir) {
return dir.dirEntries(SpanMode.shallow)
.filter!(isDirNothrow);
}).cache().joiner;
}

int main(string[] args)
{
auto r = args[1..$].subDirs;
writefln("Found %s subdirs", count(r));
return 0;
}

Using strace I inspect how many stat calls it uses. Like this:

strace -C -e stat path/to/binary

strace reports some duplicated stat calls, specifically on the 
first provided directory and first subdirectory of each 
directories.


How can I avoid redundant stat calls? Adding array() after each 
filter() removes duplicates but it leads to allocations 
obviously. Changing the cache() to array() before joiner also 
solve the issue.


I suspect there's something wrong in combination of filters and 
joiner.


Re: what am I missing here with that working dir?

2019-03-16 Thread FreeSlave via Digitalmars-d-learn

On Friday, 15 March 2019 at 21:48:50 UTC, DFTW wrote:

What am I missing here?


Maybe the terminal and your utility you run wkhtmltopdf from have 
different environment?


Re: std.process: spawnProcess

2018-09-08 Thread FreeSlave via Digitalmars-d-learn

On Friday, 7 September 2018 at 16:44:09 UTC, Russel Winder wrote:


I guess this might work on Windows, but I am on Linux and OSX, 
so I'll have to try another route.


On Posix systems you may try using SIGCHLD handler. Google for 
exact examples.


Re: std.process: spawnProcess

2018-09-08 Thread FreeSlave via Digitalmars-d-learn

On Friday, 7 September 2018 at 14:36:42 UTC, Russel Winder wrote:
From what I can see, processes created with std.process: 
spawnProcess are not terminated when the creating process 
terminates, i.e. it seems Config.detached is the default for 
these process.


No, detached is not default. By default you should call wait on 
processes to free OS resources. Process may stay as zombie 
otherwise and it can be visible in process manager.


Is there a way of all spawned processes being terminated on 
main termination?


You probably need to register all child processes. Or spawn them 
as detached so you won't need to worry about freeing them.


Re: Convert path to file system path on windows

2018-06-21 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 21 June 2018 at 18:46:05 UTC, Dr.No wrote:

How can I do that with D?

In C# you can do that:

var filename = @"C:\path\to\my\file.txt";
var file = new Uri(filename).AbsoluteUri;
// file is "file:///C:/path/to/my/file.txt"

How can I do that in D?


import std.stdio;
import std.exception;
import core.sys.windows.windows;
import std.windows.syserror;

@safe void henforce(HRESULT hres, lazy string msg = null, string 
file = __FILE__, size_t line = __LINE__)

{
if (hres != S_OK)
throw new WindowsException(hres, msg, file, line);
}

@trusted wstring absoluteUri(string path)
{
import std.path : absolutePath;
import std.utf : toUTF16z;
import core.sys.windows.shlwapi;
import core.sys.windows.wininet;

auto shlwapi = wenforce(LoadLibraryA("Shlwapi"), "Failed to 
load shlwapi");

enforce(shlwapi !is null);
auto urlCreateFromPath = 
cast(typeof())wenforce(shlwapi.GetProcAddress("UrlCreateFromPathW"), "Failed to find UrlCreateFromPathW");

scope(exit) FreeLibrary(shlwapi);
wchar[INTERNET_MAX_URL_LENGTH] buf;
auto size = cast(DWORD)buf.length;
henforce(urlCreateFromPath(path.absolutePath.toUTF16z, 
buf.ptr, , 0));

return buf[0..size].idup;
}

int main(string[] args)
{
foreach(path; args)
{
writeln(absoluteUri(path));
}
return 0;
}



Re: Idiomatic way to add examples to dub package

2018-04-28 Thread FreeSlave via Digitalmars-d-learn

On Friday, 27 April 2018 at 12:37:04 UTC, Basile B. wrote:

On Thursday, 26 April 2018 at 18:16:01 UTC, FreeSlave wrote:
Most dub packages are libraries and should provide runnable 
examples.

What's the current idiomatic way to add examples?


IMO the most simple way (and the best too) is to put single 
file packages in the example folder, so that an example can 
just be run with DUB like that:


`dub example1.d`.

Other good point is that you can specify that the dependency to 
the main package is local, like here: 
https://github.com/BBasile/kheops/blob/master/runnable/actions_window.d#L5.


And finally the example folder is neither polluted with 
sub-folders nor with sub.selection JSON, FTW.


That's probably the best option. No need for using subPackages, 
nor for creating dub.json per every example. And no --root option 
is needed.


Idiomatic way to add examples to dub package

2018-04-26 Thread FreeSlave via Digitalmars-d-learn
Most dub packages are libraries and should provide runnable 
examples.
What's the current idiomatic way to add examples? I used 
sub-packages with dependency on the library and "*" as version 
and running them as dub run :examplename
Now I've noticed vibed uses a different scheme - examples are 
like separate packages that are supposed to ran with --root 
option (if running from the library root directory) and specify 
the dependency with "path" property like here 
https://github.com/vibe-d/vibe.d/blob/master/examples/http_server/dub.json
That involves more typing when running an example but keeps the 
main dub.json independent from examples (no need to specify 
sub-packages)


Also I still don't understand if I need to include 
dub.selections.json in VCS repo. I read somewhere that it should 
be included but vibed examples don't have dub.selections.json. 
E.g. here 
https://github.com/dlang/dub/issues/829#issuecomment-215741874 
jacob-carlborg  said
For applications the dub.selection.json files should be in 
version control, for libraries it should not be


Examples are applications so I thought dub.selections.json should 
be included. But it may be an outdated information.


If there're tutorials on both topics (how to include examples and 
when one should include dub.selections.json in VCS), I would like 
to read them. I could not find any useful info on code.dlang.org 
regarding these issues, while those look like basic issues that 
must be covered in manuals.


Re: Disk space used and free size of a Network share folder in Windows

2018-02-14 Thread FreeSlave via Digitalmars-d-learn

On Wednesday, 14 February 2018 at 15:24:42 UTC, Vino wrote:
On Wednesday, 14 February 2018 at 12:29:13 UTC, rikki 
cattermole wrote:

[...]


Hi Rikki,

   Wouldn't this be easy to use with std.process: execute 
package and calling wmic.exe, the only problem is i am not sure 
hot to get the out put without the headings(Caption  
FreeSpace,Size) any help on same is much appreciated.


import std.process: execute;
import std.stdio : writeln;

void main () {
version(Windows) {
auto result = execute(["wmic.exe", "logicaldisk", "get", 
"size,freespace,caption"]);

writeln(result.output);
}
}
Output :
Caption  FreeSpaceSize
C:   19702837248  180043665408
H:   85580382208  824633720832

From,
Vino.B


Don't call external processes when you can call a function. 
Running another process is overhead and not reliable.


Re: Check whether a file is empty.

2017-12-09 Thread FreeSlave via Digitalmars-d-learn

On Friday, 8 December 2017 at 19:13:20 UTC, vino wrote:


Hi,

 The code is same just copy pasted the code form Windows 7 into 
Windows 2003 and executed, in Windows 7 the log file is of size 
0 where as in windows 2003 the log file is of size 2 byte where 
the log file in both the server is empty.


From,
Vino.B


What do you mean exactly by empty log file? If the file looks 
blank in notepad it does not mean it's empty. What are those 2 
bytes?
Which program does create this file? It may work differently 
depending on the system or different versions are installed.


Re: Check whether a file is empty.

2017-12-08 Thread FreeSlave via Digitalmars-d-learn

On Friday, 8 December 2017 at 09:40:18 UTC, Vino wrote:

Hi All,

  Request your help on how to check whether a given file is 
empty, I tried the getSize from std.file but no luck as in 
windows 7 is the file is empty the size of the file is 0 bytes 
but in Windows 2003 if the file is empty the size of the file 
show as 2 bytes.



From,
Vino.B


Was it the same file on Windows 7 and Windows 2003?
Maybe the file on Windows 2003 had a byte order mark or carriage 
return + newline characters.


Re: Generating DDOX documentation

2017-10-20 Thread FreeSlave via Digitalmars-d-learn

On Friday, 20 October 2017 at 10:47:57 UTC, Andrew Edwards wrote:
Given a documented source file (eg. process.d), I can generate 
the DDOC version of the documentation with the -D switch of DMD 
as such:


$ dmd -Dfprocess.html process.d

What do I modify on that line to get the DDOX version of the 
same file?


Thanks,
Andrew


dmd has no knowledge of ddox. Ddox is a separate program that 
takes a json output of dmd ddoc and generates nicer docs. 
https://github.com/rejectedsoftware/ddox


Example of usage:
dmd -o- -X -Xfdocs.json [list of options that used to build the 
project, including the list of source files...]
/path/to/ddox generate-html --navigation-type=ModuleTree 
docs.json docs/


If you're using dub to build your project, then generating ddox 
documentation as easy as

dub build --build=ddox


Re: spawnProcess: Exit parent process without terminating child process

2017-08-26 Thread FreeSlave via Digitalmars-d-learn

On Friday, 25 August 2017 at 19:55:09 UTC, timvol wrote:

Hi guys,

I want execute a process. I know, I can execute a process using 
"spawnProcess" or "executeShell". But I want exit the parent.


My code for testing purposes is the following:

int main(string[] asArgs_p)
{
if ( (asArgs_p.length >= 2) && asArgs_p[1].isDir() )
{
while(1) {}
}
else
{
import std.process;
spawnProcess([asArgs_p[0], "test"]);
}
return 0;
}

So, starting the application without any parameter, it calls 
"spawnProcess" with an parameter. Now, I want that the parent 
process (the process started without parameter) terminates, 
while the created process remains running.


At the moment, the parent process creates the child and remains 
open (because of the while(1)-loop).


Any ideas how I can exit the parent and keep the child process 
running?


Note that in your particular case the spawnProcess as used now 
should work too. It should run in parallel with its parent. 
Parent will exit and child process will remain. I'm not sure why 
the parent does not exit in your case. When starting this program 
without parameters it will not run into while(1) branch at all.


Re: spawnProcess: Exit parent process without terminating child process

2017-08-26 Thread FreeSlave via Digitalmars-d-learn

On Friday, 25 August 2017 at 19:55:09 UTC, timvol wrote:

Hi guys,

I want execute a process. I know, I can execute a process using 
"spawnProcess" or "executeShell". But I want exit the parent.


My code for testing purposes is the following:

int main(string[] asArgs_p)
{
if ( (asArgs_p.length >= 2) && asArgs_p[1].isDir() )
{
while(1) {}
}
else
{
import std.process;
spawnProcess([asArgs_p[0], "test"]);
}
return 0;
}

So, starting the application without any parameter, it calls 
"spawnProcess" with an parameter. Now, I want that the parent 
process (the process started without parameter) terminates, 
while the created process remains running.


At the moment, the parent process creates the child and remains 
open (because of the while(1)-loop).


Any ideas how I can exit the parent and keep the child process 
running?


Running process in detached state will be available in the future 
versions of Phobos. This functionality has been already merged in 
master https://github.com/dlang/phobos/pull/5483


Until then you may consider to use a third-party library 
https://github.com/FreeSlave/detached


Re: Atomicity of file-copying/moving

2017-05-16 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 16 May 2017 at 08:32:56 UTC, Nordlöw wrote:
What's the status of atomicity of file-copying and -moving 
(renaming) using std.file on different platforms?


Not sure about renaming but copying is not atomic on Posix 
because it does not handle interruption by signal. I opened issue 
about that https://issues.dlang.org/show_bug.cgi?id=17296


Re: Why File is exists in std.stdio and in std.file?

2017-04-25 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 25 April 2017 at 07:05:51 UTC, Suliman wrote:
Just interesting. Is there any rational reasons for this 
decision?


There's no File in std.file. It's located in std.stdio.
std.stdio and std.file are different modules. The first one has 
safe wrappers around stdio.h from C library, the second one 
provides operations on files as unit.


Re: Cleaning up Dub/Dmd builds

2017-04-18 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 18 April 2017 at 17:58:32 UTC, WhatMeWorry wrote:
On Tuesday, 18 April 2017 at 15:15:47 UTC, Stanislav Blinov 
wrote:

On Tuesday, 18 April 2017 at 15:07:27 UTC, WhatMeWorry wrote:

When I try to upload these files to my new repo, GitHub 
(rightfully so) complains that
I have too many files. Since I'm using sdl and not json, can 
I safely delete all the files
that pertain to json?  Can I do this some way at the command 
line?



You shouldn't upload files from the .dub directory, that's 
local build cache that shouldn't  be published. You can simply 
add the .dub directory to your .gitignore file.


Thanks. That seems like an elegant solution.  Sorry if that is 
documented somewhere. I never came across it or didn't 
understand it when I did.


If you create dub project by "dub init" command it automatically 
creates .gitignore file.
Also github provides premade .gitignore files for many 
programming languages ("Add .gitignore" button on Create new 
repository). Those files are from 
https://github.com/github/gitignore repo.


Re: Interfacing C++ to D

2017-04-02 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 2 April 2017 at 16:03:51 UTC, FreeSlave wrote:

On Sunday, 2 April 2017 at 16:02:06 UTC, FreeSlave wrote:

On Sunday, 2 April 2017 at 09:58:19 UTC, ANtlord wrote:

[...]


Now I see. 'Using C++ Classes From D' crashes for me too. It 
also returns the wrong value from 'field' method. Should be 5, 
but it returns 0. Probably regression.


Funny thing: If I replace interface with abstract class, it 
works as it should.


Reported issue: https://issues.dlang.org/show_bug.cgi?id=17293


Re: Interfacing C++ to D

2017-04-02 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 2 April 2017 at 16:02:06 UTC, FreeSlave wrote:

On Sunday, 2 April 2017 at 09:58:19 UTC, ANtlord wrote:

On Saturday, 1 April 2017 at 16:39:28 UTC, FreeSlave wrote:
This page has many examples. Which exactly do you try to run 
and how do you build it? Which compilers, OS?


My bad. I've tested example under caption Using C++ Classes 
From D. I used several combinations of compilers, and no one 
works for me.

OS: ArchLinux
D compilers: DMD 2.073.2, LDC 1.1.0
C++ compiler: gcc 6.3.1, clang 3.9

Also I've created reposotory contains test project. Anyone can 
take a look on that for clearance. 
https://github.com/ANtlord/cpp_to_d_test


Now I see. 'Using C++ Classes From D' crashes for me too. It 
also returns the wrong value from 'field' method. Should be 5, 
but it returns 0. Probably regression.


Funny thing: If I replace interface with abstract class, it works 
as it should.


Re: Interfacing C++ to D

2017-04-02 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 2 April 2017 at 09:58:19 UTC, ANtlord wrote:

On Saturday, 1 April 2017 at 16:39:28 UTC, FreeSlave wrote:
This page has many examples. Which exactly do you try to run 
and how do you build it? Which compilers, OS?


My bad. I've tested example under caption Using C++ Classes 
From D. I used several combinations of compilers, and no one 
works for me.

OS: ArchLinux
D compilers: DMD 2.073.2, LDC 1.1.0
C++ compiler: gcc 6.3.1, clang 3.9

Also I've created reposotory contains test project. Anyone can 
take a look on that for clearance. 
https://github.com/ANtlord/cpp_to_d_test


Now I see. 'Using C++ Classes From D' crashes for me too. It also 
returns the wrong value from 'field' method. Should be 5, but it 
returns 0. Probably regression.


Re: Interfacing C++ to D

2017-04-01 Thread FreeSlave via Digitalmars-d-learn

On Saturday, 1 April 2017 at 07:37:25 UTC, ANtlord wrote:

Hello!

Can somebody give a relevant example shows how to use C++ 
classes in D? I've used the exmaple from 
https://dlang.org/spec/cpp_interface.html but I get a 
segmentation fault as result of D application. My application 
shows "Program exited with code -11"


Thanks.


This page has many examples. Which exactly do you try to run and 
how do you build it? Which compilers, OS?


Re: Cannot spawn process: npm start

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

On Tuesday, 4 October 2016 at 17:02:34 UTC, Adam D. Ruppe wrote:

On Tuesday, 4 October 2016 at 16:55:22 UTC, Andre Pany wrote:
Spawn process is working fine on linux, only on windows it 
doesn't work.

I will create a bug report.


This isn't really a bug if it is a cmd file like the other 
poster said... cmd files are scripts that need to be run 
through the interpreter.


shellExec probably handles it, or you could spawnProcess "cmd" 
with the npm being an argument to it.


There's no shellExec, but executeShell.
spawnShell would fit better since author used spawnProcess in 
original post.


Whether spawnProcess should handle .bat and .cmd is a matter of 
function design really. Actually I would like to treat 
spawnProcess more like double-click on application and 
double-click works for scripts on windows. So there will be no 
special code for phobos user to handle this case.


Re: Cannot spawn process: npm start

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

On Tuesday, 4 October 2016 at 12:58:19 UTC, Andre Pany wrote:

Hi,

I need to call a Node application. node and npm are in windows 
path variable.

I have following folder structure:
./app.d
./js/helloworld.js
./js/package.json

[...]


npm is .cmd file on Windows. Maybe this is issue. Looks like 
cmd.exe knows how to deal with them, while CreateProcess does not.


Re: Get program stats at run time

2016-07-01 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 30 June 2016 at 21:56:57 UTC, Special opOps wrote:
How can I get the program stats at run time such as minimum and 
maximum amount of memory and cpu used, cpu architecture, os, 
etc?


OS is compile-time constant. 
http://dlang.org/phobos/std_system.html#.os


Or do you look for something like detecting that windows 
application is ran actually in wine on some other operating 
system?


For memory and cpu usage detecting I wrote 
https://github.com/MyLittleRobo/resusage a while ago. Currently 
works only on Linux and Windows though.


Re: Recommended coding convention for combining unix and windows code ?

2016-06-07 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 7 June 2016 at 15:33:57 UTC, chmike wrote:

Hello

I'm writing some code that I want to be portable across Posix 
and Windows.


What is the recommended code convention for such type of code ?

80% of the class implementation is the same for both OS.

Should I write the following and copy past the 80%

version( Windows ) {
import core.sys.windows;
class MyInfo {...}
} else version( Posix ) {
import core.sys.posix;
class MyInfo {...}
} else {
static assert(false, "Unsupported platform");
}

or should I do it the C way with multiple embedded static if... 
?


version( Windows ) {
import core.sys.windows;
} else {  //Posix
import core.sys.posix;
}

class MyInfo {
...
static if(windows) {
enum Value {...}
} static else {  //Posix
enum Value {...}
}
...
}


I think there's no need for copy-paste approach in user code when 
the most parts are shared.


Copy-pasting would eventually make classes out of sync in terms 
of function declarations (parameters, attributes) which in its 
turn will lead to unexpected bugs and errors when compiling on 
other platform.
Also copy-pasting of class would require to copy-paste 
documentation comments and unittests, which is another PITA. You 
can write declarations specifically for documentation comments, 
but it means even more copy-pasting and can lead to the situation 
where documentation is out of sync with actual declarations.


By the way phobos has example of copy-paste - DirEntry struct. 
And its functions have different attributes across Windows and 
Posix (e.g. const vs non-const) which really hurts cross-platform 
programming.


Re: What's wrong with my usage of std.algorithm.map in this code example?

2016-05-25 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 24 May 2016 at 20:03:14 UTC, pineapple wrote:
I would've expected this to work, but instead I get a compile 
error. Is my syntax wrong? Is this just not a case that map can 
handle, and I should be doing something else?


import std.algorithm : map;
import std.conv : to;
import std.stdio : writeln;
import std.string : join;

string test(Args...)(in Args items){
immutable string[items.length] itemstrings = 
map!(to!string)(items);

return join(itemstrings, ", ");
}

unittest{
writeln(test(1, 2, 3, 4));
}


Works with 'only', 'array' and static array slicing.

import std.algorithm : map;
import std.range : only;
import std.conv : to;
import std.stdio : writeln;
import std.string : join;
import std.array : array;

string test(Args...)(in Args items){
immutable string[items.length] itemstrings = 
map!(to!string)(only(items)).array;

return join(itemstrings[], ", ");
}

unittest{
writeln(test(1, 2, 3, 4));
}


Linking to library dependent on Objective-C functions

2016-04-30 Thread FreeSlave via Digitalmars-d-learn
I have two files. The one has Objective-C functions and 
interfaces declarations written in D. Another file is main app 
and it imports the first and uses its functions.


Imported file: http://codepad.org/jqdBb6sh
Main file: http://codepad.org/0gKBqKxi

When I compile them in one command it run without problems.
dmd main.d domaindir.d -L-framework -LFoundation

But I want domaindir.d to be static library and link main.d 
against this library. So I do:


dmd -lib domaindir.d
dmd main.d -I. -L-framework -LFoundation domaindir.a

The second command prints warning:

ld: warning: can't parse __DATA/__objc_imageinfo section in 
domaindir.a(domaindir_5_397.o)


When I try to run ./main it fails:

2016-04-30 13:05:55.733 main[15762:685588] *** NSForwarding: 
warning: selector (0x1040f5e58) for message 'defaultManager' does 
not match selector known to Objective C runtime 
(0x7fff8aeed3af)-- abort
2016-04-30 13:05:55.734 main[15762:685588] +[NSFileManager 
defaultManager]: unrecognized selector sent to class 
0x7fff7baaad28
2016-04-30 13:05:55.736 main[15762:685588] *** Terminating app 
due to uncaught exception 'NSInvalidArgumentException', reason: 
'+[NSFileManager defaultManager]: unrecognized selector sent to 
class 0x7fff7baaad28'

*** First throw call stack:
(
	0   CoreFoundation  0x7fff95fab03c 
__exceptionPreprocess + 172
	1   libobjc.A.dylib 0x7fff99ac176e 
objc_exception_throw + 43
	2   CoreFoundation  0x7fff95fadfad 
+[NSObject(NSObject) doesNotRecognizeSelector:] + 205
	3   CoreFoundation  0x7fff95ef3e24 
___forwarding___ + 1028
	4   CoreFoundation  0x7fff95ef3998 
_CF_forwarding_prep_0 + 120
	5   main0x0001040baf58 
D9domaindir9domainDirFNemmbZAya + 56
	6   main0x0001040ba9cb 
_Dmain + 283
	7   main0x0001040d515c 
D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv + 40
	8   main0x0001040d5090 
D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ7tryExecMFMDFZvZv + 36
	9   main0x0001040d5101 
D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZv + 45
	10  main0x0001040d5090 
D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ7tryExecMFMDFZvZv + 36
	11  main0x0001040d4ff6 
_d_run_main + 498
	12  main0x0001040baa80 main 
+ 16
	13  libdyld.dylib   0x7fff92ee25c9 start 
+ 1
	14  ??? 0x0001 0x0 + 
1

)
libc++abi.dylib: terminating with uncaught exception of type 
NSException

Abort trap: 6

Using dmd v2.071.0 on OS X 10.10.5


Re: "inline" conversion of array to immutable

2016-04-22 Thread FreeSlave via Digitalmars-d-learn

On Friday, 22 April 2016 at 11:07:47 UTC, Jeff Thompson wrote:

On Friday, 22 April 2016 at 09:40:14 UTC, FreeSlave wrote:

On Friday, 22 April 2016 at 09:25:32 UTC, Jeff Thompson wrote:
Hello. The following code compiles OK where func creates a 
mutable array and main assigns it to an immutable variable:


[...]


Probably this is what you look for 
http://dlang.org/phobos/std_exception.html#.assumeUnique


OK, we lose the compiler check for correctness. What if I put 
func directly in main with the hopes that the compiler will 
check correctness and also inline the function? But it won't 
assign to the immutable array. Why not? It's the same function.


void main(string[] args) {
  int[] func(int x) pure {
int[] result = new int[10];
result[0] = x;
return result;
  }
  immutable int[] array = func(1);
}


Not sure why, but making func static fixes this:

void main(string[] args) {
  static int[] func(int x) pure {
int[] result = new int[10];
result[0] = x;
return result;
  }
  immutable int[] array = func(1);
}



Re: "inline" conversion of array to immutable

2016-04-22 Thread FreeSlave via Digitalmars-d-learn

On Friday, 22 April 2016 at 09:25:32 UTC, Jeff Thompson wrote:
Hello. The following code compiles OK where func creates a 
mutable array and main assigns it to an immutable variable:


[...]


Probably this is what you look for 
http://dlang.org/phobos/std_exception.html#.assumeUnique


Is it legal to use std.windows modules?

2016-04-08 Thread FreeSlave via Digitalmars-d-learn
std.windows.syserror and others have documentation comments, but 
they are not listed in online documentation on dlang.org. Is it 
ok to use functions and classes from this modules in D 
applications?


Re: Can D interface with Free Pascal?

2016-01-28 Thread FreeSlave via Digitalmars-d-learn
On Thursday, 28 January 2016 at 04:26:26 UTC, Taylor Hillegeist 
wrote:
Just curious... I had a thought that perhaps since Objective C 
was a replacement for Pascal on the mac. that they might have 
the same interface. but I'm not savvy enough with fpc to figure 
out how to try it.


Not directly. You can declare cdecl function on Free Pascal side 
and call it as extern(C).


Re: Distribution of D apps

2016-01-21 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 21 January 2016 at 13:26:15 UTC, W.J. wrote:
On Wednesday, 20 January 2016 at 16:01:11 UTC, Dibyendu 
Majumdar wrote:

Hi,

I am trying to understand the options for distributing a D app 
to users. My assumption is that only the shared libraries and 
binaries need to be distributed, and I need to include the D 
libraries. Is this correct?


Thanks and Regards
Dibyendu


Hi,

On Linux you can use 'ldd' to print shared library dependencies.
On Windows you can use Dependency Walker.
On Mac there's likely a similar program.
Mind also that license terms for distributing libraries apply.


OS X has otool -L

Note that these tools don't show runtime dependencies. Many 
libraries can be loaded at runtime, especially when you use 
derelict-like modules. These libraries in their turn may depend 
on others, etc.


assumeSorted can't access private function when compiling with -debug

2016-01-09 Thread FreeSlave via Digitalmars-d-learn

Here's code:


private {
import std.algorithm;
import std.range;
import std.typecons;
alias Tuple!(int, string) Data;
}

private bool myCmp(Data a, Data b) {
return a[0] < b[0];
}

auto bar() {
return [Data(1, "one"), Data(2, "two")].assumeSorted!myCmp;
}

void main()
{
bar();
}

Build it with -debug and without. It gives me error when building 
with -debug.


/usr/include/dmd/phobos/std/algorithm/sorting.d(154): Error: 
function sorttest.myCmp is not accessible from module sorting


Is it bug?



Re: Regression?

2015-09-08 Thread FreeSlave via Digitalmars-d-learn
On Tuesday, 8 September 2015 at 04:04:16 UTC, Sebastiaan Koppe 
wrote:

Fixed it by changing into:

```
import std.conv : text;
	string json = 
File("../languages.json","r").byLineCopy().joiner.text;

auto ls = json.parseJSON();
```


Why would you read file by line and then merge all into one 
string? You end up with reading the whole file (well, getting rid 
of line ends) anyway, so probably the more efficient solution 
would be just read the whole file at once with std.file.read and 
cast to string.


Using dub configurations with libraries

2015-09-07 Thread FreeSlave via Digitalmars-d-learn

Let's say I have two dub packages: A and B.
A is a library. B is library or application (does not matter) and 
depends on A.


A has several configurations in dub.json.

How to build the B package that way it will use non-default 
configuration of A?


Re: Are there any Phobos functions to check file permissions on Windows and Posix?

2015-09-07 Thread FreeSlave via Digitalmars-d-learn
On Sunday, 6 September 2015 at 23:05:29 UTC, Jonathan M Davis 
wrote:


http://dlang.org/phobos/std_file.html#.getAttributes will get 
you all of the file attributes for a file, though you'll have 
to look at the Windows and POSIX documentation to know how to 
interpret that.


- Jonathan M Davis


It will give you attributes from owner's point of view (i.e. what 
owner can, what users in the same group can, and what all other 
users can)


Not sure if phobos has functions to check if file is readable or 
writable by current user. You can use access on Posix: 
http://linux.die.net/man/2/access


Re: Why ElementType!(char[3]) == dchar instead of char?

2015-09-02 Thread FreeSlave via Digitalmars-d-learn

On Wednesday, 2 September 2015 at 05:00:42 UTC, drug wrote:
02.09.2015 00:08, Jonathan M Davis via Digitalmars-d-learn 
пишет:
On Tuesday, September 01, 2015 20:05:18 drug via 
Digitalmars-d-learn wrote:
My case is I don't know what type user will be using, because 
I write a

library. What's the best way to process char[..] in this case?


char[] should never be anything other than UTF-8. Similarly, 
wchar[] is
UTF-16, and dchar[] is UTF-32. So, if you're getting something 
other than
UTF-8, it should not be char[]. It should be something more 
like ubyte[].
If you want to operate on it as char[], you should convert it 
to UTF-8.
std.encoding may or may not help with that. But pretty much 
everything in D
- certainly in the standard library - assumes that char, 
wchar, and dchar
are UTF-encoded, and the language spec basically defines them 
that way.
Technically, you _can_ put other encodings in them, but it's 
just asking for

trouble.

- Jonathan M Davis

I see, thanks. So I should always treat char[] as UTF in D 
itself, but because I need to pass char[], wchar[] or dchar[] 
to a C library I should treat it as not UTF but ubytes sequence 
or ushort or uint sequence - just to pass it correctly, right?


You should just keep in mind that strings returned by Phobos are 
UTF encoded. Does your C library have UTF support? Is it relevant 
at all? Maybe it just treats char array as binary data. But if it 
does some non-trivial string and character manipulations or talks 
to file system, then it surely should expect strings in some 
specific encoding, and if it's not UTF, you should re-encode data 
before passing from D to this library.


Also C does not have wchar and dchar, but has wchar_t which size 
is not fixed and depends on particular platform.


Re: Decrease number of front evaluations

2015-08-26 Thread FreeSlave via Digitalmars-d-learn

On Wednesday, 26 August 2015 at 08:30:04 UTC, Yazan D wrote:

On Wed, 26 Aug 2015 08:27:05 +, FreeSlave wrote:


Are there ways to fix this? Should I consider writing my own 
range type probably?


Check 
http://dlang.org/phobos/std_algorithm_iteration.html#.cache


I tried it. It can help with map (still calls 2 times though) but 
the number of filter's predicate calls stay the same.


Decrease number of front evaluations

2015-08-26 Thread FreeSlave via Digitalmars-d-learn

Example:

import std.stdio;
import std.algorithm;
import std.path;
import std.file;
import std.exception;
import std.getopt;
import std.array;
import std.range;

auto algo(string fileName, string[] dirs, string[] extensions)
{
return dirs.filter!(delegate(dir) {
bool ok;
collectException(dir.isDir, ok);
return ok;
}).map!(dir = extensions
.map!(delegate(ext) {
string path = buildPath(dir, fileName ~ ext);
writefln(Map: %s, path);
return path;
}).filter!(delegate(filePath) {
bool ok;
writefln(Check: %s, filePath);
collectException(filePath.isFile, ok);
return ok;
})
).joiner;
}

void main(string[] args)
{
string fileName;
string extensionsStr;
getopt(args,
   fileName, file name to search without extension, 
fileName,
   extensions, list of extensions separated by ':', 
extensionsStr

  );

string[] dirs = args[1..$];

if (fileName.empty) {
stderr.writeln(File name not given);
return;
}

if (dirs.empty) {
dirs = [.];
}

string[] extensions = extensionsStr.splitter(':').array;

if (extensions.empty) {
extensions = [.d];
}

foreach(item; algo(fileName, dirs, extensions)) {
writefln(Found: %s, item);
}
}

When I run this it like this (assuming main.d exists):

main --fileName=main

It gives me:

Map: .\main.d
Check: .\main.d
Map: .\main.d
Check: .\main.d
Map: .\main.d
Check: .\main.d
Map: .\main.d
Found: .\main.d

In this simple example it calls map 4 times and filter 3 times. 
The map transformer and filter predicate can be expensive, so I 
would want to avoid redundant front evaluations.


The real code is more complicated and can be found here 
https://github.com/MyLittleRobo/icontheme/blob/master/source/icontheme.d#L427
It can call filter's predicate with the same argument up to 8 
times, which is not nice.


Are there ways to fix this? Should I consider writing my own 
range type probably?




Re: A couple questions about a simple project

2015-08-17 Thread FreeSlave via Digitalmars-d-learn

On Monday, 17 August 2015 at 15:05:56 UTC, Andre Polykanine wrote:

Hi everyone,
I'm  new to D (I'm learning it by reading the great online book 
by Ali
Çehreli  -  thank  you  very  much for it, sir!), and, more 
than that,
programming  is  my hobby, so please bear with me if I'm asking 
stupid

questions.
I've  made  a  toy  project  which  is  a small command-line 
XML files

validator:
https://github.com/Oire/dxv/
and I have a couple questions about it:
1.  I'm  using std.getopt but don't know how to make it display 
a help

message if no options are present at all:
D:\repos\git\dxv\dxv.exe
(nothing   happens   but   I   would  like it to show the help 
as with

--help switch)
2. As you can see, I check whether the file to validate can be 
read. I

tried both `try...catch` and `enforce` (current version:
`string  s  =  enforce(cast(string)std.file.read(f),  Unable  
to read

file);`
),  but  this  very  exception  for  some reason can be caught 
only in

`main()`.
What am I missing?
Thanks!


1. getopt modifies args array leaving not processed arguments in 
it, i.e. name of the program and positional arguments (those 
without leading - or --). If there're no command line arguments 
given, args array will contain the only one element - the name of 
executable. Therefore you can check for args.length == 1 after 
processing by getopt.


2. catch can handle only exception of type specified in its 
argument and derived. std.file.read throws FileException on fail, 
while you catch only CheckException. To cover all cases you can 
catch any exception by using Exception type (it's the base class 
for all exception classes), or write two catch-statements in a 
row for both FileException and CheckException.


You don't need enforce here, unless you want to check if 
std.file.read returns null slice.


Re: How to provide this arg or functor for algorithm?

2015-08-16 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 16 August 2015 at 12:30:54 UTC, cym13 wrote:

On Sunday, 16 August 2015 at 11:53:42 UTC, FreeSlave wrote:

[...]


Ok, so as my lambda proposition obviously doesn't work, here is 
one way that does using a templated function. There may be a 
way to make it shorter, I don't know.



import std.conv;
import std.stdio;

template fun(uint context) {
static uint withContext(uint value) {
return value * context;
}

auto fun(uint[] arr) @nogc {
return arr.map!withContext;
}
}

void main(string[] args) {
[1, 2, 3].to!(uint[])
 .fun!2
 .writeln;
}


It works only because 2 is known constant at compile time.


How to provide this arg or functor for algorithm?

2015-08-16 Thread FreeSlave via Digitalmars-d-learn

Let's say I want to map some range using some context.
The obvious way is to do:

uint[3] arr = [1,2,3];
uint context = 2;
auto r = arr[].map!(delegate(value) { return value * context; });

The problem is that this allocates delegate, so it can't be used 
in @nogc code.

What I want to do might look like this:

static struct Caller
{
this(uint context) @nogc {
_context = context;
}
auto opCall(uint value) @nogc {
return value * _context;
}
uint _context;
}

auto caller = Caller(2);
auto r = arr[].map!(caller.opCall);

But it will not work of course since function must be a 
compile-time parameter.


So the way to go would be:

auto caller = Caller(2);
auto r = arr[].map!(Caller.opCall)(caller);

But map and other algorithms don't support this interface.

The other way is

auto r = arr.map!(Caller(2));

But again, since it's template parameter, it can't use variables 
unknown at compile time:


uint context = ...;
auto r = arr.map!(Caller(context)); //will not work

So what's the solution? Of course besides rewriting the whole 
std.algorithm.


Re: How to provide this arg or functor for algorithm?

2015-08-16 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 16 August 2015 at 16:23:05 UTC, FreeSlave wrote:

On Sunday, 16 August 2015 at 15:29:10 UTC, Ali Çehreli wrote:

On 08/16/2015 04:53 AM, FreeSlave wrote:

 The problem is that this allocates delegate, so it can't be
used in
 @nogc code.

Would constructing the delegate by setting its .funcptr and 
.ptr properties work in this case? You can have a pool of 
context objects which become the context for the delegate.


  http://ddili.org/ders/d.en/lambda.html#ix_lambda..funcptr

Ali


I don't see how this can solve the problem.

What I tried:

import std.stdio;
import std.range;
import std.algorithm;

struct Caller
{
this(uint context) {
_context = context;
}
uint method(uint value) {
return _context * value;
}

uint _context;
}

@nogc auto func(uint[] arr, uint function(uint) f)
{
return arr.map!(f);
}

void main(string[] args)
{
uint[] arr = [1,2,3];
uint context = 2;
auto c = Caller(context);
auto d = c.method;
writeln(func(arr, d.funcptr));
}

It still says it needs allocation:

test.d(17): Error: function test.func @nogc function allocates 
a closure with the GC


funcptr does not play any role here, since passing the delegate 
directly leads to the same error.


Forgot about data ptr.

@nogc auto func(uint[] arr, uint function(uint) f, void* data)
{
uint delegate(uint) d;
d.funcptr = f;
d.ptr = data;
return arr.map!(d);
}

void main(string[] args)
{
uint[] arr = [1,2,3];
uint context = 2;
auto c = Caller(context);
auto d = c.method;
writeln(func(arr, d.funcptr, d.ptr));
}

Still the same error though.


Re: How to provide this arg or functor for algorithm?

2015-08-16 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 16 August 2015 at 15:29:10 UTC, Ali Çehreli wrote:

On 08/16/2015 04:53 AM, FreeSlave wrote:

 The problem is that this allocates delegate, so it can't be
used in
 @nogc code.

Would constructing the delegate by setting its .funcptr and 
.ptr properties work in this case? You can have a pool of 
context objects which become the context for the delegate.


  http://ddili.org/ders/d.en/lambda.html#ix_lambda..funcptr

Ali


I don't see how this can solve the problem.

What I tried:

import std.stdio;
import std.range;
import std.algorithm;

struct Caller
{
this(uint context) {
_context = context;
}
uint method(uint value) {
return _context * value;
}

uint _context;
}

@nogc auto func(uint[] arr, uint function(uint) f)
{
return arr.map!(f);
}

void main(string[] args)
{
uint[] arr = [1,2,3];
uint context = 2;
auto c = Caller(context);
auto d = c.method;
writeln(func(arr, d.funcptr));
}

It still says it needs allocation:

test.d(17): Error: function test.func @nogc function allocates a 
closure with the GC


funcptr does not play any role here, since passing the delegate 
directly leads to the same error.




Re: Environment variable for application storage under OSX ?

2015-07-17 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 16 July 2015 at 21:12:05 UTC, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
version(Win32) p = environment.get(APPDATA);
version(linux) p = /home/ ~ environment.get(USER);
version(OSX) p = ?;
}
---

what would be the OSX equivalent (to get the path where the 
applications data are commonmly stored)?


Hello. You may take a look at this library 
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API 
(which is newer), but it's Objective-C.
Also you may consider standard path for data storage without 
using any api or spec. It's usually $HOME/Library/Application 
Support/ on OSX.


Re: Environment variable for application storage under OSX ?

2015-07-17 Thread FreeSlave via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:33:43 UTC, Anonymous wrote:

On Friday, 17 July 2015 at 07:14:24 UTC, FreeSlave wrote:

On Thursday, 16 July 2015 at 21:12:05 UTC, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
version(Win32) p = environment.get(APPDATA);
version(linux) p = /home/ ~ environment.get(USER);
version(OSX) p = ?;
}
---

what would be the OSX equivalent (to get the path where the 
applications data are commonmly stored)?


Hello. You may take a look at this library 
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API 
(which is newer), but it's Objective-C.
Also you may consider standard path for data storage without 
using any api or spec. It's usually $HOME/Library/Application 
Support/ on OSX.


So for a software named 'SuperDownloader2015'  it would be

$HOME/Library/Application Support/SuperDownloader2015

right ?

so it's not user-specific and it's writable for the current 
user ?

sorry but it looks a bit strange, anyone can confirm ?


It is user specific obviously since it's in user home.
Can you elaborate on what do you want exactly?
From Windows and Linux examples you provided I assumed you need 
user-specific paths (APPDATA is defined per user on Windows). 
System-wide application data path is different.


Re: linking external libs

2015-07-02 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 2 July 2015 at 12:47:52 UTC, Nicholas Wilson wrote:
On Thursday, 2 July 2015 at 12:19:06 UTC, Steven Schveighoffer 
wrote:

On 7/2/15 8:10 AM, Nicholas Wilson wrote:

[...]


Try dmd -v, it will tell you the link line. Then you can try 
it yourself to see how to get it to work. I know dmd has 
problems with link line parameters, because it always puts 
Phobos somewhere. But this is generally for libraries that 
Phobos needs, not user code.


A full example may be useful too.

-Steve


linker command is
gcc test2.o -o test -m64 -L/usr/share/dmd/lib -L/usr/local/lib 
-lgmp -lphobos2 -L/Users/nicholaswilson/d/lib/ -lphobos2 
-lpthread -lm


Are you on OSX? (I consider it from /Users instead of /home) Try 
export LIBRARY_PATH=/usr/local/lib.

Can you build C application linked to libgmp this way?


Re: Calling a cpp function from d

2015-06-16 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

Hi,
I encountered the following error:

Error: function files.SHGetFolderPath (void* hwndOwner, int 
nFolder, void* hToken, uint dwFlags, char* pszPath) is not 
callable using argument types (typeof(null), int, typeof(null), 
int, immutable(char)*)


When I'm try to run this code:
...
{
import std.utf : toUTF8;
static string cache;

wchar[MAX_PATH + 2] buf;

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);

return cache;
}
...
extern(Windows) HRESULT SHGetFolderPath(HWND hwndOwner, int 
nFolder, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath);


I tried everything I know about D and CPP. What can be the 
solution?


I don't know what binding to shell32.dll you use. Probably you 
need set -version=Unicode to compiler flags, so WinAPI aliases 
refer to W variants of functions.


Personally I prefer to call explicitly W or A variants of WinAPI 
functions.

Therefore declaration should look like this:

extern(Windows) HRESULT SHGetFolderPathW(HWND hwndOwner, int 
nFolder, HANDLE hToken, DWORD dwFlags, wchar* pszPath)


Or even better

extern(Windows) @nogc @system HRESULT SHGetFolderPathW(HWND 
hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, wchar* 
pszPath) nothrow


to allow using this function in %nogs nothrow code.

Also you may want to take a look at my library [1] where I use 
SHGetSpecialFolderPath (I know, it's deprecated, but it still 
works, so why not. I don't really need to bother with access 
tokens here).



[1] 
https://github.com/MyLittleRobo/standardpaths/blob/master/source/standardpaths.d#L299


Re: Calling a cpp function from d

2015-06-16 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 13:31:47 UTC, FreeSlave wrote:
Also you may want to take a look at my library [1] where I use 
SHGetSpecialFolderPath (I know, it's deprecated, but it still 
works, so why not. I don't really need to bother with access 
tokens here).


Note that I load shell32 dynamically, so no need to link it while 
building. Even if dmd links to shell32 by default, I'm not sure 
if this is true for gdc and ldc (never used them on win). At 
least, as I remember Mingw does not link to shell32 by default.


Re: What is a mutable method?

2015-05-22 Thread FreeSlave via Digitalmars-d-learn

On Friday, 22 May 2015 at 12:12:46 UTC, tcak wrote:

I know there is mutable variables, but what is a mutable method?

Error message says mutable method 
project.mariadb.connector.ver2p1.resultset.ResultSetColumn.info 
is not callable using a const object.


The method that can change the state of the object.
This kind of error says that you try to call non-const method on 
const object, which is prohibited. You can call only the methods 
marked as const on the const object.


Re: Linking C++ standard library works with GDC... but not DMD. (Linux)

2015-04-16 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 16 April 2015 at 08:51:15 UTC, TheGag96 wrote:

Hi, I've got this project that requires me to link into a C++
backend. It works just fine when using GDC:

gdc *.d [client libraries]

However, this command using DMD does not work:

dmd -L-lstdc++ *.d [client libraries]

I still get errors involving the standard library not being 
added

like:

/usr/include/c++/4.8/iostream:74: undefine reference to
`std::ios_base::Init::Init()'
(etc.)

What do I need to do to make this work? Thanks.


Can't get to linux machine now, but you can try place -L-lstdc++
after source files.


Re: stdout redirect

2015-04-12 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 12 April 2015 at 04:39:06 UTC, Philip Stuckey wrote:

why not:
import std.stdio;
stdout = File(args[4], w+);
stderr = File(args[4], w+);


It just replaces the object, not redirects output. E.g. if you 
use printf somewhere it will use stdout, not file.


Re: Binary search in structs

2015-04-06 Thread FreeSlave via Digitalmars-d-learn

I think I found solution using opBinaryRight

import std.range;

struct S
{
int i;
string s;

int opCmp(int i) {
return this.i - i;
}

int opCmp(ref const S s) {
return this.i - s.i;
}

int opBinaryRight(string op)(int i) if (op == ) {
return i - this.i;
}
}

void main(string [] args)
{
S[] structs = [{1,hello}, {2,world}, {3, !}]; //sorted 
by i


auto sortedRange = assumeSorted(structs);

auto t = sortedRange.trisect(2);
}


Binary search in structs

2015-04-05 Thread FreeSlave via Digitalmars-d-learn
I have array of structs sorted by specific field. How can I 
perform binary search using this field as a key?


Currently I ended up with this, but it gives error:

struct S
{
int i;
string s;
}

import std.range;

void main(string [] args)
{
S[] structs = [{1,hello}, {2,world}, {3, !}]; //sorted 
by i


auto sortedRange = assumeSorted!(function bool(ref const S 
item, int needle) {

return item.i  needle;
})(structs);

sortedRange.trisect(2); //compilation error
}


Re: Binary search in structs

2015-04-05 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 5 April 2015 at 23:15:04 UTC, w0rp wrote:

On Sunday, 5 April 2015 at 23:06:27 UTC, FreeSlave wrote:
I have array of structs sorted by specific field. How can I 
perform binary search using this field as a key?


Currently I ended up with this, but it gives error:

struct S
{
   int i;
   string s;
}

import std.range;

void main(string [] args)
{
   S[] structs = [{1,hello}, {2,world}, {3, !}]; 
//sorted by i


   auto sortedRange = assumeSorted!(function bool(ref const S 
item, int needle) {

   return item.i  needle;
   })(structs);

   sortedRange.trisect(2); //compilation error
}


I believe you have to pass trisect a value of S. So S(2, ) 
would do here, I suppose.


Of course I could pass dummy object, but this is ugly solution. I 
hoped there's some better one.


Re: Loading Symbols from Loaded Libraries

2014-09-01 Thread FreeSlave via Digitalmars-d-learn

On Monday, 1 September 2014 at 13:31:32 UTC, Matt wrote:
If I were to use Runtime.loadLibrary(), it claims to merge any 
D GC in the shared lib with the current process' GC.


Do I need to version away symbol loading code for each platform?
Or is there already code in Phobos that allows us to do this 
independent of platform?


There was high level Library wrapper by Martin Nowak ( 
https://github.com/MartinNowak/druntime/commit/f8f512edea2370759ab75703dceece5e069645be 
), but it seems it was not added to main dmd repository.
So you should use dlsym / GetProcAddress. Use 
core.demangle.mangle to get mangled names of D functions.


I also made some similar wrapper in my project 
https://bitbucket.org/FreeSlave/dido But it was not updated for a 
long time and now it's outdated (code uses dlopen and LoadLibrary 
which is wrong and should be changed to Runtime.loadLibrary. Same 
for dlclose and FreeLibrary)


Re: struct or class

2014-08-24 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 24 August 2014 at 11:56:44 UTC, nikki wrote:
I come from languages that don't offer structs, I have this 
json load function that has to keep some data and intuitively 
I've written a struct, I've read about the differences, heap vs 
stack, value vs reference, but know I think i am overthinking 
it.


Is this decent:
bool loadFromFile (string path)
{
auto data = readText(path);
JSONValue parsed = parseJSON(data);

struct AtlasSpriteData
{
SDL_Rect clipRectangle;
int xOffset;
int yOffset;
}
AtlasSpriteData[string] dict;

foreach( string name, value; parsed[frames] ){
SDL_Rect clipRectangle;
auto spriteSourceSize = 
value[spriteSourceSize];

clipRectangle.x = to!int(frame[x].toString());
clipRectangle.y = to!int(frame[y].toString());
clipRectangle.w = to!int(frame[w].toString());
clipRectangle.h = to!int(frame[h].toString());
int xOffset = to!int(spriteSourceSize[x].toString());
int yOffset = to!int(spriteSourceSize[y].toString());
auto data = AtlasSpriteData(clipRectangle, xOffset, 
yOffset);
dict[name] = data;
}

Or should I use a class for that AtlasSpriteData?
reading about it I get the impression everytime I'll look up 
data from that dictionary data will get copied ?


Your struct instance will occupy only 24 bytes. It's ok even if 
you will copy it. I would avoid heap allocation in this case. 
Also what is 'frame' variable? I don't see local declaration of 
it. Or you just forgot to replace 'value' with 'frame'. Does not 
JSONValue.integer fit in this case instead of 
to!int(JSONValue.toString()) ?


Reading does not perform copy if you access struct directly as 
dict[name].some_field. Copying is performed only if you pass 
struct by value or assign it to variable.


Re: Crash writing and reading back class instance address to void*

2014-08-18 Thread FreeSlave via Digitalmars-d-learn

On Monday, 18 August 2014 at 10:07:30 UTC, Remi Thebault wrote:

Hi

Starting to use GtkD TreeModel, I write an instance of an 
abstract class to TreeIter.userData.


When reading back the void pointer and casting to my abstract 
class leads to crash when instance is used (Task is the 
abstract class):



int fillIter(TreeIter iter, Task t)
{
if (!t || !iter) return 0;

iter.stamp = stamp_;

writeln(writing , cast(void*)t);
iter.userData = cast(void*)t;

return 1;
}


Task taskFromIter(TreeIter iter)
{
if (!iter || iter.stamp != stamp_) return null;

writeln(reading , iter.userData);
writeln(cast(Task)iter.userData);
return cast(Task)iter.userData;
}

the code prints
writing 18FC98
reading 18FC98

and crashes at the 2nd writeln call in taskFromIter function 
with message object.Error@(0): Access violation


The instance is referenced somewhere else in the model, so it 
should not get garbage collected. should I check this anyway?


Any idea?

thanks
Rémi


Classes are reference types. You take reference of local 
reference (it's address on stack). Use just cast(void*)t


Re: extern (c++) std::function?

2014-08-15 Thread FreeSlave via Digitalmars-d-learn

On Friday, 15 August 2014 at 03:10:43 UTC, Etienne Cimon wrote:
I'm looking into making a binding for the C++ API called Botan, 
and the constructors in it take a std::function. I'm wondering 
if there's a D equivalent for this binding to work out, or if I 
have to make a C++ wrapper as well?


There are some restrictions about sharing complex types between 
C++ and D. Currently only POD-structs and classes with virtual 
functions are supported for transparent interaction.


In this case things become even more complicated since 
std::function is template class and D can't instantiate C++ 
templates. You should stick with some predefined signatures and 
make wrappers on C++ side, which will accept 'plane' functions 
and construct std::function.


Re: pointer array?

2014-07-31 Thread FreeSlave via Digitalmars-d-learn
On Wednesday, 30 July 2014 at 20:51:25 UTC, Daniel Kozak via 
Digitalmars-d-learn wrote:

V Wed, 30 Jul 2014 14:33:51 +
seany via Digitalmars-d-learn 
digitalmars-d-learn@puremagic.com

napsáno:

In Ali's excllent book, somehow one thing has escaped my 
attention, and that it the mentioning of pointer arrays.


Can pointers of any type of pointed variable be inserted in an 
int array? Using to!(int) perhaps? If not directly, then what 
else would achieve the same effect?


It depends on pointer size, for eg, on 64bit system with 64bit 
pointers

something like this should works:
long[] arr = (cast(long*)pointersArray.ptr)[0 .. 
pointersArray.length];

or
long[] arr = cast(long[])pointersArray; // but I am not sure if 
this is

OK


Don't use long in this case, use size_t and ptrdiff_t. They are 
required to be integer types with size of pointer (size_t is 
unsigned, ptrdiff_t is signed)


Re: Split class declaration and definition

2014-07-31 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 31 July 2014 at 11:34:38 UTC, Kozzi11 wrote:

Is possible to somehow split class declaration and definition.

I mean something like this:

class C
{
void hello(); // just prototype
}

class C
{
void hello()
{
//actual code
}
}

or something like this
void C.hello() {
//actual code
}


dmd -c -o- -H yourmodule.d

will create .di file (i.e. interface)


Re: Get the default hash function.

2014-07-31 Thread FreeSlave via Digitalmars-d-learn
On Thursday, 31 July 2014 at 12:05:53 UTC, francesco cattoglio 
wrote:

Really simple question:
how do I get the compiler-generated hash function for a given 
type?


For example:
Struct S
{
int i;
}

can be used in an associative array. That means the compiler 
generates a toHash function. Is there any simple way to call 
it directly?


I believe you may use typeid to get TypeInfo instance. It has 
getHash method - http://dlang.org/phobos/object.html#.TypeInfo


Re: Grabing C(++) stdout

2014-07-23 Thread FreeSlave via Digitalmars-d-learn

On Wednesday, 23 July 2014 at 15:35:59 UTC, Chris wrote:

The C++ code does this:

size_t fwrite ( const void * ptr, size_t size, size_t count, 
FILE * stream );

// stream is stdout

and text appears in the console (a string).

I don't how to grab the text that is written to console. I 
might have to redirect it from within the C++ code.


I've created simple example (for Linux) - 
https://bitbucket.org/FreeSlave/redirect-example/src

It works as expected. Nothing writes to console, but to file.


Re: fork/waitpid and std.concurrency.spawn

2014-07-22 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 22 July 2014 at 07:58:50 UTC, Puming wrote:

Is there a fork()/wait() API similar to std.concurrency spawn()?

The best thing I've got so far is module 
core.sys.posix.unistd.fork(), but it seems to only work in 
posix. Is there a unified API for process level concurrency? 
ideally with actor and send message support too.


You need std.process.


Re: How to know whether a file's encoding is ansi or utf8?

2014-07-22 Thread FreeSlave via Digitalmars-d-learn
Note that BOMs are optional and may be not presented in Unicode 
file. Also presence of leading bytes which look BOM does not 
necessarily mean that file is encoded in some kind of Unicode.


Re: fork/waitpid and std.concurrency.spawn

2014-07-22 Thread FreeSlave via Digitalmars-d-learn

On Tuesday, 22 July 2014 at 14:26:05 UTC, Puming wrote:
I've only found spawnProcess/spawnShell and the like, which 
executes a new command, but not a function pointer, like fork() 
and std.concurrency.spawn does.


What is the function that does what I describe?

On Tuesday, 22 July 2014 at 10:43:58 UTC, FreeSlave wrote:

On Tuesday, 22 July 2014 at 07:58:50 UTC, Puming wrote:
Is there a fork()/wait() API similar to std.concurrency 
spawn()?


The best thing I've got so far is module 
core.sys.posix.unistd.fork(), but it seems to only work in 
posix. Is there a unified API for process level concurrency? 
ideally with actor and send message support too.


You need std.process.


I'm not sure what you're trying to do. Posix fork does not just 
spawn function, it spawns new process as copy of its parent and 
continue execution from the point where fork returns.
Windows creates processes in some different way, and it seems 
there is no function with same functionality as Posix fork in 
WinAPI (by the way you can try to find some implementations on 
the Internet / use Cygwin / try to use Microsoft Posix Subsystem).
I think the reason why phobos does not have functionality you 
want is that standard library should be platform-agnostic. So 
instead of emulating things which are not supported by some 
platform, it just truncates them.


Re: DUB help plz

2014-07-03 Thread FreeSlave via Digitalmars-d-learn
Derelict contains bindings to other libraries, not these 
libraries themselves. dub downloads only these bindings, not 
original libraries (since they are written in C, not D, and not 
included in dub repositories). You should manually get necessary 
libraries and put them in folder where .exe will be placed or in 
some path from PATH environment variable, so application would be 
able to find them at runtime.


Re: close program by code

2014-06-26 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 26 June 2014 at 09:05:23 UTC, pgtkda wrote:

How can i close my application by code?


Do you mean exit status? Just call exit function from C library.

import std.c.stdlib;

void main()
{
exit(0);
}


Re: close program by code

2014-06-26 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 26 June 2014 at 11:07:37 UTC, Rene Zwanenburg wrote:

On Thursday, 26 June 2014 at 10:40:00 UTC, John Colvin wrote:

On Thursday, 26 June 2014 at 09:58:50 UTC, FreeSlave wrote:

On Thursday, 26 June 2014 at 09:05:23 UTC, pgtkda wrote:

How can i close my application by code?


Do you mean exit status? Just call exit function from C 
library.


import std.c.stdlib;

void main()
{
  exit(0);
}


Will destructors and/or scope statements be executed if you 
exit this way?


They won't. Same for module destructors.


Module destructors are called. At least in DMD v2.065. I believe 
d runtime automatically register this with atexit function.




Re: Passing around a list of differently typed functions

2014-06-23 Thread FreeSlave via Digitalmars-d-learn

On Monday, 23 June 2014 at 01:16:49 UTC, Evan Davis wrote:
As the subject says, I would like to pass around an array of 
functions. The trick is, that the functions have different type 
signatures. Is there a way to put the two functions


int foo(int a, int b);
bool bar(bool a, bool b);

into one array, that I can pass around and cast as necessary?

Thanks, Evan


You can pass them as pointers, for example cast to void*. But you 
still need correct signature to cast pointer to actual type 
before call function.


dub --annotate option

2014-06-19 Thread FreeSlave via Digitalmars-d-learn

Dub has option called --annotate. It's described like this:

Do not perform any action, just print what would be done

I supposed it's something similar to -n option of Jam build 
system (I really like this feature). But dub's annotate prints 
nothing. So what is that? I have DUB version 0.9.21


Re: Subclass of Exception

2014-06-15 Thread FreeSlave via Digitalmars-d-learn
I don't think you always need documentation for all exception 
classes, since the most of them have the same interface. Usually 
it's worth to describe where is some exception able to be thrown 
from, not exception itself. And it's covered by function 
documentation, not by documentation of exception class.
If you need to just mention exception class in documentation then 
my method is way to go, because you can document alias 
declaration, and mention that it has same interface as Exception 
(not difficult to remember).


Re: Subclass of Exception

2014-06-14 Thread FreeSlave via Digitalmars-d-learn

On Saturday, 14 June 2014 at 11:59:53 UTC, Paul wrote:
One stupid question: in Python subclassing of Exception looks 
like:

  class MyError(Exception): pass
but in D, if I'm right, we should write more code:
  class MyError : Exception {
this(string msg) { super(msg); }
  }
(without constructor we get error: ...Cannot implicitly 
generate a default ctor when base class BASECLASS is missing 
a default ctor...)


Is any shorter D way?


In this regard D is same as C++. When you create derived class, 
you need to define constructors, even if all they do is passing 
arguments to base class' constructor. It's really annoying, 
especially when base class has many constructors.
But in D you can apply some template magic to automate this 
process for exceptions.

Example:

import std.stdio;

template TemplateException(T)
{
class TemplateException : Exception
{
public:
this(string msg, string file = __FILE__, size_t line = 
__LINE__, Throwable next = null) {

super(msg, file, line, next);
}
}
}

void throwException(Exception ex)
{
try {
throw ex;
}
catch(TemplateException!int e) {
writeln(int);
}
catch(TemplateException!double e) {
writeln(double);
}
catch(TemplateException!string e) {
writeln(string);
}
}

int main()
{
auto intEx = new TemplateException!int(int error);
auto doubleEx = new TemplateException!double(double error);
auto stringEx = new TemplateException!string(string error);

throwException(intEx);
throwException(doubleEx);
throwException(stringEx);
return 0;
}

You also can tempalte with string literals instead of types to 
gain more flexibility and use alias statement to provide 
convenient names.


Re: crt1.o: could not read symbols: Bad value

2014-06-11 Thread FreeSlave via Digitalmars-d-learn
It seems like you're trying to compile 64-bit code when you are 
on 32-bit system and you have 32-bit libphobos.


Re: crt1.o: could not read symbols: Bad value

2014-06-11 Thread FreeSlave via Digitalmars-d-learn
I conclude that because I have similar errors when trying to 
build 64-bit library on 32-bit system.


/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(format_712_5b3.o): 
relocation R_X86_64_32 against `.rodata' can not be used when 
making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libphobos2.a: error adding symbols: Bad 
value

collect2: error: ld returned 1 exit status
--- errorlevel 1

But paths in your error log look like you're on x64, so it's 
probably not the case.


Re: crt1.o: could not read symbols: Bad value

2014-06-10 Thread FreeSlave via Digitalmars-d-learn

dmd has -shared option. Try it instead of -L-shared.


Re: Can't link libs?

2014-06-08 Thread FreeSlave via Digitalmars-d-learn

On Friday, 6 June 2014 at 16:33:27 UTC, Adam D. Ruppe wrote:
When you compile the final program, the library .d file needs 
to be available too, either in the folder based on its name or 
passed straight to dmd explicitly.


Despite the presence of the .lib file, the .d file is still 
needed so it can get code prototypes and type names, etc., out 
of it.


(If you have the .d though, the lib is rarely needed. Indeed, 
the way I do most D libraries is to just pass all the .d files 
to the compiler at once and forget about lib files.)


You are not ought to have .d files to link with library, because 
to link you need only interfaces, not implementation (except for 
templates, since they are not included in object files), 
otherwise there would be impossible to create closed-source 
developer libraries. You can generate .di files with dmd -c -o- 
-H option and use them.


Re: why can't I call const methods on shared objects?

2014-05-11 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 11 May 2014 at 07:31:10 UTC, FreeSlave wrote:

On Friday, 9 May 2014 at 21:42:14 UTC, Vlad Levenfeld wrote:

Is this still the case if the method is const or pure?


Const methods still require synchronization, because other 
threads may change some data, needed by const method while 
method is executed, and then you may get wrong results.


Consider:

class Point
{
public:
float x;
float y;


}


I send before I end(

class Point
{
public:
float x;
float y;

Tuple!(float, float) getLengthAndAngle() const
{
float l = sqrt(x*x+y*y);
//other thread change x or y
float a = atan2(x, y);
return tuple(l, a);
}
}



Re: why can't I call const methods on shared objects?

2014-05-11 Thread FreeSlave via Digitalmars-d-learn

On Friday, 9 May 2014 at 21:42:14 UTC, Vlad Levenfeld wrote:

Is this still the case if the method is const or pure?


Const methods still require synchronization, because other 
threads may change some data, needed by const method while method 
is executed, and then you may get wrong results.


Consider:

class Point
{
public:
float x;
float y;


}


Re: Configuring Phobos from the 1-click installer

2014-05-11 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 11 May 2014 at 05:34:38 UTC, Moses wrote:

On Sunday, 11 May 2014 at 04:33:24 UTC, Ali Çehreli wrote:

On 05/10/2014 07:12 PM, Moses wrote:
After using the 1-click Ubuntu installer, I'm having trouble 
figuring
out how to import standard library functions for Phobos. I 
get the message:


Error: module io is in file 'std/std/io.d' which cannot be 
read


Judging from the repeated stds up there I think you put a dot 
before io:


import std.std.io;  // -- WRONG

The second dot should not be there. Do this instead:

import std.stdio;  // -- correct

Ali



Thanks, I also found that I need to include the flag 
-I/usr/include/dmd/phobos to get it to compile. I tried doing:


export PATH=$PATH:/usr/include/dmd/phobos

but apparently I still need the -I flag. Is there another way 
to get around this?


Does your /etc directory contain dmd.conf file? You can add 
standard flags there


Example of dmd.conf:

[Environment]
DFLAGS=-I/usr/include/dmd/phobos 
-I/usr/include/dmd/druntime/import


Re: Temporary silence output (stdout)

2014-05-11 Thread FreeSlave via Digitalmars-d-learn

On Saturday, 10 May 2014 at 20:24:50 UTC, MarisaLovesUsAll wrote:

Hi!
I sometimes got a useless messages in stdout from SDL_Image
library, and I want to temporary silence it. How do I do?


You can temporary redirect output to file. Example (on C):

#include stdio.h
#include unistd.h
#include fcntl.h

int main ()
{
int stdout_copy = dup(STDOUT_FILENO);

close (STDOUT_FILENO);

int stdout_file = creat(myfile.txt, O_RDWR); //it obtains 
the lowest free descriptor - 1, i.e. stdout.

printf(Hello file\n);
fflush(stdout); //don't forget to flush
close(stdout_file);

dup2(stdout_copy, STDOUT_FILENO);
printf(Hello console\n);
return 0;
}

But it's not very portable, you probably will need to write 
something other for Windows system. And there are no checks for 
errors in this example.


Also in SDL specific case it seems like it should redirect by 
default - http://sdl.beuc.net/sdl.wiki/FAQ_Console but I don't 
know whether it's true or not for SDL_Image.


Re: Messy code in console

2014-05-11 Thread FreeSlave via Digitalmars-d-learn

On Sunday, 11 May 2014 at 07:43:07 UTC, Kagamin wrote:

Known bug https://issues.dlang.org/show_bug.cgi?id=2742


It's not bug. Write-functions are designed to output text to 
stdout, and it's issue of programmer to make sure that expected 
acceptor can interpret them properly. Note that stdout may be 
redirected to file or be part of pipe, that does nothing with cmd 
console.


Re: Get and set terminal size

2014-04-19 Thread FreeSlave via Digitalmars-d-learn
What are compiler and platform do you use? Probably you are 
trying to link with 64-bit library while being on 32-bit OS (or 
vice versa)

It works fine on my 32-bit Debian with ldc2 and dmd.


  1   2   >