samedi 27 juin 2015

What's the difference between GtkApplication and gtk_init?

I am now learning to use GTK+3.0 with C in Linux. After reading some tutorials and sample code, I have some questions regarding how to initialize an application.

Here are two versions of code I have seen.

#include <gtk/gtk.h>

static void
activate (GtkApplication* app,
          gpointer        user_data)
{
  GtkWidget *window;

  window = gtk_application_window_new (app);
  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
  gtk_widget_show_all (window);
}

int
main (int    argc,
      char **argv)
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

This code used gtk_application_new() to init a GtkApplication and g_application_run() to start it.

This is the second one.

#include <gtk/gtk.h>

int main(int argc,char *argv[])
{
  GtkWidget *window;
  gtk_init(&argc,&argv);

  window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window),"helloworld");
  gtk_widget_show(window);
  gtk_main();

  return 0;
}

This code used gtk_init() to init the application and gtk_main() to run it.

However, I can't figure out the difference between them as the running result seems the same.

Replacing multiple new lines in a file with just one

This function is supposed to search through a text file for the new line character. When it finds the newline character, it increments the newLine counter, and when there are more than 2 consecutive blank new lines, its suppose to squeeze all the blank lines into just one blank line.

In my code if there are 2 new lines it's suppose to get rid of them and squeeze them into one, for testing purposes I also have it printing "new line" when it reaches the newLine < 2 condition. Right now it prints new line for every new line, whether its blank or not, and its not getting rid of the extra new lines. What am I doing wrong?

EDIT: HERE IS MY FULL CODE http://ift.tt/1GSqY1v

So basically the program is suppose to concatenate two files together and than perform various operations on them, like what I'm trying to do which is get rid of multiple consecutive blank new lines. So in order to execute it in cygwin I do ./a -s file1 file2 Its suppose to concatenate file1 and file2 together into a file called contents.txt and than get rid of the consecutive new lines and display them on my cygwin terminal (stdout). (the -s calls the function to get rid of the consecutive lines). The third and fourth arguments passed in (file1 and file2) are the two files its suppose to concatenate together into one file called contents.txt The squeeze_lines function than reads the contents.txt file and is suppose to squeeze new lines. You can see below for an example for the contents I put in file1.txt. file2.txt just has a bunch of words followed by empty new lines.

int newLine = 1;
int c; 

if ((fileContents = fopen("fileContents.txt", "r")) == 0) 
{
    perror("fopen");
    return 1; 
}

while ((c = fgetc(fileContents)) != EOF)
{   
    if (c == '\n')
    {
        newLine++;
        if (newLine < 2) 
        {
            printf("new line");
            putchar(c); 
        }
    }
    else 
    {
        putchar(c); 
        newLine = 0;
    }
}

The file the program reads in a .txt file with these contents. Its suppose to read the file, get rid of the leading, and consecutive new lines, and output the new formatted contents to stdout on my cywgin terminal.

/* hello world program */


#include <stdio.h>

    tab
            2tabs

Why getting out of memory exception when trying to play images in pictureBox?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Player_Manager
{
    public partial class ScreenShotsPlayer : Form
    {
        FileInfo[] images;
        DirectoryInfo di1;
        int current = 0;

        public ScreenShotsPlayer()
        {
            InitializeComponent();

            di1 = new DirectoryInfo(@"e:\screenshots");
            images = di1.GetFiles("*.bmp");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            current = (current >= images.Length - 1) ? 0 : ++current;
            pictureBox1.Image = new Bitmap(images[current].FullName);
            pictureBox1.Refresh();
        }
    }
}

There are 1200 images on the hard disk and the timer is set to 100ms. After about 258-270 images played it's throwing the out of memory exception on the line:

pictureBox1.Refresh();

System.OutOfMemoryException was unhandled
  HResult=-2147024882
  Message=Out of memory.
  Source=System.Drawing
  StackTrace:
       at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
       at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height)
       at System.Drawing.Graphics.DrawImage(Image image, Rectangle rect)
       at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
       at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
       at System.Windows.Forms.Control.WmPaint(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException: 

If i will remove the line pictureBox1.Refresh(); Then it will throw the exception on:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Player_Manager
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

On the line Application.Run(new Form1());

Same exception.

Overwritting null character in C array

Consider the case:

char s1[] = "abc";
s1[3] = 'x';
printf("%s", s1);

As I know, printf prints characters until it finds the null character and then stops.

When I overwrite the null character by 'x', why does printf print the s1 array correctly? How does it find the null character?

Create pyside widget in C/C++

I have a very complex custom widget derived from QWidget in PySide.

At first its paintEvent was taking more than 1sec to complete. Then I've implemented a lot of caching with QPixmap to each layer of the "image" that I'm drawing. Now my paintEvent finishes in about 90ms, that is really fine, but not enough.

I'm wondering if I can implement this custom widget in plain C or C++ and them use it as an abstract widget in PySide (like PySide does with all other available widget).

I found here that in PyQt I could use sip for this. But I can't find a match for this in PySide.

Does any one knows who to do that?

Array of chars to linked list - Using the address in array

i am trying to pass words from a string to a linked list, the thing is, i can't reallocate memory to my string inside my struct, i should be using the address of each word inside the array.

my struct:

typedef struct slist{
    char *string;
    struct slist * prox;
} *SList;

my function:

int words (char t[], SList *l){
    int i, p;
    p=0;
    *l = (SList) calloc(1, sizeof(struct slist));

    SList aux = NULL;


    SList li = *l;
    for(i=0; t[i]!='\0' ;){
        aux = (SList) calloc(1, sizeof(struct slist));

        li->string = &t[i];
        li->prox = aux;
        li = aux;

        while(t[i]!=' ') i++;

        //t[i++] = '\0'; -> this doesn't work, bus error 10;

        while(t[i]==' ') i++;

        p++; //This counts words
    }

    return p;

}

This works, kind of, my doubt is, i can't change the initial array to include a NULL char at the end of each word (Strings declared in C are read-only right?)

So, i tried to add the t[i]='\0' in vain.

At this moment, running the code with this string

char *str = "this is one sentence";

will get me the following strings in my linked list:

this is one sentence
is one sentence
one sentence
sentence

the expected result is not this one, it should add the NULL char after the first word inside my list->string

PS: The linked list is not well defined, it adds a NULL at the end unnecessarily but i can deal with that later on.

Thank you for your help!

the C program does not execute the function outside the main

If I execute the exec() function in another C program as a main function it works perfectly, while if I put it as a function called in the main menu it gives me some warning and the function does not run.

My code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */

int exec (void) {

        char array[100];
        char character;
        int i = 0;
        char* point;
        int j = 0;

        printf ("Digita una stringa");
        printf ("\n");
        do {
            character = getchar();
            array[i] = character;
            i++;
        }
        while (character != '\n');
        array[i-1] = '\0';
        i = 0;

        char* string[100];

        char *word = strtok(array, " .");
        j = 0;
        while (word != NULL) {
            printf("%s\n", word);
            string[j++] = word; // Increment j
            word = strtok(NULL, " .");
        }
        string[j] = NULL; // Make sure the array is NULL term

        printf ("\n");  

    pid_t  pid;
    pid = fork();
    int status;

    if (pid == -1) {
        perror("");
    }else if (pid == 0) {
        execvp(string[0], string);     /* execute the command  */
                fprintf(stderr, "Failed to exec");  
                exit(1);
            }
    else {

        //.. wait until the child ends
        waitpid(-1, &status, 0);
      }

return;
}

int read_input (void) {
    int choice;
    printf("Seleziona una voce dal menu");
    do {    
        printf("\n");
        scanf ("%i", &choice);
        if (choice > 8 || choice < 1)
            printf ("Attenzione, inserisci un valore contemplato dal menu");
    }
    while ( choice > 8 || choice < 1);

return choice;
}

void main (int argc, char *argv[]) {

    printf ("------------------------\n");
    printf ("          MENU         \n");
    printf ("------------------------\n");
    printf ("  \n");
    printf ("1) Esecuzione in foreground di un processo\n");
    printf ("2) Ctrl -C\n");
    printf ("3) Exit\n");
    printf ("4) Background\n");
    printf ("5) Pipe\n");
    printf ("6) Jobs\n");
    printf ("7) fg\n");
    printf ("8) kill\n");
    int menu = read_input();
    switch (menu) {

        case '1' :  
                exec ();
                break; 
        case '2' :
                //ctrl();
                break;
        case '3' :
                //exit_();
                break; 
        case '4' : 
                //background();
                break;
        case '5' :
                //pipe();
                break;
        case '6' : 
                //jobs();
                break;
        case '7' : 
                //fg();
                break;
        case '8' : 
                //kill();
                break;
    }
}

this is the warning:

elaborato.c:31:16: warning: initialization makes pointer from integer without a cast [enabled by default] char *word = strtok(array, " ."); 

How to compare 2 char in C

Why this don't work? months[5] == name is equal. months[5] is Jun and name is Jun but if never execute...

 int getMonthNum(char * name){
    char *months[12] ={"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    char *pointertoarray = &months;
    int i;
        for(i = 1; i <= 12; i++){
            if(months[5] == name){
                return i;
            }
        }
    return i;
    }

Macro with zero arguments

I can't figure out what is wrong with this code. When I pass 1 argument to LOG_INFO, it works fine, but fails with 0 arguments.

#define LOG_INFO(...) CLOG(INFO, "default", ##__VA_ARGS__)

LOG_INFO() << "Log using default file";

error:
expected primary-expression before ‘)’ token

Segmentation Fault in C

My code is giving me a segmentation fault and I can't seem to find what I'm doing wrong:

#include <stdio.h>
#include <string.h>
char find(char name[], char allNames[][10], int length)
{
int i=0;
for (i = 0; i < length; i++) {
if (strcmp(allNames[i],name) == 1) {
printf("%i",i);
return *name;
}
}
return -1;
}

main(){
  char allNames[][10] = {"cat","dog","frog","log","bog"};
  char name[] = "log";
int length=5;
  printf("%s",find(name,allNames,length));

}

I'm really keen to understand all the mechanisms happening here and what I'm doing wrong for tomorrows exam. Thanks for your help!

fully-buffered stream get flushed when it is not full

I really confused with how exactly a buffer work. So I write a little snippet to verify:

#include<stdio.h>
#define BUF_SIZE 1024 

char buf[BUF_SIZE];
char arr[20];

int main()
{
        FILE* fs=fopen("test.txt","r");
        setvbuf(fs,buf,_IOFBF,1024);
        fread(arr,1,1,fs);
        printf("%s",arr);

        getchar();

        return 0;
}

As you see, I set the file stream fs to fully buffered stream(I know most of the time it would default to fully-buffered. just making sure). And I also set its related buffer to be size 1024, which mean that the stream would not be flushed until it contain 1024 bytes of stuff(right?).

In my opinion, the routine of fread() is that, it read data from the file stream, store it at its buffer buf,and then the data in the buf would be send to the arr as soon as it is full of 1024 bytes of data(right?).

But now, I read only one character from the stream!!And also, there is are only four characters in the file test.txt. why can I find something in the arr in case that there is only one char(I can print that one character out)

Convert C/C++ function's header to C# DLLExport

I'm looking for a program (or c# algorithm) that will convert my C++ function headers to C# DLLImport headers. For example:

idevice_error_t idevice_get_device_list (char ***   devices, int *  count);

to

[DllImport("DLL Path here", EntryPoint = "idevice_get_device_list", CallingConvention = CallingConvention.Cdecl)]
internal static extern idevice_error_t idevice_get_device_list(out IntPtr devices, out int count);

I have already found PInvoke Interop Assistant, but I can't convert header from example because it doesn't know idevice_error_t. I want a program that will ignore everything it doesn't know and just paste inline the name idevice_error_t in c# code. I will change that letter.

Why is my byte stream that is sent over serial (written to /dev/tty*) coming back remapped?

This has been a rather frustrating problem. Basically, I'm writing a sequence of bytes to an external device connected via serial, and to debug the program, I'm echoing it back to my Linux machine (Ubuntu 14.04 LTS).

For the most part, most of the functionality seems to work. For instance, I write 16 bytes, and I receive 16 bytes. However, the received 16 bytes appear to be remapped:

  Serial Write: AF 0A D1 07 01 00 10 00 00 00 00 00 00 00 00 00 
  Number of bytes written: 16

  Serial Response: AF CB DD F7 FD FF 9F FF FF FF FF FF FF FF FF FF 
  Bytes Received: 16

This is a consistent pattern: AF -> AF, 00 -> FF, D1 -> DD, and so forth.

The code that is processing this is fairly simple (there are three parts).

The first part reads from a pipe that contains the data to be written, and then sends it to the specified tty file:

void* ttyPortWrite(void*)
{
  //Local Variables
    int err, i, j, bytesRead, bytesWritten = 0;
    uint8_t bufferBytes[6144];
    std::string cadetWrite = "";
    uint8_t ch[1];
    pollfd pollList;


  //Create a pipe
    err = pipe(fileDesc);
    if(err < 0)
    {
      pthread_mutex_lock(&stdIO);
        std::cerr << "\nThere was an error creating a pipe.\nThe program will now exit."
                  << std::endl;
      pthread_mutex_unlock(&stdIO);
      exit(-1);
    }

  //Build poll structure
    pollList.fd = fileDesc[0];
    pollList.events = POLLIN | POLLPRI;

  //Continuously write out to terminal
    while(1)
    {
      //Flush streams
        pthread_mutex_lock(&stdIO);
        std::cout << std::endl;
        pthread_mutex_unlock(&stdIO);


      //Poll pipe
        if(poll(&pollList, (unsigned long) 1, -1))
        {
          //Read one byte at a time, looking for special character (~)
            for(i = 0;; i++)
            {
              bytesRead = read(fileDesc[0], &ch, 1);

              if(bytesRead < 0)
              {
                pthread_mutex_lock(&stdIO);
                std::cerr << "\nREAD ERROR: System reported bytes were ready to be read, but read() returned an error code: "
                          << "\n\t"
                          << strerror(errno) 
                          << std::endl;
                pthread_mutex_unlock(&stdIO);
              }

              else if(bytesRead == 0)
              {
                pthread_mutex_lock(&stdIO);
                std::cout << "\nPOTENTIAL ERROR: System reported bytes were ready to be read, but no bytes were found."
                          << std::endl;
                pthread_mutex_unlock(&stdIO);
              }

               else
               {
                 //Quick check if special character was found
                   if(ch[0] == 0x7E)
                   {    
                      //Print out to user
                        pthread_mutex_lock(&stdIO);
                        printf("\nSerial Write: ");
                        for(j = 0; j < i; j++)
                          printf("%02X ", bufferBytes[j]);
                        pthread_mutex_unlock(&stdIO);

                  //Write to TTY file
                    bytesWritten = write(fdSerial, &bufferBytes, i);

                    if(bytesWritten <= 0)
                    {
                      pthread_mutex_lock(&stdIO);
                      std::cerr << "\nTTY WRITE ERROR: Bytes were ready to be written to TTY file, but the system reported an error during a write attempt."
                                << std::endl;
                      pthread_mutex_unlock(&stdIO);
                     }
                     else
                     {
                        pthread_mutex_lock(&stdIO);
                        std::cout << std::endl
                                  << "Number of bytes written: "
                                  << bytesWritten;
                        pthread_mutex_unlock(&stdIO);
                      }
                      //Break out of loop
                        break;
                 }
                 else
                 {
                   //Save to buffer
                   bufferBytes[i] = ch[0];
                 }      
             }
           }//End for

        } //End if poll()
      } //End while 
}//End function

I'm fairly certain there isn't anything wrong with this function. The input written to the pipe (which is handled by another thread), is read byte for byte by this thread, and it matches perfectly.

The second snippet of code simply waits for data to come in to the tty file:

void* ttyPortRead(void*)
{
  //Local Variables
    uint8_t bufferBytes[2048];
    int i = 0;
    int bytesRead = 0;
    std::string cadetResponse = "";
    pollfd pollList;

  //Build poll structure
    pollList.fd = fdCadet;
    pollList.events = POLLIN | POLLPRI;

  //Continuously monitor the file descriptor
    while(1)
    {
      if(poll(&pollList, (unsigned long) 1, -1))
      {
        //Sleep for 1 second - found it works best
          sleep(1);

        //Ready to read
          bytesRead = read(fdCadet, &bufferBytes, 2048);

        //Determine how many bytes were read
          if(bytesRead < 0)
          {
            pthread_mutex_lock(&stdIO);
              std::cerr << "\nREAD ERROR: System reported bytes were ready to be read, but read() returned an error code: "
                        << "\n\t"
                        << strerror(errno) 
                        << std::endl;
            pthread_mutex_unlock(&stdIO);
          }

          else if(bytesRead == 0)
          {
            pthread_mutex_lock(&stdIO);
              std::cout << "\nPOTENTIAL ERROR: System reported bytes were ready to be read, but no bytes were found."  
                        << std::endl;
            pthread_mutex_unlock(&stdIO);
          }

          else
          {       
            //Print out string in hexadecimal   
              pthread_mutex_lock(&stdIO);
                printf("\nSerial Response: ");
                for(i = 0; i < bytesRead; i++)
                {
                  printf("%02X ", bufferBytes[i]);
                }
                std::cout << "\nBytes Received: "
                          << bytesRead
                          << std::endl;
              pthread_mutex_unlock(&stdIO);

          } // END IF bytesRead

      } //End IF poll()

    } //End while


} // End Function

Now I don't believe anything is wrong with this function, being that it's simply reading whatever came into the tty file and printing it out. It's not (or at least shouldn't) be manipulating the data.

The third code snippet is just Arduino code (used for testing) - it simply echoes whatever data comes in.

void setup()
{
   Serial.begin(57600);
}

void loop()
{
   if(Serial.available())
     Serial.write(Serial.read());
}

I doubt anything is wrong with this either - but I can't say I know the Arduino functions that well.

And finally, the code below is where I suspect I have a problem. It's my setup code for the 'dev/tty*' serial settings.

   void setInterfaceAttribs(int fd, int baud, int databits, int stopbits, int parity, std::string flow)
   {
      //Local Variables
        speed_t baudRate = B57600;

      //Allocate termios structure
        struct termios tty;
        memset(&tty, 0, sizeof(tty));

      //Grab attributes and check for errors
        if(tcgetattr(fd, &tty) != 0)
        {
          std::cerr << "\nError encountered when calling tcgetattr: "
                    << errno
                    << "\nThe program will now exit."
                    << std::endl;

          exit(-1);
        }

      //Set to raw mode
        cfmakeraw(&tty); //Some of the commands below will be redundant or may modify certain values

      //Set BAUD Rate
        switch(baud)
        {
          case 9600:
            baudRate = B9600;
            break;

          case 19200:
            baudRate = B19200;
            break;

          case 38400:
            baudRate = B38400;
            break;

          case 57600:
            baudRate = B57600;
            break;

          case 115200:
            baudRate = B115200;
            break;

          case 230400:
            baudRate = B230400;
            break;

          case 460800:
            baudRate = B460800;
            break;

          case 921600:
            baudRate = B921600;
            break;

          default:
            baudRate = B9600;
            break;
        }

        cfsetospeed(&tty, speed);
        cfsetispeed(&tty, speed);

     //Set number of data bits
       tty.c_cflag &= ~CSIZE;

       switch(databits)
       {
          case 5:
            tty.c_cflag |= CS5;
            break;

          case 6:
            tty.c_cflag |= CS6;
            break;

          case 7:
            tty.c_cflag |= CS7;
            break;

          case 8: 
            tty.c_cflag |= CS8;
            break;

          default:
            tty.c_cflag |= CS8;
            break;
       }

    //Set number of stop bits
      switch(stopbits)
      {
        case 1:
          tty.c_cflag &= ~CSTOPB;
          break;

        case 2: 
          tty.c_cflag |= CSTOPB;
          break;

        default:
          tty.c_cflag |= CSTOPB;
          break;
     }

  //Set Parity Encoding
    switch(parity)
    {
      case 0: //Even
        tty.c_cflag &= ~(PARENB | PARODD);
        tty.c_cflag |= PARENB;
        break;

      case 1: //Odd
        tty.c_cflag &= ~(PARENB | PARODD);
        tty.c_cflag |= (PARENB | PARODD);
        break;

      case 2: //None
        tty.c_cflag &= ~(PARENB | PARODD);
        break;

      default:
        tty.c_cflag &= ~(PARENB | PARODD);
        break;
    }

  //Set flow control
     if( (!flow.compare("true")) || (!flow.compare("t")) )
       tty.c_cflag |= CRTSCTS;
     else
       tty.c_cflag &= ~CRTSCTS;

  //NOTE: (XON/XOFF) always disabled
     tty.c_iflag &= ~(IXON | IXOFF | IXANY);

  //Finish some stuff up...
     tty.c_cflag |= (CLOCAL | CREAD); //Ignore modem controls, enable read
     tty.c_iflag &= ~IGNBRK; //disable break processing
     tty.c_lflag = 0; //no signalling characters, etc
     tty.c_cc[VMIN] = 0; //Read doesn't block
     tty.c_cc[VTIME] = 5; //0.5 second timeout
     //tty.c_ispeed = baud;
     //tty.c_ospeed = baud;

  //Flush, then apply attributes
    tcflush(fd, TCIOFLUSH);

    if(tcsetattr(fd, TCSANOW, &tty) != 0)
    {
      std::cerr << "\nError encountered when calling tcsetattr: "
                << errno
                << "\nThe program will now exit."
                << std::endl;

      exit(-1);
    }
  return;
}

The reason I suspect this code is because of the settings I see when I run stty -F /dev/ttyACM1, where /dev/ttyACM1 is the file my Arduino comes up as.

By default, the settings should be 57600 BAUD, 8N1, raw, and no flow control. However, this is what comes up:

stty -F /dev/ttyACM1 
  speed 0 baud; line = 0;
  min = 1; time = 0;
  -brkint -icrnl -imaxbel
  -opost -onlcr
  -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke

I'm not sure what's going on. Any input would be appreciated.

_mm_cvt_ss2si gives different results than simple rounding

In the code below, method A differs from method B. Can someone explain why _mm_cvt_ss2si rounds to even number when decimal part is exactly 0.5 ?

float f;

// rounding method  A
_mm_cvt_ss2si(_mm_load_ss(&f));

// rounding method B
(long)((f>0.0f) ? (f + 0.5f):(f -0.5f));

Segmentation Fault C (1d array to 2d array and back)

I am given a 1d array that contains color values for an image's pixels. The array is of size cols*rows. I want to change the color of a specific region. The function call is given the 1d array, its size, left, top, bottom, right, and also the desired color. What I tried to do is copy the values of the 1d array into a 2d array, do the deed on the 2d array then copy back the new values to the 1d array. I keep getting a segmentation fault error. Here's the code:

void region_set( uint8_t array[], 
     unsigned int cols, 
     unsigned int rows,
     unsigned int left,
     unsigned int top,
     unsigned int right,
     unsigned int bottom,
     uint8_t color )

{

if(!(left == right || top == bottom)){


    uint8_t Array2[cols][rows];


    int x, y;

    for(int i= 0; i < rows * cols; i++){            
        x = i / rows;
        y = i % cols;
        Array2[y][x] = array[i];
    }

    for(int y=left; y < right-1; y++){
         for(int x = top; x < bottom-1 ; x++){
            Array2[y][x] = color;
        }
    }

    for(int i= 0; i < rows * cols; i++){            
        x = i / rows;
        y = i % cols;
        array[i] = Array2[y][x];
    }


}

}

Is this one-based indexing trick in C safe?

I saw someone doing this to have array index starting at 1 instead of 0 in C.

a = (int *) malloc(sizeof(int)*3) - 1

Is there any risk in this?

Scaling an 8-bit Greyscale RAW in C

Currently, I'm trying to scale a 320x200, 8-bit RAW image to whatever size the user specifies as their preferred resolution. If their resolution is 320x200, It simply uses fread to read the data directly to fill it in, otherwise it'll double all pixels horizontally, producing a 640x200 image. However, this isn't what I want to do, I want to scale exactly to the value of PIXX/PIXY, even if it isn't a multiple. How would I do this?

Here's the important part of the code:

FILE    *f;

int x,y;
int x1,y1;

int c;

char    *p;

f = dopen("art",name,"rb");
if (f == 0) GTFO("Unable to open title");

p = vpage;

if ((PIXX == 320) && (PIXY == 200))
{
    fread(vpage,320,200,f);
}
else
{
    for (y1 = 0; y1 < 200; y1++)
    {
        for (x1 = 0; x1 < 320; x1++)
        {
            c = getc(f);

            *p = c;
            *(p + 1) = c;
            p += 2;
        }
    }
}

fclose(f);

If a function or libary exists that can take the image produced by fread, and perform linear scaling, outputting back to 8-bit raw would be excellent. The image gets stored in vpage.

Reverse a C-style string

Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.) Nothing is printed out.Why?

`void ReverseString(char *p){
    int length = strlen(p);
    for (int i = 0, j = length; i < j; i++, j--){
        swap(p[i], p[j]);
    }

}


int main()
{
    char a[] = "12345";
    ReverseString(a);
    cout << a;
    system("pause");
    return 0;
}`

CSV file data in structure data for hashing with C

I need to read some data from a CSV file and create a data structure, so that I create a hashtable. I have tried a lot and lost a lot of hours but without a result. Please check my code and help me find where the mistake is ...

Here are the file data, output and code.

Thanks in advance!! (I wrote the code alone, with help from C programming language of Deitel and Deitel book.)

Code

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

struct clientData
{
   int acctNum; 

   char breaker[50]; 
   char datetime[60];
   double current;
 };

int main()
{ 
  FILE *cfPtr;

  struct clientData client = {0,"","",0.0 };
  if ( ( cfPtr = fopen("data1.csv","rb") ) == NULL)
  {
    printf("File could not be opened.\n");
  }   
  else
  {
    printf("%-6s%-16s%-11s%10s\n","Acct","Last Name","First Name","Balance");

    while ( !feof( cfPtr) )
    {
        fread( &client , sizeof ( struct clientData ), 1 , cfPtr );

        if ( client.acctNum !=0 )
        {
            printf ("%-6d%-16s%-11s%10.2f\n",
                    client.acctNum,client.breaker,client.datetime,client.current );
        }
    }
    fclose ( cfPtr );
  }
  return 0 ;
}

CSV Input file

acct,breaker,S_TimeStamp,MeasurementValue 1,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20158:30,37.6 2,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20159:00,34.2 3,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20159:30,37.2 4,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:00,40.6 5,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Current,1/12/201511:00,45.8

Output

Acct Last Name First Name Balance 1952670561,breaker,S_TimeStamp,MeasurementValue 1,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20158:30,37.6 2,EthiotideAtalantiMVBreak@talantiMVBreakerBB2Q2Current,1/12/20158:30,37.6 2,EthiotideAtalantiMVBreak@178724158464812467496986462827554460798109233540662154481413250685702096704425934569739618465990294960631478737616585889239313529311067888348744695823558167564353119398296863451093505908419875899425197001801728.00 11116509172Q2Current,1/12/20159:00,34.2 3,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/20159:30,37.2 4,EthiotideAtalantiMVBreakerBB2Q2C@VBreakerBB2Q2Current,1/12/20159:30,37.2 4,EthiotideAtalantiMVBreakerBB2Q2C@5155825882657381.00 1701999221nt,1/12/201510:00,40.6 5,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren@rBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren@62020397019943253271215041932658580009235443368333447944639125867547040589859590642175830919754237423637956114804980964218473105282339526865630710982971497957257635386734871861549462238776468516448931338295812955819267325952.00 79175179612/201511:00,45.8 40.6 5,EthiotideAtalantiMVBreakerBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren@rBB2Q2Current,1/12/201510:30,41.8 6,Eth1iotideAtalantiMVBreakerBB2Q2Curren@62020397019943253271215041932658580009235443368333447944639125867547040589859590642175830919754237423637956114804980964218473105282339526865630710982971497957257635386734871861549462238776468516448931338295812955819267325952.00

Opening file issue

I have a problem with my code and I hope you can help. I won't post all the code because it's a little long, but I will focus on the troublesome part. The program is about algebraic operation with arrays. The read_array2 reads the first nxn real numbers from a file and place them in a global array. The problem is that I always get the same message "I cannot open this file". I even added a printf() to test if the name is properly stored in fname and I found that it is. And yes, I have verified that the files I use exist and I type their names correctly. I don't know if it is important, but the files have 10000 real numbers separated by a single space. I know it is difficult to tell without all the code available, but do you see something out of place that could cause this issue?

int read_array2(double table[N_MAX][N_MAX], int n){
int i, j;
FILE *infile;
char fname[25];

printf("\nFile Name: ");
scanf("%s",&fname);

if ((infile = fopen(fname,"r")) == NULL){
    printf("\nI cannot open this file.\n");
    return 1;
}

for (i = 0; i < n; i++)
    for(j = 0; j < n; j++){
    fscanf(infile, "%lf ", &table[i][j]);
}

fclose(infile);

return 0;
}

Blocking sockets

I'm programing a small c linux local server. I've read a lot of documentation about threads, select function, nonblocking options, etc. But I can't find any documentation about how to deal with client-side failures.

More specifically, working with threads and blocking sockets (not the best idea, I know, but I'm just running some tests), what happens when the client connection goes too slow? or what happens when the client doesn't close the connection properly (or not closing it at all)? Will my socket remain blocked? or the thread will never finish?

How to deal with this situations?

undefined reference to conj, conjf, conjl

I cannot figure out how to fix this linking problem in GCC.
I am running CodeBlocks 13.12, under Windows 8, GCC+MingWG 4.8.1.
I have created a project having two files:

main.c

#include <complex.h>
int main(void)  
{  
    double complex (*FUNC)(double complex) = conj;   
    return 0;  
}  

test.c

#include <complex.h>  
double complex (*CEXP)(double complex) = cexp;  
double complex (*CONJ)(double complex) = conj;  

When the project is compiled in CodeBlocks (I use the compiler option -std=c11, only),
an error results, saying: "Undefined reference to conj".

I think this is extrange, since the function conj is defined in complex.h, as function cexp is, but the reference to cexp seems to work well.

On the other hand, the error is not triggered for the reference to conj in file main.c.
(SORRY: It seems that the error is triggered in main.c, also)

Is this a particular issue of GCC?
How I must configure CodeBlocks to fix this problem?
Thanks in advance.

More information. The compiler window shows these lines in CodeBlocks:

mingw32-gcc.exe -Wall -g -std=c11 -g -std=c11 -c C:\Users\Machine\Desktop\myapp\myapp.c -o obj\Debug\myapp.o
mingw32-gcc.exe -Wall -g -std=c11 -g -std=c11 -c C:\Users\Machine\Desktop\myapp\test.c -o obj\Debug\test.o
mingw32-g++.exe -o bin\Debug\sempha.exe obj\Debug\myapp.o obj\Debug\test.o
obj\Debug\myapp.o: In function main': C:/Users/Machine/Desktop/myapp/myapp.c:9: undefined reference toconj' obj\Debug\test.o:test.c:(.data+0x4): undefined reference to `conj' collect2.exe: error: ld returned 1 exit status

ALSO: I've tried to write the option -lm in several places on CodeBlocks without any success (for example, in Settings/Compiler/Other options, or Settings/Compiler/Linker, or Project/Build options..., etc.).

Access Violation error. AVL TREE during insertion. C

So I got an AVL tree online for a project. and I am trying to insert elements with a loop to see if it works. obviously its not working. am getting an access violation error.

here is the tree. the code is long. I know. but I can tell you that its in the insert function not the others

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

#define FALSE 0
#define TRUE 1




MY_TREE deldata(MY_TREE pRoot, int, int *);
MY_TREE delete_node(MY_TREE pRoot, MY_TREE hNode, int *);
Node_ptr balright(Node_ptr pRoot, int *);
Node_ptr balleft(Node_ptr pRoot, int *);
void display(MY_TREE pRoot);
void tree_destroy(MY_TREE pRoot);
Node_ptr  balleft(Node_ptr pRoot, int *h);
MY_TREE insert(MY_TREE hRoot, int data, int *h);
void init_tree_functions(Node_ptr pRoot);


struct node
{


    MY_TREE(*deldata)(MY_TREE pRoot, int, int *);
    void(*display)(MY_TREE pRoot);
    void(*tree_destroy)(MY_TREE pRoot);
    MY_TREE(*insert)(MY_TREE hRoot, int data, int *h);



    int data;
    int balfact;
    Node_ptr left;
    Node_ptr right;
};


void init_tree_functions(Node_ptr pRoot){

    pRoot->tree_destroy = tree_destroy;
    pRoot->deldata = deldata;
    pRoot->display = display;
    pRoot->insert = insert;


}


//MY_TREE my_tree_init_default(){
//
//  Node_ptr pRoot;
//
//  pRoot =(Node_ptr) malloc(sizeof(Node));
//  
//  if (pRoot == NULL){
//
//      printf("Bad stuff \n"); 
//
//      exit(1);
//  }
//
//  pRoot->left = NULL;
//  pRoot->right = NULL;
//  pRoot->data = NULL;
//  pRoot->balfact = 0;
//  init_tree_functions(pRoot);
//
//  
//
//  return (MY_TREE)pRoot;
//
//}

MY_TREE insert(MY_TREE hRoot, int data, int *h)
{
    Node_ptr  node1, node2;
    Node_ptr pRoot = (Node_ptr)hRoot;



    if (pRoot==NULL)
    {
        pRoot = (Node_ptr) malloc(sizeof(Node));



        pRoot->data = data;
        pRoot->left = NULL;
        pRoot->right = NULL;
        pRoot->balfact = 0;
        *h = TRUE;



        return ((MY_TREE)pRoot);
    }

    if (data < pRoot->data)
    {
        pRoot->left = insert((MY_TREE)pRoot->left, data, h);

        if (*h)
        {
            switch (pRoot->balfact)
            {
            case 1:
                node1 = pRoot->left;
                if (node1->balfact == 1)
                {

                    pRoot->left = node1->right;
                    node1->right = pRoot;
                    pRoot->balfact = 0;
                    pRoot = node1;
                }
                else
                {

                    node2 = node1->right;
                    node1->right = node2->left;

                    node2->left = node1;
                    pRoot->left = node2->right;
                    node2->right = pRoot;
                    if (node2->balfact == 1)
                        pRoot->balfact = -1;
                    else
                        pRoot->balfact = 0;
                    if (node2->balfact == -1)
                        node1->balfact = 1;
                    else
                        node1->balfact = 0;
                    pRoot = node2;
                }
                pRoot->balfact = 0;
                *h = FALSE;
                break;

            case 0:
                pRoot->balfact = 1;
                break;

            case -1:
                pRoot->balfact = 0;
                *h = FALSE;
            }
        }
    }

    if (data > pRoot->data)
    {
        pRoot->right = insert((MY_TREE)pRoot->right, data, h);

        if (*h)
        {
            switch (pRoot->balfact)
            {
            case 1:
                pRoot->balfact = 0;
                *h = FALSE;
                break;

            case 0:
                pRoot->balfact = -1;
                break;

            case -1:
                node1 = pRoot->right;
                if (node1->balfact == -1)
                {

                    pRoot->right = node1->left;
                    node1->left = pRoot;
                    pRoot->balfact = 0;
                    pRoot = node1;
                }
                else
                {

                    node2 = node1->left;
                    node1->left = node2->right;
                    node2->right = node1;

                    pRoot->right = node2->left;
                    node2->left = pRoot;

                    if (node2->balfact == -1)
                        pRoot->balfact = 1;
                    else
                        pRoot->balfact = 0;
                    if (node2->balfact == 1)
                        node1->balfact = -1;
                    else
                        node1->balfact = 0;
                    pRoot = node2;
                }
                pRoot->balfact = 0;
                *h = FALSE;
            }
        }
    }

    return ((MY_TREE)pRoot);
}


MY_TREE deldata(MY_TREE hRoot, int data, int *h)
{
    Node_ptr pRoot = (Node_ptr)hRoot;
    Node_ptr node;

    if (!pRoot)
    {

        return (pRoot);
    }
    else
    {
        if (data < pRoot->data)
        {
            pRoot->left = deldata((MY_TREE)pRoot->left, data, h);
            if (*h)
                pRoot = balright(pRoot, h);
        }
        else
        {
            if (data > pRoot->data)
            {
                pRoot->right = deldata((MY_TREE)pRoot->right, data, h);
                if (*h)
                    pRoot = balleft(pRoot, h);
            }
            else
            {
                node = pRoot;
                if (node->right == NULL)
                {
                    pRoot = node->left;
                    *h = TRUE;
                    free(node);
                }
                else
                {
                    if (node->left == NULL)
                    {
                        pRoot = node->right;
                        *h = TRUE;
                        free(node);
                    }
                    else
                    {
                        node->right = delete_node((MY_TREE)node->right, node, h);
                        if (*h)
                            pRoot = balleft(pRoot, h);
                    }
                }
            }
        }
    }
    return ((MY_TREE)pRoot);
}

MY_TREE  delete_node(MY_TREE hSucc, MY_TREE hNode, int *h)
{

    Node_ptr node = (Node_ptr)hNode;
    Node_ptr succ = (Node_ptr)hSucc;

    Node_ptr temp = succ;
    if (succ->left != NULL)
    {
        succ->left = delete_node((MY_TREE)succ->left, node, h);
        if (*h)
            succ = balright(succ, h);
    }
    else
    {
        temp = succ;
        node->data = succ->data;
        succ = succ->right;
        free(temp);
        *h = TRUE;
    }
    return ((MY_TREE)succ);
}


Node_ptr balright(Node_ptr pRoot , int *h)
{
    Node_ptr node1, node2;

    switch (pRoot->balfact)
    {
    case 1:
        pRoot->balfact = 0;
        break;

    case 0:
        pRoot->balfact = -1;
        *h = FALSE;
        break;

    case -1:
        node1 = pRoot->right;
        if (node1->balfact <= 0)
        {

            pRoot->right = node1->left;
            node1->left = pRoot;
            if (node1->balfact == 0)
            {
                pRoot->balfact = -1;
                node1->balfact = 1;
                *h = FALSE;
            }
            else
            {
                pRoot->balfact = node1->balfact = 0;
            }
            pRoot = node1;
        }
        else
        {

            node2 = node1->left;
            node1->left = node2->right;
            node2->right = node1;

            pRoot->right = node2->left;
            node2->left = pRoot;

            if (node2->balfact == -1)
                pRoot->balfact = 1;
            else
                pRoot->balfact = 0;
            if (node2->balfact == 1)
                node1->balfact = -1;
            else
                node1->balfact = 0;
            pRoot = node2;
            node2->balfact = 0;
        }
    }
    return (pRoot);
}


Node_ptr  balleft(Node_ptr pRoot, int *h)
{
    Node_ptr  node1, node2;

    switch (pRoot->balfact)
    {
    case -1:
        pRoot->balfact = 0;
        break;

    case 0:
        pRoot->balfact = 1;
        *h = FALSE;
        break;

    case 1:
        node1 = pRoot->left;
        if (node1->balfact >= 0)
        {

            pRoot->left = node1->right;
            node1->right = pRoot;
            if (node1->balfact == 0)
            {
                pRoot->balfact = 1;
                node1->balfact = -1;
                *h = FALSE;
            }
            else
            {
                pRoot->balfact = node1->balfact = 0;
            }
            pRoot = node1;
        }
        else
        {

            node2 = node1->right;
            node1->right = node2->left;
            node2->left = node1;

            pRoot->left = node2->right;
            node2->right = pRoot;

            if (node2->balfact == 1)
                pRoot->balfact = -1;
            else
                pRoot->balfact = 0;
            if (node2->balfact == -1)
                node1->balfact = 1;
            else
                node1->balfact = 0;
            pRoot = node2;
            node2->balfact = 0;
        }
    }
    return (pRoot);
}


void display(MY_TREE hRoot)
{

    Node_ptr pRoot = (Node_ptr)hRoot;
    if (pRoot != NULL)
    {
        display(pRoot->left);
        printf("%d\t", pRoot->data);
        display(pRoot->right);
    }
}


void tree_destroy(MY_TREE hRoot)
{
    Node_ptr pRoot = (Node_ptr)hRoot;
    if (pRoot != NULL)
    {
        tree_destroy(pRoot->left);
        tree_destroy(pRoot->right);
    }
    free(pRoot);
}

this is the loop I have.

MY_TREE pRoot=NULL;

//pRoot = my_tree_init_default();



for (i = 0;  i < 99; i++){
    number = i;
    pRoot=pRoot->insert(pRoot, number, pResult);
    printf("a");


}

its crashing before 1 element is added. however when I do the init function. 1 element is added before it crashes. I think it has to do with the function pointers.

How to add an int at the end of an uint8_t*?

I have a variable :

uint8_t* data

And I want to add a header to these data. Exactly two numbers. I want my data like these : data+my_int+my_second_int

Do you know how to do this please ?

Thanks ! :)

C Programming with NetBeans on Mac OSX

I am pretty new to programming and I am trying to learn C. I installed net beans 8.0.2 on a mac with OS 10.10.3. And I tried to run my first code:

/* HelloWorld.c */
    #include <stdio.h> 
    #include <stdlib.h>
    int main(void) {
    puts("Hello PROGC"); /* prints > Hello PROGC */ 
    return EXIT_SUCCESS;
    }

Now I am getting this Error Message:

"/Library/Developer/CommandLineTools/usr/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf
"/Library/Developer/CommandLineTools/usr/bin/make"  -f nbproject/Makefile-Debug.mk dist/Debug/GNU-MacOSX/cppapplication_1
mkdir -p build/Debug/GNU-MacOSX
rm -f "build/Debug/GNU-MacOSX/Hello World.o.d"
gcc    -c -g -MMD -MP -MF "build/Debug/GNU-MacOSX/Hello World.o.d" -o build/Debug/GNU-MacOSX/Hello\ World.o Hello\ World.c
mkdir -p dist/Debug/GNU-MacOSX
gcc     -o dist/Debug/GNU-MacOSX/cppapplication_1 build/Debug/GNU-MacOSX/Hello\ World.o build/Debug/GNU-MacOSX/main.o 
duplicate symbol _main in:
    build/Debug/GNU-MacOSX/Hello World.o
    build/Debug/GNU-MacOSX/main.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [dist/Debug/GNU-MacOSX/cppapplication_1] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 687ms)

Could you please let me know what I have to change? Many thanks in advance!

memccpy return lower memory address than the src starting address

I've got a school project where I have to recode the memccpy() function.

Here is my code:

void    *ft_memccpy(void *str_dest, const void *str_src, int c, size_t n)
{
    unsigned int    i;
    char            *dest;
    char            *src;
    char            *ptr;

    dest = (char *)str_dest;
    src = (char *)str_src;
    i = 0;
    ptr = 0;
    while (i < n && ptr == 0)
    {
        dest[i] = src[i];
        if (src[i] == ((char)c))
            ptr = dest + i + 1;
        i++;
    }
    return (ptr);
}

I use 2 programs to check if my code works properly and when I test my function in an unique program, it works.

void main(void)
{
    char    src[] = "Ceci est un test.";
    char    dest[200];
    void    *ptr, *ptr2;

    ptr = ft_memccpy(dest, src, 'i', 10);
    ptr2 = memccpy(dest, src, 'i', 10);
}

With the code above, the two function return the same exact address.

But with another test program the memccpy() function return an address lower than the first character of the src pointer.

For example:

  • Starting address of the src value: Ptr found: 0x7fff712edc40
  • Memccpy return pointer address: 0x712edc44
  • My memccpy function return pointer: 0x7fff712edc44

Here is the code that provides this behavior:

char    buf1[] = "Ceci est un test.";
char    buf2[200];
void    *p1, *p2;

p1 = memccpy(buf2, buf1, 'i', 10);
p2 = ft_memccpy(buf2, buf1, 'i', 10);

So I don't really understand because the two program have the same code, except that the second is much bigger.

Does somebody know what can cause this kind of behavior?

  • I tried to search on Google but the answer was not very helpful.
  • I read the man multiple times ^^' (not more helpful).
  • I read that memccpy have an undefined behavior when memory overlap, but they don't overlap.

Floating Point Exception C

I keep getting this error while testing the following function. It's supposed to normalize the values of an image that contains pixels of colors 0 to 255. I found the min and max, changed them to 0 and 255, then changed all inbetween values accordingly to accomodate the same previous ratio of difference:

    void normalize( uint8_t array[],
        unsigned int cols,
        unsigned int rows )
{
         uint8_t minValue = 255;
     uint8_t maxValue = 0; 

    for (int i = 0; i < cols*rows ; ++i)
    {
            if(array[i] < minValue) minValue = array[i];
    }



    for (int i = 0; i < cols*rows; ++i)
    {
     if(array[i] < maxValue) maxValue = array[i];
    }

        int difference1 = maxValue - minValue;

    uint8_t ratios[cols*rows];


    for (int i = 0; i < cols*rows ; ++i){
        ratios[i] = 0;
    }

    //find the ratios
    for (int i = 0; i < cols*rows ; ++i){
        ratios[i] = (array[i] / difference1) - 1;
    }

    for (int i = 0; i < cols*rows ; ++i){

        if(array[i] == minValue){
            array[i] = 0;
        }else if(array[i] == maxValue){
            array[i] = 255;
        }else{
            array[i] = round(ratios[i] * 255);
        }
    }

}

How to allocate memory for an array of pointers within a structure

I have these structures:

struct generic_attribute{
    int current_value;
    int previous_value;
};

union union_attribute{
    struct complex_attribute *complex;
    struct generic_attribute *generic;
};

struct tagged_attribute{
    enum{GENERIC_ATTRIBUTE, COMPLEX_ATTRIBUTE} code;
    union union_attribute *attribute;
};

I keep getting segmentation fault errors because I am not allocating memory properly when creating an object of type tagged_attribute.

struct tagged_attribute* construct_tagged_attribute(int num_args, int *args){
    struct tagged_attribute *ta_ptr;
    ta_ptr = malloc (sizeof(struct tagged_attribute));
    ta_ptr->code = GENERIC_ATTRIBUTE;
    //the problem is here:
    ta_ptr->attribute->generic = malloc (sizeof(struct generic_attribute));
    ta_ptr->attribute->generic = construct_generic_attribute(args[0]);
    return  ta_ptr;
}

Construct_generic_attribute returns a pointer to a generic_attribute object. I want ta_ptr->attribute->generic to contain a pointer to a generic_attribute object. This pointer to a generic_attribute object is output by the construct_generic_attribute function.

What would be the proper way to do this?

Convert cell id to longitude latitude

How to convert the location based coordinates in MCC(mobile country code), MNC(mobile network code), LAC(location area code) and CellID to GPS coordinates in longitudes and latitudes? Is there any algorithm/process for the conversion?

How to use Doxygen with Prolog

I was struggling trying to make doxygen work with prolog.

At first I was only trying to include an "external and unknown" file, but as doxygen users know, it won't print a thing if it can't find useful (documented) functions.

Searching stackoverflow for both tags gives no single answer, and so I decided to ask, even if I already solved the puzzle, so people will have a hit in case of search.

I will let this question here, as people can suggest simple workarounds, and we may learn a bit more about the subject, but I'll use it to register my own answer after some (hard) efforts. Thanks.


To explain where I did start:

My first (almost) successful approach worked fine in a program that used both C and PROLOG.

It almost worked because latter on I saw this approach would not work in a PROLOG only project.

Anyway, what I did was simply add this

INPUT = README.md groups.dox c-and-pl.c c-and-pl.pl
FILE_PATTERNS = *.pl
EXTENSION_MAPPING += pl=c
EXTRACT_ALL = YES
EXTRACT_STATIC = YES
SOURCE_BROWSER = YES

And PROLOG code would look like:

/**
 * @file cpl.pl
 * @ingroup GroupUnique
 * @brief CPL - C calls Prolog (Prolog module)
 * @cond SKIPPROLOG
 */

 /* brief explanation in a normal (non-doxygen) comment */
 clause(A) :- 
     rule(X),
     test(A, X).

 and(so, on).

 /** @endcond */

This would work because C would create the site anyway, and PROLOG page would be just a brief, no clauses, but a link to see the complete code, with normal comments explaining the clauses.

Why this doesn't work for a pure PROLOG project? And how to do that?

Convert this C-Code to Delphi-Code

I need to convert this C-Code to Delphi-Code and because my Delphi-Knowledge is not good enough I need your help!

My main problem is, that I don't know how to cast pointers / calculate with pointers in Delphi.

Of course i tried to convert it and for whoever is familiar with both languages should this be easy to do :)

Original code (C):

void* GetPayloadExportAddr( LPCWSTR lpPath, HMODULE hPayloadBase, LPCSTR lpFunctionName ) {
  // Load payload in our own virtual address space
  HMODULE hLoaded = LoadLibrary( lpPath );

  if( hLoaded == NULL ) {
    return NULL;
  } else {
    void* lpFunc   = GetProcAddress( hLoaded, lpFunctionName );
    DWORD dwOffset = (char*)lpFunc - (char*)hLoaded;

    FreeLibrary( hLoaded );
    return (DWORD)hPayloadBase + dwOffset;
  }
}

and

BOOL InitPayload( HANDLE hProcess, LPCWSTR lpPath, HMODULE hPayloadBase, HWND hwndDlg ) {
  void* lpInit = GetPayloadExportAddr( lpPath, hPayloadBase, "Init" );
  if( lpInit == NULL ) {
    return FALSE;
  } else {
    HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0,
        lpInit, hwndDlg, 0, NULL );

    if( hThread == NULL ) {
      return FALSE;
    } else {
      CloseHandle( hThread );
    }
  }

And the partally converted Delphicode:

function GetPayloadExportAddr( lpPath: LPCWSTR; hPayloadBase: HMODULE; lpFunctionName: LPCWSTR) : Pointer;
var
  hLoaded: HMODULE;
  lpFunc: pointer;
  dwOffset: DWORD;
begin
   hLoaded := LoadLibrary( lpPath );

  if( hLoaded = 0 ) then
  begin
    Result := 0;
  end
  else
  begin
    lpFunc   := GetProcAddress( hLoaded, lpFunctionName );
    dwOffset := DWORD(PCHAR(lpFunc) - PCHAR(hLoaded));

    FreeLibrary( hLoaded );
    Result := PDWORD(DWORD(hPayloadBase) + dwOffset);
  end;
end;

and

procedure CallStopHack( hProcess: THandle; lpPath: LPCWSTR; hPayloadBase: HMODULE);
var
  lpInit : Pointer;
  hThread: THandle;
  bla:Cardinal;
begin
  lpInit := GetPayloadExportAddr(lpPath, hPayloadBase, 'StopSpeedhack');
  if( lpInit = nil ) then
  begin
    Exit;
  end
  else
  begin
     hThread := CreateRemoteThread( hProcess, nil, 0,
        lpInit, 0, 0, bla);

    if( hThread = 0 ) then
    begin
      Exit;
    end
    else
    begin
      CloseHandle( hThread );
    end;
  end;
end;

I assume that I messed up with the PDWORD()-Cast etc. I'm sorry but I don't know how to cast it correctly.

Thanks in advance! Regards

Float value not being stored correctly

I'm writing a function that's suppose have the float "length" passed to it and then display a timer like output. The float "length" is meant to be in minutes.

When I run it, the output should be: 02:03:27:00. Instead it displays 02:03:26:100, while being technically correct it's A) Not how it should displayed and B) Shows that there's a bug somewhere that may cause undesired results in the future.

After going through it manually with a calculator and finding all the math to be sound. I then commented out the parts that formats the zeros to see if that was causing the bug and the problem was still there. I then went through putting printf's after every calculation and found that while "length" is set to 123.45 it's being stored as 123.449997?

I haven't a clue way it's doing this. And because I don't know way or how this is happening I can't write a reliable fix for it.

int main()
{

float length;
float working;
int hour;
int min;
int sec;
int centi_sec;
char hzero[2];
char mzero[2];
char szero[2];
char czero[2];

    length=123.45;
    working=floor(length);
    working=(length-working)*60;
    sec=floor(working);
    working-=floor(working);
    centi_sec=(working*100)+.5;
    working=floor(length);
    hour=floor((working/60));
    min=working-(hour*60);
    if(hour<10){
        hzero[0]='0';
        hzero[1]="";
    }
    else if(hour==0){
        hzero[0]='0';
        hzero[1]='0';
    }
    else{
        hzero[0]="";
        hzero[1]="";
    }
    if(min<10){
        mzero[0]='0';
        mzero[1]="";
    }
    else if(min==0){
        mzero[0]='0';
        mzero[1]='0';
    }
    else{
        mzero[0]="";
        mzero[1]="";
    }
    if(sec<10){
        szero[0]='0';
        szero[1]="";
    }
    else if(sec==0){
        szero[0]='0';
        szero[1]='0';
    }
    else{
        szero[0]="";
        szero[1]="";
    }
    if(centi_sec<10){
        czero[0]='0';
        czero[1]="";
    }
    else if(centi_sec==0){
        czero[0]='0';
        czero[1]='0';
    }
    else{
        czero[0]="";
        czero[1]="";
    }
    printf("%s%d:%s%d:%s%d:%s%d\n", hzero, hour, mzero, min, szero, sec, czero, centi_sec);
    system("pause");

}

I've also written a short program just to cheek that the problem wasn't being influence by something in the full program that I had missed and it's having the same issue.

    int main()
{
float length=123.45;
printf("%f\n", length);
system("pause");
}

P.S. When I was using printf to troubleshoot the problem, I discovered that the printf's were messing up the formatting of the zeros. Not too big of a issue since when I removed them the formatting went back to how it should be. Still it doesn't make any sense that printf's would be messing up the formatting. If anyone can provide an answer to this too, it would be appreciated.

Thanks in advance.

Static external linkage C In the output addresses of a comes different ..why?

#include <stdio.h>
main()
{
    static int a = 5;
    printf("%d \t",&a);
    {
        int a=6; 
        printf("%d\t",&a);
    }
    // In the output addresses of a comes different ..why?
}

In the output addresses of a comes different ..why?

When to cast size_t

I'm a little confused as how to use size_t when other data types like int, unsigned long int and unsigned long long int are present in a program. I try to illustrate my confusion minimally. Imagine a program where I use

void *calloc(size_t nmemb, size_t size)

to allocate an array (one- or multidimensional). Let the call to calloc() be dependent on nrow and sizeof(long int). sizeof(long int) is obviously fine because it returns size_t. But let nrow be such that it needs to have type unsigned long int. What do I do in such a case? Do I cast nrow in the call to calloc() from unsigned long int to size_t?

Another case would be

char *fgets(char *s, int size, FILE *stream)

fgets() expects type int as its second parameter. But what if I pass it an array, let's say save, as it's first parameter and use sizeof(save) to pass it the size of the array? Do I cast the call to sizeof() to int? That would be dangerous since int isn't guaranteed to hold all possible returns from sizeof().

What should I do in these two cases? Cast, or just ignore possible warnings from tools such as splint?

How to compare date in Windows with C

Here is example how I do that in Linux, but in Windows I don't have strptime function anyone can help me solve this problem?

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

time_t to_seconds(const char *date)
{
    struct tm storage = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    char     *p       = NULL;
    time_t    retval  = 0;

    p = (char *) strptime(date, "%d-%b-%Y", &storage);
    if (p == NULL)
    {
        retval = 0;
    }
    else
    {
        retval = mktime(&storage);
    }
    return retval;
}

int main(int argc, char** argv) 
{
    time_t d1 = to_seconds("16-Jun-2015");
    time_t d2 = to_seconds("13-Jun-2015");
    if(d1 > d2)
    {
        printf("date 1 > date 2");
    }
}

Output of the following code- macros in c

For the following code I am getting output as- Geeks.

#include <stdio.h>
#define ISEQUAL(X, Y) X == Y
int main()
{
    #if ISEQUAL(X, 0)
        printf("Geeks");
    #else
        printf("Quiz");
    #endif
    return 0;
}

Explain the reason for such output.

Fork example output

Can anyone explain why this piece of code prints n=3 and not n=4?

int main() {
    int n = 1;
    if (fork() == 0) {
        n = n + 1;
        exit(0);
    }
    n = n + 2;
    printf("%d: %d\n", getpid(), n);
    wait(0);
    return 0;
}

Using enum inside header in c

i'm having a little bit of trouble trying to use enum inside header in c. Here's how my code look like

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "listaEstatica.h"

int main(int argc, char** argv) {
    CACHORRO Tobias;
    strcpy(Tobias.nome, "Tobias");
    Tobias.registro = 123456789;
    Tobias.idade = 6;
    inserir(Tobias);

    exibirCachorro(cachorros[0]);

    return (EXIT_SUCCESS);
}

listaEstatica.c

#include "listaEstatica.h"

fim = 0;

enum Porte { Pequeno, Medio, Grande };
enum Estado { Machucado, Doente, DoencaInfeccosa};

int vazia() {
    if (fim == 0) {
        return 1;
    }
    return 0;
}

void inserir(CACHORRO cachorro) {
    if (fim == MAX) {
        printf("Não inseriu %s, lista cheia\n", cachorro.nome);
    } else {
        cachorros[fim] = cachorro;
        fim++;
        printf("Inserido %s OK\n", cachorro.nome);
    }
}

void exibirCachorro(CACHORRO cachorro) {
    printf("Nome: %s\n", cachorro.nome);
    printf("Registro: %i\n", cachorro.registro);
    printf("Idade: %i\n", cachorro.idade);
}

listaEstatica.h

typedef struct {
    char nome[30];
    int registro;
    int idade;
    enum Porte porte;
    enum Estado estado;
} CACHORRO;

int fim;
#define MAX 3
CACHORRO cachorros[MAX];

int vazia();

void inserir(CACHORRO cachorro);

void exibirCachorro(CACHORRO cachorro);

Trying to compile this game me the following error

 listaEstatica.h:5:16: error: field ‘porte’ has incomplete type
     enum Porte porte;
            ^
 listaEstatica.h:6:17: error: field ‘estado’ has incomplete type
     enum Estado estado;

Thanks in advance, any help is welcome

Arithmetic right-shift a size_t value

The size_t type is an unsigned type. As such, right-shifting a value of type size_t will shift logically. Given that the width of size_t is implementation dependent, is there any way to right-shift a size_t value arithmetically?

If my goal is to create a bitmask from a size_t value containing a 1 or a 0, is there another way to do it? For integers with known widths, the easiest way I know to make a bitmask is to left-shift the width of the integer - 1, then arithmetically right-shift all the way back.

This works on my 64-bit system:

const size_t width = (sizeof(size_t) << 3)) - 1;
size_t value = {boolean value};
value = ((int64_t) (value << width)) >> width;

But of course it's specific to my system and systems like it. What can I use instead?

Reading camera input from /dev/video0 in python or c

I want to read from the file /dev/video0 either through c or python,and store the incoming bytes in a different file. Here is my c code:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
    int fd,wfd;
    fd=open("/dev/video0",O_RDONLY);
    wfd=open("image",O_RDWR|O_CREAT|O_APPEND,S_IRWXU);
    if(fd==-1)
        perror("open");
    while(1)
    {
        char buffer[50];
        int rd;
        rd=read(fd,buffer,50);
        write(wfd,buffer,rd);
    }

    return 0;
}

When i run this code and after some time terminate the program nothing happens except a file name "image" is generated which is usual.

This is my python code:

    image=open("/dev/video0","rb")
    image.read()

and this is my error when my run this snippet:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] Invalid argument

I want to know how to do this using pure c or python code.Please no external library suggestions.

Keep functions private into a lib in C

I recently had to face a fairly complex issue regarding lib management, but I would be very surprised to be the first one.

Let's imagine you are creating a library (static or dynamic) called lib1 in C. Inside lib1 are a few functions that are exposed through an API, and a few other ones which remain private.

Ideally, the private functions would be static. Unfortunately, let's assume one of the source files, called extmod.c, come from another project, and it would be beneficial to keep it unmodified. Therefore, it becomes unpractical to static the functions it defines.

As a consequence, all the functions defined into extmod are present into lib1 ABI, but not the API, since the relevant *.h is not shipped. So no one notice.

Unfortunately, at later stage, someone wants to link both lib1 and another lib2 which also includes extmod. It results in a linking error, due to duplicate definitions.

In C++, the answer to this problem would be a simple namespace. In C, we are less lucky.

There are a few solutions to this problem, but I would like to probe if anyone believes to have found an efficient and non-invasive way. By "non-invasive", I mean a method which avoids if possible to modify extmod.c.

Among the possible workaround, there is the possibility to change all definitions from extmod.c using a different prefix, effectively emulating namespace. Or the possibility to put the content of extmod.c into extmod.h and static everything. Both method do extensively modify extmod though ...

Note that I've looked at this previous answer, but it doesn't address this specific concern.

Transform C++/C object symbols

objcopy --prefix-symbols allows me to prefix all symbols exported by an object file / static library.

Can I perform a more sophisticated transformation?

In particular, I would like to be able to add a C++ namespace to an object file / static library, i.e., demangle the symbols, prefix the result, and remangle it.

How to configure shared library search path after building GCC on my own?

I just built GCC 5.1 on Ubuntu 14.04, which has gcc 4.8 as default. When I try to build things with it, I find that ld will use the default libstdc++ instead of the newly build one. Here is the output:

drizzlex@dx ~/test
$ g++ hello.cpp 

drizzlex@dx ~/test
$ ldd a.out 
    linux-vdso.so.1 =>  (0x00007ffde0d25000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6     (0x00007fa181ad2000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fa1817cc000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fa1815b5000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fa1811f0000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fa181dfd000)

And if I use $ export LD_LIBRARY_PATH=/usr/local/lib64/, it will find the right one.

drizzlex@dx ~/test
$ ldd a.out 
    linux-vdso.so.1 =>  (0x00007fffeeaf5000)
    libstdc++.so.6 => /usr/local/lib64/libstdc++.so.6 (0x00007f4583d92000)
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f4583a67000)
    libgcc_s.so.1 => /usr/local/lib64/libgcc_s.so.1 (0x00007f4583850000)    
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f458348b000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f458410e000)

I would like to know what should I do to make it correct? Since I know set LD_LIBRARY_PATH is not the best choice.

Why doesn't my program stop when I press 0? C program

I made a simple program asking if you could enter a bar if you were of age. Then proceeded to ask how much you were willing to spend, and after asked how much would your first buy be. it proceeds to ask if you would like to buy more, however if I didn't want to buy more I could enter the value "0", but when I enter "0" it doesn't close the program.

The code is as follows:

#include <stdio.h>

int main() {
int age, legal = 18;
float money, buy;

    printf("At the bar the security must ID the customers that look underage, what is your age?: ");
    scanf("%d", &age);

        if(age < legal){
            printf("\nYou are not allowed!\n");
        }

        else if(age >= legal){
            printf("\nYou may enter, and buy whatever you wish!\n");

            printf("\nHow much money are you willing to spend tonight?: ");
            scanf("%f", &money);

            printf("\nWith the %.2f dollars you want to spend tonight what is the price of food or beverage you wish to buy first?: ", money);
            scanf("%f", &buy);

            money = money - buy;

            while(money > 0 || buy==0) {
                printf("\nYou now have %.2f dollars remaining, what else would you like to buy? (Press 0 to stop if you don't wish to buy any more!!): ", money);
                scanf("%f", &buy);
                money = money - buy;
            }
                if(money == 0){
                    printf("\nYou have spent all the money that you wished to spend at the bar, we hope you enjoyed your stay!!\n");
                }

                else if(money > 0){
                    printf("\nYou still have %.2f dollars left, We hope you enjoyed your stay at the bar!!\n");
                } 

        }       
}

Iterating through a string and separating input by spaces in C

I have a string such as "first second" and my desired result is for this output:

first 
second

But the output I am getting is:

first
first second

I know there is a problem either in my update statements or when I create a substring. If anybody could help me out that would be great. Here is my code down below:

int counter = 0; //counter used in loop
int index = test->current_index; //holds the current index of my string, it's initially 0
char *string = test->myString; //holds the whole string

char token_buffer = string[index];

   //before loop: index = 0, counter = 0

   while(test->current_index <= test->end_index) //test->end_index holds last index of string

    {
       while(token_buffer != ' ')
       {
         counter++;
         token_buffer = string[index + counter];

       }    

    char *output_token = malloc(counter+1);


   strncpy( output_token, string, counter );

  //printing token
  printf("%s \n", output_token);


 //update loop (possible problem area!)
  test->current_index += counter;
  index += counter;
  token_buffer+=string[counter];
  counter =0;
  }

return 0;
}

How to check where a function is referenced from

In a bare metal C/C++ project, I use gcc-arm-embedded (currently the most recent 4.9-2015-q2).

For some reasons, I have to avoid using some functions, like some of stdio et cetera (don't want to use retargeting or semihosting).

Further, I use FreeRtos with heap_4.c and had e.g. malloc() redirected directly to pvPortMalloc() like this:

void* malloc(size_t s) {
    return pvPortMalloc(s);
}

Therefore, I don't want to have any parts of the toolchain's heap management code within my binary.

Now, there are some situations, as were a developer of my team means to use e.g. printf() which indirectly references _malloc_r() (and some more) and it's actually quite hard to find out where it's referenced from and so where to fix.

(The use printf() is just an example here. In my project, I have custom implementation of printf() which prints directly to uart without using stdio. But there are other cases, e.g. type info demangeling, …)

Currently, I have the situation that my project (which consists of about 200 c and c++ source files) compiles well without referencing _malloc_r() in any way - as long as I build with gcc 4.8.

But when building with gcc 4.9, I see unwanted references to _malloc_r and some more.

Might there be command line tool to analyze my elf file for finding out where specific functions are referenced from?

Replacing multiple new lines in a file with just one

This function is supposed to search through a text file for the new line character. When it finds the newline character, it increments the newLine counter, and when there are more than 2 consecutive blank new lines, its suppose to squeeze all the blank lines into just one blank line.

In my code if there are 2 new lines it's suppose to get rid of them and squeeze them into one, for testing purposes I also have it printing "new line" when it reaches the newLine < 2 condition. Right now it prints new line for every new line, whether its blank or not, and its not getting rid of the extra new lines. What am I doing wrong?

EDIT: HERE IS MY FULL CODE http://ift.tt/1GSqY1v

So basically the program is suppose to concatenate two files together and than perform various operations on them, like what I'm trying to do which is get rid of multiple consecutive blank new lines. So in order to execute it in cygwin I do ./a -s file1 file2 Its suppose to concatenate file1 and file2 together into a file called contents.txt and than get rid of the consecutive new lines and display them on my cygwin terminal (stdout). (the -s calls the function to get rid of the consecutive lines). The third and fourth arguments passed in (file1 and file2) are the two files its suppose to concatenate together into one file called contents.txt The squeeze_lines function than reads the contents.txt file and is suppose to squeeze new lines. You can see below for an example for the contents I put in file1.txt. file2.txt just has a bunch of words followed by empty new lines.

int newLine = 1;
int c; 

if ((fileContents = fopen("fileContents.txt", "r")) == 0) 
{
    perror("fopen");
    return 1; 
}

while ((c = fgetc(fileContents)) != EOF)
{   
    if (c == '\n')
    {
        newLine++;
        if (newLine < 2) 
        {
            printf("new line");
            putchar(c); 
        }
    }
    else 
    {
        putchar(c); 
        newLine = 0;
    }
}

The file the program reads in a .txt file with these contents. Its suppose to read the file, get rid of the leading, and consecutive new lines, and output the new formatted contents to stdout on my cywgin terminal.

/* hello world program */


#include <stdio.h>

    tab
            2tabs

Imported skills beside matlab for developing engineering application [on hold]

Recently I graduated from college, math was my major. My first employment will be in some engineering company. I will support engineers to solve engineering Problems as well as developing a GUI for there application. Both will be done in matlab. Besides picking up some Matlab skills I also would like the refresh my programming skills before I start. In college I took a courses on C and Java. Now, my question is: What would be better so start with? In my opinion I should start with C because I think for developing engineering application object orientated Programming (=OOP) will most likely not occur. But I also read that one can do OOP stuff with matlab. Maybe It is import to know the basics there as well. What do you think would be better to start with?

Rotating array anti-clockwise, unexpected debug output in one step

I'm using the simplest approach to rotate array anti-clockwise i.e by storing elements from index=0 to index=number of rotating positions required, in a temporary array and finally inserting these elements int he end of another array. Here's the code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int *a, *temp, i, j=0, n,np,*b;
    printf("Enter no. of elements in arr:\n");
    scanf("%d",&n);
    a=(int*) malloc(n*sizeof(int));//Primary array
    b=(int*) malloc(n*sizeof(int));//Final array that would be printed in the end
    printf("Enter elements:\n");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter positions to be rotated anti-clockwise:\n");
    scanf("%d",&np);
    temp=(int*) malloc(np*sizeof(int));//storing elements left of index=0
    for(i=0;i<np;i++,j++)
    {
        //printf("hi\n");
        temp[j]=a[i];
        printf("temp[%d]=%d\n",j,temp[j]);
    }
    j=0;
    printf("After rotating:\n");
    for(i=n-1;i>=0;i--)
    {
        printf("i=%d ",i);
        b[i-np]=a[i];
        printf("b[%d]=%d\n",i-np,b[i]); /*Here is 1 unexpected thing happening, the program is not picking up correct value of array a at index i.*/
    }
    for(i=np-1;i<n;i++,j++)
        b[i]=temp[j];//storing temp elements in final array

    printf("Finally matrix is\n");

    for(i=0;i<n;i++)
        printf("%d\n",b[i]);

    getch();
    return 0;
}

locking inside system calls using kernel modules

I have replaced the sys_open system call in the system call table to implement a tallying system. What lock must I use? The spin_lock_irqsave() function freezes the system. I am using an Intel Core i3-4330 on Linux 3.16.0-4-686-pae.

Partial but revelant code:

static DEFINE_SPINLOCK(spin);
static int tally = 0;

static asmlinkage long my_sys_open(const char __user *filename, int flags, int mode)
{
    unsigned long fl;
    spin_lock_irqsave(&spin, fl); // system freeze

    tally++;

    spin_unlock_irqrestore(&spin, fl);

    printk("sys_open used %i times\n", tally);

    return old_sys_open(filename, flags, mode);
}

samedi 9 mai 2015

regex - camel case that doesnt contain consecutive uppercase letters

Consider the following description of identifiers: "Identifiers are alphanumeric, but must start with a lowercase letter and may not contain consecutive uppercase letters." Write a DFA that accepts these identifiers.

this is my regex that i will use to translate to the DFA but i dont think its correct

[a-z].( ([a-z0-9] | [a-z0-9][A-Z])* | ([a-z0-9] | [A-Z][a-z0-9])* )

Social security Regular Expression validator in asp.net

i want to use regular expression to validate SSN with dashes. This is the format i would like to see: 000-00-0000. This expression does not work for me for some reason.

  <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="^(\\d{3}-\\d{2}-\\d{4}|\\d{9})$" ControlToValidate="txtSSN" ForeColor="Red" />

How to properly use Pattern in Java with a String of numbers

I'm trying to use Pattern in Java and I'm having a problem.

I want to find from a String[] that contains numbers (that I retrieved from a file) if they match another string of numbers (also from a file).

E.g. I have the number 1 and I want to search in a String like this: 5 10 1 8 6 3 -1 10 8 10 10 4 10 -1 10 10 10 10 9 10 -1 10 10 10 10 10 10 -1 10 10 10 10 10 10 -1 -2.

Obviously the -1 and 10 are not what I'm locking for. Is there a way to solve this?

I can't use use Pattern.compile() with an integer.

Regular expression to split by forward slash

I have a parse tree which includes some information. To extract the information that I need, I am using a code which splits the string based on forward slash (/), but that is not a perfect code. I explain more details here:

I had used this code in another project earlier and that worked perfectly. But now the parse trees of my new dataset are more complicated and the code makes wrong decisions sometimes.

The parse tree is something like this:

(TOP~did~1~1 (S~did~2~2 (NPB~I~1~1 I/PRP ) (VP~did~3~1 did/VBD not/RB (VP~read~2~1 read/VB (NPB~article~2~2 the/DT article/NN ./PUNC. ) ) ) ) ) 

As you see, the leaves of the tree are the words right before the forward slashes. To get these words, I have used this code before:

parse_tree.split("/");

But now, in my new data, I see instances like these:

1) (TOP Source/NN http://ift.tt/1cuAduD ./. )

where there are multiple slashes due to website addresses (In this case, only the last slash is the separator of the word).

2) (NPB~sister~2~2 Your/PRP$ sister/NN //PUNC: )

Where the slash is a word itself.

Could you please help me to replace my current simple regular expression with an expression which can manage these cases?

To summarize what I need, I would say that I need a regular expression which can split based on forward slash, but it must be able to manage two exceptions: 1) if there is a website address, it must split based on the last slash. 2) If there are two consecutive slashes, it must split based on the second split (and the first slash must NOT be considered as a separator, it is a WORD).

Javascript strip Latex form of English letter variants

How can I replace Latex characters using {\'<1 alpha>} pattern with corresponding English letter?

For example

L{\'o}pez

Should change to

Lopez

It should not affect any other character out of {\'<1 alpha>} pattern. It should be greedy as well since there might be several characters required to be pruned.

Transform characters; like A to B, B to C,

I want to have a short and easy way to replace the character A to B, B to C, Z to A,... in PHP.

I already have tried this:

$pwd = "Abc";
for($char = ord('A'); $char <= ord('Z'); $char++) {
  $newc = $char+1;
  if($newc > 90)
    $newc = 65;
  $pwd = str_replace(chr($char), chr($newc), $pwd);
  $pwd = str_replace(chr($char+32), chr($newc+32), $pwd);
}
echo $pwd;

But when I use it I only get "Aaa"... :(

I can't find anything on the internet. Could you maybe help me?

Thanks in advance, Luuc

regular expression: may or may not contain a string

I want to match a floating number that might be in the form of 0.1234567 or 1.23e-5 Here is my python code:

import re
def main():
    m2 = re.findall(r'\d{1,4}:[-+]?\d+\.\d+(e-\d+)?', '1:0.00003 3:0.123456 8:-0.12345')
    for svs_elem in m2:
         print svs_elem

main()

It prints blank... Based on my test, the problem was in (e-\d+)? part. Thank you!

How to do URL matching regex for routing framework?

I already have a routing method that matches this pattern:

/hello/:name

that set name to be a dynamic path, I want to know how to make it:

/hello/{name}    

with the same regex. How to add optional trailing slash to it, like this?

/hello/:name(/)

or

/hello/{name}(/)

This is the regex I use for /hello/:name

@^/hello/([a-zA-Z0-9\-\_]+)$@D

The regex is auto generated from PHP class

private function getRegex($pattern){
        $patternAsRegex = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($pattern)) . "$@D";
        return $patternAsRegex;
    }

If the route is /hello/:name(/) I want it to make the match with optional thing else continue normal

Lua: String.match/string.gsub - Casing for true/false

I've been trying to figure this out for a while, but I fear I'm not seeing the entire solution quickly, and now I'm needing a fresh set of eyes to accomplish what I need.

I have a very particular script for the MUD I play to help me differentiate between MOBs and players when in a room. The script itself works, but now I want to add a new element that will check if my group mates are in the same room. This is what I have so far:

function strends(s)
  if s:match("%u%w+ is here%.") or s:match("%u%w+ is fighting .-%.") or s:match("%u%w+ is sleeping here%.") then
    return true
  else
    return false
  end
end

That's working great - it checks if an upper case name is in the room and returns information as requested.

I have a table of my group mates, though I may find it easier to do it as a string and do string.find. The problem I'm running into is casing it for each of the scenarios:

  1. Return true if there are players outside my group in the room.
  2. Return false if it's only players outside my group.
  3. Return false if there is no one in the room aside from myself.

In scenario one, it MUST return true, even if there are people in my group as well as people outside my group. But my Lua knowledge isn't expansive enough that I can work out the problem. The reason for the non-beginning string.matches is because it's possible for the particular line to have xx amount of characters before it. How should I approach this, or what should I be doing in order to accomplish my goal?

join rows in CSV with different sized sections python

I have a csv file structered like this:

|     publish_date     |sentence_number|character_count|    sentence       |
----------------------------------------------------------------------------
|          1           |               |               |                   |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |      -1       |       0       | Sentence 1 here.  |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |       0       |      14       | Sentence 2 here.  |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |       1       |      28       | "Sentence 3 here. |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |       2       |      42       | Sentence 4 here." |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |       3       |      56       | Sentence 5 here.  |
----------------------------------------------------------------------------
|         end          |               |               |                   |
----------------------------------------------------------------------------
|          2           |               |               |                   |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |      -1       |       0       | Sentence 1 here.  |
----------------------------------------------------------------------------
| 02/01/2012  00:12:00 |       0       |      14       | Sentence 2 here.  |
----------------------------------------------------------------------------
|         end          |               |               |                   |
----------------------------------------------------------------------------
|         end          |               |               |                   |
----------------------------------------------------------------------------

What I'd like to do is combine each block of sentences into paragraphs to output individual paragraphs:

["Sentence 1 here.", "Sentence 2 here.", ""Sentence 3 here.", "Sentence 4 here."", "Sentence 5 here."]

Some sentences are quotes which continue into a new sentence, whilst others are entirely embedded within a sentence.

So far I've got this:

def read_file():

    file = open('test.csv', "rU")
    reader = csv.reader(file)
    included_cols = [3]

    for row in reader:
        content = list(row[i] for i in included_cols)

        print content    
    return content

read_file()

But this just outputs a list of sentences like so:

['Sentence 1 here.']
['Sentence 2 here.']

Any suggestions appreciated.

Why is this python regular expression matching only one character not the whole words?

I am trying to extract the title of this text, which is all in uppercase. I want to avoid a long dashed sequence and some acronyms like NOM-059-SEMARNAT 2010, of which may be some other ones to exclude. So I did a regex in python for a findall (with library re under python 2.'7.7, in spyder, windows8.1):

(?!(?:[- ]{2,}|NOM\-059\-SEMARNAT))([A-Z0-9ÁÉÍÓÚÑ:;¿\?\(\)\-\+\. ,]{10,})

A sample of the summaries document with this pattern I am scanning is this:

--------------------------------------------- Congreso Mexicano
RELACIÓN ENTRE EL TAMAÑO DEL FOROFITO Y LA RIQUEZA DE EPÍFITAS EN LOS PANTANOS DE CENTLA, TABASCO Dwers Aasrd Jxcxéas Lóasd1*, Rasdé de Jawdúz Rasdw Vasde1 Instituto de Ciencias Biologicas, Universidad de Ciencias y Artes de Chiapas awdsd.w@hlksajk.com Las plantas epífitas son poco comunes en manglares, no epífitas y las características de los forofitos de Rhizophora mangle, especie amenazada de acuerdo a la NOM-059-SEMARNAT 2010; en áreas conservadas de la reserva Pantanos de Centla, al noroeste de Tabasco. Se evaluó la relación entre La riqueza de epífitas estuvo significativamente relacionada con la cobertura de raíz y DAP de los forofitos. Las zonas I y III de los forofitos fueron las más similares y compartieron 47% del total de las especies. La zona I, que son las Palabras clave: Epífitas vasculares, distribución vertical, composición, Rhizophora mangle, raíces aéreas. ID: 96 lunes, 20 de abril de 2015, 3:30:00 PM, Sala: 8 Eje temático: Ecología de Comunidades


re.sub() negative look behind + negative look ahead

Remove every occurence of ' from a string except when it is found before an 's or after an s'. with the exception being if it encapsulated the whole word it should be removed.

Example:

Andrea's -Stays as is
Kids' - stays as is
'Kids' --> Kids
Ki'd's' --> Kids

WHat I came up with so far :

\'(?!s ) 

this matches the first example and ignores it.

here is it working

I have a problem with the rest

How to grep a unknown distance line above a pattern

Sorry to edit the question again. I found that I didn't ask my question clearly before.
I asked a question yesterday but I found another problem today /.\
Here is my file:

Time 00:00:01
kkk
lll
ccc
aaa: 88
...
Time 00:00:03
jjj
kkk
lll
ccc
aaa: 89
ooo
bbb
aaa
kkk
lll
ccc
aaa: 90
...
Time 00:00:04
kkk
lll
...

Here is the output I want:

Time 00:00:01
kkk
lll
ccc
aaa: 88
Time 00:00:03
kkk
lll
ccc
aaa: 89
Time 00:00:03
kkk
lll
ccc
aaa: 90

Last time I was looking for one line and the other line above it. This time I am looking for a pattern with multiple lines:

kkk
lll
ccc
aaa: /any thing here/

and a line

Time /any thing here/

From the question I asked yesterday, I tried

awk '/Time/{a=$0}/kkk\nlll\nccc\naaa/{print a"\n"$0}' file

and

perl -ane '$t=$_ if /Time/; print $t,$_ if /kkk\nlll\nccc\naaa/' test2

and

pcregrep.exe -M 'kkk.*(\n|.)lll.*(\n|.)ccc.*(\n|.)*aaa' test2

from this but they are not working or the output is not what I want.

I found a thread like this which is talking about state machine but it is complex since I have several lines to match.

Any suggestion that can solve this problem easily?

Regular expression to extract word

given a String like this: "today is a nice day".

Is it possible to extract only the words "day" from this String?

Using [^day] works letter-wise, hence not what I want.

How to str_replace Google News RSS for Facebook Share?

Hi I'm using simpleXML to display a news.google.com feed.

The displayed entries link to the original article in this way:

http://ift.tt/1dTSQsr

I need the entries to link to this instead: http://ift.tt/1KujlPl

The reason is that Facebook Sharer cannot interpret the following link:

http://ift.tt/1dTSQst

Facebook Sharer needs it to look like this:

http://ift.tt/1dTSQsv

Is there a way that I can use regex (str_replace or preg_match) to remove the Google redirect URL so that social sharing sites can recognize the link?

The Google redirect URL is dynamic and so it will be slightly different each time and so I will need something that can replace each variant.

My working, functional code:

    $feed = file_get_contents("http://ift.tt/1dTSQIN");
$xml = new SimpleXmlElement($feed);
foreach ($xml->channel->item as $entry){
  $date = $entry->pubDate; 
  $date = strftime("%m/%d/%y %I:%M:%S%P", strtotime($date));
  $desc = $entry->description;
  $desc = str_replace("and more&nbsp;&raquo;", "","$desc");
  $desc = str_replace("font-size:85%", "font-size:100%","$desc");
  ?>
  <div class="item"></div>
  <?php echo $desc; ?>
  <div class="date">
  <?php echo $date; ?></div>
  <?php } ?>
 $desc = $entry->description;
 $date = $entry->pubDate; 
 $date = strftime("%A, %m/%d/%Y, %H:%M:%S", strtotime($date));
 $desc = str_replace("and more »","x","and more »");
  echo $date; 
  echo $desc;
  }

I'm using $desc to display the link instead of $link, but URL to the article with the Google redirectURL is still in $link if you would like to str_replace or preg_match $link instead of $desc

Link to working Google News feed below: http://ift.tt/1dTSQIN

If you know how to fix this you're a hero. Thank you Overflowers