Search Results

Search found 6123 results on 245 pages for 'unsigned char'.

Page 60/245 | < Previous Page | 56 57 58 59 60 61 62 63 64 65 66 67  | Next Page >

  • Is apparent NULL pointer dereference in C actually pointer arithmetic?

    - by karthik A
    hey ive got this piece of code. It dereferences a null pointer here. But then there is an and with unsigned int. I really dont understand the whole part. Can someone explain the output.?? struct hi { long a; int b; long c; }; int main() { struct hi ob={3,4,5}; struct hi *ptr=&ob; int num= (unsigned int) & (((struct hi *)0)->b); printf("%d",num); printf("%d",*(int *)((char *)ptr + (unsigned int) & (((struct hi *)0)->b))); } The output I get is 44. But how does it work?

    Read the article

  • what's the meaning of ~0 in cpp or c

    - by rima
    Hi what's the meaning of ~0 in this code???? somebody can analysis this code for me? unsigned int Order(unsigned int maxPeriod = ~0) const { Point r = *this; unsigned int n = 0; while( r.x_ != 0 && r.y_ != 0 ) { ++n; r += *this; if ( n > maxPeriod ) break; } return n; } please help me soon....

    Read the article

  • Debugging metaprograms [C++]

    - by atch
    Hi, Is there any way to check step by step what's going on in let's say template? I mean how it is instantiated step by step and so on? In book I've mentioned here , I found (2 minutes ago) quite interesting example of how binary could be implemented as a metafunction. template <unsigned long N> struct binary { static unsigned const value = binary<N/10>::value << 1 // prepend higher bits | N%10; // to lowest bit }; template <> // specialization struct binary<0> // terminates recursion { static unsigned const value = 0; }; and I think it could be quite useful to be able to see step by step what's been done during the instantiation of this template. Thanks for your replies.

    Read the article

  • including a string as a parameter to a function in a header file? c++

    - by Nara
    hello everyone, total newbie is here :) i have this header file, zeeheader.h, and i wrote some classes in it, i'm having problems giving a string as a parameter to one of the functions: class DeliTest { public: void DeliCheck(Stack*,string); void ComCheck (unsigned,string); bool EofCheck (unsigned,string); }; as i was implementinng it in the cpp file, i added #include to it, it seemed to be working, for example : as i was writing the "data." i got the "length()" appear by the intellisense, so i thought that it was working, but it wasn't. i got errors like: syntax error : identifier 'string' overloaded member function not found in 'DeliTest' this is one of the fucntions in the cpp file: bool DeliTest::EofCheck(unsigned i, string data) { if (i == data.length()-1) return 1; return 0; } am i supposed to be adding something to the header file??

    Read the article

  • Synergy 1.5 crash (OSX 10.6.8)

    - by Oliver
    THANKS FOR TAKING THE TIME TO READ THIS I recently installed Synergy 1.5 r2278 (for Mac OSX 10.6.8) and was using it fine for most of the day, then it decided to stop working (the only thing I changed systemwise was the screensaver - and then after it started crashing disabled it - to see if it would resolve). When I start Synergy (on the Mac - Client) it says: after about 5 seconds (and successfully connecting to the Server) "synergyc quit unexpectedly" Here is the crash log (w/ binery info removed - too long for post requirements) Process: synergyc [1026] Path: /Applications/Synergy.app/Contents/MacOS/synergyc Identifier: synergy Version: ??? (???) Code Type: X86 (Native) Parent Process: Synergy [1023] Date/Time: 2014-05-28 15:36:17.746 +0930 OS Version: Mac OS X 10.6.8 (10K549) Report Version: 6 Interval Since Last Report: 2144189 sec Crashes Since Last Report: 23 Per-App Interval Since Last Report: 10242 sec Per-App Crashes Since Last Report: 9 Anonymous UUID: 86D5A57C-13D4-470E-AC72-48ACDDDE5EB0 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Crashed Thread: 5 Application Specific Information: abort() called Thread 0: Dispatch queue: com.apple.main-thread 0 libSystem.B.dylib 0x95cf3afa mach_msg_trap + 10 1 libSystem.B.dylib 0x95cf4267 mach_msg + 68 2 com.apple.CoreFoundation 0x95af02df __CFRunLoopRun + 2079 3 com.apple.CoreFoundation 0x95aef3c4 CFRunLoopRunSpecific + 452 4 com.apple.CoreFoundation 0x95aef1f1 CFRunLoopRunInMode + 97 5 com.apple.HIToolbox 0x93654e04 RunCurrentEventLoopInMode + 392 6 com.apple.HIToolbox 0x93654bb9 ReceiveNextEventCommon + 354 7 com.apple.HIToolbox 0x937dd137 ReceiveNextEvent + 83 8 synergyc 0x000356d0 COSXEventQueueBuffer::waitForEvent(double) + 48 9 synergyc 0x00010dd5 CEventQueue::getEvent(CEvent&, double) + 325 10 synergyc 0x00011fb0 CEventQueue::loop() + 272 11 synergyc 0x00044eb6 CClientApp::mainLoop() + 134 12 synergyc 0x0005c509 standardStartupStatic(int, char**) + 41 13 synergyc 0x000448a9 CClientApp::runInner(int, char**, ILogOutputter*, int (*)(int, char**)) + 137 14 synergyc 0x0005c4b0 CAppUtilUnix::run(int, char**) + 64 15 synergyc 0x000427df CApp::run(int, char**) + 63 16 synergyc 0x00006e65 main + 117 17 synergyc 0x00006dd9 start + 53 Thread 1: 0 libSystem.B.dylib 0x95d607da __sigwait + 10 1 libSystem.B.dylib 0x95d607b6 sigwait$UNIX2003 + 71 2 synergyc 0x00009583 CArchMultithreadPosix::threadSignalHandler(void*) + 67 3 libSystem.B.dylib 0x95d21259 _pthread_start + 345 4 libSystem.B.dylib 0x95d210de thread_start + 34 Thread 2: 0 libSystem.B.dylib 0x95d21aa2 __semwait_signal + 10 1 libSystem.B.dylib 0x95d2175e _pthread_cond_wait + 1191 2 libSystem.B.dylib 0x95d212b1 pthread_cond_timedwait$UNIX2003 + 72 3 synergyc 0x00009476 CArchMultithreadPosix::waitCondVar(CArchCondImpl*, CArchMutexImpl*, double) + 150 4 synergyc 0x0002b18f CCondVarBase::wait(double) const + 63 5 synergyc 0x0002ce68 CSocketMultiplexer::serviceThread(void*) + 136 6 synergyc 0x0002d698 TMethodJob<CSocketMultiplexer>::run() + 40 7 synergyc 0x0002b8f4 CThread::threadFunc(void*) + 132 8 synergyc 0x00008f30 CArchMultithreadPosix::doThreadFunc(CArchThreadImpl*) + 80 9 synergyc 0x0000902a CArchMultithreadPosix::threadFunc(void*) + 74 10 libSystem.B.dylib 0x95d21259 _pthread_start + 345 11 libSystem.B.dylib 0x95d210de thread_start + 34 Thread 3: Dispatch queue: com.apple.libdispatch-manager 0 libSystem.B.dylib 0x95d1a382 kevent + 10 1 libSystem.B.dylib 0x95d1aa9c _dispatch_mgr_invoke + 215 2 libSystem.B.dylib 0x95d19f59 _dispatch_queue_invoke + 163 3 libSystem.B.dylib 0x95d19cfe _dispatch_worker_thread2 + 240 4 libSystem.B.dylib 0x95d19781 _pthread_wqthread + 390 5 libSystem.B.dylib 0x95d195c6 start_wqthread + 30 Thread 4: 0 libSystem.B.dylib 0x95d19412 __workq_kernreturn + 10 1 libSystem.B.dylib 0x95d199a8 _pthread_wqthread + 941 2 libSystem.B.dylib 0x95d195c6 start_wqthread + 30 Thread 5 Crashed: 0 libSystem.B.dylib 0x95d610ee __semwait_signal_nocancel + 10 1 libSystem.B.dylib 0x95d60fd2 nanosleep$NOCANCEL$UNIX2003 + 166 2 libSystem.B.dylib 0x95ddbfb2 usleep$NOCANCEL$UNIX2003 + 61 3 libSystem.B.dylib 0x95dfd6f0 abort + 105 4 libSystem.B.dylib 0x95d79b1b _Unwind_Resume + 59 5 synergyc 0x00008fd1 CArchMultithreadPosix::doThreadFunc(CArchThreadImpl*) + 241 6 synergyc 0x0000902a CArchMultithreadPosix::threadFunc(void*) + 74 7 libSystem.B.dylib 0x95d21259 _pthread_start + 345 8 libSystem.B.dylib 0x95d210de thread_start + 34 Thread 5 crashed with X86 Thread State (32-bit): eax: 0x0000003c ebx: 0x95d60f39 ecx: 0xb0288a7c edx: 0x95d610ee edi: 0x00521950 esi: 0xb0288ad8 ebp: 0xb0288ab8 esp: 0xb0288a7c ss: 0x0000001f efl: 0x00000247 eip: 0x95d610ee cs: 0x00000007 ds: 0x0000001f es: 0x0000001f fs: 0x0000001f gs: 0x00000037 cr2: 0x002fe000 Model: MacBook2,1, BootROM MB21.00A5.B07, 2 processors, Intel Core 2 Duo, 2.16 GHz, 2 GB

    Read the article

  • Why Doesn’t Partition Elimination Work?

    - by Paul White
    Given a partitioned table and a simple SELECT query that compares the partitioning column to a single literal value, why does SQL Server read all the partitions when it seems obvious that only one partition needs to be examined? Sample Data The following script creates a table, partitioned on the char(3) column ‘Div’, and populates it with 100,000 rows of data: USE Sandpit; GO CREATE PARTITION FUNCTION PF ( char (3)) AS RANGE RIGHT FOR VALUES ( '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9'...(read more)

    Read the article

  • Non-Unicode strings in VB.NET? (7 replies)

    I've been reading the MSDN documentation on the System.Char and System.String types and they mention Unicode throughout without even mentioning non Unicode versions. How do I get a gool 'ol one byte char and non Unicode string in .NET? Thanks, Alain

    Read the article

  • Non-Unicode strings in VB.NET? (7 replies)

    I've been reading the MSDN documentation on the System.Char and System.String types and they mention Unicode throughout without even mentioning non Unicode versions. How do I get a gool 'ol one byte char and non Unicode string in .NET? Thanks, Alain

    Read the article

  • GLM Velocity Vectors - Basic Maths to Simulate Steering

    - by Reanimation
    UPDATE - Code updated below but still need help adjusting my math. I have a cube rendered on the screen which represents a car (or similar). Using Projection/Model matrices and Glm I am able to move it back and fourth along the axes and rotate it left or right. I'm having trouble with the vector mathematics to make the cube move forwards no matter which direction it's current orientation is. (ie. if I would like, if it's rotated right 30degrees, when it's move forwards, it travels along the 30degree angle on a new axes). I hope I've explained that correctly. This is what I've managed to do so far in terms of using glm to move the cube: glm::vec3 vel; //velocity vector void renderMovingCube(){ glUseProgram(movingCubeShader.handle()); GLuint matrixLoc4MovingCube = glGetUniformLocation(movingCubeShader.handle(), "ProjectionMatrix"); glUniformMatrix4fv(matrixLoc4MovingCube, 1, GL_FALSE, &ProjectionMatrix[0][0]); glm::mat4 viewMatrixMovingCube; viewMatrixMovingCube = glm::lookAt(camOrigin, camLookingAt, camNormalXYZ); vel.x = cos(rotX); vel.y=sin(rotX); vel*=moveCube; //move cube ModelViewMatrix = glm::translate(viewMatrixMovingCube,globalPos*vel); //bring ground and cube to bottom of screen ModelViewMatrix = glm::translate(ModelViewMatrix, glm::vec3(0,-48,0)); ModelViewMatrix = glm::rotate(ModelViewMatrix, rotX, glm::vec3(0,1,0)); //manually turn glUniformMatrix4fv(glGetUniformLocation(movingCubeShader.handle(), "ModelViewMatrix"), 1, GL_FALSE, &ModelViewMatrix[0][0]); //pass matrix to shader movingCube.render(); //draw glUseProgram(0); } keyboard input: void keyboard() { char BACKWARD = keys['S']; char FORWARD = keys['W']; char ROT_LEFT = keys['A']; char ROT_RIGHT = keys['D']; if (FORWARD) //W - move forwards { globalPos += vel; //globalPos.z -= moveCube; BACKWARD = false; } if (BACKWARD)//S - move backwards { globalPos.z += moveCube; FORWARD = false; } if (ROT_LEFT)//A - turn left { rotX +=0.01f; ROT_LEFT = false; } if (ROT_RIGHT)//D - turn right { rotX -=0.01f; ROT_RIGHT = false; } Where am I going wrong with my vectors? I would like change the direction of the cube (which it does) but then move forwards in that direction.

    Read the article

  • IrrKlang with Ogre

    - by Vinnie
    I'm trying to set up sound in my Ogre3D project. I have installed irrKlang 1.4.0 and added it's include and lib directories to my projects VC++ Include and Library directories, but I'm still getting a Linker error when I attempt to build. Any suggestions? (Error 4007 error LNK2019: unresolved external symbol "__declspec(dllimport) class irrklang::ISoundEngine * __cdecl irrklang::createIrrKlangDevice(enum irrklang::E_SOUND_OUTPUT_DRIVER,int,char const *,char const *)" (_imp?createIrrKlangDevice@irrklang@@YAPAVISoundEngine@1@W4E_SOUND_OUTPUT_DRIVER@1@HPBD1@Z) referenced in function "public: __thiscall SoundManager::SoundManager(void)" (??0SoundManager@@QAE@XZ)

    Read the article

  • Image loaded from TGA texture isn't displayed correctly

    - by Ramy Al Zuhouri
    I have a TGA texture containing this image: The texture is 256x256. So I'm trying to load it and map it to a cube: #import <OpenGL/OpenGL.h> #import <GLUT/GLUT.h> #import <stdlib.h> #import <stdio.h> #import <assert.h> GLuint width=640, height=480; GLuint texture; const char* const filename= "/Users/ramy/Documents/C/OpenGL/Test/Test/texture.tga"; void init() { // Initialization glEnable(GL_DEPTH_TEST); glViewport(-500, -500, 1000, 1000); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45, width/(float)height, 1, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0); // Texture char bitmap[256][256][3]; FILE* fp=fopen(filename, "r"); assert(fp); assert(fread(bitmap, 3*sizeof(char), 256*256, fp) == 256*256); fclose(fp); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, bitmap); } void display() { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); glColor3ub(255, 255, 255); glBegin(GL_QUADS); glVertex3f(0, 0, 0); glTexCoord2f(0.0, 0.0); glVertex3f(40, 0, 0); glTexCoord2f(0.0, 1.0); glVertex3f(40, 40, 0); glTexCoord2f(1.0, 1.0); glVertex3f(0, 40, 0); glTexCoord2f(1.0, 0.0); glEnd(); glDisable(GL_TEXTURE_2D); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowPosition(100, 100); glutInitWindowSize(width, height); glutCreateWindow(argv[0]); glutDisplayFunc(display); init(); glutMainLoop(); return 0; } But this is what I get when the window loads: So just half of the image is correctly displayed, and also with different colors.Then if I resize the window I get this: Magically the image seems to fix itself, even if the colors are wrong.Why?

    Read the article

  • C Minishell Command Expansion Printing Gibberish

    - by Optimus_Pwn
    I'm writing a unix minishell in C, and am at the point where I'm adding command expansion. What I mean by this is that I can nest commands in other commands, for example: $> echo hello $(echo world! ... $(echo and stuff)) hello world! ... and stuff I think I have it working mostly, however it isn't marking the end of the expanded string correctly, for example if I do: $> echo a $(echo b $(echo c)) a b c $> echo d $(echo e) d e c See it prints the c, even though I didn't ask it to. Here is my code: msh.c - http://pastebin.com/sd6DZYwB expand.c - http://pastebin.com/uLqvFGPw I have a more code, but there's a lot of it, and these are the parts that I'm having trouble with at the moment. I'll try to tell you the basic way I'm doing this. Main is in msh.c, here it gets a line of input from either the commandline or a shellfile, and then calls processline (char *line, int outFD, int waitFlag), where line is the line we just got, outFD is the file descriptor of the output file, and waitFlag tells us whether or not we should wait if we fork. When we call this from main we do it like this: processline (buffer, 1, 1); In processline, we allocate a new line: char expanded_line[EXPANDEDLEN]; We then call expand, in expand.c: expand(line, expanded_line, EXPANDEDLEN); In expand, we copy the characters literally from line to expanded_line until we find a $(, which then calls: static int expCmdOutput(char *orig, char *new, int *oldl_ind, int *newl_ind) orig is line, and new is expanded line. oldl_ind and newl_ind are the current positions in the line and expanded line, respectively. Then we pipe, and recursively call processline, passing it the nested command(for example, if we had "echo a $(echo b)", we would pass processline "echo b"). This is where I get confused, each time expand is called, is it allocating a new chunk of memory EXPANDEDLEN long? If so, this is bad because I'll run out of stack room really quickly(in the case of a hugely nested commandline input). In expand I insert a null character at the end of the expanded string, so why is it printing past it? If you guys need any more code, or explanations, just ask. Secondly, I put the code in pastebin because there's a ton of it, and in my experience people don't like it when I fill up several pages with code. Thanks.

    Read the article

  • Shakespeare and storing Unicode characters

    - by John Paul Cook
    This post is about the political issues involved with using multiple languages in a global organization and how to troubleshoot the technical details. The CHAR and VARCHAR data types are NOT suitable for global data. Some people still cling to CHAR and VARCHAR justifying their use by truthfully saying that they only take up half the space of NCHAR and NVARCHAR data types. But you’ll never be able to store Chinese, Korean, Greek, Japanese, Arabic, or many other languages unless you use NCHAR and NVARCHAR...(read more)

    Read the article

  • Glm Vector Transformations [duplicate]

    - by Reanimation
    This question already has an answer here: Car-like Physics - Basic Maths to Simulate Steering 2 answers I have a cube rendered on the screen which represents a car (or similar). Using Projection/Model matrices and Glm I am able to move it back and fourth along the axes and rotate it left or right. I'm having trouble with the vector mathematics to make the cube move forwards no matter which direction it's current orientation is. (ie. if I would like, if it's rotated right 30degrees, when it's move forwards, it travels along the 30degree angle on a new axes). I hope I've explained that correctly. This is what I've managed to do so far in terms of using glm to move the cube: glm::vec3 vel; //velocity vector void renderMovingCube(){ glUseProgram(movingCubeShader.handle()); GLuint matrixLoc4MovingCube = glGetUniformLocation(movingCubeShader.handle(), "ProjectionMatrix"); glUniformMatrix4fv(matrixLoc4MovingCube, 1, GL_FALSE, &ProjectionMatrix[0][0]); glm::mat4 viewMatrixMovingCube; viewMatrixMovingCube = glm::lookAt(camOrigin, camLookingAt, camNormalXYZ); vel.x = cos(rotX); vel.y=sin(rotX); vel*=moveCube; //move cube ModelViewMatrix = glm::translate(viewMatrixMovingCube,globalPos*vel); //bring ground and cube to bottom of screen ModelViewMatrix = glm::translate(ModelViewMatrix, glm::vec3(0,-48,0)); ModelViewMatrix = glm::rotate(ModelViewMatrix, rotX, glm::vec3(0,1,0)); //manually turn glUniformMatrix4fv(glGetUniformLocation(movingCubeShader.handle(), "ModelViewMatrix"), 1, GL_FALSE, &ModelViewMatrix[0][0]); //pass matrix to shader movingCube.render(); //draw glUseProgram(0); } keyboard input: void keyboard() { char BACKWARD = keys['S']; char FORWARD = keys['W']; char ROT_LEFT = keys['A']; char ROT_RIGHT = keys['D']; if (FORWARD) //W - move forwards { globalPos += vel; //globalPos.z -= moveCube; BACKWARD = false; } if (BACKWARD)//S - move backwards { globalPos.z += moveCube; FORWARD = false; } if (ROT_LEFT)//A - turn left { rotX +=0.01f; ROT_LEFT = false; } if (ROT_RIGHT)//D - turn right { rotX -=0.01f; ROT_RIGHT = false; } Where am I going wrong with my vectors? I would like change the direction of the cube (which it does) but then move forwards in that direction.

    Read the article

  • How to write comments to explain the "why" behind the callback function when the function and parameter names are insufficient for that?

    - by snowmantw
    How should I approach writing comments for callback functions? I want to explain the "why" behind the function when the function and parameter names are insufficient to explain what's going on. I have always wonder why comments like this can be so ordinary in documents of libraries in dynamic languages: /** * cb: callback // where's the arguments & effects? */ func foo( cb ) Maybe the common attitude is "you can look into source code on your own after all" which pushes people into leaving minimalist comments like this. But it seems like there should be a better way to comment callback functions. I've tried to comment callbacks in Haskell way: /** * cb: Int -> Char */ func foo(cb) And to be fair, it's usually neat enough. But it gets into trouble when I need to pass some complex structure. The problem being partly due to the lack of type system: /** * cb: Int -> { err: String -> (), success: () -> Char } // too long... */ func foo(cb) Or I have tried this too: /** * cb: Int -> { err: String -> (), * success: () -> Char } // better ? */ func bar(cb) The problem is that you may put the structure in somewhere else, but you must give it a name to reference it. But then when you name a structure you're about to use immediately looks so redundant: // Somewhere else... // ResultCallback: { err: String -> (), success: () -> Char } /** * cb: Int -> ResultCallback // better ?? */ func foo(cb) And it bothers me if I follow the Java-doc like commenting style since it still seems incomplete. The comments don't tell you anything that you couldn't immediately see from looking at the function. /** * @param cb {Function} yeah, it's a function, but you told me nothing about it... * @param err {Function} where should I put this callback's argument ?? * Not to mention the err's own arguments... */ func foo(cb) These examples are JavaScript like with generic functions and parameter names, but I've encountered similar problems in other dynamic languages which allow complex callbacks.

    Read the article

  • Keep Getting Syntax Error C2199?

    - by DARK3ZOOZ
    Here's my problem I'm trying to define something, but keep getting a syntax error Code: #define R_RegisterShader 0x50C8A0 int (*trap_R_RegisterShader)( const char *name, int Arg_1 ) = (int (_cdecl *)(const char *, int ))R_RegisterShader; ^^^^^^^ This last part is where I keep getting the error if you need more lines of codes, just let me know. thanks http://gyazo.com/1a47ebc12cfbd6ea72feb72c686ae84d screenshot of error

    Read the article

  • Using sscanf for the dynamic delimiters (inputted by users) in parsing an input string in C? [migrated]

    - by Zuhakasa
    I'm encountering a problem in parsing a string using sscanf() function. My function gets 2 string parameters. One for input string and another one for a dynamic list of delimiters. How can I use sscanf to parse the input string with the defined delimiters inputted by users. For example: Myfunction(char * input_string, char * delimiter_list){ scanf("%s", input_string); scanf("%s", delimiter_list); sscanf(input_string, ???...); ................ }

    Read the article

  • texture mapping with lib3ds and SOIL help

    - by Adam West
    I'm having trouble with my project for loading a texture map onto a model. Any insight into what is going wrong with my code is fantastic. Right now the code only renders a teapot which I have assinged after creating it in 3DS Max. 3dsloader.cpp #include "3dsloader.h" Object::Object(std:: string filename) { m_TotalFaces = 0; m_model = lib3ds_file_load(filename.c_str()); // If loading the model failed, we throw an exception if(!m_model) { throw strcat("Unable to load ", filename.c_str()); } // set properties of texture coordinate generation for both x and y coordinates glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); // if not already enabled, enable texture generation if(! glIsEnabled(GL_TEXTURE_GEN_S)) glEnable(GL_TEXTURE_GEN_S); if(! glIsEnabled(GL_TEXTURE_GEN_T)) glEnable(GL_TEXTURE_GEN_T); } Object::~Object() { if(m_model) // if the file isn't freed yet lib3ds_file_free(m_model); //free up memory glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); } void Object::GetFaces() { m_TotalFaces = 0; Lib3dsMesh * mesh; // Loop through every mesh. for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next) { // Add the number of faces this mesh has to the total number of faces. m_TotalFaces += mesh->faces; } } void Object::CreateVBO() { assert(m_model != NULL); // Calculate the number of faces we have in total GetFaces(); // Allocate memory for our vertices and normals Lib3dsVector * vertices = new Lib3dsVector[m_TotalFaces * 3]; Lib3dsVector * normals = new Lib3dsVector[m_TotalFaces * 3]; Lib3dsTexel* texCoords = new Lib3dsTexel[m_TotalFaces * 3]; Lib3dsMesh * mesh; unsigned int FinishedFaces = 0; // Loop through all the meshes for(mesh = m_model->meshes;mesh != NULL;mesh = mesh->next) { lib3ds_mesh_calculate_normals(mesh, &normals[FinishedFaces*3]); // Loop through every face for(unsigned int cur_face = 0; cur_face < mesh->faces;cur_face++) { Lib3dsFace * face = &mesh->faceL[cur_face]; for(unsigned int i = 0;i < 3;i++) { memcpy(&texCoords[FinishedFaces*3 + i], mesh->texelL[face->points[ i ]], sizeof(Lib3dsTexel)); memcpy(&vertices[FinishedFaces*3 + i], mesh->pointL[face->points[ i ]].pos, sizeof(Lib3dsVector)); } FinishedFaces++; } } // Generate a Vertex Buffer Object and store it with our vertices glGenBuffers(1, &m_VertexVBO); glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, vertices, GL_STATIC_DRAW); // Generate another Vertex Buffer Object and store the normals in it glGenBuffers(1, &m_NormalVBO); glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsVector) * 3 * m_TotalFaces, normals, GL_STATIC_DRAW); // Generate a third VBO and store the texture coordinates in it. glGenBuffers(1, &m_TexCoordVBO); glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(Lib3dsTexel) * 3 * m_TotalFaces, texCoords, GL_STATIC_DRAW); // Clean up our allocated memory delete vertices; delete normals; delete texCoords; // We no longer need lib3ds lib3ds_file_free(m_model); m_model = NULL; } void Object::applyTexture(const char*texfilename) { float imageWidth; float imageHeight; glGenTextures(1, & textureObject); // allocate memory for one texture textureObject = SOIL_load_OGL_texture(texfilename,SOIL_LOAD_AUTO,SOIL_CREATE_NEW_ID,SOIL_FLAG_MIPMAPS); glPixelStorei(GL_UNPACK_ALIGNMENT,1); glBindTexture(GL_TEXTURE_2D, textureObject); // use our newest texture glGetTexLevelParameterfv(GL_TEXTURE_2D,0,GL_TEXTURE_WIDTH,&imageWidth); glGetTexLevelParameterfv(GL_TEXTURE_2D,0,GL_TEXTURE_HEIGHT,&imageHeight); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // give the best result for texture magnification glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //give the best result for texture minification glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); // don't repeat texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // don't repeat textureglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // don't repeat texture glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE); glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,imageWidth,imageHeight,0,GL_RGB,GL_UNSIGNED_BYTE,& textureObject); } void Object::Draw() const { // Enable vertex, normal and texture-coordinate arrays. glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // Bind the VBO with the normals. glBindBuffer(GL_ARRAY_BUFFER, m_NormalVBO); // The pointer for the normals is NULL which means that OpenGL will use the currently bound VBO. glNormalPointer(GL_FLOAT, 0, NULL); glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordVBO); glTexCoordPointer(2, GL_FLOAT, 0, NULL); glBindBuffer(GL_ARRAY_BUFFER, m_VertexVBO); glVertexPointer(3, GL_FLOAT, 0, NULL); // Render the triangles. glDrawArrays(GL_TRIANGLES, 0, m_TotalFaces * 3); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } 3dsloader.h #include "main.h" #include "lib3ds/file.h" #include "lib3ds/mesh.h" #include "lib3ds/material.h" class Object { public: Object(std:: string filename); virtual ~Object(); virtual void Draw() const; virtual void CreateVBO(); void applyTexture(const char*texfilename); protected: void GetFaces(); unsigned int m_TotalFaces; Lib3dsFile * m_model; Lib3dsMesh* Mesh; GLuint textureObject; GLuint m_VertexVBO, m_NormalVBO, m_TexCoordVBO; }; Called in the main cpp file with: VBO,apply texture and draw (pretty simple, how ironic) and thats it, please help me forum :)

    Read the article

  • Pythonika installation error on ubuntu 12

    - by user1426913
    I have been following links: to install pythonika on ubuntu: How to install Pythonika on Ubuntu? I get error: $ sudo make -f Makefile.linux cc -c Pythonika.c -I/usr/local/Wolfram/Mathematica/9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux/CompilerAdditions -I/usr/include/python2.7/ Pythonika.c: In function ‘PyUnicodeString’: Pythonika.c:109:5: warning: passing argument 1 of ‘PyUnicodeUCS4_FromUnicode’ from incompatible pointer type [enabled by default] /usr/include/python2.7/unicodeobject.h:464:23: note: expected ‘const Py_UNICODE *’ but argument is of type ‘short unsigned int *’ Pythonika.c: In function ‘python_to_mathematica_object’: Pythonika.c:411:13: warning: passing argument 2 of ‘MLPutUnicodeString’ from incompatible pointer type [enabled by default] /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux/CompilerAdditions/mathlink.h:4299:1: note: expected ‘const short unsigned int *’ but argument is of type ‘Py_UNICODE ’ "/usr/local/Wolfram/Mathematica/9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux/CompilerAdditions/mprep" Pythonika.tm -o Pythonikatm.c /bin/sh: 1: /usr/local/Wolfram/Mathematica/9.0/SystemFiles/Links/MathLink/DeveloperKit/Linux/CompilerAdditions/mprep: not found make: ** [Pythonikatm.o] Error 127

    Read the article

  • OpenGL error LNK2019

    - by Ghilliedrone
    I'm trying to compile a basic OpenGL program. I linked opengl32.lib and glu32.lib but I'm getting errors. The errors I get are: error LNK1120: 7 unresolved externals error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup error LNK2019: unresolved external symbol "public: float __thiscall GLWindow::getElapsedSeconds(void)" (?getElapsedSeconds@GLWindow@@QAEMXZ) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: bool __thiscall GLWindow::isRunning(void)" (?isRunning@GLWindow@@QAE_NXZ) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: void __thiscall GLWindow::attachExample(class Example *)" (?attachExample@GLWindow@@QAEXPAVExample@@@Z) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: void __thiscall GLWindow::destroy(void)" (?destroy@GLWindow@@QAEXXZ) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: __thiscall GLWindow::GLWindow(struct HINSTANCE__ *)" (??0GLWindow@@QAE@PAUHINSTANCE__@@@Z) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "private: void __thiscall GLWindow::setupPixelFormat(void)" (?setupPixelFormat@GLWindow@@AAEXXZ) referenced in function "public: long __stdcall GLWindow::WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@GLWindow@@QAGJPAUHWND__@@IIJ@Z)

    Read the article

  • What is the logic behind this C Program?

    - by iamanimesh19
    Here is a small piece of program (14 lines of program) which counts the number of bits set in a number. Input-Output -- 0--0(0000000), 5--2(0000101), 7--3(0000111) int CountBits (unsigned int x) { static unsigned int mask[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF } ; int i ; int shift ; /* Number of positions to shift to right*/ for (i =0, shift =1; i < 5; i ++, shift *= 2) x = (x & mask[i ])+ ( ( x >> shift) & mask[i]); return x; } Can someone explain the algorithm used here/why this works?

    Read the article

  • Getting current time in milliseconds

    - by user90293423
    How to get the current time in milliseconds? I'm working on a hacking simulation game and when ever someone connects to another computer/NPC, a login screen popups with a button on the side called BruteForce. When BruteForce is clicked, what i want the program to do is, calculate how many seconds cracking the password is going to take based on the player's CPU speed but that's the easy part. The hard part is i want to enter a character in the password's box every X milliseconds based on a TimeToCrack divided by PasswordLength formula. But since i don't know how to find how many milliseconds have elapsed since the second has passed, the program waits until the CurrentTime is higher than the TimeBeforeTheLoopStarted + HowLongItTakesToTypeaCharacter which is always going to be a second. How would you handle my problems? I've commented the game breaking part. std::vector<QString> hardware = user.getHardware(); QString CPU = hardware[0]; unsigned short Speed = 0; if(CPU == "OMG SingleCore 1.8GHZ"){ Speed = 2; } const short passwordLength = password.length(); /* It's equal to 16 */ int Time = passwordLength / Speed; double TypeSpeed = Time / passwordLength; time_t t = time(0); struct tm * now = localtime(&t); unsigned short EndTime = (now->tm_sec + Time) % 60; unsigned short CurrentTime = 0; short i = passwordLength - 1; do{ t = time(0); now = localtime(&t); CurrentTime = now->tm_sec; do{ t = time(0); now = localtime(&t); }while(now->tm_sec < CurrentTime + TypeSpeed); /* Highly flawed */ /* Do this while your integer value is under this double value */ QString tempPass = password; tempPass.chop(i); ui->lineEdit_2->setText(tempPass); i--; }while(CurrentTime != EndTime);

    Read the article

  • How optimize code with introspection + heavy alloc on iPhone

    - by mamcx
    I have a problem. I try to display a UITable that could have 2000-20000 records (typicall numbers.) I have a SQLite database similar to the Apple contacts application. I do all the tricks I know to get a smoth scroll, but I have a problem. I load the data in 50 recods blocks. Then, when the user scroll, request next 50 until finish the list. However, load that 50 records cause a notable "pause" in loading and scrolling. Everything else works fine. I cache the data, have opaque cells, draw it by code, etc... I swap the code loading the same data in dicts and have a performance boost but wonder if I could keep my object oriented aproach and improve the actual code. This is the code I think have the performance problem: -(NSArray *) loadAndFill: (NSString *)sql theClass: (Class)cls { [self openDb]; NSMutableArray *list = [NSMutableArray array]; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; DbObject *ds; Class myClass = NSClassFromString([DbObject getTableName:cls]); FMResultSet *rs = [self load:sql]; while ([rs next]) { ds = [[myClass alloc] init]; NSDictionary *props = [ds properties]; NSString *fieldType = nil; id fieldValue; for (NSString *fieldName in [props allKeys]) { fieldType = [props objectForKey: fieldName]; fieldValue = [self ValueForField:rs Name:fieldName Type:fieldType]; [ds setValue:fieldValue forKey:fieldName]; } [list addObject :ds]; [ds release]; } [rs close]; [pool drain]; return list; } And I think the main culprit is: -(id) ValueForField: (FMResultSet *)rs Name:(NSString *)fieldName Type:(NSString *)fieldType { id fieldValue = nil; if ([fieldType isEqualToString:@"i"] || // int [fieldType isEqualToString:@"I"] || // unsigned int [fieldType isEqualToString:@"s"] || // short [fieldType isEqualToString:@"S"] || // unsigned short [fieldType isEqualToString:@"f"] || // float [fieldType isEqualToString:@"d"] ) // double { fieldValue = [NSNumber numberWithInt: [rs longForColumn:fieldName]]; } else if ([fieldType isEqualToString:@"B"]) // bool or _Bool { fieldValue = [NSNumber numberWithBool: [rs boolForColumn:fieldName]]; } else if ([fieldType isEqualToString:@"l"] || // long [fieldType isEqualToString:@"L"] || // usigned long [fieldType isEqualToString:@"q"] || // long long [fieldType isEqualToString:@"Q"] ) // unsigned long long { fieldValue = [NSNumber numberWithLong: [rs longForColumn:fieldName]]; } else if ([fieldType isEqualToString:@"c"] || // char [fieldType isEqualToString:@"C"] ) // unsigned char { fieldValue = [rs stringForColumn:fieldName]; //Is really a boolean? if ([fieldValue isEqualToString:@"0"] || [fieldValue isEqualToString:@"1"]) { fieldValue = [NSNumber numberWithInt: [fieldValue intValue]]; } } else if ([fieldType hasPrefix:@"@"] ) // Object { NSString *className = [fieldType substringWithRange:NSMakeRange(2, [fieldType length]-3)]; if ([className isEqualToString:@"NSString"]) { fieldValue = [rs stringForColumn:fieldName]; } else if ([className isEqualToString:@"NSDate"]) { NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; NSString *theDate = [rs stringForColumn:fieldName]; if (theDate) { fieldValue = [dateFormatter dateFromString: theDate]; } else { fieldValue = nil; } [dateFormatter release]; } else if ([className isEqualToString:@"NSInteger"]) { fieldValue = [NSNumber numberWithInt: [rs intForColumn :fieldName]]; } else if ([className isEqualToString:@"NSDecimalNumber"]) { fieldValue = [rs stringForColumn :fieldName]; if (fieldValue) { fieldValue = [NSDecimalNumber decimalNumberWithString:[rs stringForColumn :fieldName]]; } } else if ([className isEqualToString:@"NSNumber"]) { fieldValue = [NSNumber numberWithDouble: [rs doubleForColumn:fieldName]]; } else { //Is a relationship one-to-one? if (![fieldType hasPrefix:@"NS"]) { id rel = class_createInstance(NSClassFromString(className), sizeof(unsigned)); Class theClass = [rel class]; if ([rel isKindOfClass:[DbObject class]]) { fieldValue = [rel init]; //Load the record... NSInteger Id = [rs intForColumn:[theClass relationName]]; if (Id>0) { [fieldValue release]; Db *db = [Db currentDb]; fieldValue = [db loadById: theClass theId:Id]; } } } else { NSString *error = [NSString stringWithFormat:@"Err Can't get value for field %@ of type %@", fieldName, fieldType]; NSLog(error); NSException *e = [NSException exceptionWithName:@"DBError" reason:error userInfo:nil]; @throw e; } } } return fieldValue; }

    Read the article

  • Mysql query help - Alter this mysql query to get these results?

    - by sandeepan-nath
    Please execute the following queries first to set up so that you can help me:- CREATE TABLE IF NOT EXISTS `Tutor_Details` ( `id_tutor` int(10) NOT NULL auto_increment, `firstname` varchar(100) NOT NULL default '', `surname` varchar(155) NOT NULL default '', PRIMARY KEY (`id_tutor`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=41 ; INSERT INTO `Tutor_Details` (`id_tutor`,`firstname`, `surname`) VALUES (1, 'Sandeepan', 'Nath'), (2, 'Bob', 'Cratchit'); CREATE TABLE IF NOT EXISTS `Classes` ( `id_class` int(10) unsigned NOT NULL auto_increment, `id_tutor` int(10) unsigned NOT NULL default '0', `class_name` varchar(255) default NULL, PRIMARY KEY (`id_class`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ; INSERT INTO `Classes` (`id_class`,`class_name`, `id_tutor`) VALUES (1, 'My Class', 1), (2, 'Sandeepan Class', 2); CREATE TABLE IF NOT EXISTS `Tags` ( `id_tag` int(10) unsigned NOT NULL auto_increment, `tag` varchar(255) default NULL, PRIMARY KEY (`id_tag`), UNIQUE KEY `tag` (`tag`), KEY `id_tag` (`id_tag`), KEY `tag_2` (`tag`), KEY `tag_3` (`tag`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ; INSERT INTO `Tags` (`id_tag`, `tag`) VALUES (1, 'Bob'), (6, 'Class'), (2, 'Cratchit'), (4, 'Nath'), (3, 'Sandeepan'), (5, 'My'); CREATE TABLE IF NOT EXISTS `Tutors_Tag_Relations` ( `id_tag` int(10) unsigned NOT NULL default '0', `id_tutor` int(10) default NULL, KEY `Tutors_Tag_Relations` (`id_tag`), KEY `id_tutor` (`id_tutor`), KEY `id_tag` (`id_tag`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `Tutors_Tag_Relations` (`id_tag`, `id_tutor`) VALUES (3, 1), (4, 1), (1, 2), (2, 2); CREATE TABLE IF NOT EXISTS `Class_Tag_Relations` ( `id_tag` int(10) unsigned NOT NULL default '0', `id_class` int(10) default NULL, `id_tutor` int(10) NOT NULL, KEY `Class_Tag_Relations` (`id_tag`), KEY `id_class` (`id_class`), KEY `id_tag` (`id_tag`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `Class_Tag_Relations` (`id_tag`, `id_class`, `id_tutor`) VALUES (5, 1, 1), (6, 1, 1), (3, 2, 2), (6, 2, 2); In the present system data which I have given , tutor named "Sandeepan Nath" has has created class named "My Class" and tutor named "Bob Cratchit" has created class named "Sandeepan Class". Requirement - To execute a single query with limit on the results to show search results as per AND logic on the search keywords like this:- If "Sandeepan Class" is searched , Tutor Sandeepan Nath's record from Tutor Details table is returned(because "Sandeepan" is the firstname of Sandeepan Nath and Class is present in class name of Sandeepan's class) If "Class" is searched Both the tutors from the Tutor_details table are fetched because Class is present in the name of the class created by both the tutors. Following is what I have so far achieved (PHP Mysql):- <?php $searchTerm1 = "Sandeepan"; $searchTerm2 = "Class"; mysql_select_db("test"); $sql = "SELECT td.* FROM Tutor_Details AS td LEFT JOIN Tutors_Tag_Relations AS ttagrels ON td.id_tutor = ttagrels.id_tutor LEFT JOIN Classes AS wc ON td.id_tutor = wc.id_tutor LEFT JOIN Class_Tag_Relations AS wtagrels ON td.id_tutor = wtagrels.id_tutor LEFT JOIN Tags as t1 on ((t1.id_tag = ttagrels.id_tag) OR (t1.id_tag = wtagrels.id_tag)) LEFT JOIN Tags as t2 on ((t2.id_tag = ttagrels.id_tag) OR (t2.id_tag = wtagrels.id_tag)) where t1.tag LIKE '%".$searchTerm1."%' AND t2.tag LIKE '%".$searchTerm2."%' GROUP BY td.id_tutor LIMIT 10 "; $result = mysql_query($sql); echo $sql; if($result) { while($rec = mysql_fetch_object($result)) $recs[] = $rec; //$rec = mysql_fetch_object($result); echo "<br><br>"; if(is_array($recs)) { foreach($recs as $each) { print_r($each); echo "<br>"; } } } ?> But the results are :- If "Sandeepan Nath" is searched, it does not return any tutor (instead of only Sandeepan's row) If "Sandeepan Class" is searched, it returns Sandeepan's row (instead of Both tutors ) If "Bob Class" is searched, it correctly returns Bob's row If "Bob Cratchit" is searched, it does not return any tutor (instead of only

    Read the article

  • Getting timing consistency in Linux

    - by Jim Hunziker
    I can't seem to get a simple program (with lots of memory access) to achieve consistent timing in Linux. I'm using a 2.6 kernel, and the program is being run on a dual-core processor with realtime priority. I'm trying to disable cache effects by declaring the memory arrays as volatile. Below are the results and the program. What are some possible sources of the outliers? Results: Number of trials: 100 Range: 0.021732s to 0.085596s Average Time: 0.058094s Standard Deviation: 0.006944s Extreme Outliers (2 SDs away from mean): 7 Average Time, excluding extreme outliers: 0.059273s Program: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sched.h> #include <sys/time.h> #define NUM_POINTS 5000000 #define REPS 100 unsigned long long getTimestamp() { unsigned long long usecCount; struct timeval timeVal; gettimeofday(&timeVal, 0); usecCount = timeVal.tv_sec * (unsigned long long) 1000000; usecCount += timeVal.tv_usec; return (usecCount); } double convertTimestampToSecs(unsigned long long timestamp) { return (timestamp / (double) 1000000); } int main(int argc, char* argv[]) { unsigned long long start, stop; double times[REPS]; double sum = 0; double scale, avg, newavg, median; double stddev = 0; double maxval = -1.0, minval = 1000000.0; int i, j, freq, count; int outliers = 0; struct sched_param sparam; sched_getparam(getpid(), &sparam); sparam.sched_priority = sched_get_priority_max(SCHED_FIFO); sched_setscheduler(getpid(), SCHED_FIFO, &sparam); volatile float* data; volatile float* results; data = calloc(NUM_POINTS, sizeof(float)); results = calloc(NUM_POINTS, sizeof(float)); for (i = 0; i < REPS; ++i) { start = getTimestamp(); for (j = 0; j < NUM_POINTS; ++j) { results[j] = data[j]; } stop = getTimestamp(); times[i] = convertTimestampToSecs(stop-start); } free(data); free(results); for (i = 0; i < REPS; i++) { sum += times[i]; if (times[i] > maxval) maxval = times[i]; if (times[i] < minval) minval = times[i]; } avg = sum/REPS; for (i = 0; i < REPS; i++) stddev += (times[i] - avg)*(times[i] - avg); stddev /= REPS; stddev = sqrt(stddev); for (i = 0; i < REPS; i++) { if (times[i] > avg + 2*stddev || times[i] < avg - 2*stddev) { sum -= times[i]; outliers++; } } newavg = sum/(REPS-outliers); printf("Number of trials: %d\n", REPS); printf("Range: %fs to %fs\n", minval, maxval); printf("Average Time: %fs\n", avg); printf("Standard Deviation: %fs\n", stddev); printf("Extreme Outliers (2 SDs away from mean): %d\n", outliers); printf("Average Time, excluding extreme outliers: %fs\n", newavg); return 0; }

    Read the article

< Previous Page | 56 57 58 59 60 61 62 63 64 65 66 67  | Next Page >