mardi 4 août 2015

need help for improving my snake game in C

Its not a programming help

There is a gap coming in the snake body while moving top and bottom , I tried my part and found that its due to console fixed character width in Microsoft OS . can we overcome this in any way ... Please don't say "go for GUI".

Here's the video link



via Chebli Mohamed

Threads creation in C

void print_hello_world() {
    pid_t pid = getpid();
    printf("Hello world %d\n", pid);
    pthread_exit(0);
}

void main() {
    pthread_t thread;
    pthread_create(&thread, NULL, (void *) &print_hello_world, NULL);
    print_hello_world();
}

I really couldn't understand what is the need of (void *) in pthread_create. And do we need "&print_hello_world" in the same or could drop "&" as I have read somewhere that while passing function pointers we don't need to place "&" before the function name.



via Chebli Mohamed

How to convert c program to fully portable for ios

I wrote a simple c program for connect to ldap server using opelLdap c library. now I want to run that c program on ios device. but when I move that c program to xcode project it says ldap.h is missing. ldap.h file is saved in standard include file location so it include this way #include <ldap.h> but I move this file to my xcode project and include it this way #include "ldap.h" it generate so many error because this ldap.h header file contain lot of other standard header files and they have their own dependencies and so on. they all are include this way #include <header.h> it is not possible to convert all the <> to " " one by one. is there any way to to this thing. actually I need to move my code with it's all dependencies I am new to both of this c and xcode(swift/objective-c)



via Chebli Mohamed

Xlib difference between _NET_ACTIVE_WINDOW and XGetInputFocus

What's the difference between _NET_ACTIVE_WINDOW and XGetInputFocus() ? Do they always point to the same window? When use one over the other?

Thanks.



via Chebli Mohamed

C Programming - fprintf and printf in while cicle doesn't work

I'm getting a strange problem with a while cicle inside of a function.

I have to look for the extreme vertices of a .ply model. All the data is stored in a linked list. When I'm done creating the list, I call the findExtremeVertex function, that modifies 6 global variables (leftVertex, rightVertex, downwardVertex, upwardVertex, backVertex and frontVertex).

To see if the values are right (the models I use are a bit too big to control every single line to find the maximum of every vertex) I decided to print every change in the max-min values but, when I try to print them in a file, the file is empty. Why is that? Also, when I saw that the file was empty, I tried to print something directly in the console but that didn't work either.

Here's the code of the funcion:

void findExtremeVertex(Vertex *vertex){
    FILE *modelInfoFile;
    int i = 0;

    ///Giving data to direction-vertices pointers
    leftVertex = malloc(sizeof(Vertex));
    rightVertex = malloc(sizeof(Vertex));
    upwardVertex = malloc(sizeof(Vertex));
    downwardVertex = malloc(sizeof(Vertex));
    frontVertex = malloc(sizeof(Vertex));
    backVertex = malloc(sizeof(Vertex));

    ///Giving the direction-vertices the values of the parameter
    leftVertex = vertex;
    rightVertex = vertex;
    upwardVertex = vertex;
    downwardVertex = vertex;
    frontVertex = vertex;
    backVertex = vertex;

    ///Opening file
    modelInfoFile = fopen(us2, "w");
    if(modelInfoFile == NULL){
        printf("Error in file opening. Exiting.");
        exit(EXIT_FAILURE);
    }

    ///Scrolling the list
    while(vertex->prev != NULL){
        vertex = vertex->prev;

        ///If the given element of the list is more to the right than the global variable,
        ///I assign the values of the element to the global variable
        if(vertex->vertexCoordinates.x > rightVertex->vertexCoordinates.x){
            rightVertex = vertex;
        }

        /**
            I'm omitting the other if constructs because are basically
            the same, but the syntax is correct
        **/

        ///Printing in file the cycle information
        fprintf(modelInfoFile, "********** CYCLE %d **********\n\n", i);
        fprintf(modelInfoFile, "Vertex sx\n");
        fprintf(modelInfoFile, "%1.4f %1.4f %1.4f %1.4f %1.4f %1.4f\n\n", leftVertex->vertexCoordinates.x,
                                                                      leftVertex->vertexCoordinates.y,
                                                                      leftVertex->vertexCoordinates.z,
                                                                      leftVertex->vertexNormals.x,
                                                                      leftVertex->vertexNormals.y,
                                                                      leftVertex->vertexNormals.z);

        /**
            Again, I'm omitting some repetitions but the syntax is correct
        **/
        }
    }

I call this function in another function, but there's no segmentation fault signal, the compiler doesn't tell me anything, the program doesn't crash. I have no clue of the error, except from the fact that the file where I print the infos about the cycles is empty. What am I doing wrong?



via Chebli Mohamed

I'm copying printf code from word, but the quotation marks don't work

So I'm currently doing a reasonably big program, and I need to add in some images. I decided to do this by way of ascii art, so I converted my image, stuck it in word, and using aragrah points and find and replace I stuck 'printf("' at the start of each line, and '\n)"' at the end.

The problem I'm facing is that the " don't work, and considering I've got literally thousands to do before my program has the amount of art it needs, I could really use some help on how to fix them without manually changing them.



via Chebli Mohamed

Tiny Linked List error in C

I have this four files,

tinyll.c tinyll.h in /home/user/lib

test.c tinyll.h in /home/user/code

and compile with this instructions for create a static library libtinyll.a and use it.

; in lib
$ gcc -c tinyll.c
$ ar -cvq libtinyll.a *.o

; in code
$ gcc -o test test.c ../lib/libtinyll.a

Until here all is ok. But I don't know why I obtain segmentation fault because the lines from [CODE ERROR] but showElements work. The target is not pass code from test.c to tinyll.c for treat the tiny list linked. How fix that?

/////////////////////////////////// test.c

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

#include "tinyll.h"

int main(int argc, char *argv[])
{    
    progname = argv[0];

    char *file = "fwords";
    int n;
    PTLL lsone = NULL;
    n = loadfileinTLL(file,&lsone);

    // work. good. 
    showElements(lsone);

    // [CODE ERROR]
    // Why here dont work?
    // segmentation fault, load the first word
    // but in the second crash.
    while (lsone != NULL) {
        printf("%s",lsone->word);
        lsone = lsone->next;
    }    
    return 0;
}

/////////////////////////////////// tinyll.c

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

#include "tinyll.h"

void addElement(PPTLL lst, char data[])
{
    PTLL elemt;
    elemt = (PTLL) malloc(sizeof(TLL));

    if (elemt == NULL) {
        fprintf(stderr, "%s: insufficient memory.\n", progname);
        exit(1);    
    }

    if (*lst == NULL)
    {
        strncpy(elemt->word, data, 45);
        elemt->next = NULL;
        *lst = elemt;
    }
    else {
        // add in front of list
        strncpy(elemt->word, data, 45);
        elemt->next = *lst;
        *lst = elemt;
    }
}

void showElements(PTLL lst)
{
    while (lst != NULL) {
        printf("%s\n",lst->word);
        lst = lst->next;
    }
}

int loadfileinTLL(char *filepath, PPTLL plst) 
{
    FILE *f;
    if ((f = fopen(filepath, "r")) == NULL) {
        fprintf(stderr, "%s: error to load file %s.\n", progname, filepath);
        exit(1);
    }

    char buf[45]; int n=0;
    while (fgets(buf,sizeof(buf),f) != NULL) {
        char *nl;
        if ((nl = strchr(buf,'\n')) != NULL) {
            *nl = '\0';
        }
        addElement(plst,buf);
        n++;
    }

    fclose(f);

    return n;
}

//////////////////////////////////// tinyll.h

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

#ifndef _TINYLL_
#define _TINYLL_

struct list {
    char word[45];
    struct list *next;
};

// Tiny Linked List
typedef struct list TLL;
typedef struct list *PTLL;
typedef struct list **PPTLL;
char *progname;

#endif



via Chebli Mohamed

Choose a C binary according to the enviroment

I have compiled my code with specific flags (-Os, -O2, -march=native and their combinations) in order to produce a faster execution time.

But my problem is that I don't run always in the same machine (because in my lab there are several different machines). Sometimes I run within a MacOS, or within a Linux (in both cases with different OS versions).

I wonder if there is a way to determine which binary will be run depending on the environment where the binary will run (I mean cache size, cpu cores, and other properties about the specific machine)?. In other words, how to choose (when the program loads) the faster binary (previously compiled with different target binary sizes and instruction-set extensions) according to the specific machine used?

Thanks in advance.



via Chebli Mohamed

sscanf hex ints into array of ints vs. unsigned chars

I am converting a string representation of a mac address into an array of UINT8s defined as unsigned char. I am curious why sscanf() will read all 0s when I read into an array of UINT8s and actual values when I read into an array of regular 32 bit ints. Its almost like it's chopping off the 8 bits of the wrong end of the int.

char strMAC = "11:22:33:AA:BB:CC";

typedef unsigned char UINT8;
UINT8 uMAC[6];

int iMAC[6];

sscanf( (const char*) strMac, 
        "%x:%x:%x:%x:%x:%x", 
        &uMAC[0], &uMAC[1], &uMAC[2], &uMAC[3], &uMAC[4], &uMAC[5] );
printf( "%x:%x:%x:%x:%x:%x", 
        uMAC[0], uMAC[1], uMAC[2], uMAC[3], uMAC[4], uMAC[5] );
// output: 0:0:0:0:0:0

sscanf( (const char*) strMac, 
        "%x:%x:%x:%x:%x:%x", 
        &iMAC[0], &iMAC[1], &iMAC[2], &iMAC[3], &iMAC[4], &iMAC[5] );
printf( "%x:%x:%x:%x:%x:%x", 
        iMAC[0], iMAC[1], iMAC[2], iMAC[3], iMAC[4], iMAC[5] );
// output: 11:22:33:AA:BB:CC



via Chebli Mohamed

Want to grab text from anywhere on my phone screen

I want to code this in java for Android use. The desired outcome is that I could grab a text from my phone screen from anywhere in any other app that displays text on the phone screen. How would I go about coding this app?



via Chebli Mohamed

Plot lat and lon from C code

I'm wondering, is there any way to plot map coordinates directly from C code? I'm getting a lat and lon from a TCP Stream I dissect using Wireshark and I want to create a dynamic map representation of the various points. Is there any API or system I can use to display these coordinates?

One situation I have is that the system has to run on a offline PC, so I would need to cache de various map data.

Is there any possible way of implementing this?

Thank you.



via Chebli Mohamed

What alterations must I do to this code.. I am receiving a Wrong answer message

All submissions for this problem are available.

Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction. Input

Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw. Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance. Output

Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.

  • Example - Successful Transaction

Input: 30 120.00

Output: 89.50

  • Example - Incorrect Withdrawal Amount (not multiple of 5)

Input: 42 120.00

Output: 120.00

  • Example - Insufficient Funds

Input: 300 120.00

Output: 120.00

**

  • In reference to the above problem... I am receiving a wrong output message on submission! Can somebody help me out? I believe i have covered all cases! But guys, do take a look

**

#include<stdio.h>
#define bank_charge 0.5
int main()
{
    float X, Y,new_balance;
    X=0, Y = 0;

    printf("With amt and balance ");
    scanf("%f%f", &X, &Y);
    if (X > 0 && X <= 2000 && Y >= 0 && Y <= 2000)
    {
        if (X > Y || ((Y-0.5-X)<0))
        {   printf("Insufficient Funds\n");
            printf("%0.2f", Y);
            return 0;

        }
        if ((int)X % 5 == 0)
        {
            new_balance = (Y - X) - bank_charge;
            printf("%0.2f", new_balance);
            return 0;

        }
        printf("%0.2f", Y);
            }
    return 0;
}



via Chebli Mohamed

how to delete an if statement without any code

I've constructed a Heap by using this code. However, there is one if statement without any codes so I'm trying to avoid using the if statement by giving it to the while statement.

Since the while statement is the opposite with the if. For instance, if(i==1) TRUE while(i!=1) TRUE

I've made the if statement opposite

if((*h).data[temp]<(*h).data[temp*2]&&(*h).data[temp]<(*h).data[temp*2+1])

while((*h).data[temp]>(*h).data[temp*2]&&(*h).data[temp]>(*h).data[temp*2+1])

and the result becomes different.

Here is my real source

int pop(heap* h)
{
int temp=1;
int min=(*h).data[1];
(*h).index--;
//head에 있는 것을 index의 것과 교환
(*h).data[1]=(*h).data[(*h).index];
(*h).data[(*h).index]=NULL;

//root가 가장 작은 경우
while(temp<(*h).capacity)
{
    if((*h).data[temp*2]!=NULL&&(*h).data[temp*2+1]!=NULL)
    {
        if((*h).data[temp]<(*h).data[temp*2]&&(*h).data[temp]<(*h).data[temp*2+1])
        {
        }
        else if((*h).data[temp*2]<(*h).data[temp*2+1])
        {
            //작은 것을 root와 교환
            (*h).data[temp*2]^=(*h).data[temp];
            (*h).data[temp]^=(*h).data[temp*2];
            (*h).data[temp*2]^=(*h).data[temp];
        }
        else if((*h).data[temp*2]>(*h).data[temp*2+1])
        {
            //작을 것을 root와 교환
            (*h).data[temp*2+1]^=(*h).data[temp];
            (*h).data[temp]^=(*h).data[temp*2+1];
            (*h).data[temp*2+1]^=(*h).data[temp];
        }
    }
    else if((*h).data[temp*2]!=NULL)
    {
        if((*h).data[temp*2]<(*h).data[temp])
        {
            (*h).data[temp*2]^=(*h).data[temp];
            (*h).data[temp]^=(*h).data[temp*2];
            (*h).data[temp*2]^=(*h).data[temp];
        }
    }
    temp*=2;
}

return min;

}



via Chebli Mohamed

Output of ++*p++

Can anyone explain me the output.

#include<stdio.h>
int main() {
    int a[]={10,20,30};
    int *p=a;
    ++*p++;
    printf("%d  %d  %d  %d",*p,a[0],a[1],a[2]);
}

output is 20 11 20 30

Postfix incrementation has a higher precedence, so value of second index should have been incremented. Why is the value of first index incremented?



via Chebli Mohamed

How to reduce a random hash to a boolean value

In c or a c-like language assuming I have a random_hash what is the cheapest way to reduce it to a boolean value i.e. 0 or 1?

An example random_hash to normalise answers: 0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa

Restrictions: no method/stdlib calls.

Why c-like, I'm actually trying to do it in a language called Solidity, which is modeled after c/javascript, which has a very limited runtime/stdlib.



via Chebli Mohamed

How to increase the potential value of an variable in a 16 bit machine using C

I have created a binary to decimal converter but even small numbers written in binary have many digits and thus are too large to be held by an integer variable on a 16 bit machine. Is there any way around this. The program is in C. Here is the code, thanks:

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

void main()
{
 clrscr();
 int a,b,d=0,x=1;
 int check(int y);
 printf("Enter your number in Binary:");
 scanf("%d",&a);
 if(check(a)==0)
 {
  printf("Number tolerable. Conversion Process Initiated.");
 }
 else 
 {
  printf("Number not binary. Try again.");
  exit(1);
 }

 while(a!=0)
 {
   if(a%10==1)
    {
     d=d+x;
    }
   a=a/10;
   x=x*2;
 }
 printf("\nDecimal:%d",d);
 getch();
}

int check(int y)
{
  while(y!=0)
  {
   if(y%10!=0&&y%10!=1)
   {
    return 1;
   }
   else
   {
    y=y/10;
   }
  }
 return 0;
}



via Chebli Mohamed

C unknown syntax for variable declaration [duplicate]

This question already has an answer here:

I have just come across a piece of code that looks pretty much like this:

int a = ({

    int b = 10;
    b;
});

printf("%d", a);

I've never seen anything like this. It turns out that we can declare a variable this way. But why the language allows this? What is the concept behind it? When it can be of a good use to use such a syntax?



via Chebli Mohamed

Memory sharing between Matlab and C++ in MEX

I'm currently trying to write a program that processes a fairly large file (~16GB) and then performs analysis upon it. Ideally, I would do the data processing in C/C++ (I already have an efficient implementation written) and then do the analysis in Matlab to make use of its efficient algorithms and ease of use.

My natural inclination is to use MEX to call routines written in C at the beginning of the program and then continue in Matlab. What I want to know (and what I for whatever reason can't seem to find online) is the way in which memory would be shared if I were to use this method:

Say that I were to make a single large heap-allocated array in C to pass to Matlab. Would this array need to be copied in memory before my Matlab functions could work on it, or would Matlab be able to access the original array directly, with no extra copying? I assume and hope that this will work in the second way, but I would rather make sure before spending my time and effort.



via Chebli Mohamed

Using a pointer to access typedef struct

Objective: Writing to an internal buffer from the values of members of a structure.

I have a structure that contains members of type Uint16 (unsigned int); here is a small portion of it:

typedef unsigned int    Uint16;
typedef struct 
{
    Uint16 ee_Speed_Control_Mode;
    Uint16 ee_Motor_Type;
    Uint16 ee_Max_Electrical_Speed;
    Uint16 ee_Carrier_Frequency;
    Uint16 ee_Rated_Motor_Frequency;
    Uint16 ee_Rated_Motor_Current;
    Uint16 ee_Rs; // extern
    Uint16 ee_Rr; // extern
    Uint16 ee_L_lkg; // extern
    Uint16 ee_Lm;    // extern
    Uint16 ee_No_Load_Current;
    Uint16 ee_Phase_Reversal;
    .....
    .....
} EEPROM_PARAMETERS;

EEPROM_PARAMETERS eepromParameters;

My attempt:

Here is a function that is intended to write to eeprom: (Most of it is not shown for simplicity; the focus is occurring in the 'for' loop

void eeprom_write(Uint16 address, Uint32 *data, Int16 len)
{
    Uint16 i;

    // Multiple bytes will be written
    // Page Write operation will be used
    // Page Write bits to be sent:

    // bit 0: Start condition, a high-to-low transition of SDA with SCL high
    startCondition();

    // bits 1-8: Device address
    I2caRegs.I2CDXR = DEVICE_ADDRESS_WRITE;

    // bit 9: EEPROM outputs 0 as ACK bit
    // Check for ACK bit
    while (I2caRegs.I2CDRR != 0)
    {
        wait();
    }

    // bits 10-17, bit 18 (ACK) and bits 19-26: two 8-bit word addresses
    I2caRegs.I2CDXR = address;

    // After setting the address, page write is capable of writing 64 bytes without stopping
    // The EEPROM will respond with a zero after each data word has been received
    // The data word address lower 6 bits are internally incremented following the receipt of each data word
    // If more than 64 data words are written, data word addresses will "roll over" and previous data will be overwritten

    for (i = 0; i < len; i++)
    {
        // How to increment address in data structure?
        I2caRegs.I2CDXR = *data++; 
    }

    // After page write operation is complete, execute stop condition
    stopCondition();
}

When I try to call this function with my parameters..

eeprom_write(0, &eepromParameters, sizeof(eepromParameters) );

I get a incompatible type error:

error #169: argument of type "EEPROM_PARAMETERS *" is incompatible with parameter of type "Uint16 *"

My next thought would be that I need a middle man to bring them together and make it a compatible match. Any tips please on what I can try? Thanks



via Chebli Mohamed

Why does the image extracted from the Project Tango Tablet appear gray?

  • I am using the Project Tango C API
  • I am writing the entire buffer pointed to by TangoImageBuffer.data to a file.

    // open a file
    std::fstream f(app.getNextFileName(), std::ios::out | std::ios::binary);
    
    // write the entire stride * height * 4 buffer into the file
    f.write((const char *) tango_image_buffer->data, 
        tango_image_buffer->stride * buffer->height * 4 * sizeof(uint8_t)
    );
    
    f.close();
    
    
  • I then export the file to my PC and visualize it using python-opencv and numpy:

    import sys
    
    import cv2
    import numpy as np
    
    # dimensions of the image
    stride    = 1280
    width     = 1280
    height    = 720
    
    # I am using 3 channels so that the resulting image is not
    # transluscent
    channels  = 3
    
    input_filename  = sys.argv[1]
    output_filename = sys.argv[2]
    
    # load the image buffer into a list
    data = np.fromfile(input_filename, dtype=np.uint8)
    
    # create a height x width x channels matrix with the datatype uint8 
    # and all elements set to zero
    img = np.zeros((height, width, channels), dtype=np.uint8);
    
    # map elements in array to image matrix
    for y in range(0, height):    
        for x in range(0, width):
            img[y, x, 0] = data[y * stride + x + 2] #blue
            img[y, x, 1] = data[y * stride + x + 1] #green
            img[y, x, 2] = data[y * stride + x + 0] #red
    
    # display and save the resulting image
    cv2.namedWindow("tango-rgba")
    cv2.imshow("tango-rgba", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite(output_filename, img)
    
    
  • Unfortunately, the resulting image looks gray

  • The image only appears to be gray. Upon closer inspection of the pixels, you will find that the red, green, and blue components of the pixels are different.

  • EDIT: I have changed this post to specify that the buffer I am using is in RGBA8888 format. From the Project Tango Reference, "Only RGBA 8888 is provided"

  • EDIT: It actually seems RGBA8888 format is not used. rhashimoto suggests that the format is YV12.



via Chebli Mohamed

Strange segmentation fault in x86 assembly

While I'm debugging a segmentation fault in x86-Linux, I've ran into this problem:

Here goes the seg-fault message from the GDB

0xe2a5a99f in my_function (pSt=pSt@entry=0xe1d09000, version=43)

Here goes the faulting assembly:

0xe2a5a994 <my_function>      push   %ebp
0xe2a5a995 <my_function+1>    push   %edi
0xe2a5a996 <my_function+2>    push   %esi
0xe2a5a997 <my_function+3>    push   %ebx
0xe2a5a998 <my_function+4>    lea    -0x100b0c(%esp),%esp
0xe2a5a99f <my_function+11>   call   0xe29966cb <__x86.get_pc_thunk.bx>
0xe2a5a9a4 <my_function+16>   add    $0x9542c,%ebx

As you can see above, the faulting line is "call get_pc_thunk" which is just getting the pc value. And, I checked the memory at 0xe29966cb is valid and accessible with the following command:

(gdb) x/10i 0xe29966cb
   0xe29966cb <__x86.get_pc_thunk.bx>:  nop
   0xe29966cc <__x86.get_pc_thunk.bx+1>:        nop
   0xe29966cd <__x86.get_pc_thunk.bx+2>:        nop
   0xe29966ce <__x86.get_pc_thunk.bx+3>:        nop
   0xe29966cf <__x86.get_pc_thunk.bx+4>:        nop
   0xe29966d0 <__x86.get_pc_thunk.bx+5>:        nop
   0xe29966d1 <__x86.get_pc_thunk.bx+6>:        nop
   0xe29966d2 <__x86.get_pc_thunk.bx+7>:        nop
   0xe29966d3 <__x86.get_pc_thunk.bx+8>:        mov    (%esp),%ebx
   0xe29966d6 <__x86.get_pc_thunk.bx+11>:       ret    

Which looks perfectly fine. But Strangely, if I use "si" to step into the "get_pc_thunk" function, it seg-faults without even entering the first nop.

Any help would be appreciated.



via Chebli Mohamed

wrong answer on test case 1 in this code?

http://ift.tt/1SIFHF8

i tried to solve it. But my code all time results in wrong answer on test case 1. I don't understand the problem in this code.

#include <stdio.h>
int main ()
{ int n;
char a[10];
int s=0;
scanf ("%d",&n);

fflush(stdin);
for (int i=1;i<=n;i++)
{ gets(a);


    if (a[0]=='+' || a[1]=='+') s++;

   else  if (a[0]=='-' || a[1]=='-') s--;

}
printf ("%d\n",s);
return 0;
}



via Chebli Mohamed

Out of order print statements when using fortran program to call c subroutine

I am experiencing problems with displaying values on the console while invoking a C subroutine from a fortran subroutine. I have print statements immediately before and after the call to the C subroutine, as well as a print statement within the C subroutine. However, upon executing the program, the C statements are printed before the two Fortran statements, rather than between them. I’ve looked thoroughly within the code, and there are no calls to the C subroutine elsewhere, so there is no obvious reason why the c statement should be printed before the Fortran statement. I created a simpler Fortran-C program (below) to try to reproduce the problem, but the code executed the print statements in the expected order. I wonder if someone has any insights as to what could be the problem. Thank you.

Sample Fortran code:

  program test

     print *, 'Calling C program'

     call cprog()

     print *, 'Finished calling C program.'

   end program test

sample c code to be invoked from fortran:

void cprog()
{

  printf("THIS IS A TEST\n");

  return;
}

Output:

Calling C program

THIS IS A TEST

Finished calling C program.

Output similar to what I’m experiencing with more complex code:

THIS IS A TEST

Calling C program

Finished calling C program



via Chebli Mohamed

Array size calculation without using inbuilt functions

How to find the size of an integer array without using any inbuilt function?

int fun(int a[25],int ele)
{

    int flag=0,i=0;
    while(a[i]!=NULL)
    {
        flag++;
        i++;
    }
    return flag;
 }



via Chebli Mohamed

calculate lowesr differents between 5 cells to other 5 cells

I have this row - [11,19,59,69,9] lets call it FIRST and i have another ~ 100 million rows with the same format

[10,20,30,20,50],
[15,50,60,70,10]
...
...

I need to compare each number from FIRST row to each number in the corresponding cell in each row from the 100M rows , and take the abs diff between those two values and sum all of the diff.

Example :

FIRST - [11,19,59,69,9]
row   - [10,20,30,20,50]
diff  - [|11-10|,|19-20|,|59-30|,|69-20|,|9-50|]  = [1,1,29,49,41] 
sum(diff) = 1+1+29+49+41 =121

And i need to do this comparison between the FIRST and the rest of the rows and output the row with the smallest diff.

What is the best way to do it ? I need to implement it on my SQL DATABASE . Maybe there is SQL query for this ? or maybe i should develop some inner function via c, or c++?



via Chebli Mohamed

why the first index of the column of a matrix is negative?

why in this simple part of code to modify the point in the lower left of the bidimensional array have I to put in the coordinate m[37][-40]?

#include <stdio.h>
#include <stdlib.h>
#define MAX 40

int main()
{
    int i, j;
    char m[MAX][MAX];

    for(i=0; i<MAX; i++){
        for(j=0; j<MAX; j++)
            m[i][j]=' ';
    }

    m[37][-40]='X';

    for(i=0; i<MAX; i++){
        for(j=0; j<MAX; j++)
            printf("%c", m[i][j]);
    }
    return 0;
}

Souldn't it be m[37][0]? Becouse the row is 37 and the column is 0...



via Chebli Mohamed

Xlib get mouse wheel rate

Is there a property in X11 that tells how many scroll lines should there be in one scroll wheel event?



via Chebli Mohamed

Is there a difference in speed between using const and static const inside a function?

In C, what is the difference between static const and const inside a function?

For instance, take the given code examples:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int( 1 );
  return 0;
}

Versus:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  static const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int(1);
  return 0;
}

Would the generated assembly be optimized better if I used static const instead of const, or would the output be the same for both examples?



via Chebli Mohamed

Eclipse error when trying to run C code

I'm trying to understand binary and hexadecimal numbers. I want to know why my program won't launch in eclipse. It gives me this error:

launch has encountered a problem

It was running when i used int. My computer is 64bit. I'm trying to understand hardware. I need to know what I'm doing wrong. What can I improve on? Is it okay to declare buffer as a global variable? Thanks.

My code is here.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * convertBase(unsigned long int numberToConvert, long int base)
{

    char buffer[65];
    char *pConvertedNumber;
    char allValues[] = "0123456789abcdef";

    pConvertedNumber = &buffer[sizeof(buffer)-1];

    *pConvertedNumber = '\0';

    do {

        int value = numberToConvert % base;

        pConvertedNumber = pConvertedNumber - 1;

        *pConvertedNumber = allValues[value];

        numberToConvert /= base;

    } while(numberToConvert != 0);

    printf("%s", pConvertedNumber);

    return pConvertedNumber;
}

int main(void){

    unsigned long int numberOne = 1000000000;
    printf("\n%ld in Base 16 = ", numberOne);
    convertBase(numberOne, 16);

    printf("\n");

return 0;
}



via Chebli Mohamed

Headers Vs. Static Libraries

I am planning to do some utility code for using in other projects, but I am doubting between making it a mostly-headers code, a static library with headers just exposing the interface or something in between. Most of the code will be simple functions that wrap other standard functions but there will be also some bigger functions.

I think I mostly understand the differences between the header approach and the static library approach:

For the headers:

  • All the code will be in headers
  • Better oportunities for the compiler to inline code
  • Every function will have to be compiled every time it is used

For the static library:

  • Mixed code between the library and the headers
  • Worse oportunities for the compiler to inline code
  • Compile once and forget

I have been looking at some code and I have seen both approaches, but I don't know which will be better. Any thoughts?



via Chebli Mohamed

How to control multiple robots through raspberry pi using bluetooth

I am trying to control two arduino robots through raspberry pi using Bluetooth, I have already created the rfcomm file to control one robot, should i include the address of the second one in same rfcomm file? if yes, could someone please tell me how?I've done this is it correct?please ignore the 'enter code here' part everywhere

RFCOMM configuration file.

enter code hererfcomm0 { enter code here # Automatically bind the device at startup enter code here bind yes;

   `enter code here` # Bluetooth address of the device
    `enter code here`device 30:14:10:15:20:90;


   `enter code here` # RFCOMM channel for the connection
   `enter code here` channel 0;


    `enter code here`# Description of the connection
    `enter code here`comment "Example Bluetooth device";

enter code here}

enter code hererfcomm1 { enter code here# Automatically bind the device at startup enter code herebind yes;

   `enter code here`# Bluetooth address of the device

   `enter code here` device 10:14:06:16:00:09;

  `enter code here` # RFCOMM channel for the connection
  `enter code here`  channel 0;

`enter code here` # Description of the connection
`enter code here`    comment "Example Bluetooth device";

enter code here}`



via Chebli Mohamed

Is there any limit to the number of expressions|parameters in a 'while loop' [duplicate]

This question already has an answer here:

Traditional programming with while-loop is done with a single parameter ex:

  • while(1) (or) while(a==b) (or) while(a&&b) (or) while(!a) etc
  • The code below takes two parameters in the while loop

    ssize_t r_read(int fd, void *buf, size_t size) 
    {
        ssize_t retval;
        while (retval = read(fd, buf, size), retval == -1 && errno == EINTR);
        return retval;
    }
    
    
    1. Is there any limit to the parameters inside the while loop?
    2. Is there any possible explanation for this or does this methodology have a name?


via Chebli Mohamed

8 Bit (Binary) array checking in c (embedded c)

I have an array a[j] . In it has an 8 bit binary digit . I need to check each bit whether it was zero or one . How to write the program in C .



via Chebli Mohamed

How to store 3 different types of data in one array

I need to store 3 linked bits of data in c. My original thought was a 3 dimensional array but that won't work as all 3 data types are different. The top level needs to be a char. The second level needs to be a date/time so a integer. The third level is a temperature reading so needs to be a float.

Is the correct way to do this an array of pointers pointing to an array of pointers pointing to a array of floats? If so how would that be written in C?



via Chebli Mohamed

Modify if-counter inside a loop

I'm trying to modify a counter in if loop because one array index number needs to be corresponded by the other in order for me to change the place of it's text, but the space between the strings add 1 to the counter.

for(int i = 0, n = strlen(p); i < n; i++){

    if(isspace(p[i])){
        c1 = x[i-1];
        printf("%c", p[i]);
    }
    if(isalpha(p[i])){
        c1 = x[i];
        c2 = c1-96;
        printf("%c --- %c ---%d\n",p[i],c1, c2);
    }

This is one of the attempts but it made an infinite loop, I've tried different approach like:

    if(isspace(p[i))){
        printf("%c", p[i]);
        i -= 1;
    }



via Chebli Mohamed

Why does my program display the Array address instead of its contents?

My C program consists of an array called 'test_var'. It has another integer array 'arr_int' that consists of a set of integer numbers. My code looks something like this:

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

 int State(var);
 int main()
       {
         int arr_int[3] ={1000, 1001, 1002, 1003};
         int var;
         int *test_var[4]={0};

         State(var)
         {
            int i;
            for(i=0; i<4; i++){
               test_var[i] = arr_int[i];
               i++;
                }
          return test_var[var];
          }

          printf("Enter a number between 0 and 3\n");
          scanf("%d",&var);   
          State(var);
          printf ("The array structure is %d", test_var[var]);

          return 0;
          }

However now when I try to print the returned value array test_var for the user input var=0 instead of the whole array(1000) I just get 0. What am I doing wrong here ? COuld somebody please tell me? Am I dereferencing the array in a wrong way?



via Chebli Mohamed

C: Zlib compress not working

I'm trying a very simple thing: read a minimal text file and compress it with the compress() utility from zlib. I think I've done everything fine, I allocate filesize * 10 for the output, it should be more that enough, but I keep getting -5 (Z_BUF_ERROR) as result of the operation. Any help?

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

#define FILE_TO_OPEN "text.txt"

static char* readcontent(const char *filename, int* size)
{
    char* fcontent = NULL;
    int fsize = 0;
    FILE* fp = fopen(filename, "r");

    if(fp) {
        fseek(fp, 0, SEEK_END);
        fsize = ftell(fp);
        rewind(fp);

        fcontent = (char*) malloc(sizeof(char) * fsize);
        fread(fcontent, 1, fsize, fp);

        fclose(fp);
    }

    *size = fsize;
    return fcontent;
}

int main(int argc, char const *argv[])
{
    int input_size;
    char* content_of_file = readcontent(FILE_TO_OPEN, &input_size);

    printf("%d\n", input_size);

    uLongf compressed_data_size;
    char* compressed_data = malloc(sizeof(char) * (input_size * 10));

    int result = compress((Bytef*) compressed_data, (uLongf*)&compressed_data_size, (const Bytef*)content_of_file, (uLongf)input_size);
    printf("%d\n", result);

    return 0;
}



via Chebli Mohamed

Compiling on Mac

I am brand new to this forum, and have just begun to learn C. The book I am going through wants me to compile the code that was written. I have a file "cards.c", I am on a Mac, have Xcode installed, downloaded gcc from Apple and installed it.

$ gcc -v
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.4.0
Thread model: posix

When I type:

gcc cards.c -o cards

I get:

clang: error: no such file or directory: 'cards.c'
clang: error: no input files

I have tried going to Xcode downloads to install Xcode's Command Line Tools, it doesn't show up there, maybe I have a newer version?

I cannot figure out how to compile this, any ideas on what I am doing wrong?

Does the cards.c file need to be in a specific folder somewhere?



via Chebli Mohamed

Efficient way to copying array of pointer to another pointer

How to copy array of pointer to another pointer.

My approach this way

int *ptr2[(i-1)*100];
int *ptr1;

ptr1=&ptr2[(i-1)*100];

What is the efficient way to copy so that it takes less cpu cycle.



via Chebli Mohamed

Expose c-library functionality to node

I have been working on using a c library in my node project. After little bit investigation I found node-gyp.

I was successfully able to execute example but when I am trying to using third party c library functions in the code it was giving me linking error on run time.

Library can be found here http://ift.tt/1SZL7q7

I compiled the library independently to have *.a objects

I am using following example http://ift.tt/1KO1IOs

So I have following questions as I can infer

  • Shall I convert bibutils from make to gyp?
  • Shall I convert each source file to work with V8? I don't know how to do this.
  • How can I easily link this project to work with node-gyp with less noise?

Details related to script can be found below. bibutils folder is placed along with addon.cc

binding.gyp looks like

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ],
      "include_dirs": ["bibutils/lib"],
      "library_dirs": ["bibutils/lib/libbibutil.a","bibutils/lib/libbibprogs.a"]
    }
  ]
}

modified addon.cc

#include <node.h>
#include "bibutils.h"
#include "bibprogs.h"

using namespace v8;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
      /****This is not production code just to check the execution***/
      bibl b;   
      bibl_init( &b );
      bibl_free( &b );
      /**************************************************************/
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

Compilation Result

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ npm install

> function_factory@0.0.0 install /home/user1/node-addon-examples/5_function_factory/node_0.12
> node-gyp rebuild

make: Entering directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'
  CXX(target) Release/obj.target/addon/addon.o
  SOLINK_MODULE(target) Release/obj.target/addon.node
  COPY Release/addon.node
make: Leaving directory `/home/user1/node-addon-examples/5_function_factory/node_0.12/build'

On Execution

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ node addon.js
node: symbol lookup error: /home/user1/node-addon-examples/5_function_factory/node_0.12/build/Release/addon.node: undefined symbol: _Z9bibl_initP4bibl

Debug Info:

user1@ubuntu:~/node-addon-examples/5_function_factory/node_0.12$ nm -C build/Release/addon.node | grep bibl_init
                 U bibl_init(bibl*)



via Chebli Mohamed

Custom DNS answers

I'm currently working on a project for my summer internship and I've got to make an oblivious DNS translation server. I'm not here to speak about the oblivious part in detail but I'll explane the architecture of my program.

There is a server side that receives obfuscated requests and sends back an answer that it doesn't understand itself.

On the client side there is a proxy that translate requests into obfuscated requests. For that I use an iptables rule to send all DNS requests to a NFQUEUE, and then I work with libnetfilter_queue to handle the packet. After that I received the answer from the server I make a DNS answer with all the information I get (from the DNS request and from the server) and send it using libnet.

Now let's talk about my problem : When using my proxy I check the traffic with Wireshark and it seems that my proxy sends valid answers but if I try to browse the Internet with Firefox it doesn't work. You can find my code here : http://ift.tt/1SZL7pX

Is there a problem in my way of building DNS packets ?

Here is the DNS sender :

int send_answer(char *dst_ip_array, char *src_ip_array, int dport, int sport, int dns_id, char *query, char *req_ip, int logfd)
{
char c;
u_long src_ip = arrayToLong(src_ip_array), dst_ip = arrayToLong(dst_ip_array), requested_ip_long=dotToLong(req_ip);
char requested_ip[4];
u_short type = LIBNET_UDP_DNSV4_H;
libnet_t *l;

libnet_ptag_t ip;
libnet_ptag_t ptag4; /* TCP or UDP ptag */
libnet_ptag_t dns;

char errbuf[LIBNET_ERRBUF_SIZE];
char payload[1024];
u_short payload_s;
char log_buffer[500];
int length = 0;

/*
 *  Initialize the library.  Root priviledges are required.
 */
l = libnet_init(
        LIBNET_RAW4,                            /* injection type */
        NULL,                                   /* network interface */
        errbuf);                                /* error buffer */

if (!l)
{
    length += sprintf(log_buffer + length, "\tlibnet_init: %s", errbuf);
    exit(EXIT_FAILURE);
}

/* 
 * build dns payload 
 */
requested_ip[0]=requested_ip_long/(256*256*256);
requested_ip_long=requested_ip_long%(256*256*256);
requested_ip[1]=requested_ip_long/(256*256);
requested_ip_long=requested_ip_long%(256*256);
requested_ip[2]=requested_ip_long/256;
requested_ip_long=requested_ip_long%256;
requested_ip[3]=requested_ip_long;

payload_s = snprintf(payload, sizeof payload, "%c%s%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 
         (char)(strlen(query)&0xff), query, 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x0d, 0xe0, 0x00, 0x04, requested_ip[0], requested_ip[1], requested_ip[2], requested_ip[3]);

/* 
 * build packet
 */
dns = libnet_build_dnsv4(
type,          /* TCP or UDP */
dns_id,        /* id */
0x8100,        /* request */
1,             /* num_q */
1,             /* num_anws_rr */
0,             /* num_auth_rr */
0,             /* num_addi_rr */
payload,
payload_s,
l,
0
);

if (dns == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build  DNS packet: %s\n", libnet_geterror(l));
    goto bad;
}

ptag4 = libnet_build_udp(
    sport,                                /* source port */
    dport,                                    /* destination port */
    LIBNET_UDP_H + LIBNET_UDP_DNSV4_H + payload_s, /* packet length */
    0,                                      /* checksum */
    NULL,                                   /* payload */
    0,                                      /* payload size */
    l,                                      /* libnet handle */
    0);                                     /* libnet id */

if (ptag4 == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build UDP header: %s\n", libnet_geterror(l));
    goto bad;
}


ip = libnet_build_ipv4(
    LIBNET_IPV4_H + LIBNET_UDP_H + type + payload_s,/* length */
    0,                                          /* TOS */
    242,                                        /* IP ID */
    0,                                          /* IP Frag */
    64,                                         /* TTL */
    IPPROTO_UDP,                                /* protocol */
    0,                                          /* checksum */
    src_ip,                                     /* source IP */
    dst_ip,                                     /* destination IP */
    NULL,                                       /* payload */
    0,                                          /* payload size */
    l,                                          /* libnet handle */
    0);                                         /* libnet id */

if (ip == -1)
{
    length += sprintf(log_buffer + length, "\tCan't build IP header: %s\n", libnet_geterror(l));
    exit(EXIT_FAILURE);
}


/*
 * write to the wire
 */
c = libnet_write(l);
if (c == -1)
{
    length += sprintf(log_buffer + length, "\tWrite error: %s\n", libnet_geterror(l));
    goto bad;
}
else
{
    length += sprintf(log_buffer + length, "\tWrote %d byte DNS packet; check the wire.\n", c);
}
length = strlen(log_buffer);
write(logfd, log_buffer, length); // Write to the log.
libnet_destroy(l);
return (EXIT_SUCCESS);
bad:
length = strlen(log_buffer);
write(logfd, log_buffer, length); // Write to the log.
libnet_destroy(l);
return (EXIT_FAILURE);
}

Here is an example of DNS answer sent by my proxy: http://ift.tt/1KO1GGw



via Chebli Mohamed

Are there ready-to-use solutions (libraries, headers) or standard pattern/workflow for reading (a lot) input parameters? [on hold]

Heyho,

my situation

I have a quite big scientific c-program that needs a lot of input parameters reading out of a file. I have a "handmade" working version from the ones, working on the program before. But you have to keep a special order of the parameters, the formatted input file is kind of unhandy, adding of parameters is complicated and it is kind of error sensitive.

my ideas so far

If been looking for a while in different c introduction books and also in some advanced techniques guides, but nobody seems to write something about these kind of tasks.

The only thing, I could find, was the idea to use an external program that creates out of handy interface the sorted, unhandy to use directly input file I'm now using. But that takes more time and for adding/sorting/deleting parameters I have to change the program code and the input file generator.

my question

What kind of input handling strategy are there? Are there special coding techniques? Or a common workflow?

Please ask, if I have to specify things. I'm not use to common names and notations, sorry for that. Please correct me referring to this.



via Chebli Mohamed

Handling Decimals on Embedded C

I have my code below and I want to ask what's the best way in solving numbers (division, multiplication, logarithm, exponents) up to 4 decimals places? I'm using PIC16F1789 as my device.

float sensorValue;
float sensorAverage;

void main(){
    //Get an average data by testing 100 times
    for(int x = 0; x < 100; x++){
        // Get the total sum of all 100 data
        sensorValue = (sensorValue + ADC_GetConversion(SENSOR));
    }

    // Get the average
    sensorAverage = sensorValue/100.0;
}



via Chebli Mohamed

How to parse HEX Numbers in Bison

I have this project i'm suppose to work on and my first task is to build a deskCalculator. I want the calculator to be able to parse HEX numbers. Below is the section having the problem.

| HEX {$$ = strtol((char *)$1 , (char **)'\n', 16); }

A token HEX have been defined above and in the lex file the regular expresion have been defined as

hex [a-f0-9]+

The problem is at the level of the strtol function. Please Help me. Thanks.



via Chebli Mohamed

How to get disk name programmatically in Linux(Like "/dev/sda" or "/dev/sdb")?

I am trying out to find information related to Disk and partitions. Following are my code. But problem is that, I am passing disk name through command line by querying disk name from "/proc/partitions". Is there any api which can give me disk name as well.

#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>

int main (int argc, char *argv[])
{
 blkid_probe pr;
 blkid_partlist ls;
 int nparts, i;

 pr = blkid_new_probe_from_filename(argv[1]);
 if (!pr)
 err(2, "faild to open device %s", argv[1]);

 ls = blkid_probe_get_partitions(pr);
 nparts = blkid_partlist_numof_partitions(ls);

for (i = 0; i < nparts; i++)
{
blkid_partition par = blkid_partlist_get_partition(ls, i);
printf("PartNo = %d\npart_start = %llu\npart_size =  %llu\npart_type = 0x%x\n",
blkid_partition_get_partno(par),
blkid_partition_get_start(par),
blkid_partition_get_size(par),
blkid_partition_get_type(par));
}

blkid_free_probe(pr);
return 0;

}



via Chebli Mohamed

C file handling

I am just creating a basic file handling program. the code is this:

#include <stdio.h>
int main()
{
FILE *p;
p=fopen("D:\\TENLINES.TXT","r");
if(p==0)
{
    printf("Error",);

}

fclose(p);
}

This is giving Error, I cannot create files tried reinstalling the compiler and using different locations and names for files but no success. I am using Windows 7 and compiler is Dev C++ version 5



via Chebli Mohamed

Calling C from C#

I am from electric engineer background, therefore my knownledge is small about C#,DLL,etc.... I want to use c function into a C#. I know there is a couple post about that but I didn't find one that is enough simple.

Currently, I got C function call windows API to read/write on the USB port. First to create a .dll do I need a header file? Because I got the following function decleration function into a header. The examples that I saw on stack overflow and Internet only use a simple .c file, Can I get rid of the header files?

__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDevice(unsigned short usVID,
                                    unsigned short usPID,
                                    LPGUID lpGUID,
                                    BOOL *pbDriverInstalled);
__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDeviceByIndex(unsigned short usVID,
                                           unsigned short usPID,
                                           LPGUID lpGUID,
                                           DWORD dwIndex,
                                           BOOL bOpenDataEndpoints,
                                           BOOL *pbDriverInstalled);
__declspec(dllexport) BOOL  __stdcall TerminateDevice(LMUSB_HANDLE hHandle);
__declspec(dllexport) BOOL  __stdcall WriteUSBPacket(LMUSB_HANDLE hHandle,
                          unsigned char *pcBuffer,
                          unsigned long ulSize,
                          unsigned long *pulWritten);
__declspec(dllexport) DWORD  __stdcall ReadUSBPacket(LMUSB_HANDLE hHandle,
                         unsigned char *pcBuffer,
                         unsigned long ulSize,
                         unsigned long *pulRead,
                         unsigned long ulTimeoutMs,
                         HANDLE hBreak);
 __declspec(dllexport) BOOL  __stdcall Endpoint0Transfer(LMUSB_HANDLE hHandle, UCHAR ucRequestType,
                             UCHAR ucRequest, USHORT usValue,
                             USHORT usIndex, USHORT usLength,
                             PUCHAR pucBuffer, PUSHORT pusCount);

Second point, do I need to write __declspec(dllexport) in the cpp file? Here an function from the cpp:

extern "C" __declspec(dllexport) BOOL PASCAL EXPORT TerminateDevice(LMUSB_HANDLE hUSB)

I got no idea what "BOOL PASCAL EXPORT" does, this code is recycled from a furnisher project.

Finaly, when the DLL is properly build. How I import it in the C# project? I tried the following but without success :

[DllImport("lmusbdll.dll")]

I see that you could use right click on the project and add reference but Visual Studio pop-up an error message:

A reference to "DLL path" could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

[EDIT]

I tried the following solution , but when I tried to reference the header file in my c# project. I still get the message that I cannot reference the file.



via Chebli Mohamed

Usage of keyword const in a function argument [duplicate]

This question already has an answer here:

Taking the following example:

void foo(const int foobar);

Is the keyword const meaningful?



via Chebli Mohamed

Difference between Internal terminal, External terminal and Standard output in Netbeans

I just got to know there are multiple consoles in Netbeans when working on a C-program. Please let me know what are the differences between them and when will they be used. Please see the screenshot

enter image description here



via Chebli Mohamed

Data compare of files is wrong. Why? [on hold]

So, the thing is, this program checks if there are duplicate files in a directory. It uses mostly the windows.h library. To spare code, all the file paths are stored in the buffer finalizedList. The list is always correct, don't worry about it.

To show you the problem, here are the files in the directory:

  • duplicate_delete.exe = The program itself
  • hello.txt = The original text file
  • hello - Copy.txt = A duplicate of "hello.txt". They are exactly the same.
  • hello.cpp = A file that has the exact same name with the original text file, except its extension. (AKA "The Bad Guy")

Now, anytime I run the program while "hello.cpp" is in the directory, this is the output of the program:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.cpp --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.cpp --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DIFFERENT
Checking: hello.cpp vs. hello.txt --> DIFFERENT
Finished.
Press any key to continue . . .

But, when I delete that file the output is this:

Creating list...
Finalizing list...
Starting compare procedure...
Checking: duplicate_delete.exe vs. hello - Copy.txt --> DIFFERENT
Checking: duplicate_delete.exe vs. hello.txt --> DIFFERENT
Checking: hello - Copy.txt vs. hello.txt --> DUPLICATE
Finished.
Press any key to continue . . .

Now... Why does that happen? Or to put it in a better way, how can that happen?

Here are parts of the code:

#include <windows.h>
#include <stdio.h>

HANDLE file1, file2;
const WCHAR * finalizedList[] = { L"duplicate_delete.exe", L"hello - Copy.txt", L"hello.txt", L"hello.cpp" };
WCHAR deleteList[4][1024];
DWORD fileListP, deleteListP;

DWORD openFile1(WCHAR path[1024]);
DWORD openFile2(WCHAR path[1024]);
DWORD compare();
void startCompare();

int main(void)
{
    fileListP = 4;
    printf_s("Starting compare procedure...\n");
    startCompare();
    printf_s("Finished.\n");
    _fcloseall();
    system("pause");

    return 0;
}

DWORD openFile1(WCHAR path[1024])
{
    if ((file1 = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return 0;
    return 1;
}

DWORD openFile2(WCHAR path[1024])
{
    if ((file2 = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) return 0;
    return 1;
}

DWORD compare()
{
    DWORD a, b;
    BYTE byte1, byte2;

    while (1)
    {
        ReadFile(file1, &byte1, 1, &a, NULL);
        ReadFile(file2, &byte2, 1, &b, NULL);
        if (a != b) return 1;
        if (byte2 != byte1) return 1;
        if (a == 0 && b == 0) break;
    }

    return 0;
}

void startCompare()
{
    WCHAR currentFile[1024], comparedFile[1024];
    DWORD i, j;
    i = 0;

    for (j = 0; j < fileListP; ++j)
    {
        lstrcpy(currentFile, finalizedList[j]);
        if (!openFile1(currentFile)) wprintf(L"File \"%ls\" couldn not be opened for comparing.\n", currentFile);
        else
        {
            for (i = j + 1; i < fileListP; ++i)
            {
                lstrcpy(comparedFile, finalizedList[i]);
                if (!openFile2(comparedFile)) wprintf(L"File \"%ls\" couldn not be compared with file \"%ls\".\n", currentFile, comparedFile);
                else
                {
                    if (!compare())
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DUPLICATE\n", currentFile, comparedFile);
                        lstrcpy(deleteList[deleteListP], currentFile);
                        ++deleteListP;
                    }
                    else
                    {
                        wprintf(L"Checking: %ls vs. %ls --> DIFFERENT\n", currentFile, comparedFile);
                    }
                    CloseHandle(file2);
                }
            }
            CloseHandle(file1);
        }
    }
}

Now... Of course, when I'm to check the program without the hello.cpp file I just delete it from the finalizedList array and make fileListP equal to 3. This is the minimal code that will work.



via Chebli Mohamed

dimanche 28 juin 2015

SignalR or simillar for winforms

I need to know if there is something like SignalR but for Winforms, some nuggets or library for paid, someone who can guide me please.

The beginning of my problem is that I have the need to obtain data automatically when the table is updated.

Thanks.

Parallel.ForEach stops being parallel for the last few items

I have an external singlethreaded program that needs to be run multiple hundred times with different parameters. To make it faster I want to run it once for each core at the same time. To do that I used Parallel.ForEach running on a list with the different parameters to pass to the external program:

var parallelOptions = new ParallelOptions {
    MaxDegreeOfParallelism = Environment.ProcessorCount // 8 for me
};

Parallel.ForEach(ListWithAllTheParams, parallelOptions, DoTheStuff);

...

private void DoTheStuff(ParamType parameter, ParallelLoopState parallelLoopState, long index)
{
    // prepare process parameters etc.
    theProcess.Start();
    theProcess.WaitForExit();
}

Pretty straightforward and works nicely... until the last ~10 items - they don't get parallelized for some reason and just run one after another. I've confirmed this by looking at the cpu usage and the running programs in the Task Manager.

This does not happen when I populate the parameter list with only a few (say, 10) items.

Can somebody explain this behavior to me? Any hints or tips appreciated!

Accuracy of the decimal number type versus the double type in .Net

Consider the following code:

    Dim doubleResult = (21 / 88) * 11
    Dim decimalResult = Decimal.Divide(21, 88) * 11

The doubleResult is 2.625, as it should.

The decimalResult is 2.6249999999999996, so when rounding this to two decimal places will give an incorrect result.

When I change the assignment to:

    Dim decimalResult = Decimal.Divide(21 * 11, 88) 

The result is 2.625!

We adopted the decimal type in our application hoping that it would give us increased accuracy. However, it seems that the decimal type just gives slightly incorrect results on other calculations than the double type does, due to the the fact that it is ten based, rather than two based.

So, how do we have to deal with this idiosyncrasies to avoid rounding errors as above?

Keeping graphics unaltered when TabPage changes

I have a form that displays a set of graphics using a Paint event on a Panel that is docked inside a particular TabPage of a TabControl.

The problem is the following:

When the user switches to a different TabPage and then decides to go back to the TabPage where the graphics were originally displayed, those graphics are invalidated by default so the Panel appears blank.

I would like those graphics to stay unaltered and totally independent from the user's action when switching between different TabPages.

One Requirement:

Since the graphics are complex and take some time to be drawn by the computer, I don't want to repaint the graphics each time by calling the Paint event repeatedly. Instead, I only need to avoid the default invalidation of the graphics.

I have read this other question which may be helpful to solve my problem but it goes beyond my knowledge.

ODBC vs JDBC in social network mobile app?

I want to create an social network app. I use odbc connection in mvc web services to connect database.

I want to know in the future if many users use my app ODBC is enough for many connections or should I use JDBC connection ?

thanks in advance

After deploying site created with last version of Umbraco on iss the css and images are broken

enter image description here

I have made all the usual steps for deploy on iss. The IUSRS -NetworkService has full rights on the web project

Suitable Control for displaying various game levels in a WP8 App

There is a mobile game on which I am working. It has various difficulty sections and each section has numerous levels, 250 levels in each section precisely.

Now, I need a suitable control which can display all the levels and by tapping on a certain level's button/icon, the user is able to move on and play that level.

I tried using a simple ScrollViewer, but that is way too much scrolling for the user even if I display 10 levels in a single row.

So, is there any inbuilt/existing control in WP that I can use to solve my problem?

P.S. Do remember, there are more than 250 levels that need to be displayed.

Many thanks in advance. Cheers!

Add the Text Form Field to the MS Office Word Document

Does anybody know how can I insert the Text Form Field to the MS Office Word 2003 Document (.doc)? And I also want to set the read-only property fo this field. How can I do this with C#?

How to do a SQL Server DB schema update with zero downtime

What do you think is the best way of updating an existing SQL Server (we are using SQL Server 2014, but could update to 2016) database schema (incl its data) with zero downtime of the overall system, i.e. applications using the database?

The business requirements is to have a zero downtime of all the applications and services using the database. We could say we only do backwards and forward compatible database schema changes, e.g. adding columns, but not removing existing columns.

Of course the business would like to have a backup before we do the database change, in case something goes really wrong and we need to rollback.

The system is transactions heavy, meaning potentially thousands of transactions per second.

The applications are .net applications, where most of them run in an IIS execution container at the moment (maybe we switch to some other form like self-hosted service etc.) and exopsing their functionality through Web Services.

What would be your approach?

unit test to check uniqueness of million generated strings

I would like to write a unit test to

1) go through a list of 1 million unique random generated strings.

2) Ensure that each numer is 100% unique and there are no duplicates.

What is the best way to check and compare that there are no duplicates.

I have a List<List<int>> set of data, with string representation like this (to give the idea!):

 {{1,3},{-1,-3},{2,5},{-2,-5},{-3,4},{-5,4},{3,5,-4},{6,-8},{7,-8},{-6,-7,8},{7,9},{-7,-9},{3,8,-10},{-3,-8,-10},{-3,8,10},{3,-8,10},{4,9,-11},{-4,-9,-11},{-4,9,11},{4,-9,11},{10,11},{-1,6},{1,-6},{-2,7},{2,-7}}

I want to check if ,in all present numbers, exist a number or set of numbers which only are in positive form. I mean if in the whole data, there is 3 and -3 I should return false, otherwise I have to add 3 as a number which only is present as positive 3, in to another list. (Same thing for only negated number)

Here is how I am trying to do it:

First, generate a unique set of numbers and remove negatives:

private void GenerateCurrentExistingVariables()
{
    _uid = new List<int>();
    var all = _cnf.Data.SelectMany(list => list).ToList();
    _uid = all.Distinct().ToList(); //make list unique
    _uid.Sort(); //sort numbers
    _uid.Reverse(); //reverse so highest numbers would evalaute first!
    _uid = _uid.Where(i => i >= 0).ToList(); //remove negative numbers
}

Then I do something like this:

in a method, I call the code below:

    for (var i = 0; i < _uid.Count; i++)
    {
        if (ExistOnlyInNegatedForm(_uid[i]))
        {
            onlyNegatedList.Add(_uid[i]);
        }

        //perhaps continue

        if (ExistOnlyInPositiveForm(_uid[i]))
        {

            onlyPositiveList.Add(_uid[i]);
        }
    }

Which in turns calls the methods below:

private bool ExistOnlyInPositiveForm(int id)
{
    for (var i = 0; i < _cnf.Data.Count; i++)
    {
        for (var j = 0; j < _cnf.Data[i].Count; j++)
        {
            if (_cnf.Data[i][j] == id)
            {
                return false;
            }
        }
    }

    return true;
}

private bool ExistOnlyInNegatedForm(int id)
{
    var toCheck = -id;
    for (var i = 0; i < _cnf.Data.Count; i++)
    {
        for (var j = 0; j < _cnf.Data[i].Count; j++)
        {
            if (_cnf.Data[i][j] == -toCheck)
            {
                return false;
            }
        }
    }

    return true;
}

This is too much code for this simple task and I feel that this is getting slower and slower when data grows larger...please let me know how can I improve this. Also I would like this to be done using LINQ at least for the sake of less lines of code!

I would love to see a C++ solution as well, so I am tagging c++ in my question (not doing language spam!)

How can i convert and compress in real time batch of images to mp4 video file?

In my directory on the hard disk i have many images: screenshot000001.bmp , screenshot000002.bmp....screenshot001200.bmp

I want to do two things:

  1. For testing using the CMD and to compress and convert the images to mp4 video file.

  2. In my program in real time while my program take the screenshots and save them to the hard disk to compress them and build the mp4 video file in real time.

For the first part i tried to type in cmd :

ffmpeg -f image2 -i screenshot%d.bmp -vcodec libx264 -b 800k video.avi

But what i got is two errors:

[image2 @ 0000000004766380] Could find no file with path 'screenshot%d.bmp' and index in the range 0-4 screenshot%d.bmp: No such file or directory

I copied the ffmpeg.exe to the directory where the images are in. E:\screenshots

For the second part this how i'm taking the screenshots in real time:

A button click event that start a timer:

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

Then in the tick event:

    ScreenShot shot = new ScreenShot();
    public static int counter = 0;
    private void timer1_Tick(object sender, EventArgs e)
    {
        counter++;
        shot.GetScreenShot(@"e:\screenshots\", "screenshot");
        if (counter == 1200)
        {
            timer1.Stop();
        }
    }

This line shot.GetScreenShot(@"e:\screenshots\", "screenshot"); save the screenshots to the hard disk. Here after each screenshot save i want to compress and build the mp4 video file in real time.

Showing widget demo in mobile view

I am creating a intranet application to my company which contains different plugins developed by us or commonly used plugins. It is a responsive design. Now I have a new requirement to show the widget demos in different mobile devices like iphone, android etc.

My lead show me this example http://ift.tt/1GUdTos

Based on the device selection we need to show plugins in different devices. For example I have a widget named datatable, I need to enable different views for this. How can i achieve it. I dont have any idea how to implement it. Please help

TeamCity + ASP.NET Webapp: Error about unclosed string literal?

I have a solution where all projects are targeting .NET v4.5.1.

TeamCity (v9.0.4) previously has built the solution just fine.

Added an Asp.Net web application (MVC + WebAPI) to the solution, still targeted at .NET 4.5.1.

It Works on My Machinetm, but TeamCity now fails the build with the following MSBuild error:

[src\app\Web\Web.csproj] C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets(186, 67): error MSB4025: The project file could not be loaded. There is an unclosed literal string. Line 186, position 67.

Those might be the line numbers in the targets file that threw the error, because in my file all I see is a </ProjectReference> (which corresponds correctly to two project references that are there.

Any idea what could be causing this?

Insert and Delete error Gridview ASP.NET

I am using SQL command to insert and delete into the grid but getting errors in implementation. How can I write the syntax This is the HTML code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html xmlns="http://ift.tt/lH0Osb">
    <head id="Head1" runat="server">
        <title> </title>
    </head>





<body>

    <form id="form1" runat="server">
        <div>
            <asp:Label ID="label" runat="server">New Task</asp:Label>
            <asp:TextBox ID="textbox1" runat="server" placeHolder="Type  
            new task summary here, and click add" Width="353px">    
            </asp:TextBox>
            <asp:Button ID="button1" runat="server" OnClick="click_add" 
            Text="Add" style="margin-left: 54px" Width="67px" />
            <br />
        </div>

        <asp:GridView ID="grdStatus" runat="server" 
        OnRowCommand="grdStatus_RowCommand" AutoGenerateColumns="false">
        <Columns> 
            <asp:TemplateField HeaderText="Done?">
                <ItemTemplate>
                    <asp:CheckBox ID="checkbx" runat="server" 
                    Checked='<%#Eval("Done") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ID">
                <ItemTemplate>
                    <asp:Label ID="label12" runat="server" 
                    Checked='<%#Container.DataItemIndex+1 %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Summary">
                <ItemTemplate> 
                    <asp:Label ID="label3" runat="server" 
                    Checked='<%#Eval("Summary") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Created On">
                <ItemTemplate>
                    <asp:Label ID="label4" runat="server" 
                    Checked='<%#Eval("Date")%>' ></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:ImageButton ID="dltButton" runat="server" 
                    ImageUrl="~/images/delete.png"   
                    CommandName="DeleteTask" Text="Delete" Width="30px" 
                    Height="30px" CommandArgument="<%#     
                    Container.DataItemIndex%>" />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
        </asp:GridView>


    </form>
</body>
</html>

The c# code is this using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.Configuration; using System.Data.SqlClient;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string connectionString =    
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        string selectSQL = "SELECT * FROM Table";
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            adapter.Fill(ds, "Table");

            grdStatus.DataSource = ds;
            grdStatus.DataBind();
        }
    }
    protected void click_add(object sender, EventArgs e)
    {

            string connectionString =   
  WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("INSERT INTO 
            Table(ID,Summary,Created) values ('" + checkbx.Text + "'" + 
            Convert.ToInt32(cmd.Parameters["label2"].Value.ToString()) + 
            "'" + label3.Text + "'" + label4.Text + "'", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();


    }

    protected void grdStatus_RowCommand(object sender, EventArgs e)
    {
        if(e.CommandName == "DeleteTask")
        {
            string connectionString =    
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            string query = "delete from Table where id=" + 
            e.CommandArgument + "'";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
            fillgrid();
        }
   }

}

VB.Net Code Formatter Like perltidy for perl

Good day!

Are there any code formatter for vb.net that can automate code formatting? like perl's perltidy.

I know I can do it manually but the class that I'm working on is getting bigger and I need a constant formatting for all.

Thank you!

Applying dynamically built expression on collection throws exception

I have the following class:

public class Order
{
    public string Code { get; set; } 
}

And I have built dynamically an Expression, which looks like this:

enter image description here

and I'm building an extension method which looks like:

enter image description here

I have a list of orders which, List<Order> of the expression type and when I apply the filter like this:

var buildExpressionFilter = dynamically constructed Expression here
var orders = GetOrders();
var result = orders.Where(buildExpressionFilter).ToList();

I get the following error: enter image description here

Is obviously that buildExpressionFilter is not properly constructed but I cannot figure out what is the issue.

Does anyone have an idea on how to fix this issue? What may be wrong with my buildExpressionFilter?

Calling a VST plugin with VST.net in Unity3D. Is it possible?

I dont have any experience with VST. Just started researching.

I need to call the member function VSTPluginMain from my VST dll to do some custom audio processing in my Unity 5 project. For a VST host, I added VST.NET 1.0 CLR2 X64 Release dlls in my project. I've read Unity supports only Common Language Runtime 2.

The documentation for VST.net is not working (a blank .chm file and the online version is incomplete). I wasn't able to find any useful samples in the VST.net project templates. Also, does Unity support VST? (the Unity forums are silent about this matter)

Any help is greatly appreciated.

Thank you

Self-hosting ASP.NET 5 within .NET 4.5 Application (without DNX and IIS)

Is it possible to add an ASP.NET 5 Web Application as a reference to a traditional .NET 4.5 project (Windows Service or Console App) and start it in-process?

Ideally within one solution, so that ASP.NET application and host service can share references to other projects in the same solution.

Tried so far:

dnu publish produces packages, but attempting to add them produces following error: Install-Package : Could not install package 'WebApplication1 1.0.0'. You are trying to install this package into a project that targets '.NETFramework, Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. When changing framework dnx451 to net451, Web Application doesn't compile because of missing ASP references.

dnu build produces binaries, but how to run the application? (where to get IApplicationBuilder and IHostingEnvironment instances?)

C# searching and getting Absolute Path of Software

I am new to C# and I want to create a little Autorun Manager in a Console Application. To do that I want to read from the console a keyword like "Steam" and my programm should search on "C:\" and in all subdirectories for a folder called like my keyword but as I say I have no Idea how I can search in all subdirectories.

Thats a little code sample with steam how I would write in registry

//filePath would be the Path of the .EXE file that was found    
string filePath = "\"C:\\Programme\\Steam\\Steam.exe\""; 
string autostartPath = @"Software\Microsoft\Windows\CurrentVersion\Run\";
RegistryKey autostart = Registry.CurrentUser.OpenSubKey(autostartPath, true);
autostart.SetValue("Steam", filePath);

If someone know how to search in all subdirectories and find the correct .exe file.

I would be really grateful for a code sample.

Thanks in advance

How can i take a screenshot of the pictureBox1 handle window?

I'm using this class but that take a screenshot of the desktop handle. And i need to take a screenshot of the pictureBox1 handle.

#region Class Imports 
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
#endregion

namespace Test
{
    /// <summary>
    /// Class for taking a screen shot in code
    /// </summary>
    public class ScreenShot
    {
    /// <summary>
    /// Global variable declarations
    /// </summary>
    #region Global Variables
    private Bitmap _screenShot;
    protected static IntPtr newBMP;
    #endregion

    #region Constants
    public const int SRCCOPY = 13369376;
    public const int SCREEN_X = 0;
    public const int SCREEN_Y = 1;
    #endregion
    /// <summary>
    /// Hold the definition for the
    /// class properties
    /// </summary>
    #region Class Properties
    [Description("Gets the screenshot image")]
    public Bitmap ScreenImage
    {
        get { return _screenShot; }
    }
    #endregion

    #region Constructor
    /// <summary>
    /// Constructors for our class
    /// </summary>
    [Description("Empty constructor, instantiating _screenShot to nothing")]
    public ScreenShot()
    {
        _screenShot = null;
    }              
    #endregion

    #region Methods
    /// <summary>
    /// Method for creating an image of the current desktop
    /// </summary>
    /// <returns>A Bitmap image</returns>
    [Description("Creates an image of the current desktop")]
    public Bitmap GetScreen()
    {
        int xLoc;
        int yLoc;
        IntPtr dsk;
        IntPtr mem;
        Bitmap currentView;

        //get the handle of the desktop DC
        dsk = Win32API.GetDC(Win32API.GetDesktopWindow());

        //create memory DC
        mem = Win32API.CreateCompatibleDC(dsk);

        //get the X coordinates of the screen
        xLoc = Win32API.GetSystemMetrics(SCREEN_X);

        //get the Y coordinates of screen.
        yLoc = Win32API.GetSystemMetrics(SCREEN_Y);

        //create a compatible image the size of the desktop
        newBMP = Win32API.CreateCompatibleBitmap(dsk, xLoc, yLoc);

        //check against IntPtr (cant check IntPtr values against a null value)
        if (newBMP != IntPtr.Zero)
        {
            //select the image in memory
            IntPtr oldBmp = (IntPtr)Win32API.SelectObject(mem, newBMP);
            //copy the new bitmap into memory
            Win32API.BitBlt(mem, 0, 0, xLoc, yLoc, dsk, 0, 0, SRCCOPY);
            //select the old bitmap into memory
            Win32API.SelectObject(mem, oldBmp);
            //delete the memoryDC since we're through with it
            Win32API.DeleteDC(mem);
            //release dskTopDC to free up the resources
            Win32API.ReleaseDC(Win32API.GetDesktopWindow(), dsk);
            //create out BitMap
            currentView = Image.FromHbitmap(newBMP);
            //return the image
            return currentView;
        }
        else  //null value returned
        {
            return null;
        }    
    }
    #endregion

    #region Helpers
    [Description("Takes the information from GetScreen and creates a Bitmap image")]
    public void GetScreenShot(string folder, string name)
    {
        //check to see if the folder provided exists
       /* if (!Directory.Exists(Application.StartupPath + "\\" + folder))
        {
            //if it doesnt exist then we need to create it
            Directory.CreateDirectory(Application.StartupPath + "\\" + folder);
        }*/
        //set the ScreenImage Property to the
        //BitMap created in GetScreen()
        _screenShot = new Bitmap(GetScreen());
        //create a name based on the name passed in
        string ingName = folder + name + Elgato_Video_Capture.counter.ToString("D6") + ".bmp";
        //save the image
        _screenShot.Save(ingName);
        _screenShot.Dispose();
    }
    #endregion
    }

}

Then i'm using it like that:

    ScreenShot shot = new ScreenShot();
    public static int counter = 0;

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter++;

        shot.GetScreenShot(@"e:\screenshots\", "screenshot");
        if (counter == 1200)
        {
            timer1.Stop();
        }
    }

I need to take a screenshot of the pictureBox1.Handle window not the pictureBox1.Image. The problem is that the class ScreenShot take a screenshot of the desktop Handle and i want to take a screenshot only of the pictureBox1.Handle

Outlook Message - Disable left mouse click on a hyper-link or prevent Outlook to follow clicked hyper-link

Is there a way to intercept mouse click on a hyper-link within current Outlook Message? What I need is to figure out a way to either intercept LEFT mouse click when user tries to click on a hyper-link or to prevent Outlook to open clicked hyper-link...

I hope this is not too confusing and someone can help me with it.

Thank you!

Socket connection coming from LAN?

Is there a way to check if an incoming connection on a TCP socket is coming from a LAN or not?

I'm currently checking the incoming address and seeing if it resides in the private network range (192.168.x.x/10.x.x.x etc)

Is there a better way to do it?

I'm particularly interested in solutions in Python and .NET if that helps.

Error while reversing document in SAP using BAPI

Using BAPI_ACC_DOCUMENT_REV_POST to reverse entries posed via BAPI_ACC_DOCUMENT_POST, however we are getting following errors

E RW 609 Error in document: BKPFF $ SYS600 BKPFF

E RW 632 Document BKPFF 900026 SYS600 cannot be reversed BKPFF

E RW 630 Reversal in component Financial Accounting not possible Financial Accounting

E F5A 9 Reversal not possible, accounting document for the ref. does not exist BKPFF

code for reference

Dim companyAPI As IRfcFunction = _ecc.Repository.CreateFunction("BAPI_ACC_DOCUMENT_REV_POST")
    Dim rev As IRfcStructure = companyAPI.GetStructure("REVERSAL")
    rev.SetValue("OBJ_TYPE", "BKPFF")
    rev.SetValue("OBJ_SYS", "$")
    rev.SetValue("OBJ_KEY", "900026N0342016")
    rev.SetValue("OBJ_KEY_R", "900026N0342016")
    rev.SetValue("COMP_CODE", "D756")
    rev.SetValue("REASON_REV", "01")
    Dim transfunction = _ecc.Repository.CreateFunction("BAPI_TRANSACTION_COMMIT")
    transfunction.SetValue("WAIT", "X")
    companyAPI.Invoke(_ecc) 
    transfunction.Invoke(_ecc)
    Dim dt As DataTable = GetDataTableFromRFCTable(companyAPI.GetTable("RETURN"))

After image resize transparency is removed - gdi+

I am reading an image from file that contains transparency area in the center (frame image type).

 Image myFrame = Image.FromFile("d:\mypngfile.png");

After i call image resize custome function:

myFrame = resizeImage(myFrame, new Size(otherbmp.Width, otherbmp.Height));

The problem is that after reszing the image it seems transparency is removed.

resize function:

 public Image resizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;
        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;
        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;
        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);
        Bitmap b = new Bitmap(destWidth, destHeight,PixelFormat.Format32bppArgb);
        b.MakeTransparent();
        Graphics g = Graphics.FromImage((Image)b);
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.CompositingMode = CompositingMode.SourceOver;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();
        return (Image)b;
    }

After i am checking the alpha pixels which doesn't work after resize (it does work before resizing and returns a value). It always return 0!

  public int GetBorderWidth(Bitmap bmp)
            {
                var hy = bmp.Height/ 2;


                while (bmp.GetPixel(0, hy).A == 255 && sz.Width < hx)
                    sz.Width++;

                 return sz.width;
             }

I can't seem to solve this issue no matter what i try...

How to submit form and load view with results

How do I submit a form and loads the results from the request in a new view.

I have the following routes

    routes.MapRoute(
        name: "Default",
        url: "{controller}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "GetResults",
        url: "{gueryString}",
        defaults: new { controller = "Result", action = "ShowResults", gueryString = "" }
    );

I have a index view with includes a partial view of my form I want to submit.

@Html.Partial("../Result/SearchForm")

The form itself is

  @using (Html.BeginForm("ShowResults", "Result", method: FormMethod.Post))
    {
        <form role="form">
            <div class="input-group input-group-lg">
                @Html.TextBoxFor(m => m.searchString, new { @class = "form-control" })
                <a href="javascript:$('form').submit();" class="input-group-addon">
                    <i class="fa fa-search"></i>
                </a>
            </div>
        </form>
    }

The new action itself in class ResultController

 public ActionResult ShowResults(SearchSubmitModel model)
    {

        RequestExternalComparisonData.ValidateSearchString(model);
        ViewBag.GameComparisonList = RequestExternalComparisonData.DoSearch(model.searchString);
        return View();
    }

The problem is the default index action is always ran on the form submit unless I completely remove the default route, but I need to initially load the index with my form. How do I trigger my new action on the form submit?

Unable to dowload file using generic handler

I am using a generic handler to download csv/excel files. It was working fine until yesterday. Today suddenly it stopped working on deployment on IIS 7.5 (though he same code works well in visual studio debugging mode). Here is my code:

ASPX: This is a content page

<input type="button" class="btn-primary" id="btnDownload" title="Download" value="Download" onclick='return downloadReport(this);' data-toggle="modal" data-target="#myModal" navurl='<%: ResolveUrl("~/Handlers/DownloadData.ashx") %>' />

JS:

function downloadReport(btn) {
//I am using a kendoUI combo box and kendo js + also using bootstrap for design & modal popups & also i have applied bundling to kendo & bootstrap files. They seem to be working fine without any conflicts as all their api's are working.
var $mod = $("#masterModal");
    $mod.modal('show');
    //window.location = "Handlers/DownloadData.ashx?rtp=" + combobox.val();
    window.location.href = $(btn).attr("navurl") + "?rtp=" + combobox.val();
    setTimeout(function () {
        $mod.modal("hide");
    }, 2000);

    return false;
}

Master Page:

I am including the js file containing the above method just before end of body tag.

<script src='<%: ResolveUrl("~/Scripts/DataUploader.js") %>'></script>  
</body>
</html>

Handler: In handler Process Request Method

HttpResponse response = this._context.Response;
            HRReportData hrData = new HRReportData(ConfigMaster.DbProvider, ConfigMaster.ConnectionString, ConfigMaster.DBSchemaName);
            ReportDataManager rdm = null;
            ExcelPackage xlPackage = null;
            try
            {
                rdm = new ReportDataManager();
                DataSet ds = rdm.GetReportData(hrData, report_Type);
                if (ds != null && ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        xlPackage = new ExcelPackage();
                        ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add(report_Type.ToString());
                        worksheet.Cells["A1"].LoadFromDataTable(ds.Tables[0], true, TableStyles.Light1);
                        response.ClearHeaders();
                        response.ClearContent();
                        response.Clear();
                        response.ContentType = "application/octet-stream";
                        response.AppendHeader("content-disposition", "attachment;  filename=" + report_Type.ToString() + ".xlsx");
                        xlPackage.SaveAs(response.OutputStream);
                        response.Flush();
                        //response.Close();
                        //response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                //LogError.MethodLevelError(Convert.ToString(Session["Username"]), ex);
                if (!(ex is System.Threading.ThreadAbortException))
                {
                    //Other error handling code here
                }
            }
            finally
            {
                if (xlPackage != null)
                {
                    xlPackage.Dispose();
                    xlPackage.Dispose();
                }
            }

Bundle config:

bundles.Add(new ScriptBundle("~/Kendo/kendo").Include(
                "~/Scripts/jquery-1.11.3.min.js",
                "~/Kendo/js/kendo.all.min.js"
               // "~/Scripts/DataUploader.js"
            ));
            bundles.Add(new ScriptBundle("~/bootstrap/bootstrap").Include(
                "~/bootstrap/js/holder.js",
                "~/bootstrap/js/ie10-viewport-bug-workaround.js",
                "~/bootstrap/js/ie-emulation-modes-warning.js",
                "~/bootstrap/js/bootstrap.min.js"
            ));

All above code works well in debugging mode and was working well in deployment mode as well. Don't know what has changed that it suddenly stopped working and I am unable to find out any reasons :(

Behaviour on deployment: Instead of staying on same page and downloading file it navigates to Handler and a blank screen is displayed. No file is downloaded.

Behaviour in debuuging mode OR when run using vs2012 express: It stays on same page and downloads the file as expected.

Somebody please help me on this.