vendredi 14 août 2015

How to change VAR name without getting the undeclared error after 'make install'?

My configure.in file has:

VAR=yo
AC_SUBST(VAR)

Makefile.am has:

bin_PROGRAMS = hello
hello_SOURCES = hello.c 
hello_CFLAGS =-DVAR=@VAR@

C file is:

#include <stdio.h>
int main()
{
    printf("%s\n",VAR);
    return 0;
}

When I do 'make install' there is error

Making install in src
make[1]: Entering directory `/home/albertpod/hello/src'
if gcc -DPACKAGE_NAME=\"hello\" -DPACKAGE_TARNAME=\"hello\" -DPACKAGE_VERSION=\"1.0\" -DPACKAGE_STRING=\"hello\ 1.0\" -DPACKAGE_BUGREPORT=\"\" -DPACKAGE_URL=\"\" -DPACKAGE=\"hello\" -DVERSION=\"1.0\" -I. -I.    -DVAR=yo -g -O2 -MT hello-hello.o -MD -MP -MF ".deps/hello-hello.Tpo" -c -o hello-hello.o `test -f 'hello.c' || echo './'`hello.c; \
    then mv -f ".deps/hello-hello.Tpo" ".deps/hello-hello.Po"; else rm -f ".deps/hello-hello.Tpo"; exit 1; fi
hello.c: In function ‘main’:
hello.c:8:13: error: ‘yo’ undeclared (first use in this function)
hello.c:8:13: note: each undeclared identifier is reported only once for each function it appears in
make[1]: *** [hello-hello.o] Error 1
make[1]: Leaving directory `/home/albertpod/hello/src'
make: *** [install-recursive] Error 1

So name of VAR becomes yo, but it is undeclared. My goal is to print yo, but how to solve this case?



via Chebli Mohamed

Balanced Expression

Below is the code to determine balancing of symbol.

If the expression is balanced then print appropriate message

E.g. ((A+B))+(C+D)) --> Balanced

((A+B)+(C+D) ---> Unbalanced

((A+B)+(C+D}) --> Unbalanced

Here is the code

#include<stdio.h>
#include<stdlib.h>

struct Stack{
char data;
struct Stack *next;
};

void push(struct Stack **top,char data)
{
        struct Stack *new_node;
        if(*top==NULL)
        {
                new_node=malloc(sizeof(struct Stack));
                new_node->data=data;
                new_node->next=*top;
                *top=new_node;
        }
        else
        {
                new_node=malloc(sizeof(struct Stack));
                new_node->data=data;
                new_node->next=*top;
                *top=new_node;
        }
}
char pop(struct Stack **top,int flag)
{
        if(*top!=NULL && flag==0)
        {
                printf("\n Expression is In-Valid  :) \n");
                return '\0';
        }
        if(*top==NULL && flag ==1)
        {
                printf("\n Unbalanced Expression \n");
                return '\0';
        }
        if(*top!=NULL && flag==1)
        {
                struct Stack *temp=*top;
                char op;
                op=(*top)->data;
                *top=(*top)->next;
                free(temp);
                return op;
        }
}
/*void display(struct Stack *top)
{
        struct Stack *temp=top;
        while(temp)
        {
                printf("\n %c",temp->data);
                temp=temp->next;
        }
} */
int main(void)
{
        struct Stack *top=NULL;
        int i=0;
        char str[]="((A+B)+[C+D])",op;
        printf("\n Running the programe to check if the string is balanced or not ");
        for(i=0;str[i]!='\0';++i)
        {
                if(str[i]=='('||str[i]=='['||str[i]=='{'||str[i]=='<')
                        push(&top,str[i]);
                else if(str[i]==')'||str[i]==']'||str[i]=='}'||str[i]=='>')
                {
                        op=pop(&top,1);
                        if( (op=='('&&str[i]==')') || (op=='['&&str[i]==']') || (op=='{'&&str[i]=='}') || (op=='<'&&str[i]=='>'))
                        {
                                continue;
                        }
                        else
                        {
                                printf("\n The expression is un-balanced \n");
                                break;
                        }

                }

        }
        pop(&top,0);
        return 0;
}

But it does not give the desirable output. I have debuged the code but not able to find the issue

Can u please help and look into it ?



via Chebli Mohamed

How to use abs and div with fixed-size integers

In C99 we have fixed-size integer types, defined in stdint.h. In stdlib.h we have the abs and div functions which operate on ints, as well as their long int/long long int counterparts labs, llabs, ldiv, lldiv.

Since the size of int/long/long long varies based on platform and used compiler I wonder how to chose the right variant of abs/div when using fixed-size integers like int16_t, int32_t or int64_t?



via Chebli Mohamed

How to concatenate a name of file using fopen function?

I want to create a file which I create this code:

void create_file(char name[],char user[],char date[]){

FILE* fichier=NULL;
fichier=fopen(strcat(name,".txt"),"a+");
fprintf(fichier,"user: %s connected at : %s \n",user,date);
fclose(fichier);

}

But it doesn't work.



via Chebli Mohamed

[solved]prevent strings overflowing in c

Using C I want to allocate heap space of the maximum initial string length which is 6 in my case and then each time the string is about to overflow, double the available space. I want to build the string char by char.

size_t nstring = 6;
char *arr =  malloc(nstring);

int i;
for (i = 0; i < 55;i++){

        if (i == nstring) {
                printf("mAx sized!!");
                arr = realloc(arr, nstring*2);
                nstring = nstring*2;
            }
    arr[i] = 'f';

}
arr[i] = '\0';
printf("length %lu\n", strlen(arr));
free(arr);



via Chebli Mohamed

Re-allocating array of structure with realloc?

I'm practicing on structures, dynamic memory and file I/O but I can't understand what is wrong with this code. I suspect that the error is with realloc function. When I run the program after the file opening, the program crash. I check a lot of times and I suppose that is not a syntax related problem(especially with realloc).

Structure declaration:

#define MAXLENPATH 250
#define MAXSTRING 25

typedef struct
{
    int ID;
    char Name[MAXSTRING];
    char Surname[MAXSTRING];
    char code[MAXSTRING];
    int age;
}person;

Function to get record info:

#include <stdio.h>
#include <stdlib.h>
#include "Data.h"
#include "DataBase.h"

void initRecord(person *Person)
{
    printf("Insert ID:\n");
    scanf("%d", &Person->ID);

    printf("Insert Name:\n");
    scanf("%s", Person->Name);

    printf("Insert Surname:\n");
    scanf("%s", Person->Surname);

    printf("Insert Age:\n");
    scanf("%d", &Person->age);

    printf("Insert code:\n");
    scanf("%s", Person->code);

}

Main function:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Data.h"
#include "DataBase.h"

int main(void) {

    FILE *ts;
    char *fpath=NULL;
    int pCount=1; //variable to hold database records count
    int i=0;
    int toAdd=0;
    person *personDB=NULL;

    fpath="C:\\Users\\Pio\\Desktop\\FILEOP\\MYTXT.txt";

    personDB = malloc(pCount*sizeof(person));

    //fill the database(in memory)
    i=0;
    while( i < pCount)
    {
        printf("Record %d\n",i+1);
        initRecord(&personDB[i]); //fill i-th database record
        printf("Record %d ID:%d Name:%s Surname:%s Age:%d Code:%s \n", i+1, personDB[i].ID, personDB[i].Name, personDB[i].Surname, personDB[i].age, personDB[i].code );
        i++;


        if(i == pCount) // check if all records are filled, then ask to user how many records wants and realloc new memory
        {
            printf("Insert element to add to database records:");
            scanf("%d", &toAdd);
            personDB=realloc(personDB, toAdd*(sizeof(person)) );
            pCount += toAdd;
        }

    }

    //Print structure on file
    if ((ts=fopen(fpath, "w")) != NULL)
    {
        puts("FILE OPENED");
        fprintf(ts,"************INFO****************\n");
        i=0;
        while (i < pCount)
        {

            fprintf(ts, "Record %d ID:%d Name:%s Surname:%s Age:%d Code:%s \n", i+1, personDB[i].ID, personDB[i].Name, personDB[i].Surname, personDB[i].age, personDB[i].code );

            i++;

        }
        fclose(ts);
    }
    else
        perror("ERROR:");

    system("pause");
    return EXIT_SUCCESS;
}



via Chebli Mohamed

Can I do data buffering and data plotting at the same time?

I am using Quartus 12.1 sp1, vhdl and Altera Nios II programmed in C code for DE0-Nano Development. Basically, what I have is, data is sent from fpga vhdl block to NIos II system, Nios II system sends the data to serial port, Matlab access the serial port to real time plot the graph.

I am buffering data received from fpga vhdl say 1000 sample points and save it in sdram... after saving these 1000 sample points, the C code will send data to uart so that Matlab can access these serial port data and plot the graph real time.

Once the sdram has all the first 1000 samples points, processor sends the data to serial port for Matlab to plot the graph, then processor proceeds to save the second set of 1000 samples points, then processor sends the data to serial port for Matlab in order to plot the graph, keep repeating for following sets....etc

In my system, the rate the graph is plotted is much slower than the rate the buffering can be done.

My question is, from the perspective of C programming, when the processor is sending data for plotting, can the processor still do the buffering? If not, what should I do so that when the processor is doing the buffering, I still can get the graph plotted at the same time for the previous set of data?

Appreciate any input, forgive newbie question...thank you



via Chebli Mohamed

Example MQTT Client Code not working C

I got the example code from:

http://ift.tt/1GTJ9Ut

Using -

MQTTClient.h

However when I build I get the errors:

undefined reference to MQTTClient_create
undefined reference to MQTTClient_connect
undefined reference to MQTTClient_publishMessage
undefined reference to MQTTClient_waitForCompletion
undefined reference to MQTTClient_disconnect

In the header file these are set up as follows:

DLLExport int MQTTClient_create(MQTTClient* handle, const char* serverURI, const char* clientId,
        int persistence_type, void* persistence_context);

I am using a Windows 8 machine with Eclipse C/C++ IDE

I also have some paho-mqtt.dll's I'm not sure how to get the example code up and running.

Thank you



via Chebli Mohamed

Why is the multithreaded version of this program slower?

I am trying to learn pthreads and I have been experimenting with a program that tries to detect the changes on an array. Function array_modifier() picks a random element and toggles it's value (1 to 0 and vice versa) and then sleeps for some time (big enough so race conditions do not appear, I know this is bad practice). change_detector() scans the array and when an element doesn't match it's prior value and it is equal to 1, the change is detected and diff array is updated with the detection delay.

When there is one change_detector() thread (NTHREADS==1) it has to scan the whole array. When there are more threads each is assigned a portion of the array.

Here is the code:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#define TERMINATION_TIME 5
#define TIME_INTERVAL 100
#define CHANGES 5000

#define UNUSED(x) ((void) x)

typedef struct {
    unsigned int tid;
} parm;

static volatile unsigned int* my_array;
static unsigned int* old_value;
static struct timeval* time_array;
static unsigned int N;

static unsigned long int diff[NTHREADS] = {0};

void* array_modifier(void* args);
void* change_detector(void* arg);

int main(int argc, char** argv) {
    if (argc < 2) {
        exit(1);
    }

    N = (unsigned int)strtoul(argv[1], NULL, 0);

    my_array = calloc(N, sizeof(int));
    time_array = malloc(N * sizeof(struct timeval));
    old_value = calloc(N, sizeof(int));

    parm* p = malloc(NTHREADS * sizeof(parm));
    pthread_t generator_thread;
    pthread_t* detector_thread = malloc(NTHREADS * sizeof(pthread_t));

    for (unsigned int i = 0; i < NTHREADS; i++) {
        p[i].tid = i;
        pthread_create(&detector_thread[i], NULL, change_detector, (void*) &p[i]);
    }

    pthread_create(&generator_thread, NULL, array_modifier, NULL);

    pthread_join(generator_thread, NULL);

    usleep(500);

    for (unsigned int i = 0; i < NTHREADS; i++) {
        pthread_cancel(detector_thread[i]);
    }

    for (unsigned int i = 0; i < NTHREADS; i++) fprintf(stderr, "%lu ", diff[i]);
    fprintf(stderr, "\n");
    _exit(0);
}


void* array_modifier(void* arg) {
    UNUSED(arg);
    srand(time(NULL));

    unsigned int changing_signals = CHANGES;

    while (changing_signals--) {
        usleep(TIME_INTERVAL);
        const unsigned int r = rand() % N;

        gettimeofday(&time_array[r], NULL);
        my_array[r] ^= 1;
    }

    pthread_exit(NULL);
}

void* change_detector(void* arg) {
    const parm* p = (parm*) arg;
    const unsigned int tid = p->tid;
    const unsigned int start = tid * (N / NTHREADS) +
                               (tid < N % NTHREADS ? tid : N % NTHREADS);
    const unsigned int end = start + (N / NTHREADS) +
                             (tid < N % NTHREADS);
    unsigned int r = start;

    while (1) {
        unsigned int tmp;
        while ((tmp = my_array[r]) == old_value[r]) {
            r = (r < end - 1) ? r + 1 : start;
        }

        old_value[r] = tmp;
        if (tmp) {
            struct timeval tv;
            gettimeofday(&tv, NULL);
            // detection time in usec
            diff[tid] += (tv.tv_sec - time_array[r].tv_sec) * 1000000 + (tv.tv_usec - time_array[r].tv_usec);
        }
    }
}

when I compile & run like this:

gcc -Wall -Wextra -O3 -DNTHREADS=1 file.c -pthread && ./a.out 100

I get:

665

but when I compile & run like this:

gcc -Wall -Wextra -O3 -DNTHREADS=4 file.c -pthread && ./a.out 100

I get:

152 190 164 242

(this sums up to 748).

So, the delay for the multithreaded program is larger.

My cpu has 6 cores.



via Chebli Mohamed

Why does the compiler complain about the code

I do not understand the cause of the error:

"/pkg/qct/software/arm/RVDS/5.01BLD94/include/assert.h", line 40: Error:  #18: expected a ")"
  extern _ARMABI_NORETURN void abort(void);

The code is as follow:

28 #ifndef __assert_h                                                              
29 #   define __assert_h                                                           
30 #define _ARMABI_NORETURN __declspec(__nothrow) __declspec(__noreturn)           
31 #define __ARMCLIB_VERSION 410000                                                
32 #   undef __CLIBNS                                                              
33 #   ifdef __cplusplus                                                           
34         namespace std {                                                         
35 #           define __CLIBNS ::std::                                             
36             extern "C" {                                                        
37 #   else                                                                        
38 #       define __CLIBNS                                                         
39 #   endif  /* __cplusplus */                                                    
40     extern _ARMABI_NORETURN void abort(void);                                   
41     extern _ARMABI_NORETURN void __aeabi_assert(const char *, const char *, int)
   __attribute__((__nonnull__(1,2)));                                              
42 #   ifdef __cplusplus                                                           
43             }  /* extern "C" */                                                 
44         }  /* namespace std */                                                  
45 #   endif                                                                       
46 #else                                                                           
47 #   undef assert                                                                
48 #   undef __promise                                                             
49 #endif                                                                          

The code is from RVDS. I do not think there is a bug in the header file of the compiler.



via Chebli Mohamed

Ambiguity in 2d array declaration in C

I have defined array in the following formats, but apparently the program works fine only in CASE B.

CASE A:

int **M1;
M1 = (int **)malloc(m * sizeof(int *));
for (int i=0; i<m; i++){
    M1[i] = (int *)malloc(d * sizeof(int));
} 

CASE B:

int (*M1)[m] = malloc(sizeof(int[m][d]));

I am getting a segmentation error in CASE A. What could be the reason?



via Chebli Mohamed

Application get stuck in GDB with gettimeofday() and watchpoints on registers

I'm just doing some experiments using GDB and playing around with the registers, but I encounter a problem when using the syscall gettimeofday() and a watchpoint on a register.

first let me expose a little example of what I am doing.

ok, here is the code which I am using (very simple):

#include <stdio.h>

main()
{
        int num;

        getchar();

        num=190320;

        printf("value: %d\n", num);
}

well, what I am doing is just run the program (which stop at the getchar() funtion until I press enter) and then attach the program to a gdb session in other shell:

gdb -p <pid>

now I just add a conditional watchpoint on the "rdi" register so I can check the status of the program when the variable "num" is assigned :

(gdb) watch $rdi == 190320
Watchpoint 1: $rdi == 190320

and now continue the program execution on gdb and push enter on the other shell where I am running the program, and as you can see gdb stop the program in the watchpoint just like I wanna.

(gdb) c
Continuing.
Watchpoint 1: $rdi == 190320

well, this is the version that works like I just expect, a simple application that runs ok and a watchpoint that stop in the right moment.

Ok, now go to the problem itself.

this is the same program I used before but with the difference that I use a gettimeofday() before the variable assignation:

#include <stdio.h>

main()
{
        int num;

        struct timeval tim;

        getchar();

        gettimeofday(&tim, NULL); /* <---- Here is !!!*/

        num=190320;

        printf("value: %d\n", num);

}

and now repeat the same steps I did before:

-run the program in a shell

-attach the program to a gdb session in another shell

-set the conditional watchpoint on "rdi" register

but now when I continue the execution in gdb and push enter in the shell where the program is running, the program just get stuck at the gettimeofday() function.

if I press "Ctrl+C" on gdb I can check that the program is stuck in this function

(gdb) c
Continuing.

^C
Program received signal SIGINT, Interrupt.
0x00007ffc88b85e3c in gettimeofday ()

now if I disable the watchpoint and try to continue the execution again, all goes fine, and the program ends with no problem (obviously the watchpoint is disable and gdb doesn't stop the program in the moment that I want to).

(gdb) info breakpoint
Num     Type           Disp Enb Address    What
1       watchpoint     keep y              $rdi == 190320
(gdb) disable 1
(gdb) c
Continuing.
[Inferior 1 (process 4151) exited with code 016]

so I can verify that the cause of the program get stuck is the watchpoint set in the register...

So the question is, can someone explain why is this happening? and, is there any way to solve this issue and do the program doesn't get stuck in the gettimeofday() function and reach the watchpoint?

PD: I know that I can stop the program in the variable assignation using other methods but this is just an experiment and I just want the explanation of why is this happening

PD2: Sorry for my bad english, it's not my mattern language.



via Chebli Mohamed

What does this code mean

I found a code segment. I do not understand it. It seems that the variable __rem is useless at all. The line below does not do any useful work yet:

(void)(((typeof((n)) *)0) == ((uint64_t *)0));   \

The whole code segment is as below:

#define do_div(n,base)  do{             \
    uint32_t __base = (base);           \
    uint32_t __rem;                 \
    (void)(((typeof((n)) *)0) == ((uint64_t *)0));   \
    if (((n) >> 32) == 0) {         \
        __rem = (uint32_t)(n) % __base;     \
        (n) = (uint32_t)(n) / __base;       \
    } else                      \
        __rem = __div64_32(&(n), __base);   \
    __rem;                      \
 }while(0)
/* Wrapper for do_div(). Doesn't modify dividend and returns
 * the result, not reminder.
 */
static inline uint64_t lldiv(uint64_t dividend, uint32_t divisor)
{
    uint64_t __res = dividend;
    do_div(__res, divisor);
    return(__res);
}

Why is the useless code here?



via Chebli Mohamed

Keyboard accelerator doesn't catch CTRL + A

I have a window with a menu and an edit class handle. In the menu I have an Edit section with some options like cut, copy, paste, ecc.

I have defined 2 keyboard accelerators:

IDR_ACCELERATOR2 ACCELERATORS
BEGIN
    "A",            ID_EDIT_SALL,           VIRTKEY, CONTROL, NOINVERT
    "Z",            ID_EDIT_UNDO,           VIRTKEY, CONTROL, NOINVERT
END

CTRL + Z works, but CTRL + A doesn't. In the WM_COMMAND case I have this:

switch (LOWORD(wParam))
            {
            case ID_EDIT_CLEAR:
                SendMessage(hwndEdit, WM_CLEAR, 0, 0);
                break;
            case ID_EDIT_COPY:
                SendMessage(hwndEdit, WM_COPY, 0, 0);
                break;
            case ID_EDIT_CUT:
                SendMessage(hwndEdit, WM_CUT, 0, 0);
                break;
            case ID_EDIT_PASTE:
                SendMessage(hwndEdit, WM_PASTE, 0, 0);
                break;
            case ID_EDIT_SALL:
                SendMessage(hwndEdit, EM_SETSEL, 0, -1);
                break;
            case ID_EDIT_UNDO:
                SendMessage(hwndEdit, WM_UNDO, 0, 0);
                break;
            }

When I click on the menu option Select All, the option works well, it does select all the text in the editor handle, but when I try to use the keyboard combination CTRL+A Windows makes that error sound (like when you try to delete words in an empty document)



via Chebli Mohamed

C Programming If Statements Not Working

My if statements aren't working and I am not sure why. Can someone point out my error, thank you. This is just a kinda dumb program I am making just for practice, I am setting a lot more variables along the way.

#include <stdio.h>

main()
{

    //This is a program that determines what circle of hell the user will be put in.  Inspired by Dante's Divine Comedy
    char firstQuestion;

    float total = 0;

    printf("ABANDON ALL HOPE, YOU WHO ENTER HERE\n\n");
    printf("Welcome to the gate of hell. I am going to ask you a series of questions and you will answer them truthfully.\n\n\n");

    printf("I would first like to ask you, do you believe you are a good person?(Y or N)\n");
    scanf_s(" %c", &firstQuestion);
    if (firstQuestion == 'Y'){
        printf("We will see about that.\n");
        total = total + 10;
    }
    else if (firstQuestion == 'N'){
    printf("I'm not surprised.\n");
}
    return 0;

}



via Chebli Mohamed

preference of kmalloc over array in kernel space of a process

I was reading some material on memory allocation in kernel space of a process. even though i know that kernel has some small/limited amount of memory(usually 1GB) but why dynamic allocation of memory through kmalloc()is preferred/recommended on defining large arrays? In other words it is not preferred to allocate large array in kernel space but instead use of dynamically allocated memory is recommended.

My point of contention is that even if a very big array is defined, it will get actual memory only when needed so it will put less pressure on memory. whereas Kmalloc() will assign all demanded memory. 2nd problem is that as kmalloc assign physical memory, finding/preparing demanded size will put extra pressure on system.

But if i read this preference in many sources then there will be some justified reason far away from my reasoning. Can anybody throw light on merits and demerits(if any) for using array and kmalloc() in kernel space



via Chebli Mohamed

c/c++ socket sending data after disconnection

Im wirting a socket code with c/c++ and socket.h library and my server and clients are stream socket with tcp protocol. I've got a class User that shows the clients connected.

class User
{
private:
int sockfd;
int n;
thread * Thread;
public:
User ( int sockfd);
void Get_Message();
void Join();  
~User();
};
User::User ( int sockfd)
{
this->sockfd=sockfd;
Thread=new thread(&User::Get_Message,this);
}
void User::Get_Message()
{
while (1)
{
readmessage(sockfd);
}
}
void readmessage (int sock)
{
int n=0;
char buffer[256];
bzero(buffer,256);
n = read(sock,buffer,255);
if (n < 0) 
{
 error("ERROR reading from socket ");
}

cout<<"the message\t"<<buffer<<endl;
} 

now this code works and several clients can join my server and send message;

but when one of those clients dissconnect the server it keeps printing "the message:" and I don't know why and how to stop it... I'll be greatful if anybody helps me why and how to fix it.



via Chebli Mohamed

Overwriting character in dynamically allocated array in c

I am trying to overwrite character in 2D array.

Here is my code

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int i,j;

    char** arr=malloc(sizeof(char*)*4);
    for ( i = 0; i<4;i++){      
            arr[i] = malloc(sizeof(char)*4);            
        }
    for ( i = 0; i<4; i++){
        for ( j = 0; j<4; j++){         
            if((i==0&&j==0)||(i==0&&j==3)||(i==3&&j==0)||(i==3&&j==3)){         
                arr[i][j] = '=';    
                }
            else{
                arr[i][j] = ' ';
                }                               
            printf("%c", arr[i][j]);
            }   

        printf("\n");
        }       
    arr[1][1]= '+';
    printf("%c", arr);
    return 0;
}

2D array with spcae-bar is printed firstly and i am trying to overwrite '+' in the arr

therefore, firstly, the code will return 2D array.

Assume that 0 is space-bar since i cannot upload image yet in stackflow ;(

=00=

0000

0000

=00=

After then i want to add + in the arr[1][1], so 2D array will be printed as

=00=

0+00

0000

=00=

Any help would be appreciated



via Chebli Mohamed

Valgrind test for Extending Python with C

I want to check memory leak in my C extending modules for Python3 with valgrind. I downloaded the valgrind suppression file (http://ift.tt/1TAc7Ne) and uncomment the lines for PyObject_Free and PyObject_Realloc in this file. Then I run valrgind test:

valgrind --tool=memcheck --suppressions=valgrind-python.supp \
                                      python3 -E -tt ./my_python_script.py

But, I get many errors if I even execute just "print('hello world')", e.g:

==13735== ERROR SUMMARY: 604 errors from 45 contexts (suppressed: 0 from 0)

What's wrong? Why so many errors? How can I check my apps?

$ uname -a
Linux mongo-r4 3.8.0-31-generic #46~precise1-Ubuntu SMP Wed Sep 11 18:21:16 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

$ valgrind --version
valgrind-3.10.0.SVN

$ python3 --version
Python 3.4.0



via Chebli Mohamed

jeudi 13 août 2015

How to develop C project using maven with nar plugin.

I want to use maven to run my c project

A solution that would help me to run mvn compile so that it will compile my .c file and give a.out file.



via Chebli Mohamed

C programming Zig Zag pratice

I have a exercise in objective C by using For, If-else, printf to print a Zig-Zag like this in console :

IMAGE:
enter image description here

I try many way but keeping fail all times. I really need helps. Thank you.



via Chebli Mohamed

Find maximum damage [on hold]

Our hero Harry Potter is back in action. He is in midst of a fight against The Dark Lord Voldemort. Being a beginner in wizardry, he knows a limited number of spells and the damages they would do to Voldemort.

Here comes the Twist.

Harry knows n attacks 1,2,3,..,n with damages a[1],a[2],...,a[n]. As soon as he selects a particular spell to cast, Voldemort performs some dark magic and disables both the previous and the next attacks of Harry i.e. if Harry selects the ith spell, his i-1th and i+1th spells get disabled automatically.

Only one attack would be disabled in case Harry selects 1st or nth attack.

Harry seeks your help to find out the maximum damage he can cause to Voldemort using all the possible attacks.

Note that, if Harry is not able to do any damage to Voldemort, you need to warn Harry by printing "DANGER".

What algo should be used.

I am trying to find maximum element and remove the adjoining element but that gives wrong answer. Sample Input

2

5 6 5 1 3 4

3

4 10 1

Sample Output

11

10



via Chebli Mohamed

libva - undefined reference to 'av_frame_alloc' and more

I am trying to compile this tutorial from the libav doc: link

I changed nothing on the code!

But when I compile it with:

gcc test.c -lavformat -lswscale -lavdevice -lavformat -lavcodec -lavutil -lpthread -lm .o example

I get these errors:

undefined reference to `check_sample_fmt'
undefined reference to `select_sample_rate'
undefined reference to `select_channel_layout'
undefined reference to `av_frame_alloc'
undefined reference to `av_frame_free'

Searching Dr.google I read that it maybe has something to do with the linking order of the libs. But I did not found the correct one yet?!



via Chebli Mohamed

C/C++ API/Libraries/etc

I have been learning c and c++ for a while. basically i know everything pointers classes heap,stack,virtuals. Sure I can make classes objects whatever but I cant make something useful. Also how extacly people managed to make an API if there are not functions that can implement some of the API methods. I Have seen people using Graphics Api's,curl But never understand how it was actually built from the start and right now from what I say on the internet people don't even have a disscusion about it. cause they are just looking for short ways of making things. I would appreciate if someone could help me understand how all of this works.



via Chebli Mohamed

Can we omit the data types of function arguments?

while studying a quine program in C, I found that, main was passed with just a, there is no datatype. The below runs fine and outputs the program correctly.

main(a){printf(a="main(a){printf(a=%c%s%c,34,a,34);}",34,a,34);}

I would like to know, how does this work (not the actual quine program), but what is data-type of a? What value is it getting?



via Chebli Mohamed

'?' not working in C Posix regular expressions

I am trying to extract a string within double quotes in C. For example:

String[100] = "Hi,\"This is awesome\" and \"So is this\""

I only need to find the first match, "This is awesome". And this is what I tried,

regcomp(&preg, "\"(.*?)\"", REG_EXTENDED);
regexec(&preg, String, 2, regm, 0);

where regm is the match array.

Instead of "This is awesome", I get "This is awesome and So is this" as the match.

Shouldn't the ? in (.*?) limit the reg exp to finding the first match?



via Chebli Mohamed

A robot is programmed to move forward F meters and backwards again

Question

A robot is programmed to move forward F meters and backwards again, say B meters, in a straight line. The Robot covers 1 meter in T units of time. On Robot's path there is a ditch at a distance FD from initial position in forward direction as well as a ditch at a distance BD from initial position in backward direction. This forward and backward movement is performed repeatedly by the Robot.

Your task is to calculate amount of time taken, before the Robot falls in either ditch, if at all it falls in a ditch.

First line contains total number of test cases, denoted by N Next N lines, contain a tuple containing 5 values delimited by space F B T FD BD.

where,

  • F denotes forward displacement in meters
  • B denotes backward displacement in meters
  • T denotes time taken to cover 1 meter
  • FD denotes distance from Robot's starting position and the ditch in forward direction
  • BD denotes distance from Robot's starting position and the ditch in backward direction

Test Cases

  • Sample Input

3

9 4 3 13 10

9 7 1 11 13

4 4 3 8 12

  • Sample Output

63 F

25 F

No Ditch



via Chebli Mohamed

C - Unable to implement Tiny Encryption Algorithm (Unexpected Values)

For grins, I'm trying to implement a version of the Tiny Encryption Algorithm (TEA) that will eventually go on an Arduino. Yes, I know that TEA is broken, but that's ok -- it won't be used for anything other than my meandering curiosity.

Output:

Encrypted: [ DC2F C574 ]
Decrypted: [ 698D 5E42 ]

Code:

#include <stdio.h>
#include <stdint.h>

uint16_t KEY[4];

void encrypt(uint16_t *v) {
  uint16_t v0=v[0], v1=v[1], sum=0, i;           // set up
  uint16_t delta=0x9e37;                         // a key schedule constant
  for (i=0; i < 32; i++) {                       // basic cycle start
    sum += delta;
    v0 += ((v1<<4) + KEY[0]) ^ (v1 + sum) ^ ((v1>>5) + KEY[1]);
    v1 += ((v0<<4) + KEY[2]) ^ (v0 + sum) ^ ((v0>>5) + KEY[3]);  
  }                                              /* end cycle */
  v[0]=v0; v[1]=v1;
}       

void decrypt (uint16_t* v) {
    uint16_t v0=v[0], v1=v[1], sum=0xC6EF, i;  /* set up */
    uint16_t delta=0x9e37;                     /* a key schedule constant */
    for (i=0; i<32; i++) {                     /* basic cycle start */
        v1 -= ((v0<<4) + KEY[2]) ^ (v0 + sum) ^ ((v0>>5) + KEY[3]);
        v0 -= ((v1<<4) + KEY[0]) ^ (v1 + sum) ^ ((v1>>5) + KEY[1]);
        sum -= delta;
    }                                              /* end cycle */
    v[0]=v0; v[1]=v1;
}

int main()
{
        // uint16_t is the same as an unsigned short
        // equal to 2 bytes or 16 bits
        // each hex is a nibble so 0xFFFF or 65535 is max val
        uint16_t v[] = {0xFFFF, 0xFFFF};

        encrypt(v);

        printf(" Encrypted: ");
        printf("[ %X %X ]", v[0], v[1]);

        decrypt(v);
        printf("\n Decrypted: ");
        printf("[ %X %X ]", v[0], v[1]);
        printf("\n");

        return 0;
}



via Chebli Mohamed

What is the best youtube channel for learning programming language C?

I am new to programming. I have never done programming before. I recently bought my laptop so i am new to internet and new to youtube as well. I want to learn programming from youtube videos. So I want link to the best youtube channel for learning the C language. Thanks in advance. http://www.youtube.com



via Chebli Mohamed

Make wchar_t upper case with LCMapString API

I'm curious about the LCMapString API for a Windows app. My goal is to capitalize a single wchar_t (or 2-byte character.) Am I safe to assume that it will always map it to a single wchar_t?

Or this:

wchar_t c1 = input_character;   //Say, L'd';
wchar_t c2 = 0;
if(LCMapString(LOCALE_INVARIANT, LCMAP_UPPERCASE, &c1, 1, &c2, 1))
{
    //Success, capitalized result is in `c2`
}



via Chebli Mohamed

C program is running but the output is not as expected?

So I'm trying to code a Rock, Paper and Scissor game (my homework) the problem is that it runs but the output is not what I'm expecting Here is the code:

    #include <stdio.h>
    #include <stdlib.h>

    int main (){
    int score1=0, score2=0;
    char p1, p2;
    printf ("ROCK, PAPER, SCISSOR GAME\n[R] ROCK, [P] PAPER, [S] SCISSOR\n");
    while (1){
    printf ("\nPlayer 1: ");
    p1=getch(); printf ("*");
    printf ("\nPlayer 2: ");
    p2=getch(); printf ("*");
        if ((p1=='R')||(p1=='r')&&(p2=='S')||(p2=='s'))
        if ((p1=='P')||(p1=='p')&&(p2=='R')||(p2=='r'))
        if ((p1=='S')||(p1=='s')&&(p2=='P')||(p2=='p'))
        score1++;
        printf ("\nWinner: Player 1\nPlayer 1: %d point%s\tPlayer 2: %d point%s\n", score1, (score1!=1) ? "s" : "", score2, (score2!=1) ? "s" : "");
        if ((p1=='S')||(p1=='s')&&(p2=='R')||(p2=='r'))
        if ((p1=='R')||(p1=='r')&&(p2=='P')||(p2=='p'))
        if ((p1=='P')||(p1=='p')&&(p2=='S')||(p2=='s'))
        score2=++;
        printf ("\nWinner: Player 2\nPlayer 1: %d point%s\tPlayer 2: %d point%s\n", score1, (score1!=1) ? "s" : "", score2, (score2!=1) ? "s" : "");
        if ((p1=='S')||(p1=='s')&&(p2=='S')||(p2=='s'))
        if ((p1=='R')||(p1=='r')&&(p2=='R')||(p2=='r'))
        if ((p1=='P')||(p1=='p')&&(p2=='R')||(p2=='r'))
        printf ("\nWinner: Tie\nPlayer 1: %d point%s\tPlayer 2: %d point%s\n", score1, (score1!=1) ? "s" : "", score2, (score2!=1) ? "s" : "");
        if ((score1==5)||(score2==5))
        break;
    }
    return 0;
    }

This program should run or loop and breaks if one of them got the score 5. Please correct this for me in C language and explain just a little so that i'll understand what the heck is happening. BTW, im using CodeBlocks.



via Chebli Mohamed

Why is my program not compiling?

My code is suppose to initialise any word you type but it is refusing to compile . I don't understand the error messages it is giving to me.
1 initialize.c:24:23: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion] 2 initialize.c:21:23: error: format string is not a string literal (potentially insecure) [-Werror,-Wformat-security]

3 initialize.c:21:23: error: format string is not a string literal (potentially insecure) [-Werror,-Wformat-security] printf(toupper(s[i]));

#include <stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>

void initialize(string s);
int main(int argc, string argv[])
{ 
     printf("May I have your name?");
     string name = GetString();
     initialize(name);

}
void initialize(string s)
{    
     int space = 1;

     for (int i = 0;i < strlen(s); i++)
     {     if(space == 1)
           {
               printf(toupper(s[i])); 
               space -= 1;
           }       
           if(strncmp(s[i]," ",1 ) )  
           {

                space += 1;         

           }
     }


}



via Chebli Mohamed

Why int _$[:>=

Today I found something like

 int _$[:>=<%-!.0,};

in some old code, but in fact the code is not comment out but seems no report compile error for this line, I test it separately and it can compile too:

int main(){
    int _$[:>=<%-!.0,};
    return 0;
}

why can it compile?



via Chebli Mohamed

when does RSA_eay_private_decrypt called the rsa_mod_exp function?

I summary the function call in rsa-encryption of openssl. We can found that

if (p!=NULL && q != NULL && dmp1 !=NULL && dmq1 != NULL && iqmp !=NULL), 

RSA_eay_private_decrypt() and RSA_eay_private_encrypt() will call rsa_mod_exp(Is this the Chinese Reminder Theory(CRT) version?).

enter image description here

My questions are:

  1. In publick encrypt or public decrypt, "e too small" is the reason that only call bn_mod_exp function?
  2. In private_decrypt or private_encrypt, as I know, d is as big as modulur n. when does rsa_mod_exp() is called? and when bn_mod_exp() is called?


via Chebli Mohamed

Where's the pointer to an array stored in a struct?

I have a struct that looks like this.

struct puzzle {
  int d[16]; 
}; 

I heard that arrays and pointers are the same in C/C++, so I thought that the struct would store a pointer, and the pointer points to an int array. However, I did simple experiments using a debugger to see how exactly is it stored, and I found out that the array is directly stored in the struct.

  1. Why isn't the array pointer stored in the struct?
  2. Where is the pointer stored at?


via Chebli Mohamed

return dynamic array of struct from function

How do I dynamically create an array of struct in a function in C?

The struct:

typedef struct Track {
    char artist[LONGSTR];
    char file[LONGSTR];
    int id;
    int isAlbum;
    char name[LONGSTR];
    int pos;
    char title[LONGSTR];
    int time;
} Track;

The function:

int
processplaylist (struct Track** tracks, char* resp)
{
  //count the tracks to return
  //allocate space for the resulting tracks

  *tracks = mem_alloc (count * sizeof (struct Track));

  //process each track
  return count;
}

And the usage:

char playliststr[] = "file: some-mp3\nTitle: Dire Straits - Romeo And Juliet\nName: TheRadio\nPos: 0\nId: 12\nOK\n"
struct Track* tracks = NULL;
int count = mpd_processplaylist(&tracks, playliststr);

Within the function the tracks are nicely processed and upto the return statement tracks points to the right location to get to the tracks. Most questions I have seen are about arrays to values, not structs. This answer returns an array of structs, but I would like to return the count (question of style) and return the array through the parameter.

What is going wrong? After the function returns, count has the right value and tracks is still NULL.



via Chebli Mohamed

N dimension hilbert index in Delphi

I am trying calculate a 3d coordinate into a Hilbert index and back. I found this c code and I am trying to to convert it to Delphi. The AxestoTranspose function in the code below takes an N dimension and is supposed to output the hilbert index. There is a similar C# conversion of it here on this site.

I think having the 3 axes as individual integers instead of encoding the axes in the format in the code might more intuitive since the code is to use with 3 dimensions only.

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Functions: TransposetoAxes
//            AxestoTranspose
//
// Purpose:   Transform between Hilbert transpose and geometrical axes
//
// Example:   b=5 bits for each of n=3 coordinates
//            Hilbert transpose
//             X[0] = A D b e 3                  X[1]|  
//             X[1] = B E c 1 4    <------->         |  /X[2]
//             X[2] = C a d 2 5                axes  | /
//                    high  low                      |/______
//                                                         X[0]
//            Axes are stored conventially as b-bit integers.
//         
// History:   John Skilling  20 Apr 2001, 3 Sep 2003, 14 Oct 2003
//-----------------------------------------------------------------------------
// 
static void TransposetoAxes(
coord_t* X,            // I O  position   [n]
int      b,            // I    # bits
int      n)            // I    dimension
{
    coord_t  M, P, Q, t;
    int      i;

// Gray decode by  H ^ (H/2)
    t = X[n-1] >> 1;
    for( i = n-1; i; i-- )
        X[i] ^= X[i-1];
    X[0] ^= t;

// Undo excess work
    M = 2 << (b - 1);
    for( Q = 2; Q != M; Q <<= 1 )
    {
        P = Q - 1;
        for( i = n-1; i; i-- )
            if( X[i] & Q ) X[0] ^= P;                              // invert
            else{ t = (X[0] ^ X[i]) & P;  X[0] ^= t;  X[i] ^= t; } // exchange
        if( X[0] & Q ) X[0] ^= P;                                  // invert
    }
} 
static void AxestoTranspose(
coord_t* X,            // I O  position   [n]
int      b,            // I    # bits
int      n)            // I    dimension
{
    coord_t  P, Q, t;
    int      i;

// Inverse undo
    for( Q = 1 << (b - 1); Q > 1; Q >>= 1 )
    {
        P = Q - 1;
        if( X[0] & Q ) X[0] ^= P;                                  // invert
        for( i = 1; i < n; i++ )
            if( X[i] & Q ) X[0] ^= P;                              // invert
            else{ t = (X[0] ^ X[i]) & P;  X[0] ^= t;  X[i] ^= t; } // exchange
    }

// Gray encode (inverse of decode)
    for( i = 1; i < n; i++ )
        X[i] ^= X[i-1];
    t = X[n-1];
    for( i = 1; i < b; i <<= 1 )
        X[n-1] ^= X[n-1] >> i;
    t ^= X[n-1];
    for( i = n-2; i >= 0; i-- )
        X[i] ^= t;
}



via Chebli Mohamed

stack frames and gdb

I'm new to reverse engeneering. I wrote the following C code to help me understand a bit more about stack frames.

#include <stdio.h>

int sum(int a, int b,int c)
{
        return(a+b+c);
}

int media(int a, int b,int c)
{
        int total;
        total = a + b + c;
        return (total/3);

}

int main ()
{
        int num1,num2,num3;
        char keypress[1];

        num1 = 5;
        num2 = 10;
        num3 = 15;

        printf ("\nCalling sum function\n");
        sum(num1,num2,num3);
        printf ("\nWaiting a keypress to call media function\n");
        scanf ("%c",keypress);
        media(num1,num2,num3);
        printf ("\nWaiting a keypress to end\n");
        scanf ("%c",keypress);
        return(0);
}

As far as I know every time you call a function a stack frame is created (see: http://ift.tt/1hAE6k0). So, my goal with the above C code is to see, at least, three stack-frames.

1) main function - stack frame

2) sum function - stack frame

3) media function - stack frame

BTW: Those printfs are just to help me 'follow' the program in gdb. =)

So I guess if I compare the output of info frame after the program started with the output of info frame just after sum function is called I would get different output right? I did not got it as you can see:

Temporary breakpoint 1, main () at parastack.c:27
warning: Source file is more recent than executable.
27              num1 = 5;
(gdb) nexti
28              num2 = 10;
(gdb) info frame
Stack level 0, frame at 0x7fffffffdf00:
 rip = 0x400605 in main (parastack.c:28); saved rip = 0x7ffff7a3c790
 source language c.
 Arglist at 0x7fffffffdef0, args:
 Locals at 0x7fffffffdef0, Previous frame's sp is 0x7fffffffdf00
 Saved registers:
  rbp at 0x7fffffffdef0, rip at 0x7fffffffdef8
(gdb) nexti
29              num3 = 15;
(gdb) nexti
31              printf ("\nCalling sum function\n");
(gdb) nexti
0x0000000000400618      31              printf ("\nCalling sum function\n");
(gdb) nexti

Calling sum function
32              sum(num1,num2,num3);
(gdb) info frame
Stack level 0, frame at 0x7fffffffdf00:
 rip = 0x40061d in main (parastack.c:32); saved rip = 0x7ffff7a3c790
 source language c.
 Arglist at 0x7fffffffdef0, args:
 Locals at 0x7fffffffdef0, Previous frame's sp is 0x7fffffffdf00
 Saved registers:
  rbp at 0x7fffffffdef0, rip at 0x7fffffffdef8
(gdb) nexti
0x0000000000400620      32              sum(num1,num2,num3);
(gdb) info frame
Stack level 0, frame at 0x7fffffffdf00:
 rip = 0x400620 in main (parastack.c:32); saved rip = 0x7ffff7a3c790
 source language c.
 Arglist at 0x7fffffffdef0, args:
 Locals at 0x7fffffffdef0, Previous frame's sp is 0x7fffffffdf00
 Saved registers:
  rbp at 0x7fffffffdef0, rip at 0x7fffffffdef8



via Chebli Mohamed

How can you mmap in parallel for faster file reading?

I am working through this code and have the mmap working now, but I am wondering if I can use mmap in parallel and if so, how to accomplish it. Suppose I have my data on a parallel file system (GPFS, RAID0, whatever) and I want to read it using n processes.

How could I, for example, have each processor read 1/nth contiguous block of the data into memory? Or, alternatively, read every nth memory block (1 B, 1 MB, 100 MB, 1 GB, whatever I choose for optimization) into memory?

I am assuming a posix file system here.



via Chebli Mohamed

How to intialize variable with cleanup attribute?

Is there a way to initialize a variable with the cleanup compiler attribute? or do I have to set the value after declaring the variable?

I've tried putting the cleanup attribute in front of = malloc(10); like in the example below and behind = malloc(10); but neither compiles.

#include <stdio.h>
#include <stdlib.h>

static inline void cleanup_buf(char **buf)
{
    if(*buf == NULL)
    {
        return;
    }

    printf("Cleaning up\n");

    free(*buf);
}

#define auto_clean __attribute__((cleanup (cleanup_buf)));

int main(void)
{
    char *buf auto_clean = malloc(10);
    if(buf == NULL)
    {
        printf("malloc\n");
        return -1;
    }

    return 0;
}

Is there a different syntax for using cleanup and initializing the variable on one line? Or do I have to set the value after declaring the variable like in the example below?

#include <stdio.h>
#include <stdlib.h>

static inline void cleanup_buf(char **buf)
{
    if(*buf == NULL)
    {
        return;
    }

    printf("Cleaning up\n");

    free(*buf);
}

/* Use this attribute for variables that we want to automatically cleanup. */
#define auto_clean __attribute__((cleanup (cleanup_buf)));

int main(void)
{
    char *buf auto_clean;

    buf = malloc(10);
    if(buf == NULL)
    {
        printf("malloc\n");
        return -1;
    }

    return 0;
}



via Chebli Mohamed

C loop optimization help for final assignment

So for my final assignment in my Computer Systems class, we need to optimize these forloops to be faster than the original. The basic grade is under 7 seconds and the full grade is under 5 seconds with our linux server. This code that I have right here gets about 5.6 seconds. I am thinking I may need to use pointers with this in some way to get it to go faster but I'm not really sure. Could anyone offer any tips or options that I have? Thank you so much!

QUICKEDIT: The file must remain 50 lines or less and I am ignoring those commented lines the instructor has included.

#include <stdio.h>
#include <stdlib.h>

// You are only allowed to make changes to this code as specified by the comments in it.

// The code you submit must have these two values.
#define N_TIMES     600000
#define ARRAY_SIZE   10000

int main(void)
{
    double  *array = calloc(ARRAY_SIZE, sizeof(double));
    double  sum = 0;
    int     i;

    // You can add variables between this comment ...
    register double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0, sum5 = 0, sum6 = 0, sum7 = 0, sum8 = 0, sum9 = 0;
    register int j;
    // ... and this one.

    printf("CS201 - Asgmt 4 - \n");

    for (i = 0; i < N_TIMES; i++)
    {
        // You can change anything between this comment ...
        for (j = 0; j < ARRAY_SIZE; j += 10)
        {
            sum += array[j];
            sum1 += array[j + 1];
            sum2 += array[j + 2];
            sum3 += array[j + 3];
            sum4 += array[j + 4];
            sum5 += array[j + 5];
            sum6 += array[j + 6];
            sum7 += array[j + 7];
            sum8 += array[j + 8];
            sum9 += array[j + 9];
        }
        // ... and this one. But your inner loop must do the same
        // number of additions as this one does.
    }                   

    // You can add some final code between this comment ...
    sum += sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7 + sum8 + sum9;
    // ... and this one.

    return 0;
}



via Chebli Mohamed

Is there any performance difference between accessing a hardcode array and a run time initialization array?

For example, I want to create a square root table using array SQRT[i] to optimize a game, but I don't know if there is performance difference between the following initialization when accessing the value of SQRT[i]:

  1. Hardcode array

    int SQRT[]={0,1,1,1,2,2,2,2,2,3,3,.......255,255,255}
    
    
  2. Generate value at run time

    int SQRT[65536];
    int main(){
        for(int i=0;i<65536;i++){
            SQRT[i]=sqrt(i);
        }
        //other code
        return 0;
    }
    
    

Some example of accessing them:

    if(SQRT[a*a+b*b]>something)
    ...

At start, I thought they should be the same, but I don't know if the program stores or access a hard-code array in different way. Also, I don't know if compiler will optimize the hard-code array to speed up the access time, is there performance difference between them when accessing the array?



via Chebli Mohamed

Calculating CRC16 in C#

I'm trying to port an old code from C to C# which basically receives a string and returns a CRC16 of it...

The C method is as follow:

#define CRC_MASK 0x1021 /* x^16 + x^12 + x^5 + x^0 */

UINT16 CRC_Calc (unsigned char *pbData, int iLength)
{
    UINT16 wData, wCRC = 0;
    int i;

    for ( ;iLength > 0; iLength--, pbData++) {
        wData = (UINT16) (((UINT16) *pbData) << 8);
        for (i = 0; i < 8; i++, wData <<= 1) {
            if ((wCRC ^ wData) & 0x8000)
                wCRC = (UINT16) ((wCRC << 1) ^ CRC_MASK);
            else
                wCRC <<= 1;
        }
    }
    return wCRC;
}

My ported C# code is this:

private static ushort Calc(byte[] data)
    {
        ushort wData, wCRC = 0;
        for (int i = 0; i < data.Length; i++)
        {
            wData = Convert.ToUInt16(data[i] << 8);
            for (int j = 0; j < 8; j++, wData <<= 1)
            {
                var a = (wCRC ^ wData) & 0x8000;
                if ( a != 0)
                {
                    var c = (wCRC << 1) ^ 0x1021;
                    wCRC = Convert.ToUInt16(c);
                }
                else
                {
                    wCRC <<= 1;
                }
            }
        }
        return wCRC;
    }

The test string is "OPN"... It must return a uint which is (ofc) 2 bytes A8 A9 and the #CRC_MASK is the polynomial for that calculation. I did found several examples of CRC16 here and around the web, but none of them achieve this result since this CRC calculation must match the one that the device we are connecting to.

WHere is the mistake? I really appreciate any help.

Thanks! best regards

Gutemberg

UPDATE

Following the answer from @rcgldr, I put together the following sample:

_serial = new SerialPort("COM6", 19200, Parity.None, 8, StopBits.One);
        _serial.Open();
        _serial.Encoding = Encoding.GetEncoding(1252);
        _serial.DataReceived += Serial_DataReceived;
        var msg = "OPN";
        var data = Encoding.GetEncoding(1252).GetBytes(msg);
        var crc = BitConverter.GetBytes(Calc(data));
        var msb = crc[0].ToString("X");
        var lsb = crc[1].ToString("X");
        //The following line must be something like: \x16OPN\x17\xA8\xA9
        var cmd = string.Format(@"{0}{1}{2}\x{3}\x{4}", SYN, msg, ETB, msb, lsb);
        //var cmd = "\x16OPN\x17\xA8\xA9";
        _serial.Write(cmd);

The value of the cmd variable is what I'm trying to send to the device. If you have a look the the commented cmd value, this is a working string. The 2 bytes of the CRC16, goes in the last two parameters (msb and lsb). So, in the sample here, msb MUST be "\xA8" and lsb MUST be "\xA9" in order to the command to work(the CRC16 match on the device).

Any clues?

Thanks again.

UPDATE 2 For those who fall in the same case were you need to format the string with \x this is what I did to get it working:

protected string ToMessage(string data)
    {
        var msg = data + ETB;
        var crc = CRC16.Compute(msg);
        var fullMsg = string.Format(@"{0}{1}{2:X}{3:X}", SYN, msg, crc[0], crc[1]);
        return fullMsg;
    }

This return to me the full message that I need inclusing the \x on it. The SYN variable is '\x16' and ETB is '\x17'

Thank you all for the help!

Gutemberg



via Chebli Mohamed

Error code 2556,2040

I keep getting error code error C2556: 'int myArray::operator const' : overloaded function differs only by return type from 'int &myArray::operator const'

see declaration of 'myArray::operator []'

error C2040: 'myArray::operator []' : 'int (int) const' differs in levels of indirection from 'int &(int) const'

This is my myArray .cpp file

#include <iostream>
#include "myArray.h"

using namespace std;

    myArray::myArray(int newSize)
    {
        startIndex=0;
        size = newSize;
        PtrArray = new int[size];
        for(int i=0; i< size; i++)
            PtrArray[i] = 0;
    }

    myArray::myArray(int newStartIndex, int newSize)
    {
        startIndex = -newStartIndex;
        size = newSize;
        PtrArray= new int [size + startIndex];

        for(int i=0; i< (size + startIndex); i++)
            PtrArray[i]= 0;
    }

    myArray::~myArray()
    {
        delete [] PtrArray;
    }

    int &myArray::operator[] (int index)
    {
        if ((index <-startIndex || index >= size))
        {
            cerr<<"Error: Index "<<index<<" is our of range"<<endl;
            system("pause");
            exit(1);
        }

        return PtrArray[index+startIndex];
    }

            int myArray:: operator[](int index) const
            {
                if (index <-startIndex || index >= size)
                {
                    cerr<<"Error:Index"<< index<<"isout of range"<<endl;
                        system("pause");
                        exit(2);
                }

        return PtrArray[index + startIndex];
            }

This is my program .cpp code

#include <iostream>
#include "myArray.h"

using namespace std;

int main()
{
    myArray list(5);
    myArray myList(2,13);
    myArray yourList(-5,9);

for(int i=0; i<5; i++)
    list[i]=i*i;

for(int j=2; j<13; j++)
    myList[j]=j*j;

for(int k=-5; k<9; k++)
    yourList[k]=k*k;

cout<<"The elements stored in the first object list are:"<<endl;

for(int i=0; i<5; i++)
{
    cout<<"list["<<i<<"[\t\t="<<list[i]<<endl;
}

cout<<"The elements stored in the second object myList are:"<<endl;

for(int j=2; j<13; j++)
{
    cout<<"myList["<<j<<"]\t="<<myList[j]<<endl;

}

cout<<"The elements stored in the third object yourList are:"<<endl;

for (int k=-5;k<9;k++)
{
    cout<<"yourList["<<k<<"]\t"<<yourList[k]<<endl;
}

cin>>yourList[-13];
system("pause");
return 0;
}

This is my myArray header:

#ifndef H_myArray
#define H_Array
#include <iostream>

using namespace std;

class myArray
{
public:
    myArray(int);
    myArray(int,int const);
    ~myArray();

    int &operator[](int);
    int &operator[](int) const;

private:
    int startIndex;
    int size;
    int *PtrArray;


};

#endif



via Chebli Mohamed

Does compiler provide these functions ,printf,scanf?

I'm studying C language nowadays.

In this book, It is said that "Compiler provides these library functions , 'printf','scanf'..";

I can't understand.

Those functions are defined in the header file, 'stdio.h', aren't those?

Why this book explain those functions are provided from compiler?



via Chebli Mohamed

Understand VSYSCALL_ADDR and function pointer

I came across the following code. I have two questions here. 1. where to find this __NR_vgetcpu? What other values could I get by callign VSYSCALL_ADDR? 2. What does this line "my_getpuc =( int(*)) .....)" do?

int (*my_getcpu)(unsigned *cpu, unsigned *node, struct getcpu_cache *tcache);
char *addr3 = (char *)VSYSCALL_ADDR(__NR_vgetcpu);
printf("vgetcpu addr is %p \n", addr3);
my_getcpu = (int (*)(unsigned *, unsigned *, struct getcpu_cache *))addr3;
my_getcpu(&cpu, &node, &cache);



via Chebli Mohamed

libgps C code example

I am writing a number-crunching data-logging C program for my GPS enabled Raspberry Pi. I grabbed gpsd, and its sample app cgps displays gps information correctly. I wanted to use libgps to interface with the daemon so that I could have all that handy information in my app, but I was quickly overwhelmed by the complexity of its API.

The documentation on its HOWTO page points me to look at cgps and gpxlogger for example code, but there's so much coupling that I can't wade through it all. On the opposite end of the spectrum, the C code example on the libgps page is so stripped back that it's unusable.

Can anybody point me to a single class sample that might demystify this? Perhaps something that contains a getCoordinates() function?



via Chebli Mohamed

setup a series function pointers and callbacks in c

I've read a few different SO answers on function pointers as callbacks but I am still having some trouble implementing it myself.

Questions like this: How do function pointers in C work?

and this: How do function pointers in C work?

and a few others.

I am not sure if this is the best way to go about it.

file.h

typedef int (*reg_callback)(void*, void*); //generalize a bit?

int register_created(reg_callback cb);
int register_fixed_update(reg_callback cb);
int register_variable_update(reg_callback cb);
int register_render(reg_callback cb);
int register_pased(reg_callback cb);
int register_resume(reg_callback cb);
int register_resize(reg_callback cb);
int register_quit(reg_callback cb);

int init_engine(int width, int height, char *title, double fps);

//prototypes of functions that I need callbacks for atm maybe more soon
void created(void);
void fixed_update(void);
void variable_update(void);
void render(double alpha);
void paused(void);
void resumed(void);
void resized(int width, int height);
void quit(void);

file.c

static int register_callback_function(int c_type, reg_callback cb)
{
    int success = -1;
    switch(c_type)
    {
        case 000000:
            printf("registering fixed update\n");
            break;
        case 000001:
            printf("registering variable update\n");
            break;
        case 000002:
            printf("registering render\n");
            break;
        case 000003:
            printf("registering pause\n");
            break;
        case 000004:
            printf("registering resume\n");
            break;
        case 000005:
            printf("registering resize\n");
            break;
        case 000006:
            printf("registering quit\n");
            break;
        default:break;
    }
    return success;
}
int register_fixed_update(reg_callback cb)     { return register_callback_function(000000, cb); };
int register_variable_update(reg_callback cb)  { return register_callback_function(000001, cb); };
int register_render(reg_callback cb)           { return register_callback_function(000002, cb); };
int register_pased(reg_callback cb)            { return register_callback_function(000003, cb); };
int register_resume(reg_callback cb)           { return register_callback_function(000004, cb); };
int register_resize(reg_callback cb)           { return register_callback_function(000005, cb); };
int register_quit(reg_callback cb)             { return register_callback_function(000006, cb); };
int register_created(reg_callback cb)          { return register_callback_function(000007, cb); };

void created(void)                  { //call create callback func }
void fixed_update(void)             { //call fixed update callback func}
void variable_update(void)          { //...}
void render(double alpha)           { //...}
void paused(void)                   { //...}
void resumed(void)                  { //...}
void resized(int width, int height) { //...}
void quit(void)                     { //...}

currently I am getting a warning like these:

warning: incompatible pointer types passing 'void (void)' to parameter of
      type 'reg_callback' (aka 'int (*)(void *, void *)') [-Wincompatible-pointer-types]
    register_created(created);
                     ^~~~~~~
note: passing argument to parameter 'cb' here
int register_created(reg_callback cb);

incompatibile pointer types but I though that void* pointers could point to anything, even nothing?

I wanted to generalize the function pointer so that I could just use the one pointer prototype to handle all this setup code. From the code not working I know I am going about it the wrong way and would like to fix that.

maybe have a struct with some pointer to functions but I am not sure atm.



via Chebli Mohamed

Why does main(int argc, char* argv[]) take two argument?

I always thought that argc was required to mark the end of argv but I just learned that argv[argc] == nullptr by definition. Am I right in thinking that argc is totally redundant? If so, I always thought C made away with redundancy in the name of efficiency. Is my assumption wrong or there's a historic reason behind this?



via Chebli Mohamed

Cancel blocking `poll`?

So, I've run into this issue where I have many threads calling poll on different file descriptors. When I want to add a new one, I need to cancel one of those polls, add a new one, and continue. That alone sounds bad, but also I can't even see how to do that.

Some relevant code:

struct pollfd fds[size];
for(int i = 0;i<size;i++) {
    struct pollfd fd;
    fd.fd = body[i];
    fd.events = POLLIN;
    fd.revents = 0;
    fds[i] = fd;
}
if(poll(&fds[0], (nfds_t)size, -1) < 0) return NULL;

(I'm using this through JNI also).

I figure I could set a really low delay on poll, and call it over and over, but I think that would begin to defeat the purpose.



via Chebli Mohamed

samedi 1 août 2015

Hibernate Reverse Engineering tool in Visual Studio

Long story short, we have a VB.NET app which must use .NET 4.0. We are currently using DataAdapter for data transformation, which is slow programming. We have approximately 200 forms to go (these forms are all for database entry / business logic)

So I am thinking of using hibernate for an ORM approach. (Can not use entity I think as that is .NET 4.5 only?) We have a oracle backend, i'd like a reverse engineering tool to create the object for me from the the database. Does such a tool exist?

Rotate element so its pointing to a specific point in space

I'm having problems with rotating an element (BoxVisual3D).

We have two spheres. The first one is red, the second one is blue. There is a box element with the same center point as the second sphere.

What I need at this point is to rotate this box visual so that its pointing to the red dot. They are all in the same coordinate system. I've done various calculations, but none of them worked the way I wanted. The objective is to find an universal rotation solution.

A short snippet for element rotation around one of the axis.

RotateTransform3D myRotateTransform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), RotX));
myRotateTransform.CenterX = Spheres[1].Center.X;
myRotateTransform.CenterY = Spheres[1].Center.Y;
myRotateTransform.CenterZ = Spheres[1].Center.Z;

Transform3DGroup RotGroup = new Transform3DGroup();
RotGroup.Children.Add(myRotateTransform);

Models[0].Transform = RotGroup;

Thanks guys!

How to build a REST web service wrapper over an existing SOAP web service?

I want to create a new REST WCF service, consume an existing SOAP WSDL through it, get the XML result from SOAP and use selective data from there and fetch it forward as a REST service's output.

Is there a sample project I can refer to ?

What is the purpose of nameof?

Version 6.0 got a new feature of nameof, but I can't understand the purpose of it, as it just takes the variable name and changes it to a string on compilation.

I thought it might have some purpose when using <T> but when I try to nameof(T) it just prints me a T instead of the used type.

Any idea on the purpose?

stop/dispose/cancel a Task C#

i am trying to deploy DLLs inside a windows service by importing DLLs from various repositories like google drive/ dropbox/ ftp etc...

But before any new DLL can be instantiated, I would want the previous running instance to be shut down.

I am using tasks and reflection in this.

I am unable to figure out how to cancel the task that instantiate the DLL at run time ( as the instantiated dll is a long running application example file watcher.. )

    CancellationTokenSource cts = new CancellationTokenSource();
    CancellationToken ct = cts.Token;

            // instantiate the dll though reflection
        t = Task.Factory.StartNew(() =>
        {
            try
            {
                Assembly assembly = Assembly.LoadFile(Directory.GetCurrentDirectory() + @"\" + dllName);
                Type type = assembly.GetType("myclass.Program");

                MethodInfo minfo = type.GetMethod("Main", BindingFlags.Public | BindingFlags.NonPublic |
                          BindingFlags.Static | BindingFlags.Instance);
                minfo.Invoke(Activator.CreateInstance(type), null);

            }
            catch (Exception ex)
            {

                log.Error(ex.ToString());
            }
        }, cts.Token);

Ques : I want to cancel the task t before my appication detects a new dll and tries to execute that through this task code.

.NET - Can App.Config Be Embedded?

According to this : http://ift.tt/1eJLhUS

In order for .NET Framework 4/4.5 to work with .NET 2.0 apps, an app.config must be provided.

I want to maximize the compatibility of my .NET 2.0 apps, I need it to work with PCs have only .NET 2.0 only or .NET 4 only.

The problem is that, having an app.config always present with the executable is not as professional as I want it to look like.

Is there any fix for this?

Thank you for reading.

How to search for an element by custom HTML attribute using Coded UI Tests

I have a bunch of input[type=submit] buttons inside a GridView. The ids and names of these buttons, while predictable because they use an index number, are not well suited to automation using SpecFlow and Coded UI Tests. I'm finding it difficult to search for those button elements.

A snippet of the HTML delivered to the browser:

<input type="submit" id="abc_xyz_0" data-task-id="123" value="Apply">
<input type="submit" id="qrs_tuv_0" data-task-id="345" value="Renew">

The button text is generic in each row ("Apply" and "Renew"), but the data-task-id attribute is unique. I would like to use this attribute and value to identify a button to click on. I'm trying to use the SearchProperties and FilterProperties but I keep getting exceptions:

System.NotSupportedException: The property DataTaskId is not supported for this control.

How I'm attempting to find the control:

HtmlInputButton button = new HtmlInputButton(document);

button.SearchProperties["data-task-id"] = "123";
// or button.SearchProperties["DataTaskId"] = "123";

Using two versions of entity framework in the same solution

I have a webApi application in which I used EF6 in the web project and EF5 in the DAL layer.

I have this method in the crud class( in DAL) :

 public bool Delete(params T[] items)
    {
        if (context == null) context = GetContext();
        try
        {
            foreach (T item in items)
            {
                context.Entry(item).State = System.Data.EntityState.Deleted;
            }
            context.SaveChanges();
            return true;
        }
        catch
        {
            return false;
        }


    }

in the BLL I made this call :

 public void UpdatePhoto(string id, byte[] image)
   {
       if (cruder == null) cruder = new Crud<ajt_photo>();
       List<ajt_photo> lstphoto = cruder.GetAll().ToList();
       ajt_photo photo = lstphoto.Where(x => x.id_user_fk == id).FirstOrDefault();
       if (photo != null) cruder.Delete(photo);
       ajt_photo pho = new ajt_photo() { id_user_fk = id, image = image };
       cruder.AddNew(pho); 
   }

I get a weird exception :

enter image description here

It indicates that the method is not found !!! I think it is because of entity framework version in this line :

EF5

context.Entry(item).State = System.Data.EntityState.Deleted;

EF6

context.Entry(item).State = System.Data.Entity.EntityState.Deleted;

So I need to know :

  1. How can I fix this problem?

Get SQL query from user and run it against SQL Server

I want to develop very small application by C# which get some SQL query from user and execute it against specified SQL Server.

SQL Server and database must specified by user thus every things can change. My problem is user can enter various type of SQL queries, and every king of it should run in its own way.

For example

SELECT * FROM mytable

and

UPDATE mytable 
SET city = "NY" 
WHERE name = "tom"

can not execute in the same way.

I think I need to recognize user query type in my code, Is there any way to recognize it or any better way to run any possible query?

How to prevent the mousewheel from raising DataGridView.CellValidating

DataGridView is somehow inclined that scrolling must trigger validation. Is there an important reason for this behavior? If not, is there a clean way around this?

Save multipart/form-data on server in objective c but get the 500 response

I have try to save multipart/form-data on server using following code NSMutableURLRequest * request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:jsonUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0]; [request setHTTPMethod:@"POST"]; [request setValue:[NSString stringWithFormat:@"TPop %@",[Base64 encode:[[[NSUserDefaults standardUserDefaults]objectForKey:@"AuthorizationID"] dataUsingEncoding:NSUTF8StringEncoding]]] forHTTPHeaderField:@"Authorization"]; // set Content-Type in HTTP header NSString *BoundaryConstant = @"---------------------------acebdf13572468"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; if (parameterArray!=nil) { //TPPopPartsModel objPopPart=[parameterArray objectAtIndex:0]; NSMutableDictionary _params = [[NSMutableDictionary alloc] init]; [_params setObject:[NSString stringWithFormat:@"1"]forKey:[NSString stringWithFormat:@"SequencePosition"]]; // [_params setObject:[NSNumber numberWithInt:1] forKey:[NSString stringWithFormat:@"SequencePosition"]]; [_params setObject:[NSString stringWithFormat:@"Image"]forKey:[NSString stringWithFormat:@"MediaType"]]; [_params setObject:[NSString stringWithFormat:@"Hello"]forKey:[NSString stringWithFormat:@"Description"]]; [_params setObject:[NSString stringWithFormat:@"car.jpg"]forKey:[NSString stringWithFormat:@"filename"]]; for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; NSLog(@"%@",[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]]); } } UIImageView * imagicon=[[UIImageView alloc]init]; imagicon.image=[UIImage imageNamed:@"car.jpg"]; NSData *image = UIImageJPEGRepresentation(imagicon.image,1.0); // add image data if (image) { NSString filename=@"fieldNam## Heading ##eHere"; [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:image]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSURLResponse response; NSLog(@"%@",request); NSError* error = nil; //Capturing server response NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"%@",response); NSLog(@"%@",error); NSString *responseString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; } } get following server response { status code: 500, headers { "Cache-Control" = "no-cache"; "Content-Length" = 35; "Content-Type" = "application/json; charset=utf-8"; Date = "Fri, 31 Jul 2015 15:51:01 GMT"; Expires = "-1"; Pragma = "no-cache"; Server = "Microsoft-IIS/8.5"; "X-AspNet-Version" = "4.0.30319"; "X-Powered-By" = "ASP.NET"; } } how to solve this problem...

500 internal server error in asp.net website

I have two ASP.NET websites hosted on a server and connecting to the SQL database on on different server.

One of the website throwing 500 internal server errors (as custom error mode on in production). I am not sure what is causing these errors. And these errors are random, so I am not able replicate on dev environment. Both website having almost similar functionality but I am facing these errors only in one website. Recently there so many time out errors. So I asked the system admins to check the event log then they said lot of windows updates are pending, so they ran patch and rebooted both application and database servers.

After that I am getting 500 internal errors while going from login to default page in the website but I am sure there nothing wrong with code and these errors not caught in the application_error event in the global ascx file.

Any insights on how to troubleshoot this issue further?

Unable to get desired output for keydown c#

I am trying to create two synchronized textboxes using windows forms but I seem to be running into multiple problems. Maybe you guys can help me make things a little more efficient for me. This is the output screen for any clarifications

As you can see, there isn't a problem for the enter key, because I've taken care of that.

  1. I see a special symbol when I hold the shift key
  2. Pressing the backspace adds a new symbol to the line.
  3. Simultaneous pressing of the back key doesn't remove or add(the new symbol) more than once. I assumed the back key would erase 1 character each time it was pressed.
  4. Back key doesn't erase a new line ("\n\r");
  5. The last two lines are for the alt and ctrl keys respectively.

The code for this form so far is

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        //Disable usage of arrowkeys
        if(e.KeyCode==Keys.Left || e.KeyCode==Keys.Right || e.KeyCode==Keys.Up || e.KeyCode==Keys.Down)
        {
            e.SuppressKeyPress=true;
        }

        //Remove a character
        if (e.KeyCode == Keys.Back)
            textBox2.Text = textBox2.Text.Remove(textBox2.TextLength - 1, 1);

        //Upper and lower case characters
        if (!e.Shift && e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z)
            textBox2.Text += (char)(e.KeyValue + 32);
        else
            textBox2.Text += (char)(e.KeyValue);

        //Next Line
        if (e.KeyData == Keys.Enter)
            textBox2.Text += "\n\r";
    }

What do you suggest I do?

I added Using System.Configuration but still it shows error that "Configuration Manager is not found in this contex??"

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using BEL_BookApp;

namespace DEL_BookApp
{

    class BookDetaile_DAL
    {

        SqlConnection cn = new .SqlConnection(ConfigurationManager.ConnectionStrings["DB"].COnnectionString);
    }
}

Here Configuration manager is showing error.although I had written using system.configuration