Search Results

Search found 21759 results on 871 pages for 'int'.

Page 7/871 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • C++11 VS 2012 functor seems to choke when I have more than 5 parameters

    - by bobobobo
    function <void ( int a, int b, int ia, int ib, bool rev, const Vector4f& color )> benchTris = [&pts]( int a, int b, int ia, int ib, bool rev, const Vector4f& color ) { } The error is: error C2027: use of undefined type 'std::_Get_function_impl<_Tx>' with [ _Tx=void (int,int,int,int,bool,const Vector4f &) ] main.cpp(374) : see reference to class template instantiation 'std::function<_Fty>' being compiled with [ _Fty=void (int,int,int,int,bool,const Vector4f &) ] Works ok if I remove ONE parameter, for example a from the front: function <void ( int b, int ia, int ib, bool rev, const Vector4f& color )> benchTris = [&pts]( int b, int ia, int ib, bool rev, const Vector4f& color ) { // ok } Is there some parameter limit I don't know about?

    Read the article

  • Multiplying char and int together in C part 2

    - by teehoo
    If I do the following: int c0 = CHAR_MAX; //8 bit int c1 = CHAR_MAX; //8-bit int i = c0*c1; //store in 32-bit variable printf("%d\n", i); //prints 16129 We can see that there is no problem with to 8-bit numbers being multiplied together, and producing a 32-bit output. However, if I do int i0 = INT_MAX; //32-bit int i1 = INT_MAX; //32 bit variable long long int ll = i0*i1; //store in 64-bit variable printf("%lld\n", ll); //prints 1..overflow!! In this case, two 32-bit variables were multiplied together, overflowed, and then were assigned to the 64-bit variable. So why did this overflow happen when multiplying the ints, but not the chars? Is it dependent on the default word-size of my machine? (32-bits)

    Read the article

  • int cannot be dereferenced

    - by Overlord
    Hello, I am beginning in java (I'm learning in microedition) and I got this error: "int cannot be dereferenced" in the following class: class DCanvas extends Canvas{ public DCanvas(){ } public void drawString(String str, int x, int y, int r, int g, int b){ g.setColor(r, g, b); //The error is here g.drawString(str, x, y, 0); //and here } public void paint(Graphics g){ g.setColor(100, 100, 220); g.fillRect(0, 0, getWidth(), getHeight()); } } What am I doing wrong here? Well I came from PHP and ECMAScripts where I was able to pass my function arguments this way so I really don't understand this error.

    Read the article

  • int[] to string c#

    - by Robin Webdev
    Hi I'm developing an client application in C# and the server is written in c++ the server uses: inline void StrToInts(int *pInts, int Num, const char *pStr) { int Index = 0; while(Num) { char aBuf[4] = {0,0,0,0}; for(int c = 0; c < 4 && pStr[Index]; c++, Index++) aBuf[c] = pStr[Index]; *pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128); pInts++; Num--; } // null terminate pInts[-1] &= 0xffffff00; } to convert an string to int[] in my c# client i recieve: int[4] { -14240, -12938, -16988, -8832 } How do I convert the array back to an string? I don't want to use unsafe code (e.g. pointers) Any of my tries resulted in unreadable strings.

    Read the article

  • C: Recursive function for inverting an int

    - by Jorge
    I had this problem on an exam yesterday. I couldn't resolve it so you can imagine the result... Make a recursive function: int invertint( int num) that will receive an integer and return it but inverted, example: 321 would return as 123 I wrote this: int invertint( int num ) { int rest = num % 10; int div = num / 10; if( div == 0 ) { return( rest ); } return( rest * 10 + invert( div ) ) } Worked for 2 digits numbers but not for 3 digits or more. Since 321 would return 1 * 10 + 23 in the last stage. Thanks a lot! PS: Is there a way to understand these kind of recursion problems in a faster manner or it's up to imagination of one self?

    Read the article

  • C++0x error : variable 'std::packaged_task<int> pt1' has initializer but incomplete type

    - by Eternal Learner
    Hi All, Below is a simple program in c++0x that makes use of packaged_task and futures. while compiling the program i get error : variable 'std::packaged_task pt1' has initializer but incomplete type the program is below #include #include using namespace std; int printFn() { for(int i = 0; i < 100; i++) { cout << "thread " << i << endl; } return 1; } int main() { packaged_task<int> pt1(&printFn); future<int> fut = pt1.get_future(); thread t(move(pt1)); t.detach(); int value = fut.get(); return 0; }

    Read the article

  • I was stuck in implementing Simple Ftp with Winsock [migrated]

    - by user67449
    I want to implement a SimpleFtp with Winsock. But I was stuck in the maybe the file stream reading and writing. This is the Server. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } void SockBind(SOCKET sock, int port, sockaddr_in &addrsock){ addrsock.sin_family=AF_INET; addrsock.sin_port=htons(port); addrsock.sin_addr.S_un.S_addr=htonl(INADDR_ANY); if( bind(sock, (sockaddr*)&addrsock, sizeof(addrsock)) == SOCKET_ERROR ){ cout<<"Error at bind(). Error: "<<GetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } void SockListen(SOCKET sock, int bak){ int err=listen(sock, bak); if(err==SOCKET_ERROR){ cout<<"Error at listen()."<<WSAGetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } int SockSend(DataPack &dataPack, SOCKET sock, char *sockBuf){ int bytesLeft=0, bytesSend=0; int idx=0; bytesLeft=sizeof(dataPack); // ?DataPack?????sockBuf??? memcpy(sockBuf, &dataPack, sizeof(dataPack)); while(bytesLeft>0){ bytesSend=send(sock, &sockBuf[idx], bytesLeft, 0); if(bytesSend==SOCKET_ERROR){ cout<<"Error at send()."<<endl; return 1; } bytesLeft-=bytesSend; idx+=bytesSend; } return 0; } int GetFileLen(FILE *fp){ // ?????? if(fp==NULL){ cout<<"Invalid argument. Error at GetFileLen()."<<endl; exit(0); } fseek(fp, 0, SEEK_END); int tempFileLen=ftell(fp); fseek(fp, 0, SEEK_SET); return tempFileLen; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockListen==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Bind the socket. SockBind(sockListen, port, addrServ); // Listen for incoming connection requests cout<<"Waiting for incoming connection requests..."<<endl; SockListen(sockListen, 5); // Accept the connection request. sockaddr_in addrClient; int len=sizeof(addrClient); SOCKET sockConn=accept(sockListen, (sockaddr*)&addrClient, &len); if(sockConn!=INVALID_SOCKET){ cout<<"Connected to client successfully."<<endl; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at setsockopt(). ?socket????????"<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } //------------------------------------------------------------------------// DataPack dataPackSend; memset(&dataPackSend, 0, sizeof(dataPackSend)); int bytesRead; int bytesLeft; int bytesSend; int packCount; // Counts how many DataPack needed FILE *frp; // Used to read if(strcpy_s(dataPackSend.fName, "music.mp3")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } // Open the file in read+binary mode err=fopen_s(&frp, dataPackSend.fName, "rb"); if(err!=0){ cout<<"Error at fopen_s()."<<endl; return 1; } char fileBuf[FILE_BUFFER_SIZE]; // Set the buffer size of File if(setvbuf(frp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } // Get file's length int fileLen=GetFileLen(frp); cout<<"File ???:"<<fileLen<<" bytes."<<endl; // Calculate how many DataPacks needed packCount=ceil( (double)fileLen/CONTENT_SIZE ); cout<<"File Length: "<<fileLen<<" "<<"Content Size: "<<CONTENT_SIZE<<endl; cout<<"???"<<packCount<<" ?DataPack"<<endl; int i=0; for(i=0; i<packCount; i++){ //?????dataPackSend????? memset(&dataPackSend, 0, sizeof(dataPackSend)); // Fill the dataPackSend if(strcpy_s(dataPackSend.fName, "abc.txt")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } dataPackSend.packLen=DATA_PACK_SIZE; dataPackSend.fLen=fileLen; dataPackSend.packCount=packCount; if( packCount==1 ){ //??DataPack??? bytesRead=fread(fileBuf, 1, dataPackSend.fLen, frp); dataPackSend.contenLen=dataPackSend.fLen; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=0; //???????DataPack // ?????dataPackSend?Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack"<<endl; } }else if( packCount>1 && i<(packCount-1) ){ // ???(???????) bytesRead=fread(fileBuf, 1, CONTENT_SIZE, frp); dataPackSend.contenLen=CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend??????Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } }else{ // ????? bytesRead=fread(fileBuf, 1, (dataPackSend.fLen-i*CONTENT_SIZE), frp); dataPackSend.contenLen=dataPackSend.fLen-i*CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend???Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } } } fclose(frp); closesocket(sockListen); closesocket(sockConn); WSACleanup(); return 0; } And this is Client. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; //DataPack??? int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } int SockRecv(SOCKET sock, char *sockBuf){ int bytesLeft, bytesRecv; int idx=0; bytesLeft=DATA_PACK_SIZE; while(bytesLeft>0){ bytesRecv=recv(sock, &sockBuf[idx], bytesLeft, 0); if(bytesRecv==SOCKET_ERROR){ cout<<"Error at recv()."<<endl; return 1; } bytesLeft-=bytesRecv; idx+=bytesRecv; } return 0; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockClient=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockClient==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at getsockopt(). ?socket????????"<<endl; closesocket(sockClient); WSACleanup(); exit(0); } // Connect to the Server addrServ.sin_family=AF_INET; addrServ.sin_port=htons(port); addrServ.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); err=connect(sockClient, (sockaddr*)&addrServ, sizeof(sockaddr)); if(err==SOCKET_ERROR){ cout<<"Error at connect()."<<GetLastError()<<endl; closesocket(sockClient); WSACleanup(); return 1; }else{ cout<<"Connected to the FTP Server successfully."<<endl; } /* int i=0; int bytesRecv, bytesLeft, bytesWrite; int packCount=0, fLen=0; DataPack dataPackRecv; //?????? SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; cout<<"?DataPack??fName????: "<<dataPackRecv.fName<<endl; //??????? packCount=dataPackRecv.packCount; cout<<"?? "<<packCount<<" ?DataPack."<<endl; fLen=dataPackRecv.fLen; // Create a local file to write into FILE *fwp; err=fopen_s(&fwp, dataPackRecv.fName, "wb"); if(err!=0){ cout<<"Error at creat fopen_s(). Failed to create a local file to write into."<<endl; return 1; } // Set the buffer size of File char fileBuf[FILE_BUFFER_SIZE]; if(setvbuf(fwp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; memset(fileBuf, 0, sizeof(fileBuf)); closesocket(sockClient); WSACleanup(); exit(0); } //???????content???? memcpy(fileBuf, dataPackRecv.content, sizeof(dataPackRecv.content)); bytesWrite=fwrite(fileBuf, 1, sizeof(fileBuf), fwp); if(bytesWrite<sizeof(fileBuf)){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } //?????packCount-1????????????????? for(int i=1; i<packCount; i++){ // ????????? memset(sockBuf, 0, sizeof(sockBuf)); memset(&dataPackRecv, 0, sizeof(dataPackRecv)); memset(fileBuf, 0, sizeof(fileBuf)); SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; //???? memcpy(fileBuf, dataPackRecv.content, dataPackRecv.contenLen); bytesWrite=fwrite(fileBuf, 1, dataPackRecv.contenLen, fwp); if(bytesWrite<dataPackRecv.contenLen){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } } if( (i+1)==packCount ){ cout<<"??DataPack????????!"<<endl; } fclose(fwp); closesocket(sockClient); WSACleanup(); return 0;*/ }

    Read the article

  • Require Integer Value not Memory Address whilst avoiding Invalid receiver type compiler warning

    - by Dave Anderson
    I have the following code; int days = [[SettingsUtils daysToRetainHistory] intValue]; [retainHistory setText:[NSString stringWithFormat:@"Days to retain History: %d", days]]; [daysToRetainHistory setValue:days animated:NO]; where [SettingsUtils daysToRetainHistory] is as follows; + (int) daysToRetainHistory { return (int)[[NSUserDefaults standardUserDefaults] objectForKey:@"CaseBaseDaysToRetainHistory"]; } I get the compiler warning Invalid receiver type 'int' because I call intValue on an int but unless I do this I can't seem to get the integer value out and always end up with the memory address i.e. 98765432 instead of 9 which ruins the UILabel display [retainHistory] and the UISlider [daysToRetainHistory] value. How do I avoid the compiler warning and still get my integer value in the label and the necessary float value for setting the UISlider value?

    Read the article

  • AspectJ join point with simple types

    - by Jon
    Hi! Are there defined join points in arithmetics that I can catch? Something like: int a = 4; int b = 2; int c = a + b; Can I make a pointcut that catches any one of those lines? And what context will I be able to get? I would like to add a before() to all int/float/double manipulation done in a particular method on a class, is that possible. I see in the AspectJ docs that there are defined join points for object initialization and method calls. Is declaring an int an object initialization and does the + operator count as a method call? Thanks!

    Read the article

  • Issues with signal handling [closed]

    - by user34790
    I am trying to actually study the signal handling behavior in multiprocess system. I have a system where there are three signal generating processes generating signals of type SIGUSR1 and SIGUSR1. I have two handler processes that handle a particular type of signal. I have another monitoring process that also receives the signals and then does its work. I have a certain issue. Whenever my signal handling processes generate a signal of a particular type, it is sent to the process group so it is received by the signal handling processes as well as the monitoring processes. Whenever the signal handlers of monitoring and signal handling processes are called, I have printed to indicate the signal handling. I was expecting a uniform series of calls for the signal handlers of the monitoring and handling processes. However, looking at the output I could see like at the beginning the monitoring and signal handling processes's signal handlers are called uniformly. However, after I could see like signal handler processes handlers being called in a burst followed by the signal handler of monitoring process being called in a burst. Here is my code and output #include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <signal.h> #include <cstdio> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #define NUM_SENDER_PROCESSES 3 #define NUM_HANDLER_PROCESSES 4 #define NUM_SIGNAL_REPORT 10 #define MAX_SIGNAL_COUNT 100000 using namespace std; volatile int *usrsig1_handler_count; volatile int *usrsig2_handler_count; volatile int *usrsig1_sender_count; volatile int *usrsig2_sender_count; volatile int *lock_1; volatile int *lock_2; volatile int *lock_3; volatile int *lock_4; volatile int *lock_5; volatile int *lock_6; //Used only by the monitoring process volatile int monitor_count; volatile int usrsig1_monitor_count; volatile int usrsig2_monitor_count; double time_1[NUM_SIGNAL_REPORT]; double time_2[NUM_SIGNAL_REPORT]; //Used only by the main process int total_signal_count; //For shared memory int shmid; const int shareSize = sizeof(int) * (10); double timestamp() { struct timeval tp; gettimeofday(&tp, NULL); return (double)tp.tv_sec + tp.tv_usec / 1000000.; } pid_t senders[NUM_SENDER_PROCESSES]; pid_t handlers[NUM_HANDLER_PROCESSES]; pid_t reporter; void signal_catcher_1(int); void signal_catcher_2(int); void signal_catcher_int(int); void signal_catcher_monitor(int); void signal_catcher_main(int); void terminate_processes() { //Kill the child processes int status; cout << "Time up terminating the child processes" << endl; for(int i=0; i<NUM_SENDER_PROCESSES; i++) { kill(senders[i],SIGKILL); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { kill(handlers[i],SIGKILL); } kill(reporter,SIGKILL); //Wait for the child processes to finish for(int i=0; i<NUM_SENDER_PROCESSES; i++) { waitpid(senders[i], &status, 0); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { waitpid(handlers[i], &status, 0); } waitpid(reporter, &status, 0); } int main(int argc, char *argv[]) { if(argc != 2) { cout << "Required parameters missing. " << endl; cout << "Option 1 = 1 which means run for 30 seconds" << endl; cout << "Option 2 = 2 which means run until 100000 signals" << endl; exit(0); } int option = atoi(argv[1]); pid_t pid; if(option == 2) { if(signal(SIGUSR1, signal_catcher_main) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, signal_catcher_main) == SIG_ERR) { perror("2"); exit(1); } } else { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } } if(signal(SIGINT, signal_catcher_int) == SIG_ERR) { perror("3"); exit(1); } /////////////////////////////////////////////////////////////////////////////////////// ////////////////////// Initializing the shared memory ///////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// cout << "Initializing the shared memory" << endl; if ((shmid=shmget(IPC_PRIVATE,shareSize,IPC_CREAT|0660))< 0) { perror("shmget fail"); exit(1); } usrsig1_handler_count = (int *) shmat(shmid, NULL, 0); usrsig2_handler_count = usrsig1_handler_count + 1; usrsig1_sender_count = usrsig2_handler_count + 1; usrsig2_sender_count = usrsig1_sender_count + 1; lock_1 = usrsig2_sender_count + 1; lock_2 = lock_1 + 1; lock_3 = lock_2 + 1; lock_4 = lock_3 + 1; lock_5 = lock_4 + 1; lock_6 = lock_5 + 1; //Initialize them to be zero *usrsig1_handler_count = 0; *usrsig2_handler_count = 0; *usrsig1_sender_count = 0; *usrsig2_sender_count = 0; *lock_1 = 0; *lock_2 = 0; *lock_3 = 0; *lock_4 = 0; *lock_5 = 0; *lock_6 = 0; cout << "End of initializing the shared memory" << endl; ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////// End of initializing the shared memory /////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////Registering the signal handlers/////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the signal handlers" << endl; for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { if((pid = fork()) == 0) { if(i%2 == 0) { struct sigaction action; action.sa_handler = signal_catcher_1; sigset_t block_mask; action.sa_flags = 0; sigaction(SIGUSR1,&action,NULL); if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } } else { if(signal(SIGUSR1 ,SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } struct sigaction action; action.sa_handler = signal_catcher_2; action.sa_flags = 0; sigaction(SIGUSR2,&action,NULL); } if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } while(true) { pause(); } exit(0); } else { //cout << "Registerd the handler " << pid << endl; handlers[i] = pid; } } cout << "End of registering the signal handlers" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////End of registering the signal handlers ////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////Registering the monitoring process ////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the monitoring process" << endl; if((pid = fork()) == 0) { struct sigaction action; action.sa_handler = signal_catcher_monitor; sigemptyset(&action.sa_mask); sigset_t block_mask; sigemptyset(&block_mask); sigaddset(&block_mask,SIGUSR1); sigaddset(&block_mask,SIGUSR2); action.sa_flags = 0; action.sa_mask = block_mask; sigaction(SIGUSR1,&action,NULL); sigaction(SIGUSR2,&action,NULL); if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } while(true) { pause(); } exit(0); } else { cout << "Monitor's pid is " << pid << endl; reporter = pid; } cout << "End of registering the monitoring process" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////End of registering the monitoring process//////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Sleep to make sure that the monitor and handler processes are well initialized and ready to handle signals sleep(5); ////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////Registering the signal generators/////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the signal generators" << endl; for(int i=0; i<NUM_SENDER_PROCESSES; i++) { if((pid = fork()) == 0) { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } srand(i); while(true) { int signal_id = rand()%2 + 1; if(signal_id == 1) { killpg(getpgid(getpid()), SIGUSR1); while(__sync_lock_test_and_set(lock_4,1) != 0) { } (*usrsig1_sender_count)++; *lock_4 = 0; } else { killpg(getpgid(getpid()), SIGUSR2); while(__sync_lock_test_and_set(lock_5,1) != 0) { } (*usrsig2_sender_count)++; *lock_5=0; } int r = rand()%10 + 1; double s = (double)r/100; sleep(s); } exit(0); } else { //cout << "Registered the sender " << pid << endl; senders[i] = pid; } } //cout << "End of registering the signal generators" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////End of registering the signal generators/////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Either sleep for 30 seconds and terminate the program or if the number of signals generated reaches 10000, terminate the program if(option = 1) { sleep(90); terminate_processes(); } else { while(true) { if(total_signal_count >= MAX_SIGNAL_COUNT) { terminate_processes(); } else { sleep(0.001); } } } } void signal_catcher_1(int the_sig) { while(__sync_lock_test_and_set(lock_1,1) != 0) { } (*usrsig1_handler_count) = (*usrsig1_handler_count) + 1; cout << "Signal Handler 1 " << *usrsig1_handler_count << endl; __sync_lock_release(lock_1); } void signal_catcher_2(int the_sig) { while(__sync_lock_test_and_set(lock_2,1) != 0) { } (*usrsig2_handler_count) = (*usrsig2_handler_count) + 1; __sync_lock_release(lock_2); } void signal_catcher_main(int the_sig) { while(__sync_lock_test_and_set(lock_6,1) != 0) { } total_signal_count++; *lock_6 = 0; } void signal_catcher_int(int the_sig) { for(int i=0; i<NUM_SENDER_PROCESSES; i++) { kill(senders[i],SIGKILL); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { kill(handlers[i],SIGKILL); } kill(reporter,SIGKILL); exit(3); } void signal_catcher_monitor(int the_sig) { cout << "Monitoring process " << *usrsig1_handler_count << endl; } Here is the initial segment of output Monitoring process 0 Monitoring process 0 Monitoring process 0 Monitoring process 0 Signal Handler 1 1 Monitoring process 2 Signal Handler 1 2 Signal Handler 1 3 Signal Handler 1 4 Monitoring process 4 Monitoring process Signal Handler 1 6 Signal Handler 1 7 Monitoring process 7 Monitoring process 8 Monitoring process 8 Signal Handler 1 9 Monitoring process 9 Monitoring process 9 Monitoring process 10 Signal Handler 1 11 Monitoring process 11 Monitoring process 12 Signal Handler 1 13 Signal Handler 1 14 Signal Handler 1 15 Signal Handler 1 16 Signal Handler 1 17 Signal Handler 1 18 Monitoring process 19 Signal Handler 1 20 Monitoring process 20 Signal Handler 1 21 Monitoring process 21 Monitoring process 21 Monitoring process 22 Monitoring process 22 Monitoring process 23 Signal Handler 1 24 Signal Handler 1 25 Monitoring process 25 Signal Handler 1 27 Signal Handler 1 28 Signal Handler 1 29 Here is the segment when the signal handler processes signal handlers are called in a burst Signal Handler 1 456 Signal Handler 1 457 Signal Handler 1 458 Signal Handler 1 459 Signal Handler 1 460 Signal Handler 1 461 Signal Handler 1 462 Signal Handler 1 463 Signal Handler 1 464 Signal Handler 1 465 Signal Handler 1 466 Signal Handler 1 467 Signal Handler 1 468 Signal Handler 1 469 Signal Handler 1 470 Signal Handler 1 471 Signal Handler 1 472 Signal Handler 1 473 Signal Handler 1 474 Signal Handler 1 475 Signal Handler 1 476 Signal Handler 1 477 Signal Handler 1 478 Signal Handler 1 479 Signal Handler 1 480 Signal Handler 1 481 Signal Handler 1 482 Signal Handler 1 483 Signal Handler 1 484 Signal Handler 1 485 Signal Handler 1 486 Signal Handler 1 487 Signal Handler 1 488 Signal Handler 1 489 Signal Handler 1 490 Signal Handler 1 491 Signal Handler 1 492 Signal Handler 1 493 Signal Handler 1 494 Signal Handler 1 495 Signal Handler 1 496 Signal Handler 1 497 Signal Handler 1 498 Signal Handler 1 499 Signal Handler 1 500 Signal Handler 1 501 Signal Handler 1 502 Signal Handler 1 503 Signal Handler 1 504 Signal Handler 1 505 Signal Handler 1 506 Here is the segment when the monitoring processes signal handlers are called in a burst Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Why isn't it uniform afterwards. Why are they called in a burst?

    Read the article

  • The Clocks on USACO

    - by philip
    I submitted my code for a question on USACO titled "The Clocks". This is the link to the question: http://ace.delos.com/usacoprob2?a=wj7UqN4l7zk&S=clocks This is the output: Compiling... Compile: OK Executing... Test 1: TEST OK [0.173 secs, 13928 KB] Test 2: TEST OK [0.130 secs, 13928 KB] Test 3: TEST OK [0.583 secs, 13928 KB] Test 4: TEST OK [0.965 secs, 13928 KB] Run 5: Execution error: Your program (`clocks') used more than the allotted runtime of 1 seconds (it ended or was stopped at 1.584 seconds) when presented with test case 5. It used 13928 KB of memory. ------ Data for Run 5 ------ 6 12 12 12 12 12 12 12 12 ---------------------------- Your program printed data to stdout. Here is the data: ------------------- time:_0.40928452 ------------------- Test 5: RUNTIME 1.5841 (13928 KB) I wrote my program so that it will print out the time taken (in seconds) for the program to complete before it exits. As can be seen, it took 0.40928452 seconds before exiting. So how the heck did the runtime end up to be 1.584 seconds? What should I do about it? This is the code if it helps: import java.io.; import java.util.; class clocks { public static void main(String[] args) throws IOException { long start = System.nanoTime(); // Use BufferedReader rather than RandomAccessFile; it's much faster BufferedReader f = new BufferedReader(new FileReader("clocks.in")); // input file name goes above PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("clocks.out"))); // Use StringTokenizer vs. readLine/split -- lots faster int[] clock = new int[9]; for (int i = 0; i < 3; i++) { StringTokenizer st = new StringTokenizer(f.readLine()); // Get line, break into tokens clock[i * 3] = Integer.parseInt(st.nextToken()); clock[i * 3 + 1] = Integer.parseInt(st.nextToken()); clock[i * 3 + 2] = Integer.parseInt(st.nextToken()); } ArrayList validCombination = new ArrayList();; for (int i = 1; true; i++) { ArrayList combination = getPossibleCombinations(i); for (int j = 0; j < combination.size(); j++) { if (tryCombination(clock, (int[]) combination.get(j))) { validCombination.add(combination.get(j)); } } if (validCombination.size() > 0) { break; } } int [] min = (int[])validCombination.get(0); if (validCombination.size() > 1){ String minS = ""; for (int i=0; i<min.length; i++) minS += min[i]; for (int i=1; i<validCombination.size(); i++){ String tempS = ""; int [] temp = (int[])validCombination.get(i); for (int j=0; j<temp.length; j++) tempS += temp[j]; if (tempS.compareTo(minS) < 0){ minS = tempS; min = temp; } } } for (int i=0; i<min.length-1; i++) out.print(min[i] + " "); out.println(min[min.length-1]); out.close(); // close the output file long end = System.nanoTime(); System.out.println("time: " + (end-start)/1000000000.0); System.exit(0); // don't omit this! } static boolean tryCombination(int[] clock, int[] steps) { int[] temp = Arrays.copyOf(clock, clock.length); for (int i = 0; i < steps.length; i++) transform(temp, steps[i]); for (int i=0; i<temp.length; i++) if (temp[i] != 12) return false; return true; } static void transform(int[] clock, int n) { if (n == 1) { int[] clocksToChange = {0, 1, 3, 4}; add3(clock, clocksToChange); } else if (n == 2) { int[] clocksToChange = {0, 1, 2}; add3(clock, clocksToChange); } else if (n == 3) { int[] clocksToChange = {1, 2, 4, 5}; add3(clock, clocksToChange); } else if (n == 4) { int[] clocksToChange = {0, 3, 6}; add3(clock, clocksToChange); } else if (n == 5) { int[] clocksToChange = {1, 3, 4, 5, 7}; add3(clock, clocksToChange); } else if (n == 6) { int[] clocksToChange = {2, 5, 8}; add3(clock, clocksToChange); } else if (n == 7) { int[] clocksToChange = {3, 4, 6, 7}; add3(clock, clocksToChange); } else if (n == 8) { int[] clocksToChange = {6, 7, 8}; add3(clock, clocksToChange); } else if (n == 9) { int[] clocksToChange = {4, 5, 7, 8}; add3(clock, clocksToChange); } } static void add3(int[] clock, int[] position) { for (int i = 0; i < position.length; i++) { if (clock[position[i]] != 12) { clock[position[i]] += 3; } else { clock[position[i]] = 3; } } } static ArrayList getPossibleCombinations(int size) { ArrayList l = new ArrayList(); int[] current = new int[size]; for (int i = 0; i < current.length; i++) { current[i] = 1; } int[] end = new int[size]; for (int i = 0; i < end.length; i++) { end[i] = 9; } l.add(Arrays.copyOf(current, size)); while (!Arrays.equals(current, end)) { incrementWithoutRepetition(current, current.length - 1); l.add(Arrays.copyOf(current, size)); } int [][] combination = new int[l.size()][size]; for (int i=0; i<l.size(); i++) combination[i] = (int[])l.get(i); return l; } static int incrementWithoutRepetition(int[] n, int index) { if (n[index] != 9) { n[index]++; return n[index]; } else { n[index] = incrementWithoutRepetition(n, index - 1); return n[index]; } } static void p(int[] n) { for (int i = 0; i < n.length; i++) { System.out.print(n[i] + " "); } System.out.println(""); } }

    Read the article

  • List of all TCP/IP and WinSock Repair commands

    - by Niepojety
    I am building a C# application and I am looking for all a list of TCP/IP and WinSock Repair commands. ipconfig /flushdns netsh int reset all netsh int ipv4 reset netsh int ipv6 reset netsh int ip reset netsh int ip reset c:\ipreset.log netsh int ip reset resetlog.txt netsh int ip reset c:\resetlog.txt netsh int ip reset c:\network-connection.log netsh int 6to4 reset all netsh int httpstunnel reset all netsh int isatap reset all netsh int tcp reset all netsh int teredo reset all netsh int portproxy reset all netsh branchcache reset netsh winhttp reset netsh winsock reset c:\winsock.log netsh winsock reset netsh winsock reset all netsh winsock reset catalog

    Read the article

  • difference between Convert.ToInt32 and (int)

    - by balalakshmi
    the following syntax throws an compile time error like Cannot convert type 'string' to 'int' string name=(Session["name1"].ToString()); int i = (int)name; whereas the code below compiles and executes successfully string name=(Session["name1"].ToString()); int i = Convert.ToInt32(name); I would like to know 1) why the compile time error occurs in first code 2) what's the difference between the 2 code snippets

    Read the article

  • MySQL and INT auto_increment fields

    - by PHPguy
    Hello folks, I'm developing in LAMP (Linux+Apache+MySQL+PHP) since I remember myself. But one question was bugging me for years now. I hope you can help me to find an answer and point me into the right direction. Here is my challenge: Say, we are creating a community website, where we allow our users to register. The MySQL table where we store all users would look then like this: CREATE TABLE `users` ( `uid` int(2) unsigned NOT NULL auto_increment COMMENT 'User ID', `name` varchar(20) NOT NULL, `password` varchar(32) NOT NULL COMMENT 'Password is saved as a 32-bytes hash, never in plain text', `email` varchar(64) NOT NULL, `created` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of registration', `updated` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of profile update, e.g. change of email', PRIMARY KEY (`uid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; So, from this snippet you can see that we have a unique and automatically incrementing for every new user 'uid' field. As on every good and loyal community website we need to provide users with possibility to completely delete their profile if they want to cancel their participation in our community. Here comes my problem. Let's say we have 3 registered users: Alice (uid = 1), Bob (uid = 2) and Chris (uid = 3). Now Bob want to delete his profile and stop using our community. If we delete Bob's profile from the 'users' table then his missing 'uid' will create a gap which will be never filled again. In my opinion it's a huge waste of uid's. I see 3 possible solutions here: 1) Increase the capacity of the 'uid' field in our table from SMALLINT (int(2)) to, for example, BIGINT (int(8)) and ignore the fact that some of the uid's will be wasted. 2) introduce the new field 'is_deleted', which will be used to mark deleted profiles (but keep them in the table, instead of deleting them) to re-utilize their uid's for newly registered users. The table will look then like this: CREATE TABLE `users` ( `uid` int(2) unsigned NOT NULL auto_increment COMMENT 'User ID', `name` varchar(20) NOT NULL, `password` varchar(32) NOT NULL COMMENT 'Password is saved as a 32-bytes hash, never in plain text', `email` varchar(64) NOT NULL, `is_deleted` int(1) unsigned NOT NULL default '0' COMMENT 'If equal to "1" then the profile has been deleted and will be re-used for new registrations', `created` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of registration', `updated` int(11) unsigned NOT NULL default '0' COMMENT 'Timestamp of profile update, e.g. change of email', PRIMARY KEY (`uid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; 3) Write a script to shift all following user records once a previous record has been deleted. E.g. in our case when Bob (uid = 2) decides to remove his profile, we would replace his record with the record of Chris (uid = 3), so that uid of Chris becomes qual to 2 and mark (is_deleted = '1') the old record of Chris as vacant for the new users. In this case we keep the chronological order of uid's according to the registration time, so that the older users have lower uid's. Please, advice me now which way is the right way to handle the gaps in the auto_increment fields. This is just one example with users, but such cases occur very often in my programming experience. Thanks in advance!

    Read the article

  • Making only the outer vector in vector<vector<int>> fixed

    - by Dennis Ritchie
    I want to create a vector<vector<int>> where the outer vector is fixed (always containing the same vectors), but the inner vectors can be changed. For example: int n = 2; //decided at runtime assert(n>0); vector<vector<int>> outer(n); //outer vector contains n empty vectors outer.push_back(vector<int>()); //modifying outer vector - this should be error auto outer_it = outer.begin(); (*outer_it).push_back(3); //modifying inner vector. should work (which it does). I tried doing simply const vector<vector<int>>, but that makes even the inner vectors const. Is my only option to create my own custom FixedVectors class, or are there better ways out there to do this?

    Read the article

  • nul terminating a int array

    - by robUK
    Hello, gcc 4.4.4 c89 I was just experimenting with a int array. And something just came to my mind. Can I nul terminate it. For example, I am using a 0 to nul terminate. However, 0 could well be a valid value in this array. The code below will terminate after the 5. Even though I mean 0 to be a valid number. However, I could specify the size of the array. But in this case, I don't want to this as I am just interested in this particular problem. Many thanks for any advice, #include <stdio.h> static void test(int *p); int main(void) { int arr[] = {30, 450, 14, 5, 0, 10, '\0'}; test(arr); return 0; } static void test(int *p) { while(*p) { printf("Array values [ %d ]\n", *p++); } }

    Read the article

  • Predicate<INT> match question

    - by Petr
    Hi, I do not understand how following code works. Specifically, I do not understand using of "return i<3". I would expect return i IF its < than 3. I always though that return just returns value. I could not even find what syntax is it. Second question, it seems to me like using anonymous method (delegate(int i)) but could be possible to write it with normal delegate pointing to method elsewere? Thanks List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 }; List<int> result = listOfInts.FindAll(delegate(int i) { return i < 3; });

    Read the article

  • convert int to string for use in allegro function

    - by ace
    I am trying to run the following code using allegro. textout_ex(screen, font, numbComments , 100, 100, GREEN, BLACK); numbComments is an integer, the function prototype of this function is void textout_ex(BITMAP *bmp, const FONT *f, const char *s, int x, int y, int color, int bg); and i cannot, according to my understanding pass this integer in the third position. I therefore need to convert the integer into a string. I did it like this, but it didnt work. Help please? int score = numbComments; string Str; stringstream out; // YOU MUST INCLUDE <sstream> FOR THIS. out << score; Str = out.str(); and then tried to use the string Str, which didnt work

    Read the article

  • C++ Pointers to functions.

    - by Andy Leman
    using namespace std; int addition (int a, int b) { return (a+b); } int subtraction (int a, int b) { return (a-b); } int operation (int x, int y, int (*functocall)(int,int)) { int g; g = (*functocall)(x,y); return(g); } int main() { int m,n; int (*minus)(int,int) = subtraction; m = operation (7,5,addition); n = operation (20,m,minus); cout << n; return 0; } Can anybody explain this line for me int (*minus)(int,int) = subtraction; Thanks a lot!

    Read the article

  • How to concatenate int values in java?

    - by Shamli
    hi, I have the following values: int a=1; int b=0; int c=2; int d=2; int e=1; How do i concatenate these values so that i end up with a String that is 10221; please note that multiplying a by 10000, b by 1000.....and e by 1 will not working since b=0 and therefore i will lose it when i add the values up. Thnks you in advance.

    Read the article

  • Converting c++ string to int

    - by skazhy
    Hi! I have the following data in a c++ string John Doe 01.01.1970 I need to extract the date and time from it into int variables. I tried it like this: int last_space = text_string.find_last_of(' '); int day = int(text_string.substr(last_space + 1, 2)); But I got invalid cast from type ‘std::basic_string’ to type ‘int’. When I extract the "John Doe" part in another string variable, all works fine. What's wrong? I am trying to compile it with g++ -Wall -Werror.

    Read the article

  • Why is Spritebatch drawing my Textures out of order?

    - by Andrew
    I just started working with XNA Studio after programming 2D games in java. Because of this, I have absolutely no experience with Spritebatch and sprite sorting. In java, I could just layer the images by calling the draw methods in order. For a while, my Spritebatch was working fine in deferred sorting mode, but when I made a change to one of my textures, it suddenly started drawing them out of order. I have searched for a solution to this problem, but nothing seems to work. I have tried adding layer depths to the sprites and changing the sort mode to BackToFront or FrontToBack or even immediate, but nothing seems to work. Here is my drawing code: protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Gray); Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { region[x, y].draw(((float)w / aw)); // Draws the Tile-Based background } } player.draw(spriteBatch, ((float)w / aw));//draws the character (This method is where the problem occurs) enemy.draw(spriteBatch, (float)w/aw); // draws a basic enemy Game1.spriteBatch.End(); base.Draw(gameTime); } player.draw method: public void draw(SpriteBatch sb, float ratio){ //draws the player base (The character without hair or equipment) sb.Draw(playerbase[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White,0,Vector2.Zero,SpriteEffects.None,0); //draws the player's hair sb.Draw(playerbase[3], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's shirt sb.Draw(equipment[0], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's pants sb.Draw(equipment[1], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); //draws the player's shoes sb.Draw(equipment[2], new Rectangle((int)(pos.X - (24 * ratio)), (int)(pos.Y - (48 * ratio)), (int)(48 * ratio), (int)(48 * ratio)), new Rectangle(orientation * 48, animFrame * 48, 48, 48), Color.White, 0, Vector2.Zero, SpriteEffects.None, 0); } the game has a top-down perspective much like the early legend of zelda games. It draws sections of the texture depending on which direction the character is facing and the animation frame. However, instead of drawing the character in the order the draw methods are called, it ends up drawing the character out of order. Please help me with this problem.

    Read the article

  • Casting interfaces in java

    - by owca
    I had two separate interfaces, one 'MultiLingual' for choosing language of text to return, and second 'Justification' to justify returned text. Now I need to join them, but I'm stuck at 'java.lang.ClassCastException' error. Class Book is not important here. Data.length and FormattedInt.width correspond to the width of the line. The code : public interface MultiLingual { static int ENG = 0; static int PL = 1; String get(int lang); int setLength(int length); } class Book implements MultiLingual { private String title; private String publisher; private String author; private int jezyk; public Book(String t, String a, String p, int y){ this(t, a, p, y, 1); } public Book(String t, String a, String p, int y, int lang){ title = t; author = a; publisher = p; jezyk = lang; } public String get(int lang){ jezyk = lang; return this.toString(); } public int setLength(int i){ return 0; } @Override public String toString(){ String dane; if (jezyk == ENG){ dane = "Author: "+this.author+"\n"+ "Title: "+this.title+"\n"+ "Publisher: "+this.publisher+"\n"; } else { dane = "Autor: "+this.author+"\n"+ "Tytul: "+this.title+"\n"+ "Wydawca: "+this.publisher+"\n"; } return dane; } } class Data implements MultiLingual { private int day; private int month; private int year; private int jezyk; private int length; public Data(int d, int m, int y){ this(d, m, y, 1); } public Data(int d, int m, int y, int lang){ day = d; month = m; year = y; jezyk = lang; } public String get(int lang){ jezyk = lang; return this.toString(); } public int setLength(int i){ length = i; return length; } @Override public String toString(){ String dane=""; String miesiac=""; String dzien=""; switch(month){ case 1: miesiac="January"; case 2: miesiac="February"; case 3: miesiac="March"; case 4: miesiac="April"; case 5: miesiac="May"; case 6: miesiac="June"; case 7: miesiac="July"; case 8: miesiac="August"; case 9: miesiac="September"; case 10: miesiac="October"; case 11: miesiac="November"; case 12: miesiac="December"; } if(day==1){ dzien="st"; } if(day==2 || day==22){ dzien="nd"; } if(day==3 || day==23){ dzien="rd"; } else{ dzien="th"; } if(jezyk==ENG){ dane =this.day+dzien+" of "+miesiac+" "+this.year; } else{ dane = this.day+"."+this.month+"."+this.year; } return dane; } } interface Justification { static int RIGHT=1; static int LEFT=2; static int CENTER=3; String justify(int just); } class FormattedInt implements Justification { private int liczba; private int width; private int wyrownanie; public FormattedInt(int s, int i){ liczba = s; width = i; wyrownanie = 2; } public String justify(int just){ wyrownanie = just; String wynik=""; String tekst = Integer.toString(liczba); int len = tekst.length(); int space_left=width - len; int space_right = space_left; int space_center_left = (width - len)/2; int space_center_right = width - len - space_center_left -1; String puste=""; if(wyrownanie == LEFT){ for(int i=0; i<space_right; i++){ puste = puste + " "; } wynik = tekst+puste; } else if(wyrownanie == RIGHT){ for(int i=0; i<space_left; i++){ puste = puste + " "; } wynik = puste+tekst; } else if(wyrownanie == CENTER){ for(int i=0; i<space_center_left; i++){ puste = puste + " "; } wynik = puste + tekst; puste = " "; for(int i=0; i< space_center_right; i++){ puste = puste + " "; } wynik = wynik + puste; } return wynik; } } And the test code that shows this casting "(Justification)gatecrasher[1]" which gives me errors : MultiLingual gatecrasher[]={ new Data(3,12,1998), new Data(10,6,1924,MultiLingual.ENG), new Book("Sekret","Rhonda Byrne", "Nowa proza",2007), new Book("Tuesdays with Morrie", "Mitch Albom", "Time Warner Books",2003, MultiLingual.ENG), }; gatecrasher[0].setLength(25); gatecrasher[1].setLength(25); Justification[] t={ new FormattedInt(345,25), (Justification)gatecrasher[1], (Justification)gatecrasher[0], new FormattedInt(-7,25) }; System.out.println(" 10 20 30"); System.out.println("123456789 123456789 123456789"); for(int i=0;i < t.length;i++) System.out.println(t[i].justify(Justification.RIGHT)+"<----\n");

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >