smallseo.info

c# interview questions

Top c# frequently asked interview questions

Change I2C address Linux driver kernel

I have a system which uses module Sensors LM75 with two I2C adresses (0x48 and 0x49). I'd like to cancel one address (0x48), however I don't understand where there is its initialisation.

All changes in normal_i2c , are not relevant ....

/* Addresses scanned */
static const unsigned short normal_i2c[] = { 0x48, 0x49, 0x4a, 0x4b, 0x4c,
                    0x4d, 0x4e, 0x4f, I2C_CLIENT_END };

Source: (StackOverflow)

mongoLab C driver authentication and Basic Example

I am trying to interface Official C driver with mongoLab but getting error that failed to authenticate credentials. Do anyone have any simple example on how to interface mongolab using C driver. This is my example code

const char* String_uri = "mongodb://<username>:<pwd>@ds011115.mongolab.com:11115/tempdb";

    uri = mongoc_uri_new(String_uri);
    client = mongoc_client_new_from_uri (uri);


   collection = mongoc_client_get_collection (client, "mydb", "mycoll");
   doc = bson_new_from_json ((const uint8_t *)"{\"hello\" : \"world\"}", -1, &error);

   count = mongoc_collection_count (collection, MONGOC_QUERY_NONE, doc, 0, 0, NULL, &error);

   if (count < 0) {
      fprintf (stderr, "%s\n", error.message);
   } else {
      printf ("%" PRId64 "\n", count);
   }

Source: (StackOverflow)

Connection refused on wpa_ctrl_open

I am trying to use C code to access wpa_supplicant in an ARM embedded system running linux. After searching, I realise that I could use wpa_supplicant control interface. I try to open a connection using wpa_ctrl_open(), and resulted in "Connection refused" error:

Failed to connect to wpa_supplicant global interface: /var/run/wpa_supplicant error: Connection refused

The code I am using to test:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/sockios.h>
#include <netinet/if_ether.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "includes.h"

#ifdef CONFIG_CTRL_IFACE_UNIX
#include <dirent.h>
#endif /* CONFIG_CTRL_IFACE_UNIX */
#include "wpa_ctrl.h"
#include "common.h"

struct wpa_ctrl {
    int s;
#ifdef CONFIG_CTRL_IFACE_UDP
    struct sockaddr_in local;
    struct sockaddr_in dest;
#else // CONFIG_CTRL_IFACE_UDP
    struct sockaddr_un local;
    struct sockaddr_un dest;
#endif // CONFIG_CTRL_IFACE_UDP
};

static struct wpa_ctrl *ctrl_conn;

int main(int argc,char **argv)
{
    const char *global = "/var/run/wpa_supplicant";
    ctrl_conn = wpa_ctrl_open(global);
    if (ctrl_conn == NULL)
    {
        fprintf(stderr, "Failed to connect to wpa_supplicant "
            "global interface: %s error: %s\n",global,strerror(errno));
        return -1;
    }
    else
    {
        printf("Success\n");
    }
    return 0;
}

After tracing the code in wpa_ctrl.c, I found the problem is on the following IF condition, inside wpa_ctrl_open2() function:

if (connect(ctrl->s, (struct sockaddr *) &ctrl->dest,sizeof(ctrl->dest)) < 0)

I do not know what is the problem and how I can solve it.

On the same machine, I tried to run wpa_cli and it can access wpa_supplicant perfectly.

I used the following command to compile:

gcc -o test_wpa main.c wpa_ctrl.c os_unix.c -DCONFIG_BACKEND_FILE -DCONFIG_IEEE80211W -DCONFIG_DRIVER_WEXT -DCONFIG_WIRELESS_EXTENSION -DCONFIG_DRIVER_NL80211 -DCONFIG_LIBNL20 -DEAP_PSK -DIEEE8021X_EAPOL -DCONFIG_SHA256 -DCONFIG_CTRL_IFACE -DCONFIG_CTRL_IFACE_UNIX -DCONFIG_SME -lrt

wpa_supplicant code (including wpa_ctrl.c & os_unix.c) can be download at here: http://w1.fi/releases/wpa_supplicant-2.5.tar.gz

Many thanks in advance!


Source: (StackOverflow)

Count alphabets in C using log functions(without math.h) and arrays

I'm facing a slight problem with one of my projects. I am supposed to write a c program to calculate each character present in the input/file. (It's supposed to be a basic program.) The constraints - I cannot use the math.h library to produce log functions and obtain an output in the format:

    1                                           
    5   1 2 0 2 2 5 8     4 3 6 6 2   5 5 7 2 1 1   2   
    7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2 
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The program is supposed to count the number of occurrences of each alphabetic letter (case insensitive) in the stdin input stream and display a histogram.

As you can see, the output is formatted vertically with each line printing the base 10 number of the position of the character. Now, this might seem silly, but what I have so far is this:

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

    /*
    int logBase10 (int num) {
       method to calculate the log base 10 of num
    }
    */

    int main (int argc, char * argv[]) {
        char alpha;
        int count = 0;
        int ascii[128] = {0};

        while ( (alpha = getchar()) != EOF) {
            count++;
            ascii[(int)alpha]++;
            alpha = getchar();
        }

        printf("Char \t Count \n");
        printf("------------------------\n");

        for (int i = 0; i < 127; i++) {
            if(ascii[i] > 0) {
                printf("%c \t %d \n", i, ascii[i]);
            }
        }
    }

Which produces an output like this:

    Char     Count 
    ------------------------

         5 
         93 
    ,    6 
    -    2 
    .    3 
    ;    2 
    C    2 
    I    6 
    N    1 
    T    1 
    W    2 
    a    26 
    b    5 
    c    8 
    d    13 
    e    55 
    f    11 
    g    7 
    h    28 
    i    32 
    k    3 
    l    26 
    m    17 
    n    31 
    o    27 
    p    12 
    q    1 
    r    26 
    s    22 
    t    42 
    u    11 
    v    8 
    w    8 
    y    13 
    z    1 

First off, my program is printing unwanted ascii characters (, ; - etc) and I am working on changing the print function to be more vertical, but I cannot figure out the log method at all. I know log(10) is 1 because 10^1 is 1, but I am having trouble figuring out how to use this to create the method itself. Also, for the extra characters, I tried using:

    if(ascii[i] > 65 || ascii[i] < 90 || ascii[i] >= 97 || ascii[i] <= 122 ) {
        printf("%c \t %d \n", i, ascii[i]);
    }

to no avail. Trying that produced more gibberish characters instead.

Any help/feedback is appreciated.

  • Soul

Source: (StackOverflow)

tm struct time.h not normalizing

I am adding values to the time (hours, minutes, seconds) members of my tm struct and they are not updating/normalizing even though I'm using mktime() Here is the code:

struct tm timeStruct;
char buffer[80];

timeStruct.tm_year = 2016 - 1900;
timeStruct.tm_mon = 3;
timeStruct.tm_mday = 32;
timeStruct.tm_hour = 23;
timeStruct.tm_min = 59;
timeStruct.tm_sec = 59;
timeStruct.tm_isdst = -1;

printf( "Date before adding interval: \n");
mktime(&timeStruct);
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);

printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );

/*
 * Add intervals to time
 */
timeStruct.tm_sec += 2;
timeStruct.tm_min += 2;
timeStruct.tm_hour += 5;

printf( "Date after adding interval: \n");
strftime(buffer, sizeof(buffer), "%c", &timeStruct);
printf(buffer);

printf( "\nthe year is %d\n", timeStruct.tm_year );
printf( "the month is %d\n", timeStruct.tm_mon );
printf( "the day is %d\n", timeStruct.tm_mday );
printf( "the hours are %d\n", timeStruct.tm_hour );
printf( "the minutes are %d\n", timeStruct.tm_min );
printf( "the seconds are %d\n", timeStruct.tm_sec );

Console Output:1

This is a print out of the console output:

Date before adding interval: 
Mon May  2 23:59:59 2016
the year is 116
the month is 4
the day is 2
the hours are 23
the minutes are 59
the seconds are 59
Date after adding interval: 
Mon May  2 28:61:61 2016
the year is 116
the month is 4
the day is 2
the hours are 28
the minutes are 61
the seconds are 61

I am using Eclipse, compiling with Cygwin, on a Windows 7 machine.


Source: (StackOverflow)

Having trouble using a C library via a Python API: What am I doing wrong?

I'm using a Python script in conjunction with a thermocouple and a thermocouple reader. To communicate with the thermocouple reader, which is written in C, I have to use an API. That API is PyDAQFlex. The thermocouple reader also came with a tester script, written in C. I'm trying to get a temperature reading from the thermocouple reader, but it only outputs the CJC value.

My code:

import daqflex

d = daqflex.USB_2001_TC()

def get_temperature():
    return float(d.send_message("?AI{0}:CJC/DEGC").encode("utf-8"))

The output of my code:

u'AI{0}:CJC/DEGC=23.8'

Note: 23.8 is not the temperature. That value is the CJC, as seen in the tester script's command line output below. It's related, but not the value I'm looking for.


The tester script's code:

http://pastebin.com/Atsdy7X0 (to get the temperature, I press "t" and then "k" because I have a K-type thermocouple).

The tester script's command line output:

http://pastebin.com/jq4Rr4QX (the temperature here is accurate. This is what I want to plug into my script.)


The PyDAQFlex script:

https://github.com/torfbolt/PyDAQFlex/blob/master/daqflex/devices.py (see line 105)

The C code for the thermocouple reader:

http://pastebin.com/rEDR9efR (Not included in entirety, only the relevant parts.)


I am seriously struggling to see my mistake here. This exact piece of code appears to have worked for someone else in the PyDAQFlex Github page, so I'm extremely confused. I have emailed the creator of the software, a person in Github with a similar issue as me, and I just spent 6 hours in various IRC chats. Please help me. If it helps, I used parts of this tutorial to install the drivers and things for the thermocouple reader. Thank you so much.


Source: (StackOverflow)

Read the entire contents of a file to c char *, including new lines

I'm looking for a cross platform (Windows + Linux) solution to reading the contents of an entire file into a char *.

This is what I've got now:

FILE *stream;
char *contents;
fileSize = 0;

//Open the stream
stream = fopen(argv[1], "r");

//Steak to the end of the file to determine the file size
fseek(stream, 0L, SEEK_END);
fileSize = ftell(stream);
fseek(stream, 0L, SEEK_SET);

//Allocate enough memory (should I add 1 for the \0?)
contents = (char *)malloc(fileSize);

//Read the file 
fscanf(stream, "%s", contents);     

//Print it again for debugging
printf("Read %s\n", contents);

Unfortunately this will only print the first line in the file so I assume that fscanf stops at the first newline character. However I would like to read the entire file including, and preserving, the new line characters. I'd prefer not to use a while loop and realloc to manually construct the entire string, I mean there has to be a simpler way?


Source: (StackOverflow)

Tree: Level order Traversal using queue

I wrote codes that traversing tree using queue, but dequeue function below generates error, Is there any problem with head = p->next ? I cannot figure out why this part is wrong.

void Levelorder(void) {
node *tmp, *p;


if (root == NULL) return;

tmp = root;
printf("The level order is :\n");

while (tmp != NULL) {

    printf("%d, ", tmp->data);
    if (tmp->left) {
        enqueue(tmp->left);
    }
    if (tmp->right) {
        enqueue(tmp->right);
    }
    tmp = dequeue();
}

return;
}

void enqueue(node *p) {
if (head == NULL) {
    head = p;
}
else {
    tail->next = p;
}
tail = p;
p->next = NULL;
tail->next = NULL;

return;
}

node* dequeue(void) {
node *p;
p = head;
head = p->next;


if (head == NULL) {
    tail == NULL;
}

return p;
}

Source: (StackOverflow)

Mixing bitfields in structures

Hanging on geeksforgeeks about bitfields, found this example:

#include <stdio.h>
struct test
{
   unsigned int x;
   long int y: 33;
   unsigned int z;
};
int main()
{
   struct test t;
   unsigned int *ptr1 = &t.x;
   unsigned int *ptr2 = &t.z;
   printf("%d", ptr2 - ptr1);
   return 0;
}

As result, output is 4. But why? x occupies 4 bytes, y - 8, and z - 4. Difference in addresses x and z must be 8?


Source: (StackOverflow)

Using cmake to compile CSDP

I trying to use CSDP which is a mathematical library for SDP. I download the library an extract the lib (libsdp.a). It is using lapack and blas lib, so I add -lblas and -llapack options.

I want to compile with cmake, hier is my CmakeList file (I comment a lot of line, I just want to test the compilation of example.c with is an example given by CSDP) :

# Cette commande non obligatoire est fortement conseillée.
cmake_minimum_required (VERSION 2.6)

# Déclaration du projet.
# Les fichiers CMakeLists pourront référer à la racine du projet par la variable
# ${ECMA_SOURCE_DIR} et ${ECMA_BINARY_DIR}
project(projet_ECMA)
set(EXE run)

# L'exécutable sera rangé différemment en fonction de la plateformee.
# Par défaut le binaire est construit dans le répertoire courant (?)
# set(EXECUTABLE_OUTPUT_PATH ../bin)
# set( EXECUTABLE_OUTPUT_PATH bin/${CMAKE_BUILD_TYPE} )

#     SET (CMAKE_C_COMPILER             "/usr/bin/clang")
#     SET (CMAKE_C_FLAGS                "-Wall -std=c99")
#     SET (CMAKE_C_FLAGS_DEBUG          "-g++")
#     SET (CMAKE_C_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
#     SET (CMAKE_C_FLAGS_RELEASE        "-O4 -DNDEBUG")
#     SET (CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
#
#     SET (CMAKE_CXX_COMPILER             "/usr/bin/clang++")
#     SET (CMAKE_CXX_FLAGS                "-Wall")
#     SET (CMAKE_CXX_FLAGS_DEBUG          "-g")
#     SET (CMAKE_CXX_FLAGS_MINSIZEREL     "-Os -DNDEBUG")
#     SET (CMAKE_CXX_FLAGS_RELEASE        "-O4 -DNDEBUG")
#     SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
#
#     SET (CMAKE_AR      "/usr/bin/llvm-ar")
#     SET (CMAKE_LINKER  "/usr/bin/llvm-ld")
#     SET (CMAKE_NM      "/usr/bin/llvm-nm")
#     SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
#     SET (CMAKE_RANLIB  "/usr/bin/llvm-ranlib")

#set(CSDP_DIR "/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib/libsdp.a")
#find_package(CSDP REQUIRED)
SET (BLAS "/usr/lib/libcblas.a")
SET (LAPACK "/usr/lib/liblapack.a")
SET (CSDP "/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib/libsdp.a")
# Les options de compilation
# add_definitions(-Wall -Wextra -ansi -O2 -Wwrite-strings
#                 -Wuninitialized -Wno-missing-braces
#                 -Wno-missing-field-initializers)
add_definitions(
    # -Wno-unused-private-field  # Pour inhiber un warning de cplex 12.4
#    -m64
#    -g
#    -fPIC
#    -fexceptions
#    -pg
#    -DNDEBUG
#    -DIL_STD  # Pour cplex en C++
#    -std=c++11
#    -o
    -O3
#    -pthread
    #-L/home/hassan/Bureau/ECMA/projet_ECMA/trunk/lib    
    -ansi 
    -Wall
    -DNOSHORTS
    -DUSEGETTIME   
#    -lsdp

-lsdp -llapack
-latlas 
    -lcblas 
    -lgfortran
    -lm
-lg2c
-lctmg -lf2c

)

# Config spécifique à un système
# - UNIX vrai sous une plateforme Unix (don macosx)
# - APPLE vrai pour un os apple (donc macosx !)
# - WIN32 : vrai sous Windows (32 et 64bit !)
if(APPLE)
    message("=> Détection système Apple")
    set(CMAKE_EXE_LINKER_FLAGS  "-Wl,-no_compact_unwind")
endif()


# file(
#     GLOB
#     srcs
#     src/*.cpp
#     src/*.cc
#     src/*.c
#     src/*.hh
#     src/*.h
# )

# On définit la liste des tous les fichiers sources (dont les includes)
# cmale se débrouillera pour trouver le main() et les dépendances.
# On peut préciser des sous-répertoires, des groupes de fichiers, ...
# Mais ATTENTION aux fichiers inutilisés : ils seront compiler et peuvent
# provoquer des erreurs. Il peut donc être référable de préciser exactement les
# fichiers sources
file(
    GLOB
    srcs
    # src/site.*
    # src/station.*
    # src/remorque.*
    # src/arc.*
    # src/util.*
    # src/logger.*
    # src/options.*
    # src/bench.*
    # src/*Solver.*
    # src/solver.*
    # src/cir.*
    # src/solu.*
    # src/main.*
 #   src/*hpp
 #   /home/hassan/Bureau/ECMA/projet_ECMA/trunk/include/*.*
 #   src/*cpp
    src/*.cc
    src/*.hh
    src/example.c
    src/*.h
    # src/*.*
)

# Le ou les exécutables à générer
add_executable(${EXE} ${srcs})

# Les répertoire ou chercher vos includes (ou ceux de cplex, ...)
include_directories(
  # ${PROJECT_SOURCE_DIR}
  # ${PROJECT_BINARY_DIR}
  #$ENV{CONCERT_INCLUDE_DIR}
  $ENV{CSDP_INCLUDE}
  #$ENV{CPOPTIMIZER_INCLUDE_DIR}
  #$ENV{CPLEX_INCLUDE_DIR}
  # $ENV{LEMON_INCLUDE}
  #$ENV{CPOPTIM_INCLUDE_DIR}
  # $ENV{GLPK_INCLUDE}
)

# Ajouter ici les répertoires de vos bib. dynamiques utilisées
#

link_directories(
  # ${PROJECT_BINARY_DIR}/lemon
  # $ENV{LEMON_LIB}
  # $ENV{GLPK_LIB} 
   $ENV{CSDP_LIB} 
#  $ENV{CONCERT_LIB_DIR}
#  $ENV{CPLEX_LIB_DIR}
)

#find_library(CPLEX cplex HINTS $ENV{CPLEX_LIB_DIR})
#find_library(ILO_CPLEX ilocplex HINTS $ENV{CPLEX_LIB_DIR})
#find_library(CPOTIMIZER cpoptimizer HINTS $ENV{CPOPTIMIZER_LIB_DIR})
#find_library(CONCERT concert HINTS $ENV{CONCERT_LIB_DIR})
find_library(CSDP sdp HINTS $ENV{CSDP_LIB})

# Ajouter ici les bibliothèques dynamiques que vous utilisez
#
target_link_libraries(${EXE} blas)  # pour programmation multithead
target_link_libraries(${EXE} lapack)  # pour programmation multithead
#target_link_libraries(${EXE} sdp)  # pour programmation multithead
target_link_libraries(${EXE} pthread)  # pour programmation multithead
target_link_libraries(${EXE} m)        # lib mathématique
target_link_libraries(${EXE} ${ILO_CPLEX}) # spécial cplex
target_link_libraries(${EXE} ${CPLEX})    # spécial cplex
target_link_libraries(${EXE} ${CPOPTIMIZER})    # spécial cplex
target_link_libraries(${EXE} ${CONCERT})  # spécial cplex
message("=> CSDP     is   ${CONCERT}")
#target_link_libraries(${EXE} ${BLAS})  # spécial csdp
#target_link_libraries(${EXE} ${LAPACK})  # spécial csdp
target_link_libraries(${EXE} ${CSDP})  # spécial csdp

#target_link_libraries(${EXE} ${BLAS})  # spécial csdp
# target_link_libraries(${EXE} emon)   # lib de graphe
# target_link_libraries(${EXE} glpk)   # solveur PLNE gratuit




# La liste des exécutables mono-fichiers à compiler
## set(demo_srcs
##     main.cc
##     test1.cc
##     test2.cc
## )
# file(GLOB demo_srcs src/*.cc)


## foreach(demo_src ${demo_srcs})
##     get_filename_component( demo_name ${demo_src} NAME_WE )
##     message("=> demo_src=${demo_src}")
##     message("=> demo_name=${demo_name}")
##     add_executable(${demo_name} ${demo_src})
##     target_link_libraries(${demo_name} emon)
## endforeach()

# Quelques messages précisant la configuration utilisée
#
 message("=> CSDP_INCLUDE     is   $ENV{CSDP_INCLUDE}")
 message("=> CSDP_LIB     is   $ENV{CSDP_LIB}")
 message("=> ILOG_CPLEX_INCLUDE     is   $ENV{CPLEX_INCLUDE_DIR}")
 message("=> ILOG_CPLEX_LIB         is   $ENV{CPLEX_LIB_DIR}")
 message("=> ILOG_CONCERT_INCLUDE   is   $ENV{CONCERT_INCLUDE_DIR}")
 message("=> ILOG_CONCERT_LIB       is   $ENV{CONCERT_LIB_DIR}")
# message("=> LEMON_INCLUDE          is   $ENV{LEMON_INCLUDE}")
# message("=> LEMON_LIB              is   $ENV{LEMON_LIB}")
# message("=> GLPK_INCLUDE           is   $ENV{GLPK_INCLUDE}")
# message("=> GLPK_LIB               is   $ENV{GLPK_LIB}")
message("=> srcs                   is   ${srcs}")
# Ceci affiche 8 sur un machine 64 bits ou 4 sur un machine 32 bit
message("=> CMAKE_SIZEOF_VOID_P    is   ${CMAKE_SIZEOF_VOID_P}")
message("\n")



#
# Complément pour ajouter quelques cibles personnalisées dans le Makefile généré
#
EXECUTE_PROCESS(
    COMMAND date +%Y%m%d-%Hh%M
    OUTPUT_VARIABLE date_stamp
    OUTPUT_STRIP_TRAILING_WHITESPACE
)
GET_FILENAME_COMPONENT( project_dir_name ${CMAKE_SOURCE_DIR} NAME )


# On peut compléter les cible du Makefile généré
# (la comande finale de cette ciblesera ajoutée à CMakeFiles/Makefile2)
# (puis Essayer de créer un cmake tbz !!)
ADD_CUSTOM_TARGET(distclean
    COMMAND @echo Nettoyage complet des sources
    COMMAND @echo \"Répertoire courant = `pwd`\"
    COMMAND @echo "CMAKE_CURRENT_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}"
    # COMMAND make clean
    COMMAND find ${CMAKE_CURRENT_BINARY_DIR} -name "CMakeCache.txt" | xargs rm -rf
    COMMAND rm -rf ${CMAKE_CURRENT_BINARY_DIR}/*
)
ADD_CUSTOM_TARGET(dc
    COMMAND make distclean
)
ADD_CUSTOM_TARGET(cc
    COMMAND make distclean
)
ADD_CUSTOM_TARGET(c
    COMMAND make clean
)
# Attention : cette commande construit une cible pour le Makefile.
# Il faut protéger les double-quote si l'on veux qu'elles ne soient pas consommées
# par cmake mais passée au Makefile.
# Un seul COMMENT par cible semble-t-il
ADD_CUSTOM_TARGET(tbz
    COMMENT "Création d'une archive datée du projet"
    COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
    COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    # tar -C newDir :  pour se placer dans le répertoire parent de l'archive
    COMMAND tar cjf  ${CMAKE_SOURCE_DIR}-${date_stamp}.tbz
                     -C ${CMAKE_SOURCE_DIR}/..
                     ${project_dir_name}-${date_stamp}
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND @echo \" => Archive faite :  ${project_dir_name}-${date_stamp}.tbz\"
)
ADD_CUSTOM_TARGET(txz
    COMMENT "Création d'une archive datée du projet (TEST XZ)"
    COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
    COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
    # tar -C newDir :  pour se placer dans le répertoire parent de l'archive
    COMMAND tar cf  ${CMAKE_SOURCE_DIR}-${date_stamp}.tar
                     -C ${CMAKE_SOURCE_DIR}/..
                     ${project_dir_name}-${date_stamp}
    COMMAND xz  ${CMAKE_SOURCE_DIR}-${date_stamp}.tar
    COMMAND mv    ${CMAKE_SOURCE_DIR}-${date_stamp}.tar.xz ${CMAKE_SOURCE_DIR}-${date_stamp}.txz
    COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
    COMMAND @echo \" => Archive faite :  ${project_dir_name}-${date_stamp}.tbz\"
)
# ADD_CUSTOM_TARGET(zip
#     COMMENT "Création d'une archive datée du proje (TEST ZIP°t"
#     COMMAND @echo \" => duplication du projet en : ${project_dir_name}-${date_stamp}\"
#     COMMAND cp -Rp ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}-${date_stamp}
#     COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
#     COMMAND mkdir -p ${CMAKE_SOURCE_DIR}-${date_stamp}/build/
#     COMMAND echo \"1: CMAKE_SOURCE_DIR-date_stamp==1==${CMAKE_SOURCE_DIR}-${date_stamp}\"
#     COMMAND echo \"2: project_dir_name-date_stamp==2==${project_dir_name}-${date_stamp}\"
#     # tar -C newDir :  pour se placer dans le répertoire parent de l'archive
#     # COMMAND '_pwd=`pwd`'
#     # COMMAND pushd  ${CMAKE_SOURCE_DIR}/..
#     COMMAND echo 'pushd; zip -r -v -y -o -9  ${CMAKE_SOURCE_DIR}-${date_stamp}.zip \
#                      ${project_dir_name}-${date_stamp} ; popd'
#     COMMAND sh -c "pushd; zip -r -v -y -o -9  ${CMAKE_SOURCE_DIR}-${date_stamp}.zip \
#                      ${project_dir_name}-${date_stamp} ; popd"
#     # COMMAND zip -r -v -y -o -9  ${CMAKE_SOURCE_DIR}-${date_stamp}.zip
#     #                  ${project_dir_name}-${date_stamp}
#     COMMAND 'cd $_pwd'
#     # COMMAND popd
#     COMMAND rm -r ${CMAKE_SOURCE_DIR}-${date_stamp}
#     COMMAND @echo \" => Archive faite :  ${project_dir_name}-${date_stamp}.tbz\"
# )

INCLUDE(InstallRequiredSystemLibraries)
IF(WIN32 AND NOT UNIX)
    SET(CPACK_NSIS_MODIFY_PATH ON)
ENDIF(WIN32 AND NOT UNIX)

INCLUDE(CPack)

#./

The problem is, I think that libsdp.a need library (blas, lapack and math) but, even if I add it in my Cmake, he don't succeed to find it :

    [100%] Building C object CMakeFiles/run.dir/src/example.c.o
/usr/bin/cc  -DNOSHORTS -DUSEGETTIME -I/home/hassan/Bureau/ECMA/projet_ECMA/trunk/include    -O3 -ansi -Wall -lsdp -llapack -latlas -lcblas -lgfortran -lm -lg2c -lctmg -lf2c -o CMakeFiles/run.dir/src/example.c.o   -c /home/hassan/Bureau/ECMA/projet_ECMA/src/example.c
/home/hassan/Bureau/ECMA/projet_ECMA/src/example.c: In function ‘main’:
/home/hassan/Bureau/ECMA/projet_ECMA/src/example.c:62:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
  printf("%d \n", sqrt(2));
  ^
Linking C executable run
/usr/bin/cmake -E cmake_link_script CMakeFiles/run.dir/link.txt --verbose=1
/usr/bin/cc      CMakeFiles/run.dir/src/example.c.o  -o run -rdynamic -lblas -llapack -lpthread -lm trunk/lib/libsdp.a 
trunk/lib/libsdp.a(initsoln.o): dans la fonction « initsoln »:
initsoln.c:(.text+0x2a9): référence indéfinie vers « sqrt »
initsoln.c:(.text+0x2ed): référence indéfinie vers « sqrt »
initsoln.c:(.text+0x334): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(norms.o): dans la fonction « norm2 »:
norms.c:(.text+0x1d): référence indéfinie vers « dnrm2_ »
trunk/lib/libsdp.a(norms.o): dans la fonction « norm1 »:
norms.c:(.text+0x4d): référence indéfinie vers « dasum_ »
trunk/lib/libsdp.a(norms.o): dans la fonction « norminf »:
norms.c:(.text+0x81): référence indéfinie vers « idamax_ »
trunk/lib/libsdp.a(sdp.o): dans la fonction « sdp »:
sdp.c:(.text+0x1ed7): référence indéfinie vers « dpotrf_ »
sdp.c:(.text+0x2104): référence indéfinie vers « pow »
sdp.c:(.text+0x7cf3): référence indéfinie vers « sqrt »
sdp.c:(.text+0x8651): référence indéfinie vers « sqrt »
sdp.c:(.text+0x88eb): référence indéfinie vers « sqrt »
sdp.c:(.text+0x88f5): référence indéfinie vers « sqrt »
sdp.c:(.text+0x8968): référence indéfinie vers « pow »
sdp.c:(.text+0x89bd): référence indéfinie vers « sqrt »
sdp.c:(.text+0x89e9): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(Fnorm.o): dans la fonction « Fnorm »:
Fnorm.c:(.text+0xcb): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(calc_dobj.o): dans la fonction « calc_dobj »:
calc_dobj.c:(.text+0x2d): référence indéfinie vers « ddot_ »
trunk/lib/libsdp.a(mat_mult.o): dans la fonction « mat_mult »:
mat_mult.c:(.text+0xef): référence indéfinie vers « dgemm_ »
trunk/lib/libsdp.a(mat_mult.o): dans la fonction « mat_mult_raw »:
mat_mult.c:(.text+0x479): référence indéfinie vers « dgemm_ »
trunk/lib/libsdp.a(solvesys.o): dans la fonction « solvesys »:
solvesys.c:(.text+0x40): référence indéfinie vers « dpotrs_ »
trunk/lib/libsdp.a(linesearch.o): dans la fonction « linesearch »:
linesearch.c:(.text+0x39f): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x416): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x488): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0x4ff): référence indéfinie vers « dgemv_ »
linesearch.c:(.text+0xe2b): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(matvec.o): dans la fonction « matvec »:
matvec.c:(.text+0xb8): référence indéfinie vers « dgemv_ »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_blk »:
chol.c:(.text+0x36): référence indéfinie vers « dpotrf_ »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_diag »:
chol.c:(.text+0x134): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol »:
chol.c:(.text+0x1bd): référence indéfinie vers « dpotrf_ »
chol.c:(.text+0x2e1): référence indéfinie vers « sqrt »
trunk/lib/libsdp.a(chol.o): dans la fonction « chol_inv »:
chol.c:(.text+0x42f): référence indéfinie vers « dtrtri_ »
trunk/lib/libsdp.a(qreig.o): dans la fonction « qreig »:
qreig.c:(.text+0x539): référence indéfinie vers « sqrt »
qreig.c:(.text+0x64f): référence indéfinie vers « sqrt »
qreig.c:(.text+0x718): référence indéfinie vers « sqrt »
collect2: error: ld returned 1 exit status
make[2]: *** [run] Erreur 1

Source: (StackOverflow)

why the loop does not run infinite in the below example?

This is my sample code:

int main()
{
    static int i = 5;
    if(--i)
    {
        main();
        printf("%d ",i);
    }   
}

Why is it printing 0 0 0 0? And why the loop is not infinite? This question is picked up from geeksforgeeks.


Source: (StackOverflow)

C functions in c++

#include <iostream>
#include <sstream>
#include "blocknode.h"

 using namespace std;

class MemoryManager
{
public:
MemoryManager(unsigned int memsize);
unsigned char * malloc(unsigned int request);
void free(unsigned char * blockptr);
blocknode *getFirstPtr();
friend ostream & operator<<(ostream & out,const MemoryManager &M);

private:
unsigned int memsize;
unsigned char *baseptr;
blocknode * firstBlock;

void mergeForward(blocknode *p);
void splitBlock(blocknode *p,unsigned int chunksize);
};

Here is the BLOCKNODE.h file

#include <iostream>

using namespace std;

struct blocknode
{
  unsigned int bsize;
  bool free;
  unsigned char *bptr;
  blocknode *next;
  blocknode *prev;

  blocknode(unsigned int sz,unsigned char *b,bool f=true,blocknode
  *p=0,blocknode *n=0):
  bsize(sz),free(f),bptr(b),prev(p),next(n) {}
  };

CPP FILE

#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include "MemoryManager.h"

using namespace std;


ostream & operator<<(ostream & out,const MemoryManager &M)
{
blocknode *tmp = M.firstBlock;
assert(tmp);
while(tmp)
{
  out << "[" << tmp->bsize << ",";
  if (tmp->free)
 out << "free] ";
  else
 out << "allocated] ";
  if (tmp->next)
 out << " -> "; 
  tmp = tmp->next;
}
return out;
}

MemoryManager::MemoryManager(unsigned int memtotal): memsize(memtotal)
{
baseptr = new unsigned char[memsize];
firstBlock = new blocknode(memsize,baseptr);
}

blocknode *MemoryManager::getFirstPtr()
{
return firstBlock;
}

unsigned char * MemoryManager::malloc(unsigned int request)
// Finds the first block in the list whose size is >= request
// If the block's size is strictly greater than request
// the block is split, with the newly create block being free. 
// It then changes the original block's free status to false
{
blocknode * tmp = this->firstBlock;
assert(tmp);
while (tmp){
    if (tmp->bsize >= request){
        if (tmp->bsize > request){
            splitBlock(tmp, request);
            return tmp->bptr;
        }
        tmp->free = false;
        return tmp->bptr;

    }
    tmp = tmp->next;
}

}

void MemoryManager::splitBlock(blocknode *p, unsigned int chunksize)
// Utility function. Inserts a block after that represented by p
// changing p's blocksize to chunksize; the new successor node 
// will have blocksize the original blocksize of p minus chunksize and 
// will represent a free block.  
// Preconditions: p represents a free block with block size > chunksize
// and the modified target of p will still be free.

{
if (p->free == false || p->bsize <= chunksize) {
    cout << "Error splitting memory....exiting with error code 1" << endl;
    exit(1);
}
blocknode * heap = new blocknode(p->bsize,p->bptr + chunksize,true,0,0);
heap->bsize = p->bsize - chunksize;
heap->prev = p;
p->bsize = chunksize;
p->next = heap;
 }

void MemoryManager::mergeForward(blocknode *p)
// merges two consecutive free blocks
// using a pointer to the first blocknode;
// following blocknode is deleted
{

    blocknode * tmp = p->next;
    p->bsize += p->next->bsize;
    p->next = tmp->next;
    tmp->next->prev = p;
    delete tmp;

}


void MemoryManager::free(unsigned char *blockptr)
// makes the block represented by the blocknode free
// and merges with successor, if it is free; also 
// merges with the predecessor, it it is free
{
blocknode * tmp = this->firstBlock->next;
assert(tmp);
while (tmp) {
    if (tmp->bptr == blockptr) {
        tmp->free = true;
        if (tmp->prev->free == true) {
            mergeForward(tmp->prev);
        }
        if (tmp->next->free == true) {
            mergeForward(tmp);
        }
    }
    tmp = tmp->next;
 }
 }

The goal of this program is to pretty much simulate the C heap manager which deals with malloc() and free(). I am having trouble with the last four functions of the memory manager cpp file. (refer to the comments) The code compiles however my program crashes during runtime, it says that there is an unhanded exception at memory location XxXXXXXXX does anyone know what is causing this? Line 110 ("if(tmp->next->free == true)") is where the program breaks


Source: (StackOverflow)

Convert floating point number 1864.78 to binary and IEEE format

I've been trying to convert the value of the S&P 500 which today is 1864.78 to how it would be represented in IEEE single precision format in memory.

Converting the left of the decimal (1864) is easy.

11101001000.

But how do I get the binary representation of the decimal (.78)? I tried using the technique but it produces many numbers over the 8 bit exponent IEEE format:

.78*2=1.56 1

.56*2=1.12 1

.12*2=.24 0

.24*2=.48 0

.48*2=.96 0

.96*2=1.92 1

.92*2=1.84 1

.84*2=1.68 1

.68*2=1.36 1

.36*2=.72 0

.72*2=1.44 1

.44*2=.88 1 (rounded up because now we have 23 total bits)

11101001000.110001111011 = 23 bits for mantissa

Add 0 for sign

0 11101001000.110001111011

Now I need to move the decimal over 10 places

1.1101001000110001111011 x 2^10 exponent is 10 now

add a 0 bit to make full mantissa 23 bits

1.11010010001100011110110

exponent is 10 so 10 + 127 = 137

which is equal to 10001001

so 0 10001001 11010010001100011110110 which is a 32 bit number.

Does this look like a decent approach? I tested the value and writing this question I was actually able to work through it on my own.

Testing the decimal FP with this. http://www.h-schmidt.net/FloatConverter/IEEE754.html


Source: (StackOverflow)

How to get current directory string in nmake?

I'm writing makefile for nmake.

Firstly, I want to get the current working directory like 'pwd' in Linux, for example, the result is

C:\foo\bar

Secondly, I want to insert backslash into the result and get a string like

"C:\\foo\\bar"

How can I do that?


Source: (StackOverflow)

How to create a linear list for storing 10,20,30 using linked list?

How can I implement a linked list for storing 10,20,30 .Please help me with a simple example.


Source: (StackOverflow)