Templated class requires values even though having default value

2021-05-09 Thread tcak via Digitalmars-d-learn
	public class OpenCLKernel(size_t dim = 1) if( (dim >= 1) && (dim 
<= 3) )

{
public this( OpenCLProgram program, in string kernelName )
{
// ...
}
}

I have a class definition as above. When I want to create an 
instance as below,


OpenCLKernel k = new OpenCLKernel( program, "kernelName" );

compiler tells me,

	/test2.d(168): Error: template class `OpenCLKernel(ulong dim = 
1) if (dim >= 1 && (dim <= 3))` is used as a type without 
instantiation; to instantiate it use `OpenCLKernel!(arguments)`



The "dim" template parameter has a default value of 1 already. 
Why does it still force me to give a value?


(DMD64 D Compiler v2.096.0)


Re: String concatenation segmentation error

2021-04-22 Thread tcak via Digitalmars-d-learn

On Friday, 23 April 2021 at 00:30:02 UTC, Adam D. Ruppe wrote:

On Thursday, 22 April 2021 at 21:15:48 UTC, tcak wrote:
"positions" array is defined as auto positions = new float[ 
100 ]; So, I am 100% sure, it is not out of range. "ri*dim + 
1" is not a big number at all.


Oh and *where* is that positions variable defined?


I am doing OpenCL programming. CPU side is single threaded.

As far as I see, it is not related to that array or indices at 
all. After running for a short time, if a piece of code does any 
string/char or byte array concatenation at all, all of them cause 
segmentation fault with error:


_D2gc4impl12conservativeQw3Gcx10smallAllocMFNbmKmkxC8TypeInfoZPv 
()


When I comment out those piece of codes, there is no error.

If there is no known situation that would cause this, I will need 
to update codes to C-style pre-allocate buffer and copy inside it 
instead of concatenating data.


Re: String concatenation segmentation error

2021-04-22 Thread tcak via Digitalmars-d-learn
In other parts of the code, concatenation operations are all 
failing with same error. I need guidance to get out of this 
situation. My assumption was that as long as there is empty heap 
memory, concatenation operation would succeed always. But, it 
doesn't seem like so.


String concatenation segmentation error

2021-04-22 Thread tcak via Digitalmars-d-learn

string fileContent = "";

...

writeln(ri, ": debug 1");
foreach(i; 0..dim)
{
if( i > 0 ){ fileContent ~= "\t"; }

	writeln(ri, ": debug 1.1: ", ri*dim + i, ": ", positions[ ri*dim 
+ i ]);


fileContent ~= to!string(positions[ ri*dim + i ]);

	writeln(ri, ": debug 1.2: ", ri*dim + i, ": ", positions[ ri*dim 
+ i ]);

}

-

On line "fileContent ~= ...", I get a segmentation fault.

"positions" array is defined as auto positions = new float[ 100 
]; So, I am 100% sure, it is not out of range. "ri*dim + 1" is 
not a big number at all.


...
4: debug 1.1: 9: 0.271075
4: debug 1.2: 9: 0.271075
4: debug 2
4: debug 2.1: 4
4: debug 3
4: debug 4
5: debug 1
5: debug 1.1: 10: 0.884978
5: debug 1.2: 10: 0.884978
5: debug 1.1: 11: 0.813104
Segmentation fault
...

I have compiled the code with "-g" flag and ran it with GNU 
debugger. It gives following:


Thread 1 "dataspace" received signal SIGSEGV, Segmentation fault.
0x556ca286 in 
_D2gc4impl12conservativeQw3Gcx10smallAllocMFNbmKmkxC8TypeInfoZPv 
()



So, there is a problem about small allocation. I remember I had 
this problem before in another project.


I have enough free ram. htop shows 3.96 GiB of 8 GiB is used only 
and swap is not in use.


DMD64 D Compiler v2.094.0

Is this error related to me? Is it a programmer error? Is it a 
bug? Am I doing something wrong? This is a compiler related 
operation (string concatenation), and I assume/expect that it 
would work without a problem.


Re: Read X many bytes from File to address Y

2021-04-07 Thread tcak via Digitalmars-d-learn

On Wednesday, 7 April 2021 at 12:50:01 UTC, Adam D. Ruppe wrote:

On Wednesday, 7 April 2021 at 11:42:56 UTC, tcak wrote:
There is rawRead, but it takes an array as parameter, which 
causes a dirty looking code with cast etc!


What did you wrote?


file.rawRead(address[0 .. desiredLength])


should do what you want.


Well, I have a struct, that is defined as a variable already. I 
want to read X bytes from the file (not Struct.sizeof bytes 
though), and read into the struct variable without any extra 
buffer.


Don't allow to reassign, but content is editable

2021-04-07 Thread tcak via Digitalmars-d-learn
In javascript, with "const" keyword, you assign an object to a 
variable. Later, you cannot assign anything else to that 
variable, but content of it still can be changed. No matter by 
using "immutable" or "const", I cannot imitate that. Is there a 
way to do this without an overhead (like calling a function to 
create a pointer)?


Example:

class Test
{
public int[] a;

public this(){ a = new int[5]; }

@property auto b(){ return a.ptr; }  // this is a 
possibility, but results with overhead of calling. Also, b is not 
an array anymore, just int*.

}

I want this to be possible:
test.a[3] = 7;

But this wouldn't be allowed:
test.a = new int[14];



Read X many bytes from File to address Y

2021-04-07 Thread tcak via Digitalmars-d-learn

I am talking about std.file.File.

I have opened the file, and at a specific offset.

I want to read X many bytes from the file, and want it to be 
written to given address directly without any Magical D-stuff 
like ranges etc.


Is there a way to do this without getting into C or Posix header 
files?


There is rawRead, but it takes an array as parameter, which 
causes a dirty looking code with cast etc!


Include http based module

2021-02-19 Thread tcak via Digitalmars-d-learn

I have written a test module and put it into /var/www/html:

module mymodule;

import std.stdio;

void testMe(){ writeln("I tested you!"); }


Then I have a main file where I would like to call the function 
"testMe".



My build line is as follows:

dmd main.d "http://localhost/mymodule.d";


Result:

Error: module mymodule is in file 'http://localhost/mymodule.d' 
which cannot be read

import path[0] = /usr/include/dmd/phobos
import path[1] = /usr/include/dmd/druntime/import


Is there any way to include http(s) based modules into 
compilation (Please do not suggest dub etc)?


New with alias

2020-03-09 Thread tcak via Digitalmars-d-learn

I write a code as below:

auto result = new char[4];

It allocates memory as expected.



Later I define an alias and do the above step:

alias Pattern = char[4];

auto result = new Pattern;

But compiler says:
Error: new can only create structs, dynamic arrays or class 
objects, not `char[4]`'s




Is this a bug, or `alias` doesn't work how I was thinking?


Re: Alias of template class

2019-11-30 Thread tcak via Digitalmars-d-learn

On Saturday, 30 November 2019 at 09:39:59 UTC, tcak wrote:

I defined a class:

class KNN(size_t k){}


I want to define an alias for KNN when k=5,

alias KNN5 = KNN!5;


So that I could define a variable as

KNN5 knnObject;


Then create it later as

knnObject = new KNN5();


But the compiler gives error for the alias line:

Error: template instance KNN!5 KNN is not a template 
declaration, it is a class



What is the way accomplishing this?


My mistake. It works.


Alias of template class

2019-11-30 Thread tcak via Digitalmars-d-learn

I defined a class:

class KNN(size_t k){}


I want to define an alias for KNN when k=5,

alias KNN5 = KNN!5;


So that I could define a variable as

KNN5 knnObject;


Then create it later as

knnObject = new KNN5();


But the compiler gives error for the alias line:

Error: template instance KNN!5 KNN is not a template declaration, 
it is a class



What is the way accomplishing this?


Re: String Comparison Operator

2017-04-30 Thread tcak via Digitalmars-d-learn

On Sunday, 30 April 2017 at 15:31:39 UTC, Jolly James wrote:

Is there a String Comparison Operator in D?


You normally use double equation marks (==) to do that.

auto name = "Jack";
if( name == "Jack" ) writeln("Hi Jack!");


Get list of public methods of struct

2017-03-09 Thread tcak via Digitalmars-d-learn

Is there any way to get list of public methods of a struct?

I looked at both "traits" and "std.traits".

getVirtualFunctions and getVirtualMethods are closest I guess, 
but they don't seem like general purpose due to "Virtual" part. 
(Wouldn't it work if a method was final?)


I saw "FieldNameTuple" in std.traits, but that doesn't seem like 
a proper solution.


I want to use a mixin and foreach to generate a piece of code, 
that selects which method to call based on given parameter. So, 
the generated code will be like,


if( param == "woof" )
myStruct.woof();
else if( param == "meow" )
myStruct.meow();

woof and meow are the methods of defined struct.


Re: Referring to array element by descriptive name

2017-01-14 Thread tcak via Digitalmars-d-learn

On Saturday, 14 January 2017 at 15:11:40 UTC, albert-j wrote:
Is it possible to refer to an array element by a descriptive 
name, just for code clarity, without performance overhead? E.g.


void aFunction(double[] arr) {
double importantElement = arr[3];
... use importantElement ...
}

But the above, I suppose, introduces an extra copy operation?


Unless the item type of that array is a complex like a big 
struct, copying basic types won't have much effect at all. You 
wouldn't notice it.


You could point to that element with a pointer:

double* importantElement = &arr[3];

But then you are going to define that pointer variable anyway. On 
top of that, for every access, instead of using the available 
data, CPU would look at the pointed memory address to get the 
value again and again (ignoring the cache).


Creating shared library on Monodevelop with MonoD, Implib problem

2016-11-18 Thread tcak via Digitalmars-d-learn
I am on Ubuntu. I try to create a very basic (one empty function 
declaration) shared library for testing.


MonoD (version 2.14.5), generates a command line similar to 
following:


dmd -debug -gc "myclass.d"  "-I/usr/include/dmd" 
"-L/IMPLIB:/home/user/Projects/Router/bin/Debug/libRouter.a" 
"-odobj/Debug" 
"-of/home/user/Projects/Router/bin/Debug/libRouter.so" -fPIC 
-defaultlib=libphobos2.so


/usr/bin/ld: cannot find 
/IMPLIB:/home/user/Projects/Router/bin/Debug/libRouter.a: No such 
file or directory


collect2: error: ld returned 1 exit status
Error: linker exited with status 1


I don't understand why it is trying to link the project with 
libRouter.a. Am I missing something?


Re: Real Simple Question?

2016-10-25 Thread tcak via Digitalmars-d-learn

On Saturday, 22 October 2016 at 21:34:36 UTC, WhatMeWorry wrote:
On Saturday, 22 October 2016 at 20:51:14 UTC, Jonathan M Davis 
wrote:

[...]


Ok, but now I'm getting these error in my new 
mypackage/constants.d


..\common\vertex_data.d(5,15): Error: undefined identifier 
'GLfloat'
..\common\vertex_data.d(53,12): Error: undefined identifier 
'vec3'


Is there a way to just suck in the text from say a .txt file 
that would not be compiled before inclusion in main.d?


You could format your array in JSON format, and read it in your 
program. That could be another solution.


Posix access function

2016-10-18 Thread tcak via Digitalmars-d-learn
Checked std.stdio, std.file, std.path, couldn't have found anyway 
to check permissions on a file for read, write, execute.


Without getting into core module, does it exist anywhere in std 
module?


Re: Programming in D by Ali Çehreli

2016-10-17 Thread tcak via Digitalmars-d-learn

On Monday, 17 October 2016 at 18:20:00 UTC, cym13 wrote:

On Monday, 17 October 2016 at 18:10:01 UTC, vino wrote:

[...]


I don't see what you don't understand, you said it yourself: 
"neither the slice nor its elements can be modified". So you 
can't modify the elements  of an immutable array. immSlice is 
an immutable array of which you are trying to modify an element.


I would expect him to see the first error on `immSlice ~= 3;`.


Re: Cannot link with libphobos2.a with GCC 6.2 on Ubuntu 16.10

2016-10-16 Thread tcak via Digitalmars-d-learn

On Sunday, 16 October 2016 at 22:36:15 UTC, Nordlöw wrote:

On Sunday, 16 October 2016 at 22:00:48 UTC, Nordlöw wrote:

Which flag(s) in `src/posix.mak` did you change?


Does

make -f posix.mak MODEL_FLAG=-fPIC

work?

I'm sitting on a 16.04 system right now (which I don't dare to 
upgrade until this is fixed) so I'm just guessing.


Well, I haven't made any changes anywhere at all. I always 
download the deb file and install it. My program was compiling on 
16.04, and wasn't compiling on 16.10.


So, I added

-defaultlib=libphobos2.so -fPIC

while compiling. That's it. But as you can guess, now I have to 
copy the libphobos on other computers as well as the executable. 
(libphotos2.so.0.71 is 9 MiB)


Re: Cannot link with libphobos2.a with GCC 6.2 on Ubuntu 16.10

2016-10-16 Thread tcak via Digitalmars-d-learn

On Sunday, 16 October 2016 at 17:42:44 UTC, tcak wrote:

On Thursday, 13 October 2016 at 17:02:32 UTC, Nordlöw wrote:

[...]


I have upgraded my Ubuntu to 16.10 yesterday as well, and I am 
getting following error:


/usr/bin/ld: obj/Debug/program.o: relocation R_X86_64_32 
against symbol `_D9Exception7__ClassZ' can not be used when 
making a shared object; recompile with -fPIC
/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(object_1_257.o): 
relocation R_X86_64_32 against symbol `__dmd_personality_v0' 
can not be used when making a shared object; recompile with 
-fPIC

...

I guess the problem is same. Even though I have added 
"-defaultlib=libphobos2.so" to compiler options, problem 
persists.


Hmm. As the error message says, I compiled the program by adding 
"-fPIC", it really has stopped giving error messages. That came 
to me weird.


Re: Speed of synchronized

2016-10-16 Thread tcak via Digitalmars-d-learn
On Sunday, 16 October 2016 at 08:41:26 UTC, Christian Köstlin 
wrote:

Hi,

for an exercise I had to implement a thread safe counter. This 
is what I came up with:


[...]


Could you try that:

class ThreadSafe3Counter: Counter{
  private long counter;
  private core.sync.mutex.Mutex mtx;

  public this() shared{
mtx = cast(shared)( new core.sync.mutex.Mutex );
  }

  void increment() shared {
(cast()mtx).lock();
scope(exit){ (cast()mtx).unlock(); }

core.atomic.atomicOp!"+="(this.counter, 1);
  }

  long get() shared {
return counter;
  }
}


Unfortunately, there are some stupid design decisions in D about 
"shared", and some people does not want to accept them.


Example while you are using mutex, so you shouldn't be forced to 
use atomicOp there. As a programmer, you know that it will be 
protected already. That is a loss of performance in the long run.


Re: Cannot link with libphobos2.a with GCC 6.2 on Ubuntu 16.10

2016-10-16 Thread tcak via Digitalmars-d-learn

On Thursday, 13 October 2016 at 17:02:32 UTC, Nordlöw wrote:
I just upgraded my Ubuntu to 16.10 and now my rebuilding of dmd 
from git master fails as


/usr/bin/ld: idgen.o: relocation R_X86_64_32 against symbol 
`__dmd_personality_v0' can not be used when making a shared 
object; recompile with -fPIC
/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(object_a_66e.o): 
relocation R_X86_64_32 against symbol `__dmd_personality_v0' 
can not be used when making a shared object; recompile with 
-fPIC


What's wrong?

Am I using the wrong GCC version? Should I use GCC 5 instead?

GCC 6.2 is default on 16.10.


I have upgraded my Ubuntu to 16.10 yesterday as well, and I am 
getting following error:


/usr/bin/ld: obj/Debug/program.o: relocation R_X86_64_32 against 
symbol `_D9Exception7__ClassZ' can not be used when making a 
shared object; recompile with -fPIC
/usr/bin/ld: 
/usr/lib/x86_64-linux-gnu/libphobos2.a(object_1_257.o): 
relocation R_X86_64_32 against symbol `__dmd_personality_v0' can 
not be used when making a shared object; recompile with -fPIC

...

I guess the problem is same. Even though I have added 
"-defaultlib=libphobos2.so" to compiler options, problem persists.


Re: Anonymous class

2016-10-12 Thread tcak via Digitalmars-d-learn

On Wednesday, 12 October 2016 at 11:56:21 UTC, tcak wrote:
I feel like I remember that this was added to D a while ago, 
but I am not sure. Is it possible to create anonymous classes?


public interface Runnable{
void run();
}


runIt( new Runnable(){
void run(){
/* do stuff */
}
});

I want to do this without making the things any complex.


Hmm. Yeah, after playing around, and some clues from net search. 
I found it.


runIt( new class Runnable{
 void run(){
 /* do stuff */
 }
});



Anonymous class

2016-10-12 Thread tcak via Digitalmars-d-learn
I feel like I remember that this was added to D a while ago, but 
I am not sure. Is it possible to create anonymous classes?


public interface Runnable{
void run();
}


runIt( new Runnable(){
void run(){
/* do stuff */
}
});

I want to do this without making the things any complex.


Re: Module Clarification

2016-09-21 Thread tcak via Digitalmars-d-learn
On Wednesday, 21 September 2016 at 14:17:56 UTC, Jonathan Marler 
wrote:
I'm working on a code generation tool and wanted to make sure 
my module approach was correct.  The generated code has a 
module hierarchy, where modules can appear at any level of the 
hierarchy.


module foo;
module foo.bar;

In this case, module foo and foo.bar are independent modules.  
The foo module does not publicly import foo.bar, like a typical 
package.d module would do. At first I organized the modules 
like this:


foo.d (module foo)
foo/bar.d (module foo.bar)

But this doesn't work because the module file foo.d, cannot 
have the same name as a the directory foo.  So now I organize 
it like this:


foo/package.d (module foo)
foo/bar.d (module foo.bar)

This is not the typical usage for the "package.d" file.  
Normally, package.d would publicly import other modules, 
however, in this case, package.d is an independent module.  
This also means that if another module was added, say 
foo.bar.baz, the new file system would have to look like this:


foo/package.d (module foo)
foo/bar/package.d (module foo.bar)
foo/bar/baz.d (module foo.bar.baz)

This technique seems a bit odd, but it works.  I'm just 
wondering if there's a better way to achieve these semantics, 
or if this is the appropriate solution?


I can be wrong, but if I remember correctly, when I used 
package.d as you do a while ago (~1.5 years ago), it was acting a 
little different compared to a normal module file. Some 
declarations were not working as in a normal module. It could be 
my bad observation as well. I hope it works for you, but your 
design might break at some point.


Re: Program locked at joinAll and sched_yield

2016-07-03 Thread tcak via Digitalmars-d-learn

On Sunday, 3 July 2016 at 17:19:04 UTC, Lodovico Giaretta wrote:

On Friday, 1 July 2016 at 12:02:11 UTC, tcak wrote:
I have my own Http Server. Every request is handled by a 
thread, and threads are reused.


I send 35,000 request (7 different terminals are sending 5000 
requests each) to the server again and again (each of them 
lives for short).


Anyway, everything works great, there is no problem at all.

I put "readln" in main function. So, when I press enter, all 
currently idle threads are stopped. (I use thread.join()).


Problem is that, all threads are stopped, by the last thread 
Thread#1 gets locked at sched_yield(), it uses one of CPU 
cores at 100%, and program never quits and stays there.


There is only one remaining thread at the end, and below is 
its stack trace.


sched_yield() in 
/build/glibc-GKVZIf/glibc-2.23/posix/../sysdeps/unix/syscall-template.S:84


thread_joinAll() in

rt_term() in

rt.dmain2._d_run_main(int, char**, extern(C) int(char[][]) 
function).runAll()() in


rt.dmain2._d_run_main(int, char**, extern(C) int(char[][]) 
function).tryExec(scope void() delegate)() in


_d_run_main() in

main() in

__libc_start_main(int (*)(int, char **, char **) main, int 
argc, char ** argv, int (*)(int, char **, char **) init, void 
(*)(void) fini, void (*)(void) rtld_fini, void * stack_end) in 
/build/glibc-GKVZIf/glibc-2.23/csu/../csu/libc-start.c:291


_start() in


Is there any known issue about this? or anything that is known 
to cause this problem?


Hi!

Can you provide a reduced test case that shows the issue? 
Without any code, it's difficult to tell what's going on.


Well, I actually have found out about the issue, and solved it a 
different way.


I put memory limit on the process for testing.

At some point, due to memory limitation, thread.start() method 
fails. But, this method cannot recover the system correctly, and 
Phobos thinks that thread has been started correctly.


This happens, if I understand correctly, due to the value of 
variable "nAboutToStart" in core.thread, line 685. Its value is 
increase here, and is decreased by 1 in "add" function on line 
1775. When start() fails, add() is not called for it ever, and 
thread_joinAll() on line 2271 gets into an endless loop. There 
by, the program cannot quit, and loop starts using 100% CPU.


---

What I did to solve this issue is that I created my thread by 
using pthread_create() function, and called thread_attachThis(). 
This way, problem is prevented.


---

As a solution, when thread creation is failed in start() method, 
we should decrease the value of "nAboutToStart" by 1, but it 
seems like "pAboutToStart" needs to be touched to recover the 
system properly. Fortunately there is not much code in the 
start() method.


Program locked at joinAll and sched_yield

2016-07-01 Thread tcak via Digitalmars-d-learn
I have my own Http Server. Every request is handled by a thread, 
and threads are reused.


I send 35,000 request (7 different terminals are sending 5000 
requests each) to the server again and again (each of them lives 
for short).


Anyway, everything works great, there is no problem at all.

I put "readln" in main function. So, when I press enter, all 
currently idle threads are stopped. (I use thread.join()).


Problem is that, all threads are stopped, by the last thread 
Thread#1 gets locked at sched_yield(), it uses one of CPU cores 
at 100%, and program never quits and stays there.


There is only one remaining thread at the end, and below is its 
stack trace.


sched_yield() in 
/build/glibc-GKVZIf/glibc-2.23/posix/../sysdeps/unix/syscall-template.S:84


thread_joinAll() in

rt_term() in

rt.dmain2._d_run_main(int, char**, extern(C) int(char[][]) 
function).runAll()() in


rt.dmain2._d_run_main(int, char**, extern(C) int(char[][]) 
function).tryExec(scope void() delegate)() in


_d_run_main() in

main() in

__libc_start_main(int (*)(int, char **, char **) main, int argc, 
char ** argv, int (*)(int, char **, char **) init, void (*)(void) 
fini, void (*)(void) rtld_fini, void * stack_end) in 
/build/glibc-GKVZIf/glibc-2.23/csu/../csu/libc-start.c:291


_start() in


Is there any known issue about this? or anything that is known to 
cause this problem?


Re: shared Mutex?

2016-06-09 Thread tcak via Digitalmars-d-learn

On Thursday, 9 June 2016 at 18:31:16 UTC, cy wrote:
I was thinking of using threads in a D program (ignores 
unearthly wailing) and I need 1 thread for each unique string 
resource (database connection info). So I did this:


shared BackgroundDB[string] back;

I don't see any way to make less data shared there. If it 
weren't shared, it would be thread local, and two application 
threads trying to look up the same database would end up firing 
off two BackgroundDB threads, since they had separate copies of 
"back" that could not share keys. So it pretty much has to be 
shared. But that means freaking /everything/ has to be shared.


In the dedicated thread, I had it repeatedly waiting on a 
condition, and once that condition is signaled, it removes 
what's been queued up, and processes those queued items in the 
database. Except for one problem... conditions can't be shared.


Error: non-shared method core.sync.condition.Condition.mutex 
is not callable using a shared object


Obviously you shouldn't need mutexes if you're using shared... 
but how do you do conditions, then?


When I do something like this:

struct BackgroundDB {
  Condition stuff_ready;
  ...
}

Condition is implicitly converted to shared(Condition) when I 
create a shared(BackgroundDB), and BackgroundDB is implicitly 
converted to shared(BackgroundDB) when I have a shared 
BackgroundDB[string]. But shared(Condition) then has a 
shared(Mutex) inside it, and that can't be locked, since 
Mutex.lock is a non-shared function.


Is core.sync.mutex.Mutex even usable in D anymore? It seems 
every mutex that wasn't shared would be part of thread local 
data, so two threads locking on the same mutex would actually 
be locking separate mutexes.


Mutex, Condition, and Thread classes should be defined as shared 
as you experience, but they are not unfortunately. What you need 
to do is the define them as shared, and while calling their 
method, remove shared from them. Example is below:


class MyClass{
private core.sync.mutex.Mutex mx;

public this() shared{
mx = cast(shared)( new core.sync.mutex.Mutex() );

(cast()mx).lock();

... etc.
}
}


Base64 of String without casting

2016-06-01 Thread tcak via Digitalmars-d-learn
I understand that Base64 uses Ranges, and since String is seen 
and used as unicode by Ranges (please tell me if I am wrong).


I am guessing, for this reason, auto btoa = 
std.base64.Base64.encode("Blah"); doesn't work. You need to be 
casting the string to ubyte[] to make it work which doesn't look 
and feel nice at all.


Can/shall we add another alias into the module for encode method, 
so it accepts a string, and casts it to ubyte[] by itself?





Re: Is there a 128-bit integer in D?

2016-05-22 Thread tcak via Digitalmars-d-learn

On Saturday, 21 May 2016 at 09:56:51 UTC, Stefan Koch wrote:

On Saturday, 21 May 2016 at 09:43:38 UTC, Saurabh Das wrote:
I see that 'cent' and 'ucent' are reserved for future use but 
not yet implemented. Does anyone have a working implementation 
of these types?


Alternatively, is there an any effort towards implementation 
of arbitrary-sized integers in Phobos?


Thanks,
Saurabh


There is BigInt in phobos.


I think cent and ucent could be implemented as ulong is possible 
to be used on 32-bit systems by adding extra assembly 
instructions. This way, when (and if) 128-bit systems are 
developed, compiler would be updated only.


Re: multithreading profiling

2016-04-18 Thread tcak via Digitalmars-d-learn

On Monday, 18 April 2016 at 13:33:20 UTC, jj75607 wrote:

Hello!

Is it possible to start profiling on multithreaded app with Dmd?

https://issues.dlang.org/show_bug.cgi?id=14511 is open. I am 
doing wrong or why this program segfaults if compiled with 
profiler hooks?


import core.atomic;

shared struct S
{   
uint counter;

bool inc() shared
{
atomicOp!("+=")(counter, 1);
return true;
}
}

int main(string[] argv)
{
S s;

return 0;
}

Thank you!


As far as I know, profiling system doesn't work on multithreading 
programs correctly. At least, it has never worked for me. While 
closing the program, it creates problem always. But in a signle 
threaded environment, no problem.


Re: Fiber and Thread Communication

2016-04-08 Thread tcak via Digitalmars-d-learn

On Friday, 8 April 2016 at 15:33:46 UTC, Dicebot wrote:

On Friday, 8 April 2016 at 14:08:39 UTC, Nordlöw wrote:

So a TId can represent either a thread or a fiber?


AFAIR, yes (I haven't used std.concurrency in a long while, 
telling all from memory only).


yes what? Thread or Fiber.

---

Anyway. Since, Fiber is not like a thread, and when a thread 
starts a Fiber, it is like calling a normal function, I guess TId 
represents the thread still.


Segmentation Fault on rt.tlsgc.init

2016-04-05 Thread tcak via Digitalmars-d-learn
If I create many threads (starts, does a short work, and ends) 
repeatedly (>10,000), at some point rt.tlsgc.init() gives 
SEGMENTATION_FAULT.


It doesn't check whether malloc fails to allocate any memory, and 
I cannot find the source code of "rt.sections.initTLSRanges()" 
anywhere.


Is it left there without a check purposefully?


Re: Convert wchar* to wstring?

2016-04-04 Thread tcak via Digitalmars-d-learn

On Tuesday, 5 April 2016 at 01:21:55 UTC, Thalamus wrote:
I'm sorry for this total newbie question, but for some reason 
this is eluding me. I must be overlooking something obvious, 
but I haven't been able to figure this out and haven't found 
anything helpful.


I am invoking an entry point in a D DLL from C# (via extern 
(C)), and one of the parameters is a string. This works just 
fine for ANSI, but I'm having trouble with the Unicode 
equivalent.


For ANSI, the message parameter is char*, and string info = 
to!string(message) produces the correct string.


For Unicode, I assumed this would be wchar_t*, as it is in C++. 
(In C++ you can just pass the wchar_t* value to the wstring 
constructor.) So I tried wchar_t*, wchar* and dchar* as well. 
When the message parameter is wchar*, wstring info = 
to!wstring(message) populates the string with the _address_ of 
the wchar*. So when message was in the debugger as 
0x035370e8 L"Writing Exhaustive unit tests is 
exhausting.", the wstring info variable ended up as {length=7 
ptr=0x1c174a20 L"35370E8" }. The dstring*/wchar_t* 
version had equivalent results.


Again, I'm sure I'm missing something obvious, but I poked at 
this problem with various types, casts, Phobos library string 
conversions, and I'm just stumped! :)


thanks,
Thalamus


I cannot give you any code example, but can you try that:

1. By using a loop, calculate the total byte length until finding 
0 (zero). (This would work only if it was given as 
NULL-terminated, otherwise you need to know the length already.)

2. Then define wchar[ calculated_length ] mystring;
3. Copy the content from wchar* into you array. mystring[0 .. 
calculated_length ] = wcharptr[0 .. calculated_length];
4. If you want, you can do casting for your mystring to convert 
it to wstring.


Re: Catching thread creation error

2016-04-04 Thread tcak via Digitalmars-d-learn

On Monday, 4 April 2016 at 20:28:13 UTC, tcak wrote:
In my server program, when a request comes, I create a new 
thread for that.


I put memory limit to program with setrlimit. So, when the 
limit is reached, new thread cannot be created.


I want to tell client back that there is system problem. But 
catching "Throwable" does not suffice for this it seems like. 
Program still breaks and tells that "Error creating thread". Is 
there any normal way to catch this event?


Okay. That's my mistake. I was looking at "new Thread" part 
instead of "start". The "start" function is what allocates memory 
for the new thread. So, it is the one where try-catch should be 
used.


Catching thread creation error

2016-04-04 Thread tcak via Digitalmars-d-learn
In my server program, when a request comes, I create a new thread 
for that.


I put memory limit to program with setrlimit. So, when the limit 
is reached, new thread cannot be created.


I want to tell client back that there is system problem. But 
catching "Throwable" does not suffice for this it seems like. 
Program still breaks and tells that "Error creating thread". Is 
there any normal way to catch this event?


How big memory is allocated by GC?

2016-04-03 Thread tcak via Digitalmars-d-learn
Is there any way to know how big memory has been allocated by GC 
currently (or in the last scan)?


I want to limit the total memory usage of program manually. So, 
while I am allocating some space (in server program), if the 
desired memory will exceed the limit, I will fail the operation 
immediately.


Minimise and collect by GC when OutOfMemory

2016-02-25 Thread tcak via Digitalmars-d-learn
Would it be a good idea to call "collect" and "minimize" methods 
of core.memory.GC when OutOfMemory error is received FOR A LONG 
RUNNING PROGRAM? or there won't be any benefit of that?


Example program: A web server that allocates and releases memory 
from heap continuously.


What happens if memory allocation fails?

2016-02-20 Thread tcak via Digitalmars-d-learn
This is not easy to try. So I need ask, maybe someone has 
experienced.


What happens if memory allocation fails with "new" keyword? Does 
it

throw an exception? throwable?

All I want is to be able to catch OutOfMemory event, and take 
other

steps based on that.


Re: Get memory usage report from GC

2016-02-19 Thread tcak via Digitalmars-d-learn

On Saturday, 20 February 2016 at 05:55:26 UTC, Jon D wrote:

On Saturday, 20 February 2016 at 05:34:01 UTC, tcak wrote:

On Saturday, 20 February 2016 at 05:33:00 UTC, tcak wrote:
Is there any way (I checked core.memory already) to collect 
report about memory usage from garbage collector? So, I can 
see a list of pointer and length information. Since getting 
this information would require another memory area in heap, 
it could be like logging when report is asked.


My long running but idle program starts using 41.7% of memory 
(that's close to 3GB), and it is not obvious whether the 
memory is allocated by a single variable, or many variables.


My mistake, it is close to 512MB.


Doesn't sounds like precisely what you want, but there are 
summary reports of GC activity available via the 
"--DRT-gcopt=profile:1" command line option. More info at: 
http://dlang.org/spec/garbage.html


--Jon


I checked it out now. Yes, it is not that much useful 
unfortunately.


The process is a daemon. stdin, stdout, and stderr are forwarded 
to /dev/null,
thus, there is nothing like getting a text report at the end of 
process.


I am still looking for a way to at least hook up to GC, so when 
it allocates,

or deallocates, I could log it myself.


Re: Get memory usage report from GC

2016-02-19 Thread tcak via Digitalmars-d-learn

On Saturday, 20 February 2016 at 05:33:00 UTC, tcak wrote:
Is there any way (I checked core.memory already) to collect 
report about memory usage from garbage collector? So, I can see 
a list of pointer and length information. Since getting this 
information would require another memory area in heap, it could 
be like logging when report is asked.


My long running but idle program starts using 41.7% of memory 
(that's close to 3GB), and it is not obvious whether the memory 
is allocated by a single variable, or many variables.


My mistake, it is close to 512MB.


Get memory usage report from GC

2016-02-19 Thread tcak via Digitalmars-d-learn
Is there any way (I checked core.memory already) to collect 
report about memory usage from garbage collector? So, I can see a 
list of pointer and length information. Since getting this 
information would require another memory area in heap, it could 
be like logging when report is asked.


My long running but idle program starts using 41.7% of memory 
(that's close to 3GB), and it is not obvious whether the memory 
is allocated by a single variable, or many variables.


Re: What is the best way to stop App after exception?

2016-02-15 Thread tcak via Digitalmars-d-learn

On Monday, 15 February 2016 at 11:38:05 UTC, Suliman wrote:
I have got class Config with method parseconfig. I need 
terminate App if parsing of config was failed. The problem that 
I do not know how to do it better.


void parseconfig()
{
 try
 {
  //something go wrong
 }

catch(Exception e)
 {
  writeln(e.msg);
  // throw any exception here
 }
}


But my main.d also have try catch block and parseconfig() calls 
inside it. The problem that wen exception rise I do not know 
how to terminate app. Exception simply print on screen and app 
is continue.


void main()
 {
 try
  {
   parseconfig(); // exception was already handled inside:  
void parseconfig()

  }
 }

What is the best practice to stop app?


Since C's "exit" function is not liked, best thing you can do is 
to throw an Error when you want to close the program. You are not 
supposed to catch Errors. So, it eventually will stop the 
currently running thread.


BUT (This is a big but with single t), in multithreaded process, 
throwing Error in a thread that is not the main thread won't stop 
your process still and you are still left with "exit" function.


Re: Singleton, alias to self?

2016-02-14 Thread tcak via Digitalmars-d-learn
On Sunday, 14 February 2016 at 12:56:51 UTC, Vladde Nordholm 
wrote:
I'm not sure of how to use alias efficiently, so I want to know 
if I could somehow do this (psuedo-code)


class Singleton
{
  //So instead of calling `Singleton.getSingleton()` you just 
call `Singleton`

  alias this = getSingleon()

  //code for singleton...
}

Thanks in advance,
vladde


"this" is for an instance of class (or struct). There is no 
instance of define an alias at that time. I am not sure, but you 
can check "opCall" function as static for this. Give it a try at 
least.


Re: wrapSocket for socket_t? As wrapFile for FILE*

2016-02-13 Thread tcak via Digitalmars-d-learn

On Sunday, 14 February 2016 at 04:13:12 UTC, Beginner-8 wrote:

Hi!

Anyone seen Socket constructor which uses already available 
socket of socket_t type?


I am need to use already connected socket imported from C 
library without closing them after using.


One of the constructors of class Socket is as follows:

pure nothrow @nogc @safe this(socket_t sock, AddressFamily af);


socket_t is basically a file descriptor which is the type "int".

Your C library provides you "socket_t" value already as far as I 
understand.

So, you can pass it to constructor.

Unless you explicitly call "close" method of Socket object, its 
descriptor will

stay allocated for your process/program.



Index file for ddoc

2016-02-13 Thread tcak via Digitalmars-d-learn
Maybe I am missing, but I do not see any index file when html 
files are generated by ddoc. Is there any way to generate index 
file automatically, so, a tree like links will be listed all 
created documentation files?


If the problem is about the possibility of having index.d and it 
would be confused with index.html, I can understand.


Re: What reasons are known a thread stops suddenly?

2016-02-04 Thread tcak via Digitalmars-d-learn

On Friday, 5 February 2016 at 06:23:09 UTC, Daniel Kozak wrote:

V Fri, 05 Feb 2016 03:47:40 +
tcak via Digitalmars-d-learn 
napsáno:


[...]


Did you try catch Throwable instead of Exception?


Undid the fix, and wrapped the problem causing function call with 
try-catch-Throwable, it is caught now. I always used Exception 
before, thinking that it was the base of all exceptions.


Re: What reasons are known a thread stops suddenly?

2016-02-04 Thread tcak via Digitalmars-d-learn

On Friday, 5 February 2016 at 03:47:40 UTC, tcak wrote:

On Thursday, 4 February 2016 at 22:27:31 UTC, Ali Çehreli wrote:

On 02/04/2016 12:25 PM, tcak wrote:

> [...]

That would happen when there is an exception.

> [...]

If a thread is terminated with an exception, its stack is 
unwound and unlike the main thread, the program will not 
terminate. I think this is due to an exception.


> [...]

I think putting a break point at exception construction would 
be helpful but it will be simpler to put a try-catch block 
that covers the entire body of threadFunc().


> [...]
this?

I am still betting on an exception. :)

Ali


Yup, it is exception it seems like, but with a weird result. 
Check the new codes:


void threadFunc(){
scope(exit){
writeln("Leaving 2: ", stopRequested);
}

scope(failure){
writeln("Failure");
}

try{
while( !stopRequested ){

}

writeln("Leaving 1: ", stopRequested);
}
catch( Exception ex ){
writeln("Caught the exception");
}
}

Now, the thread stops with:

Failure
Leaving 2: false


There is no "Caught the exception". And believe me other then 
the codes inside while loop, main structure as seen in the 
above code.


By testing many times, I understood that the problem occurs 
when too many requests are received suddenly (by pressing F5 
many times again and again produces the exception).


But the question is why try-catch is not able to catch it, and 
just scope(failure) can?


Okay. The cause of problem has been solved with good-old 
writeln("DEBUG"); method :)


Cause is trying to access outside of array (e.g. array[$]). But I 
didn't like that fact that scope(failure) is called for that 
properly, but no other error was seen.


Environment: MonoDevelop, Linux x64, DMD 2.070, MonoD, running in 
Debug mode.


Re: What reasons are known a thread stops suddenly?

2016-02-04 Thread tcak via Digitalmars-d-learn

On Thursday, 4 February 2016 at 22:27:31 UTC, Ali Çehreli wrote:

On 02/04/2016 12:25 PM, tcak wrote:

> void threadFunc(){
>  scope(exit){
>  writeln("Leaving 2: ", stopRequested);
>  }
>
>
>  while( !stopRequested ){
> /* THERE IS NO "RETURN" HERE AT ALL */
>  }
>
>  writeln("Leaving 1: ", stopRequested);
> }
>
>
>
> While loop is running, suddenly "Leaving 2: false" is seen.

That would happen when there is an exception.

> Checked with
> exception, but there is nothing.

If a thread is terminated with an exception, its stack is 
unwound and unlike the main thread, the program will not 
terminate. I think this is due to an exception.


> GDB doesn't show any error.

I think putting a break point at exception construction would 
be helpful but it will be simpler to put a try-catch block that 
covers the entire body of threadFunc().


> There is no
> "Leaving 1: .." message at all.
>
> Is there any known reason for a thread to suddenly stop like
this?

I am still betting on an exception. :)

Ali


Yup, it is exception it seems like, but with a weird result. 
Check the new codes:


void threadFunc(){
scope(exit){
writeln("Leaving 2: ", stopRequested);
}

scope(failure){
writeln("Failure");
}

try{
while( !stopRequested ){

}

writeln("Leaving 1: ", stopRequested);
}
catch( Exception ex ){
writeln("Caught the exception");
}
}

Now, the thread stops with:

Failure
Leaving 2: false


There is no "Caught the exception". And believe me other then the 
codes inside while loop, main structure as seen in the above code.


By testing many times, I understood that the problem occurs when 
too many requests are received suddenly (by pressing F5 many 
times again and again produces the exception).


But the question is why try-catch is not able to catch it, and 
just scope(failure) can?


What reasons are known a thread stops suddenly?

2016-02-04 Thread tcak via Digitalmars-d-learn
I have implemented a standalone HTTP server. So everything is in 
single executable. Requests come, for responding a new thread is 
started, etc.


To listen new socket connections, and socket events, a single 
thread is used (Call this event listener thread).


Everything works perfectly. Firefox asks for page, all HTML, JS, 
CSS, Image requests come and responded properly.


Now, when I start the executable, instead of calling the page on 
Firefox by pressing F5 for refresh, if I press Ctrl+Shift+F5, 
Firefox asks for same requests as always do, but that event 
listener thread suddenly stops.


You might say that is a programming error of mine, but problem is 
as follows:


void threadFunc(){
scope(exit){
writeln("Leaving 2: ", stopRequested);
}


while( !stopRequested ){
/* THERE IS NO "RETURN" HERE AT ALL */
}

writeln("Leaving 1: ", stopRequested);
}



While loop is running, suddenly "Leaving 2: false" is seen. 
Checked with exception, but there is nothing. GDB doesn't show 
any error. There is no "Leaving 1: .." message at all.


Is there any known reason for a thread to suddenly stop like this?


Re: std.socket question

2016-02-04 Thread tcak via Digitalmars-d-learn

On Thursday, 4 February 2016 at 06:40:15 UTC, sanjayss wrote:
Are the functions lastSocketError() and wouldHaveBlocked() from 
std.socket thread-safe? i.e. can they be reliably used to see 
the status of the last socket call when sockets are being 
read/written in multiple threads?


Not directly read the code for a while (but did before), those 
two functions
call C functions, and they are thread-safe by default. The 
WOULD-HAVE-BLOCKED
is understood by checking errno which comes from core.stdc.errno. 
If you read
that function's documents, you will see that it is marked as 
thread-safe.


http://linux.die.net/man/3/errno
... errno is thread-local; setting it in one thread does not 
affect its value in any other thread. ...


Re: Defining event handlers for function, method, or shared method

2016-01-26 Thread tcak via Digitalmars-d-learn

On Tuesday, 26 January 2016 at 19:22:58 UTC, Ali Çehreli wrote:

On 01/26/2016 10:41 AM, tcak wrote:
> I need/want this class to be able to bind
> a function, a method, or a shared method. From the
perspective of class
> design, there shouldn't be any
> difference. Its purpose is to let know about the event, not
to care
> about how the event
> handler is designed.

If I understand the problem correctly, an interface can define 
the interface and a templated class can provide the differences:


import std.stdio;
import std.algorithm;

interface Event {
void start();
void stop();
void itemAdded( size_t itemIndex );
}

class ConcreteEvent(alias onStart, alias onStop, alias 
onItemAdded) : Event {

void start() {
onStart();
}

void stop() {
onStop();
}

void itemAdded(size_t itemIndex) {
itemAdded(itemIndex);
}
}

void fooStart() {
}

void fooStop() {
}

void fooItemAdded(size_t itemIndex) {
}

void bar(size_t itemIndex) {
}

void main() {
Event[] events;
events ~= new ConcreteEvent!(fooStart, fooStop, 
fooItemAdded);


struct S {
void memberFunction() {
}
}
auto s = S();

auto memberClosure(ref S s) {On 01/26/2016 10:41 AM, tcak 
wrote:

> I need/want this class to be able to bind
> a function, a method, or a shared method. From the
perspective of class
> design, there shouldn't be any
> difference. Its purpose is to let know about the event, not
to care
> about how the event
> handler is designed.

If I understand the problem correctly, an interface can define 
the interface and a templated class can provide differences:


import std.stdio;
import std.algorithm;

interface Event {
void start();
void stop();
void itemAdded( size_t itemIndex );
}

class ConcreteEvent(alias onStart, alias onStop, alias 
onItemAdded) : Event {

void start() {
onStart();
}

void stop() {
onStop();
}

void itemAdded(size_t itemIndex) {
itemAdded(itemIndex);
}
}

void fooStart() {
}

void fooStop() {
}

void fooItemAdded(size_t itemIndex) {
}

void bar(size_t itemIndex) {
}

void main() {
Event[] events;
events ~= new ConcreteEvent!(fooStart, fooStop, 
fooItemAdded);


struct S {
void memberFunction() {
}
}
auto s = S();

auto memberClosure(ref S s) {
return () => s.memberFunction();
}

events ~= new ConcreteEvent!(() => memberClosure(s),
 () => writeln("stop"),
 bar);

events.each!(e => e.stop);
}

Ali

return () => s.memberFunction();
}

events ~= new ConcreteEvent!(() => memberClosure(s),
 () => writeln("stop"),
 bar);

events.each!(e => e.stop);
}

Ali


Hmm. Your example works fine for functions, but I can't pass a 
method instead of function as alias. Check my example:



import std.socket;

class EventClass{
public void eventHandlerMethod(){
writeln("Barking from method");
}   
}

class Generator(alias eventHandler){
public void bark(){
eventHandler();
}
}

public void eventHandlerFunc(){
writeln("Barking from function");
}

void main(){
auto events = new EventClass;

auto gen1 = new Generator!( eventHandlerFunc )();
auto gen2 = new Generator!( events.eventHandlerMethod )();

gen1.bark();
gen2.bark();
}


Error is given on "auto gen2 = ..." in main function due to 
passing method. I guess because it is runtime normal compile time 
information.


I was looking for something like to be defined in the class 
Generator:


public DelegateOnStart eventOnStart;

So I could set eventOnStart as either function pointer, method 
pointer, or shared method pointer. To be able to support three of 
them, for every event, I need to define another variable, another 
alias, and while calling, check whichever variable (delegate 
pointer) is set, and call that one. I hope I am making it clear 
why it turns into mess.


Re: Defining event handlers for function, method, or shared method

2016-01-26 Thread tcak via Digitalmars-d-learn

On Tuesday, 26 January 2016 at 19:42:42 UTC, tcak wrote:

On Tuesday, 26 January 2016 at 19:22:58 UTC, Ali Çehreli wrote:

[...]


Hmm. Your example works fine for functions, but I can't pass a 
method instead of function as alias. Check my example:


[...]


Edit: ... "I guess because it is runtime information, not compile 
time" ...


Defining event handlers for function, method, or shared method

2016-01-26 Thread tcak via Digitalmars-d-learn
In many multi threading module designs of mine, I generally 
design a base class, and

this class have some events. Exempli gratia:

void eventOnStart();
void eventOnStop();
void eventOnItemAdded( size_t itemIndex );

There is this problem though. I need/want this class to be able 
to bind a function, a method, or a shared method. From the 
perspective of class design, there shouldn't be any
difference. Its purpose is to let know about the event, not to 
care about how the event

handler is designed.

If I want handlers to be functions, I design it like,

public alias EventOnStart = void function();
public EventOnStart eventOnStart;


If it is for normal methods, design becomes like,

public alias EventOnStart = void delegate();


For shared methods, it becomes,

public alias EventOnStart = void delegate() shared;


As you will guess, to be able to support any of those three, it 
becomes so complex. Is
there any way generalise to support three of them without making 
this any complex? A
secondary thing, this is not D related though, whether there is 
any different approach
for event listener design like Observer pattern but with little 
overhead and complexity?


Re: Define "createXXX" functions for the constructors of class XXX

2016-01-23 Thread tcak via Digitalmars-d-learn

On Saturday, 23 January 2016 at 19:42:29 UTC, Johan Engelen wrote:

Hi all,
  While trying to interface C++ and D, I have to new a few D 
objects in C++ code. I am doing this using a D function: "XXX 
createXXX(...) { return new XXX(...); }".
I am sure there must be some great way to automatically 
generate these creator functions, but I don't know how to do it.


In the C++-header I will write manually:
  XXX* createXXX(int a, int b);
  XXX* createXXX(bool flag);

In D source:
  extern (C++) class XXX {
this(int a, int b) { /+...+/ }
this(bool flag) { /+...+/ }
  }

// Somehow define these guys automatically, 
"genCreateCtors!(XXX)" ?

  XXX createXXX(int a, int b) { return new XXX(a, b); }
  XXX createXXX(bool flag) { return new XXX(flag); }

Thanks a lot!
  Johan


Wow! There are lots of XXX there.

Anyway, I did a similar thing to yours for automatic attribute 
definition before. Three things:


1. Template
2. Mixin
3. Compile time function

You define a compile time function which generates a string that 
is valid D code.
You define template that takes some parameters (Your XXX values), 
and calls the function to merge them.
In your class, you use mixin and template to generate the string 
and inject the generated code.


Not that complex once you do it.

Try to understand this code.
http://david.rothlis.net/d/templates/

Its in there.


core.thread.Thread.start is marked as "nothrow" but documentation says it throws

2016-01-23 Thread tcak via Digitalmars-d-learn

https://dlang.org/phobos/core_thread.html#.Thread

final nothrow Thread.start()

Looking at the code, no "throw new ..." is seen, but the function 
"onThreadError" is called

which has "throw" in it.

Most weird thing is that "onThreadError" function is marked as 
"nothrow" but it still throws.


I would think that yes, maybe the compiler might not be able to 
see it because throw is found
in another function, but how come "onThreadError" throws with 
nothrow.


Re: Changing Name of a thread

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

On Saturday, 9 January 2016 at 11:02:53 UTC, Keywan Ghadami wrote:

Hello, i am trying to the set the name of thread with:

import core.thread;
auto thisThread = Thread.getThis();
thisThread.name = "kiwi";

but GDB prints the name of the programm ("helloworld")

[Thread debugging using libthread_db enabled]
Using host libthread_db library 
"/lib/x86_64-linux-gnu/libthread_db.so.1".

Edit source/app.d to start your project.
^C
Program received signal SIGINT, Interrupt.
D main () at source/app.d:17
17  }
(gdb) info threads
  Id   Target Id Frame
* 1Thread 0x77fd0800 (LWP 3232) "helloworld" D main 
() at source/app.d:17


Next thing i tried was calling pthread_setname_np (Linux) but 
it seams that is not defined in phobos, so i tried to delcare 
it by my self:


import core.sys.posix.pthread;
import std.string;
extern(C) int pthread_setname_np(pthread_t, const char*);
pthread_setname_np(pthread_self(), 
toStringz("thread_name"));


but this gives me
   helloworld ~master: building configuration "application"...
   dmd -c 
-of.dub/build/application-debug-linux.posix-x86_64-dmd_2069-AAC406C4728034581B43AEC547EAA8E7/helloworld.o -debug -g -w -version=Have_helloworld -Isource/ source/app.d source/kiwi.d -vcolumns

   Linking...
   dmd 
-of.dub/build/application-debug-linux.posix-x86_64-dmd_2069-AAC406C4728034581B43AEC547EAA8E7/helloworld .dub/build/application-debug-linux.posix-x86_64-dmd_2069-AAC406C4728034581B43AEC547EAA8E7/helloworld.o -L--no-as-needed -g
   
.dub/build/application-debug-linux.posix-x86_64-dmd_2069-AAC406C4728034581B43AEC547EAA8E7/helloworld.o: In function `_Dmain':
/home/keywan/hello_world/source/app.d:13: undefined reference 
to `_D3app4mainFZ18pthread_setname_npUmxPaZi'

   collect2: error: ld returned 1 exit status
   --- errorlevel 1
   FAIL 
.dub/build/application-debug-linux.posix-x86_64-dmd_2069-AAC406C4728034581B43AEC547EAA8E7/ helloworld executable

   dmd failed with exit code 1.

sorry for asking stupid questions but my background is more 
PHP,Perl,Java...
any help would be appreciated. (context i am trying to make 
debugging easier by giving the threads names)


I tried your code with a little addition as follows:

[code]
import core.sys.posix.pthread;
import std.string;
import std.stdio;

extern(C) int pthread_setname_np(pthread_t, const char*);

void main(){
pthread_setname_np(pthread_self(), toStringz("thread_name"));
readln();
}
[/code]

Compiled it with "dmd blah.d", and then run "./blah".

Because there is "readln" there, I opened another terminal and
used "ps H -o 'pid tid cmd comm'".

In the output:

 PID   TID CMD COMMAND
5089  5089 ./blah  thread_name

So, it works.


Re: Linking a DLL to a DLL with packages

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

On Friday, 8 January 2016 at 12:13:15 UTC, Benjamin Thaut wrote:

On Thursday, 7 January 2016 at 19:29:43 UTC, Thalamus wrote:

Hi everyone,

First off, I've been working with D for a couple of weeks now 
and I think it's the bee's knees! :) Except for DLLs.


thanks! :)


Dlls don't currently work on Windows. The only thing that works 
is giving your dlls a C-like interface. If you need any kind of 
D interface (classes, modules, etc) it won't work. I'm 
currently working on this, if you need it really badly and are 
willing to help bug testing send me a mail to code at 
benjamin-thaut.de


Kind Regards
Benjamin Thaut


I thought DLLs (shared library) had problem on *nix, but was fine 
on Windows. I have

never heard there was any problem about it on Windows.

---

Check this page. http://wiki.dlang.org/Win32_DLLs_in_D Test the 
example. If it works, then you can continue modifying it to fit 
your desired system. But I do not
think your problem is about DLL, but you are doing something 
wrong about module names and file names.


Re: Calling functions from other files/modules

2016-01-06 Thread tcak via Digitalmars-d-learn

On Wednesday, 6 January 2016 at 23:12:27 UTC, Namal wrote:
On Wednesday, 6 January 2016 at 23:06:38 UTC, Adam D. Ruppe 
wrote:

On Wednesday, 6 January 2016 at 23:00:43 UTC, Namal wrote:
I just tried to import one module with a main into another, 
but I get this:


You can't have two mains, but you can import a module with 
main from another module without one.


How can I produce a program file from that module which has no 
main but uses some functions from main module?


I think the below example clarifies everything.

entry.d
===

module project.entry;

import std.stdio;
import project.other;

void bark(){
writeln("Woof");
}

void main(){
project.other.callbark();   
}




other.d
===

module project.other;

import project.entry;

void callbark(){
project.entry.bark();
}



Re: Strange 'memset' error when using std.range.repeat and std.array.array

2016-01-04 Thread tcak via Digitalmars-d-learn

On Monday, 4 January 2016 at 10:50:17 UTC, Ur@nuz wrote:

Sorry, the actual code is:
...

lines ~= ' '.repeat.take(newIndentCount).array;

...with character quotes. But it still fails with error 
described in stack trace in Gcx.bigAlloc()


What's your OS? On Linux x64, it works without any error.


Re: How to use GDC to get .a file on Linux?

2015-12-27 Thread tcak via Digitalmars-d-learn

On Sunday, 27 December 2015 at 15:19:21 UTC, FrankLike wrote:

Hi,
   Now I need get the .a file on Linux,target system is ARM.
   If you use gcc ,you will use the 'ar' to get .a file,
but how to do by GDC ?
And how to  get the execute file by .a file and .d file?

Thank you.


I couldn't have understood your question very well, but some 
information is here.


You create .a static library file with "-lib" flag while 
compiling. Yesterday I did it.


dmd mylib.d -lib

This will generate mylib.a.

You can later use this static library while compiling another d 
code.


dmd main.d mylib.a

Pass the .a file directly as it is another source.

I have never tried these with GDC, but I don't think it is much 
different at all.


Re: basic interactive readf from stdin

2015-12-26 Thread tcak via Digitalmars-d-learn
On Saturday, 26 December 2015 at 20:19:08 UTC, Adam D. Ruppe 
wrote:
On Saturday, 26 December 2015 at 20:11:27 UTC, karthikeyan 
wrote:
I experience the same as the OP on Linux Mint 15 with dmd2.069 
and 64 bit machine.  I have to press enter twice to get the 
output. I read http://ddili.org/ders/d.en/input.html and 
inserted a space before %s but still no use. Am I missing 
something here with the latest version?


Oh, I'm sorry, it isn't buffering, it is readfing into a string 
here which is weird. Maybe try readln instead of readf.


As far as I remember, in C, if I was to be putting "\n" in scanf 
after %s, that double entering was happening. I guess that's the 
same problem. Trying same code without \n in readf can fix it I 
guess.


Convert to string an enum item

2015-12-23 Thread tcak via Digitalmars-d-learn

[code]
import std.stdio;
import std.conv;

enum Values: ubyte{ One = 1, Two = 2 }

void main(){
writeln( std.conv.to!string( Values.One ) );
}
[/code]

Output is "One".

casting works, but to be able to cast correctly, I need to tell 
compiler that it is "ubyte".


Isn't there any NON-HACKISH solution to print out the value of 
enum item? And do not decrease the performance as well please. It 
runs on web server.



Problem comes from that:
I have written a struct for JsonArray. It has multiple append 
methods. One of them is "appendNumber".


public ref JsonArray appendNumber(N)( N num )
if( __traits( compiles, {auto x=num.min + num.max;} ) || 
__traits( compiles, {auto x=num.min_normal;} ) )

{
appendJSString( std.conv.to!string( num ) );
return this;
}

While I am passing an enum item to this function, as it has "min" 
and "max" attributes, it is accepted. But the resulting string is 
the name of enum item instead of its value. I do not want casting 
while enum knows its type already.


Re: Socket - handling large numbers of incoming connections

2015-12-21 Thread tcak via Digitalmars-d-learn

On Monday, 21 December 2015 at 20:53:14 UTC, Jakob Jenkov wrote:

On Monday, 21 December 2015 at 20:20:44 UTC, Stefan wrote:
How about https://github.com/dcarp/asynchronous ? Asyncio 
Socket handling is sometimes quite nice. It's performance is 
okay for nearly no effort and the code looks clean.
Details here: 
http://dcarp.github.io/asynchronous/asynchronous/streams/startServer.html


vibe.d also offers a fiber based asyncio way of dealing with 
sockets.

http://vibed.org/docs#tcp-server

Maybe it fits your needs.


Thanks - but I am primarily looking for a solution without 
external frameworks. Frameworks have a way of bloating over 
time.


My server uses "poll" for that.


Re: Template specialization using traits?

2015-12-21 Thread tcak via Digitalmars-d-learn
On Monday, 21 December 2015 at 11:12:10 UTC, Jonathan M Davis 
wrote:
On Monday, 21 December 2015 at 11:07:16 UTC, Jonathan M Davis 
wrote:
For your example to work with template constraints, the most 
straightforward solution would be


void func(T)(T t)
if(!isIntegral!T)
{
writeln(1);
}

void func(T)(T t)
if(isIntegral!T)
{
writeln(2);
}


Alternatively, you can use static if, though you're only 
dealing with one template in that case. e.g.


void func(T)(T t)
{
static if(isIntegral!T)
writeln(2);
else
writeln(1);
}

- Jonathan M Davis


Another alternative is:

template func(T){
static if( isIntegral!T ){
void func(T t){
writeln( 2 );
}
}
else{
void func(T t){
writeln( 1 );
}
}
}


Re: Can't debug my solution

2015-12-19 Thread tcak via Digitalmars-d-learn

On Saturday, 19 December 2015 at 20:52:41 UTC, Matheus Reis wrote:

Hello, people!

I'm Matheus, a 20 y/o game developer who wants to get started 
with D. It has really caught my attention, and I've been 
playing with it for some hours now.


I've got it all working (without some "phobos.lib", is it 
really needed?) with Xamarin Studio but I can't get it to debug 
my solution when I run it. What do I need to do?


I can run it with debugging OFF (ctrl-f5) but can't run it 
"normally". What am I missing?


Thanks in advance! :)


What is the OS?

Have you installed and activated GDB plugin?

If you are not doing something special, phobos functions are 
included in your executable already. So you shouldn't have any 
problem with it.


Re: Error 42: Symbol Undefined __lseeki64

2015-12-16 Thread tcak via Digitalmars-d-learn

On Wednesday, 16 December 2015 at 18:30:41 UTC, Byron Heads wrote:
On Wednesday, 16 December 2015 at 18:21:33 UTC, Byron Heads 
wrote:
On Wednesday, 16 December 2015 at 18:14:35 UTC, Byron Heads 
wrote:

[...]



Commenting out

gzclose(fpGZip);

allows it to compile..


Submitted reduced case as a bug:
https://issues.dlang.org/show_bug.cgi?id=15457


import etc.c.zlib;

void main() {
  gzclose(null);
}


I searched the function "__lseek64" under /usr/include/dmd" with 
"grep -R __lseek64", but nothing is found. I work on Linux 
64-bit. So, I guess it is either Windows related, or 32bit dmd 
related. "lseek64" is found in "unistd.d", but this doesn't solve 
any problem.


Re: Error: undefined identifier 'selector'

2015-12-14 Thread tcak via Digitalmars-d-learn

On Monday, 14 December 2015 at 20:46:41 UTC, Mike McKee wrote:

When I run this piece of code:

// FROM: https://dlang.org/spec/objc_interface.html
module main;

[...]


UDA s cannot be used for functions/methods AFAIK.


Re: Very very noobie question about how imports work.

2015-12-10 Thread tcak via Digitalmars-d-learn

On Friday, 11 December 2015 at 04:09:19 UTC, Chris Wright wrote:

On Fri, 11 Dec 2015 03:20:29 +, J Smith wrote:

How do I make it so that I can import and use the contents of 
lib.d inside of testlib.d.


If you are not compiling everything in one step, the -I flag 
allows you to specify paths to look for imports. For instance:


$ dmd -lib src/package_name/lib.d
$ dmd -Isrc test/testlib.d libpackage_name.a


Whops. I re-read the post, and yeah, it is for other import.


Re: Very very noobie question about how imports work.

2015-12-10 Thread tcak via Digitalmars-d-learn

On Friday, 11 December 2015 at 03:20:29 UTC, J Smith wrote:

Say I have a project with the files structured like this.

package-name/
src/
package-name/
lib.d
test/
testlib.d

How do I make it so that I can import and use the contents of 
lib.d inside of testlib.d.


As you can tell I'm very new to D, and kind of new to 
programming. Forgive me for very noob and easy question, but 
couldn't really find anything out by reading the docs.


In D, directory structure doesn't matter. What matters is module 
names.


Let's say module name of lib.d is "module a;", and for testlib.d, 
it is "module b;".


Then you can access whichever you want with dot notation. 
"a.foo();", "b.var = 5;" etc.


Where directory structure matters is compiling.

dmd main.d src/package-name/lib.d test/testlib.d

Because it is logical to match directory structure and module 
name, it is done in that way mostly, but there are times you 
might not want this.


Re: Using phobos as shared library for multiple binaries

2015-12-05 Thread tcak via Digitalmars-d-learn

On Saturday, 5 December 2015 at 21:49:52 UTC, Ralf wrote:

Hi,

I've written several small command-line utilities in D that are 
to be shipped together in one package. Each one of them only 
would be only a few kB in size, but they end up being ~1Mb, I 
assume because every one links statically parts of the standard 
library.


How can this be improved?

Are there binary builds of the standard library (for OS X) 
somewhere and an option to tell the compiler to link to this 
shared library?


Alternatively, is there a way to build a shared library that 
all the binaries can use together so they can share the common 
code?


Greetings,

Ralf


Some links for you:
http://dlang.org/dmd-osx.html   Check -defaultlib

http://dlang.org/dll-linux.htmlThis is for Linux, but check 
the last code example. It can help. I did what you ask in Linux, 
it works, but don't have knowledge about OS X.


Re: Using enums as function parameters (in a minimized way)

2015-12-01 Thread tcak via Digitalmars-d-learn
On Tuesday, 1 December 2015 at 10:50:04 UTC, Rikki Cattermole 
wrote:

On 01/12/15 11:44 PM, Ozan wrote:

Hi

Let's say we have an enum like

enum SomethingAboutChristmas {
   SantaClaus,
   Angel,
   Tree
}

and want to use it in a function like

   void goingChristmas(SomethingAboutChristmas enumvalue)

it works fine like following

   goingChristmas(SomethingAboutChristmas.Tree)

I prefer to use a shorter version

   goingChristmas(Tree)

because it's clear (for me), that "Tree" in "goingChristmas()" 
is an

enum of "SomethingAboutChristmas"

Is any chance to do this? The DMD-compiler says no.

Thanke & Regards, Ozan


If you insist..
You can also use alias and with statement to emulate this too.
Or generate it at compile time.

enum SomethingAboutChristmas {
SantaClaus,
Angel,
Tree
}

enum {
SantaClaus = SomethingAboutChristmas.SantaClaus,
Angel = SomethingAboutChristmas.Angel,
Tree = SomethingAboutChristmas.Tree,
}

void main() {
SomethingAboutChristmas foo = Tree; 
}


This is like: Q) I want to write an OS. How?  A) Write in 
assembly.


What Ozan says is logical. Compiler should assume it in that way 
normally. I have thoroughly thought about whether this assumption 
would cause problem yet though.


Unfortunately compiler doesn't accept that.


Re: Using enums as function parameters (in a minimized way)

2015-12-01 Thread tcak via Digitalmars-d-learn

On Tuesday, 1 December 2015 at 13:03:37 UTC, tcak wrote:
On Tuesday, 1 December 2015 at 10:50:04 UTC, Rikki Cattermole 
wrote:

[...]


This is like: Q) I want to write an OS. How?  A) Write in 
assembly.


What Ozan says is logical. Compiler should assume it in that 
way normally. I have thoroughly thought about whether this 
assumption would cause problem yet though.


Unfortunately compiler doesn't accept that.


*haven't thought


Re: std.socket replacement

2015-11-29 Thread tcak via Digitalmars-d-learn

On Sunday, 29 November 2015 at 08:56:30 UTC, tired_eyes wrote:
I was a bit surprised to see that std.socket is deprecated as 
of 2.069. Just curious, what's wrong with it? And what should I 
use as a replacement? I know there is vibe.socket, but I don't 
want to include fullstack web framework as a dependency just to 
make some HTTP reqests.


I also don't see any proposed replacements in a review queue. 
Will std.socket and std.socketstream be just thrown away?


I would say "WTF" at first, then checked the documentation, but 
don't see anything

about deprecation. My current whole business relies on that.


Re: Retrieving call expression of a function

2015-11-28 Thread tcak via Digitalmars-d-learn
On Saturday, 28 November 2015 at 15:41:59 UTC, Quentin Ladeveze 
wrote:

On Saturday, 28 November 2015 at 15:22:51 UTC, tcak wrote:
On Saturday, 28 November 2015 at 15:02:32 UTC, Quentin 
Ladeveze wrote:

Hi,

Is it possible to retrieve the calling expression of a 
function ? Something like that


---
import std.stdio;

void funcTest(int x, float y)
{
  writefln(get_call());
}

void main()
{
  float x = 0.2;
  funcTest(1+2, x+2);
}
---

output expected : " funcTest(1+2, x+2) "

Thanks


I do not have right now to provide you with code, but three 
things:


1. Use of mixin,
2. The function call to be written in a string,
3. A wrapper that stores given function call string, saves it, 
and mixin it.


Thanks, it was a cool idea, I made something that works, but 
you can only call the function with literals, not with 
variables :


---

import std.stdio;

void main()
{
int x = 2;

enum call = "funcTest(1, 0.2);";
callPrinter!call;
}

template callPrinter(string call)
{
void callPrinter()
{
writeln(call);
mixin(call);
}
}

void funcTest(int x, float y)
{
writeln("called with ", x, " and ", y);
}

---

output :
funcTest(2, 0.2);
called with 2 and 0.2


mixin template could solve this problem as well I guess. It 
would, instead of calling a function, directly inject the code 
into where you call it. So, remove the callPrinter function, make 
template a mixin template, and in main, call it like mixin 
callPrinter!"...";


Re: Retrieving call expression of a function

2015-11-28 Thread tcak via Digitalmars-d-learn
On Saturday, 28 November 2015 at 15:02:32 UTC, Quentin Ladeveze 
wrote:

Hi,

Is it possible to retrieve the calling expression of a function 
? Something like that


---
import std.stdio;

void funcTest(int x, float y)
{
  writefln(get_call());
}

void main()
{
  float x = 0.2;
  funcTest(1+2, x+2);
}
---

output expected : " funcTest(1+2, x+2) "

Thanks


I do not have right now to provide you with code, but three 
things:


1. Use of mixin,
2. The function call to be written in a string,
3. A wrapper that stores given function call string, saves it, 
and mixin it.


Re: Multithreaded HTTP Download

2015-11-28 Thread tcak via Digitalmars-d-learn

On Saturday, 28 November 2015 at 07:05:55 UTC, Mike McKee wrote:
Hey guys, as it turns out, someone on stackoverflow.com pointed 
out in a Perl version of this question that the Bash example 
that was given is really buggy and doesn't make sense. They say 
that trying to download a single file using two socket handles 
will not speed up the download. So, this may or may not be 
possible. Your thoughts?


So, I open one TCP socket to server, and it starts sending me 
data. Your internet connection speed is max 10Gb/s. You calculate 
the download speed, and it is at its max. Opening another TCP 
socket to server wouldn't make any difference. The only case that 
would make sense is if the server limits the upload speed of each 
TCP socket. Unless you are in this position, I do not expect to 
see any difference by opening multiple sockets and requesting 
different parts of same file.


Re: switch with enum

2015-11-24 Thread tcak via Digitalmars-d-learn
On Wednesday, 25 November 2015 at 03:59:01 UTC, Steven 
Schveighoffer wrote:

On 11/24/15 10:51 PM, tcak wrote:
I have seen a code a while ago, but even by looking at 
documentation, I

couldn't have found anything about it.

Let's say I have defined an enum;

enum Status: ubyte{
  Busy = 1,
  Active = 2
}

and received a ubyte value from user.

ubyte userValue;

I want to switch over userValue, but that should depend on 
Status.


switch( userValue ){

}

What I mean is that compiler should enforce values of enum 
"Status" to
be declared in switch as it would be done with "final switch", 
but as
you can guess, user might enter a value that is not defined by 
Status.

Thus, I should be able to enter the case "default" as well.


All final switch does is ensure you are covering all possible 
enums. It assumes that the value is already a valid enum value. 
If you did final switch on userValue, it would require you 
handle all 256 possible values for ubyte. So you would have to 
cast first.




I remember it something like switch( userValue ) with( Status 
){...},
but not sure about it. Maybe it was D1 code. Is there anything 
like this

currently?


What this does (and yes, it should work) is make it so you 
don't have to type "Status.Busy" within your case statements. 
You can just type "Busy". That's all.


-Steve


As far as I see, "default" case is not allowed when final switch
is used. From compiler developer's perspective, it is meaningful
and I can understand, but thinking about use cases as I have
given an example, this limitation prevents writing "tight" code.
(That is the term I could have found to express I am trying to 
say).


switch with enum

2015-11-24 Thread tcak via Digitalmars-d-learn
I have seen a code a while ago, but even by looking at 
documentation, I couldn't have found anything about it.


Let's say I have defined an enum;

enum Status: ubyte{
 Busy = 1,
 Active = 2
}

and received a ubyte value from user.

ubyte userValue;

I want to switch over userValue, but that should depend on Status.

switch( userValue ){
...
}

What I mean is that compiler should enforce values of enum 
"Status" to be declared in switch as it would be done with "final 
switch", but as you can guess, user might enter a value that is 
not defined by Status. Thus, I should be able to enter the case 
"default" as well.


I remember it something like switch( userValue ) with( Status 
){...}, but not sure about it. Maybe it was D1 code. Is there 
anything like this currently?


Re: String interpolation

2015-11-10 Thread tcak via Digitalmars-d-learn

On Tuesday, 10 November 2015 at 11:22:56 UTC, wobbles wrote:

On Tuesday, 10 November 2015 at 10:41:52 UTC, tired_eyes wrote:
On Tuesday, 10 November 2015 at 10:33:30 UTC, Tobias Pankrath 
wrote:
On Tuesday, 10 November 2015 at 10:21:32 UTC, tired_eyes 
wrote:

[...]


std.string.format and std.format are the standard options. 
What are you missing?


Ruby:
a = 1
b = 4
puts "The number #{a} is less than #{b}"

PHP:
$a = 1;
$b = 4;
echo "The number $a is less than $b";

D:
???


int a = 1;
int b = 4;
writefln("The number %s is less than %s", a, b);


D:
int a = 1;
int b = 4;
writeln("The number ", a, " is less than ", b);


Compile time digest error

2015-11-09 Thread tcak via Digitalmars-d-learn

[code]
private static import std.digest.md;

public enum HashValue = std.digest.digest.digest!( 
std.digest.md.MD5)( "" );


void main(){}
[/code]

[output]
dmd main.d
/usr/include/dmd/phobos/std/digest/md.d(202): Error: 
reinterpreting cast from uint[16] to ubyte* is not supported in 
CTFE
/usr/include/dmd/phobos/std/digest/md.d(320):called from 
here: this.transform(&this._buffer)
/usr/include/dmd/phobos/std/digest/md.d(381):called from 
here: this.put(cast(const(ubyte)[])bits)
/usr/include/dmd/phobos/std/digest/digest.d(458):called 
from here: hash.finish()

main.d(3):called from here: digest("")
[/output]


I would expect MD5 to work on compile time, but as the error 
indicates, the uint[16] to ubyte* conversion prevents that. I 
tried with "std.digest.md.md5Of" as well, and same result. Is 
there any MD5 function that returns a fixed length array like 
ubyte[16] maybe?


Parse d source file by using compiler

2015-11-08 Thread tcak via Digitalmars-d-learn
I checked for a flag in this page http://dlang.org/dmd-linux.html 
, but couldn't have found any for this purpose.


Is there a way to parse a d source file so it generates a tree in 
JSON, XML, or something-that-can-be-processed-easily file format?


---

My real purpose:

I need to generate hash code (e.g. MD5) for a part of source code 
(let's say a class, struct, or a function). So whether the codes 
are changed or not can be detected. As you will guess, comments, 
text formatting etc. shouldn't affect the hash result.



Use-Case:

I am writing a code generator/back up system. It will check the 
last available code file. If important changes are done in a 
specific part of code, it will increase version number by 1.


Re: method has no return statement with switch

2015-11-06 Thread tcak via Digitalmars-d-learn

On Saturday, 7 November 2015 at 00:21:57 UTC, crimaniak wrote:

Hi!

I have the error message:
source/url.cache.d(20,16): Error: function 
url.Cache.UrlCache.doRequest has no return statement, but is 
expected to return a value of type string


[...]


Because the "switch" is marked as "final", eventually one of 
cases will be followed. Because both cases have a "return" point, 
code will never get out of switch statement. So the compiler acts 
correctly.


Re: Associative array with duplicated keys?

2015-11-05 Thread tcak via Digitalmars-d-learn
On Thursday, 5 November 2015 at 08:55:10 UTC, Andrea Fontana 
wrote:

Check this:
http://dpaste.dzfl.pl/ebbb3ebac60e

It doesn't give any error or warning. And writeln seems 
confused (do you see that "," at the end?)


I am sure the coder of writeln was lazy to prevent putting ", " 
after last item. You can report it as a bug I guess.


Re: good reasons not to use D?

2015-10-31 Thread tcak via Digitalmars-d-learn

On Saturday, 31 October 2015 at 14:37:23 UTC, rumbu wrote:

On Friday, 30 October 2015 at 10:35:03 UTC, Laeeth Isharc wrote:

I'm writing a talk for codemesh on the use of D in finance.

Any other thoughts?


For finance stuff - missing a floating point decimal data type. 
Things like 1.1 + 2.2 = 3.3003


I always thought that this type of arithmetic operations can be 
solved with BigInt, but never tried it. Since the issue is 
related to IEEE standard, a simulated (not supported by hardware 
directly) data type might be required.


Re: How coding bootloader with (Asm+Dlang)?

2015-10-28 Thread tcak via Digitalmars-d-learn

On Wednesday, 28 October 2015 at 15:23:11 UTC, guodemone wrote:
I would like to use (Dlang + nasm) to write bootloader, how to 
write?


Start from here:

http://wiki.osdev.org/D_Bare_Bones


I would suggest you to start by learning to do it with C first 
though. There are too many documents about this already. This 
way, you can make the conversion from C to D much easy later.


Re: I'm getting an unhelpful linker error, what've I got wrong?

2015-10-28 Thread tcak via Digitalmars-d-learn

On Wednesday, 28 October 2015 at 11:48:27 UTC, pineapple wrote:

On Wednesday, 28 October 2015 at 11:40:14 UTC, tcak wrote:
The "writebuffer" is defined to take an array as parameter. 
Yet, you are passing a pointer and a length to it. Instead, 
pass the parameter "str" to it directly. Also, you do not have 
to put "!char" to there. Compiler will solve it out by itself.


There's also a writebuffer method in the interface with this 
signature, though:


streamint writebuffer(T)(in T* buffer, in streamint count);

And regardless, changing the problematic code to this doesn't 
address the linker error:


final streamint writestring(in char[] str){
return this.writebuffer(str);
}
final streamint writestring(in string str){
return this.writebuffer(str);
}


This still doesn't solve everything, but the first thing to do is 
to define a method for those in the interface as well.


streamint writebuffer(T)(in T* buffer, in streamint count)
streamint writebuffer(T)(in T* buffer, in streamint count, bool 
dynamic);


Re: I'm getting an unhelpful linker error, what've I got wrong?

2015-10-28 Thread tcak via Digitalmars-d-learn

On Wednesday, 28 October 2015 at 11:11:01 UTC, pineapple wrote:
When I attempt to compile my code I get the same linker error 
with both dmd and ldc2. I know where the problematic code is, 
as I don't get the error when I comment out lines 102 through 
107, but I don't understand why it's bad. I must have some 
misconceptions about how templates work? Is there any way to 
get more descriptive errors out of the compiler if this sort of 
thing happens again in the future?


Here's the code:

http://pastebin.com/kGUPVa59

Here's the problematic lines:

final streamint writestring(in char[] str){
return this.writebuffer!char(str.ptr, str.length);
}
final streamint writestring(in string str){
return this.writebuffer!char(str.ptr, str.length);
}

And the linker error:

Undefined symbols for architecture x86_64:
  
"_D6stream6Stream19__T11writebufferTaZ11writebufferMFxPaxlZl", 
referenced from:

  _D6stream6Stream11writestringMFxAaZl in stream.o
  _D6stream6Stream11writestringMFxAyaZl in stream.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use 
-v to see invocation)

--- errorlevel 1


The "writebuffer" is defined to take an array as parameter. Yet, 
you are passing a pointer and a length to it. Instead, pass the 
parameter "str" to it directly. Also, you do not have to put 
"!char" to there. Compiler will solve it out by itself.


Mixin template parameter that is an undefined variable

2015-10-23 Thread tcak via Digitalmars-d-learn

[code]
mixin template Test(alias a){
int a;
}

void main(){
mixin Test!blah;
}
[/code]

Compiler says it doesn't know about "blah". My purpose is to
define the parameter as a variable. Is that possible?


Re: How to check whether an empty array variable is null?

2015-10-10 Thread tcak via Digitalmars-d-learn
On Saturday, 10 October 2015 at 20:07:11 UTC, Jonathan M Davis 
wrote:
On Saturday, October 10, 2015 15:20:02 tcak via 
Digitalmars-d-learn wrote:

[code]
  int[] list;

  list = new int[0];

  std.stdio.writeln("Is Null ? ", (list is null));
[/code]

Result is "Is Null? true".

Is this the correct behaviour? I would expect compiler to 
point to an address in the heap, but set the length as 0. So, 
it wouldn't return null, but the length would be 0 only.


It basically didn't bother to allocate an array on the heap, 
because you asked for one with a length of zero. 
Efficiency-wise, it makes no sense to allocate anything. You 
wouldn't be doing anything with the memory anyway. The only way 
that you're going to get an array of length 0 which doesn't 
have a null ptr is to slice an array down to a length of 0.


- Jonathan M Davis


The situation is that the "length" parameter comes from user. 
Also the item values come from user as well. I create the array 
with "length" parameter. At another part of code, I check firstly 
whether the array is created [code] if( array is null ) [/code], 
then the items are checked for validation.


How to check whether an empty array variable is null?

2015-10-10 Thread tcak via Digitalmars-d-learn

[code]
int[] list;

list = new int[0];

std.stdio.writeln("Is Null ? ", (list is null));
[/code]

Result is "Is Null? true".

Is this the correct behaviour? I would expect compiler to point 
to an address in the heap, but set the length as 0. So, it 
wouldn't return null, but the length would be 0 only.


Re: Check template parameter whether it has "length"

2015-10-08 Thread tcak via Digitalmars-d-learn

On Thursday, 8 October 2015 at 09:50:12 UTC, John Colvin wrote:

On Thursday, 8 October 2015 at 09:29:30 UTC, tcak wrote:

[...]


I'm 99% sure something like __traits(hasMember, int[], "length" 
) should evaluate to true. Please file a bug at 
issues.dlang.org   I notice it also doesn't work for "ptr".


The correct workaround:
__traits(compiles, A.init.length ));
or
__traits(compiles, listOfStrings.length ));

A.length doesn't work because length is not a static member, so 
it's only accessible from an instance.


The __traits(compiles, ...) solution is actually more general 
because it will work if .length is implemented via UFCS and 
opDispatch.


FYI:
If you want to check whether a statement will compile, as 
opposed to an expression, make a function/delegate out of it, 
e.g.:

__traits(compiles, { size_t n = A.init.length; });
to check that A has a member length that can be assigned to 
size_t.


P.S. always check std.traits for solutions all your static 
reflection problems, there's a lot of good stuff in there.


__traits(compiles, { size_t n = A.init.length; });  did the trick.

[code]
size_t maxLength(A)( const A[] listOfString )
if( __traits( compiles, { size_t len = A.init.length; } ) )
{
size_t len = 0;

foreach(A str; listOfString)
if( str.length > len ) len = str.length;

return len;
}
[/code]

BTW, there is nothing like std.traits.hasLength.


Re: Tell GC to use shared memory

2015-10-08 Thread tcak via Digitalmars-d-learn

On Thursday, 8 October 2015 at 05:46:31 UTC, ketmar wrote:

On Thursday, 8 October 2015 at 04:38:43 UTC, tcak wrote:
Is it possible to modify GC (without rebuilding the compiler), 
so it uses a given shared memory area instead of heap for 
allocations?


sure. you don't need to rebuild the compiler, only druntime.


Any better solution? Like overriding GC class, etc.


Check template parameter whether it has "length"

2015-10-08 Thread tcak via Digitalmars-d-learn
I am "trying" to write a function that takes an array of items, 
and returns the length of longest item.


[code]
size_t maxLength(A)( const A[] listOfString ) if( __traits( 
hasMember, A, "length" ) )

{
return 0; // not implemented yet
}
[/code]

I tried it with

if( __traits( compiles, A.length ) )

as well. But compiler doesn't match it.

writeln("Max Length: ", maxLength( ["foo", "123456789"] ));

Compilers says it cannot deduce function from argument types ...

I do not want to check whether the type "A" is string, char[], 
etc. As long as it has length (please do not put me into ranges, 
library functions etc as much as possible), I want the function 
to accept it.


Tell GC to use shared memory

2015-10-07 Thread tcak via Digitalmars-d-learn
Is it possible to modify GC (without rebuilding the compiler), so 
it uses a given shared memory area instead of heap for 
allocations?


What is the postfix for min long value?

2015-10-06 Thread tcak via Digitalmars-d-learn
While writing max ulong value, I added the "u" postfix. So 
compiler accepted it as ulong value (That's my interpretation if 
correct on compiler's side).


writeln( 18_446_744_073_709_551_615u );

But when I try to print out minimum value of long, compiler says
Error: signed integer overflow

writeln( -9_223_372_036_854_775_808 );

In case that is the wrong value, I checked it with writeln( 
long.min ); already.


Do I need to put a postfix for that number? I checked 
documentation by searching "dlang integer" etc, but couldn't have 
found any information/anything about postfix at all.


Bug? 0 is less than -10

2015-10-06 Thread tcak via Digitalmars-d-learn

Maybe I am just too stressed out to see the problem.

[code]
import std.stdio;

void main(){
size_t dec = 0;

	writeln( dec, " ", (dec <= -10), " ", (dec >= 10), " ", ((dec <= 
-10) || (dec >= 10)) );

}
[/code]

[output]
0 true false true
[/output]

How is it generating "true" for (dec <= -10) ? Is there a special 
casting or something?


DMD 2.068.2, Ubuntu 64-bit


Re: Server side command execution.

2015-09-27 Thread tcak via Digitalmars-d-learn

On Sunday, 27 September 2015 at 23:56:10 UTC, holo wrote:

Hello

Im trying to execute commands on server side. Here is my server 
based on other example from forum:


[...]


You are comparing whole buffer to "exit"


Re: Client socket sending data only one time.

2015-09-24 Thread tcak via Digitalmars-d-learn

On Thursday, 24 September 2015 at 14:20:39 UTC, holo wrote:

Hello

I'm trying to connect to server and send data, with such simple 
client:


#!/usr/bin/rdmd

import std.stdio;
import std.socket;
import std.socketstream;
import std.process;
import std.conv;
import core.time;

void main()
{
char[1024] buffer = 0;

Socket client = new TcpSocket();
auto addrServer = new InternetAddress("localhost", 
8080);

client.connect(addrServer);

while(1)
{

client.send(readln());
client.receive(buffer);
writeln(buffer);
buffer = 0;
 }
}

It is working but only one time, when I'm trying to send again 
(second loop of while) it's stooping on readln() but not 
sending input data.


What am i missing here?

Thanks in advance for any help.


Where is the other side of this client? There must be a TCP 
Server to listen connections, and create a second TCPSocket for 
communication. There is only one TCPSocket in your code. A lot of 
things are missing there. I would suggest you to check "C 
TCPSocket example" in your favourite search engine.


Re: Why is the constructor of B called?

2015-09-23 Thread tcak via Digitalmars-d-learn
On Wednesday, 23 September 2015 at 21:14:17 UTC, Adam D. Ruppe 
wrote:

On Wednesday, 23 September 2015 at 21:08:37 UTC, tcak wrote:
I wouldn't expect B's constructor to be called at all unless 
"super" is used there.


"If no call to constructors via this or super appear in a 
constructor, and the base class has a constructor, a call to 
super() is inserted at the beginning of the constructor. "



from http://dlang.org/class.html#constructors

the idea is to make sure the base class construction work is 
done too.


Is there any way to prevent this behaviour?

Quickly checked whether Java acts in the same way. Answer is yes.


  1   2   3   >