int main(int argc, char* argv[]) { // read the file into a buffer std::ifstream ifs(argv[1], std::ios::binary); std::string buffer((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); // create a new file if we're trying to comrpess an empty file if (!buffer.size()) { std::ofstream ofs(argv[2], std::ios::binary); exit(0); } // count the occurences of each char std::vector<int> freqs(256, 0); for (size_t i = 0; i < buffer.size(); ++i) { byte b = buffer[i]; ++freqs[b]; } // build the HCTree HCTree hct; hct.build(freqs); // output the compressed file std::ofstream ofs(argv[2], std::ios::binary); BitOutputStream bos(ofs); makeHeader(ofs, freqs); for (size_t i = 0; i < buffer.size(); ++i) { hct.encode(buffer[i], bos); } return 0; }
void MinosTestExport::exportEntry( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->mycall.fullCall.addIfDirty( st, "call", dirty ); ct->entrant.addIfDirty( st, "entrant", dirty ); ct->entName.addIfDirty( st, "myName", dirty ); ct->entCall.addIfDirty( st, "myCall", dirty ); ct->entAddr1.addIfDirty( st, "myAddress1", dirty ); ct->entAddr2.addIfDirty( st, "myAddress2", dirty ); ct->entCity.addIfDirty( st, "myCity", dirty ); ct->entCountry.addIfDirty( st, "myCountry", dirty ); ct->entPostCode.addIfDirty( st, "myPostCode", dirty ); ct->entPhone.addIfDirty( st, "myPhone", dirty ); ct->entEMail.addIfDirty( st, "myEmail", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogEntry", st ); stanzaCount++; } else { delete st; } }
void MinosTestExport::exportContest( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->name.addIfDirty( st, "name", dirty ); ct->band.addIfDirty( st, "band", dirty ); ct->entSect.addIfDirty( st, "section", dirty ); ct->sectionList.addIfDirty( st, "sectionList", dirty ); if ( ct->scoreMode.isDirty() ) { st->addMember( ( ct->scoreMode.getValue( dirty ) == PPKM ), "scoreKms" ); } ct->DTGStart.addIfDirty( st, "startTime", dirty ); ct->DTGEnd.addIfDirty( st, "endTime", dirty ); ct->districtMult.addIfDirty( st, "districtMult", dirty ); ct->countryMult.addIfDirty( st, "DXCCMult", dirty ); ct->locMult.addIfDirty( st, "locMult", dirty ); ct->otherExchange.addIfDirty( st, "QTHReq", dirty ); ct->allowLoc4.addIfDirty( st, "AllowLoc4", dirty ); ct->allowLoc8.addIfDirty( st, "AllowLoc8", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogContest", st ); stanzaCount++; } else { delete st; } }
int MinosTestExport::exportComment( HANDLE expfd, const ContestContact *lct ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; if ( lct->time.isDirty() ) { st->addDtgMember( lct->time.getIsoDTG( dirty ), "logTime" ); } if ( lct->contactFlags.isDirty() ) { st->addMember( bool( lct->contactFlags.getValue( dirty ) & LOCAL_COMMENT != 0 ), "LocalComment" ); st->addMember( bool( lct->contactFlags .getValue( dirty ) & DONT_PRINT != 0 ), "DontPrint" ); } lct->comments.addIfDirty( st, "comment", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogComment", st ); stanzaCount++; return 1; } else { delete st; return 0; } }
// Does the first sbrk, makes the first header, and mallocs the // first block header *firstMalloc(size_t size) { header *headerPointer = (header *) sbrk(BREAK_INCREMENT); makeHeader(headerPointer); head = headerPointer; mallocForTailHeader(headerPointer, size); return headerPointer; }
int MinosTestExport::exportQSO( HANDLE expfd, const ContestContact *lct ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, lct->getLogSequence() ); bool dirty = false; if ( lct->time.isDirty() ) { st->addDtgMember( lct->time.getIsoDTG( dirty ), "logTime" ); } if ( lct->contactFlags.isDirty() ) { st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & VALID_DISTRICT ) != 0 ), "validDistrict" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & COUNTRY_FORCED ) != 0 ), "countryForced" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & UNKNOWN_COUNTRY ) != 0 ), "unknownCountry" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & NON_SCORING ) != 0 ), "nonScoring" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & MANUAL_SCORE ) != 0 ), "manualScore" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & DONT_PRINT ) != 0 ), "dontPrint" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & VALID_DUPLICATE ) != 0 ), "validDuplicate" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & TO_BE_ENTERED ) != 0 ), "toBeEntered" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & XBAND ) != 0 ), "xBand" ); st->addMember( bool( ( lct->contactFlags.getValue( dirty ) & FORCE_LOG ) != 0 ), "Forced" ); } lct->cs.fullCall.addIfDirty( st, "callRx", dirty ); lct->reps.addIfDirty( st, "rstTx", dirty ); lct->serials.addIfDirty( st, "serialTx", dirty ); // lct->extraText.addIfDirty(st, "exchangeTx", dirty); lct->repr.addIfDirty( st, "rstRx", dirty ); lct->serialr.addIfDirty( st, "serialRx", dirty ); lct->loc.loc.addIfDirty( st, "locRx", dirty ); lct->extraText.addIfDirty( st, "exchangeRx", dirty ); lct->extraText.addIfDirty( st, "qthRx", dirty ); lct->comments.addIfDirty( st, "commentsTx", dirty ); lct->comments.addIfDirty( st, "commentsRx", dirty ); lct->mode.addIfDirty( st, "modeTx", dirty ); lct->mode.addIfDirty( st, "modeRx", dirty ); ct->power.addIfDirty( st, "power", dirty ); ct->band.addIfDirty( st, "band", dirty ); lct->forcedMult.addIfDirty( st, "forcedMult", dirty ); lct->contactScore.addIfDirty( st, "claimedScore", dirty ); lct->op1.addIfDirty( st, "op1", dirty ); lct->op2.addIfDirty( st, "op2", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogQSO", st ); stanzaCount++; return 1; } else { delete st; return 0; } }
int makeSendMsg(UINT8 *body, UINT32 encryptLen,UINT16 cmdType, UINT8 *sendbuf) { UINT16 crc; makeHeader(cmdType, encryptLen, sendbuf); makeBody(body, encryptLen, sendbuf); crc=getCRC16(sendbuf, 10+encryptLen); makeTail(crc, encryptLen, sendbuf); return 0; }
void Writer::open(const std::string &filename) { MLSGPU_ASSERT(!isOpen(), state_error); handle = handleFactory(); handle->open(filename); std::string header = makeHeader(); handle->resize(header.size() + getNumVertices() * vertexSize + getNumTriangles() * triangleSize); handle->write(header.data(), header.size(), 0); vertexStart = header.size(); triangleStart = vertexStart + getNumVertices() * vertexSize; }
void MinosTestExport::exportMode( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->readOnly.addIfDirty( st, "readOnly", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogMode", st ); stanzaCount++; } else { delete st; } }
int fileWriteHeader(struct Container * container) { struct Header * header = makeHeader(container); switch (container->storage->status) { case STORAGE_OPEN: lseek((int) container->storage->base[FILE_BASE_IND]->handle, (off_t) 0, SEEK_SET); fwrite(header, sizeof(struct Header), 1, container->storage->base[FILE_BASE_IND]->handle); fflush(container->storage->base[FILE_BASE_IND]->handle); break; case STORAGE_CLOSED: case STORAGE_UNDEF: case STORAGE_REMOVED: default: free(header); printf("unsupported storage status\n"); } return 0; }
void MinosTestExport::exportCurrent( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->entCondx1.addIfDirty( st, "condx1", dirty ); ct->entCondx2.addIfDirty( st, "condx2", dirty ); ct->entCondx3.addIfDirty( st, "condx3", dirty ); ct->entCondx4.addIfDirty( st, "condx4", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogCurrent", st ); stanzaCount++; } else { delete st; } }
void MinosTestExport::exportOperators( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->ops1.addIfDirty( st, "ops1", dirty ); ct->ops2.addIfDirty( st, "ops2", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogOperators", st ); stanzaCount++; } else { delete st; } }
void MinosTestExport::exportStation( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->power.addIfDirty( st, "power", dirty ); ct->entTx.addIfDirty( st, "transmitter", dirty ); ct->entRx.addIfDirty( st, "receiver", dirty ); ct->entAnt.addIfDirty( st, "antenna", dirty ); ct->entAGL.addIfDirty( st, "AGL", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogStation", st ); stanzaCount++; } else { delete st; } }
extern "C" Lz4MtResult lz4mtCompress(Lz4MtContext* lz4MtContext, const Lz4MtStreamDescriptor* sd) { assert(lz4MtContext); assert(sd); const Params params(lz4MtContext, sd); Ctx ctx(lz4MtContext); makeHeader(ctx, sd); if(LZ4MT_RESULT_OK != ctx.result()) { return ctx.result(); } Lz4Mt::Xxh32 xxhStream(LZ4S_CHECKSUM_SEED); if(sd->flg.blockIndependence) { compress(ctx, params, xxhStream); } else { compressBlockDependency(ctx, params, xxhStream); } if(LZ4MT_RESULT_OK != ctx.result()) { return ctx.result(); } if(!ctx.writeU32(LZ4S_EOS)) { return ctx.quit(LZ4MT_RESULT_CANNOT_WRITE_EOS); } if(params.streamChecksum) { const auto digest = xxhStream.digest(); if(!ctx.writeU32(digest)) { return ctx.quit(LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM); } } return LZ4MT_RESULT_OK; }
bool RSReflectionCpp::reflect(const string &OutputPathBase, const string &InputFileName, const string &OutputBCFileName) { mInputFileName = InputFileName; mOutputPath = OutputPathBase; mOutputBCFileName = OutputBCFileName; mClassName = string("ScriptC_") + stripRS(InputFileName); makeHeader("android::renderscriptCpp::ScriptC"); std::vector< std::string > header(mText); mText.clear(); makeImpl("android::renderscriptCpp::ScriptC"); std::vector< std::string > cpp(mText); mText.clear(); RSReflectionBase::writeFile(mClassName + ".h", header); RSReflectionBase::writeFile(mClassName + ".cpp", cpp); return false; }
void MinosTestExport::exportQTH( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); bool dirty = false; ct->myloc.loc.addIfDirty( st, "locator", dirty ); ct->location.addIfDirty( st, "district", dirty ); // We need to differentiate location from exchange! ct->location.addIfDirty( st, "location", dirty ); ct->sqth1.addIfDirty( st, "stationQTH1", dirty ); ct->sqth2.addIfDirty( st, "stationQTH2", dirty ); ct->entASL.addIfDirty( st, "ASL", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogQTH", st ); stanzaCount++; } else { delete st; } }
static LRESULT CALLBACK tableWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { struct table *t; LRESULT lResult; t = (struct table *) GetWindowLongPtrW(hwnd, GWLP_USERDATA); if (t == NULL) { // we have to do things this way because creating the header control will fail mysteriously if we create it first thing // (which is fine; we can get the parent hInstance this way too) // we use WM_CREATE because we have to use WM_DESTROY to destroy the header; we can't do it in WM_NCDESTROY because Windows will have destroyed it for us by then, and let's match message pairs to be safe if (uMsg == WM_CREATE) { CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam; t = (struct table *) tableAlloc(sizeof (struct table), "error allocating internal Table data structure"); t->hwnd = hwnd; makeHeader(t, cs->hInstance); t->selectedRow = -1; t->selectedColumn = -1; initDummyTableStuff(t); SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) t); } // even if we did the above, fall through return DefWindowProcW(hwnd, uMsg, wParam, lParam); } if (uMsg == WM_DESTROY) { printf("destroy\n"); // TODO free appropriate (after figuring this part out) components of t // TODO send EVENT_OBJECT_DESTROY events to accessibility listeners (when appropriate); see the note on proxy objects as well destroyHeader(t); tableFree(t, "error allocating internal Table data structure"); return DefWindowProcW(hwnd, uMsg, wParam, lParam); } if (runHandlers(handlers, t, uMsg, wParam, lParam, &lResult)) return lResult; return DefWindowProcW(hwnd, uMsg, wParam, lParam); }
int makeRequest(char* IP, char* request){ struct DNSHeader head; makeHeader(&head); memcpy(request,&head,12); //convert ip to correct format int placeholder = 0; int length = 0; char name[30] = ""; char *token; // break IP into chunks using strtok and concatanate with "." token = strtok(IP,"."); while(token != NULL){ if(name == NULL){ placeholder = 0; }else{ placeholder = strlen(name); } name[placeholder] = strlen(token); strcat(name,token); token = strtok(NULL,"."); } length = strlen(name); // add char post[5]; memcpy(request+12,name,length); post[0] = 0; post[1] = 0; post[2] = 1; post[3] = 0; post[4] = 1; memcpy(request+12+length,post,5); length = length + 17; return length; }
void MinosTestExport::exportBundles( HANDLE expfd ) { RPCParamStruct * st = new RPCParamStruct; makeHeader( st, 1 ); // This wants "useBundles"(?) and the bundle names selected bool dirty = false; ct->entryBundleName.addIfDirty( st, "entryBundle", dirty ); ct->QTHBundleName.addIfDirty( st, "QTHBundle", dirty ); ct->stationBundleName.addIfDirty( st, "stationBundle", dirty ); ct->VHFContestName.addIfDirty(st, "VHFContestName", dirty ); if ( dirty ) { sendRequest( expfd, "MinosLogBundles", st ); stanzaCount++; } else { delete st; } }
static PyObject * spec_get_source_header(specObject *s, void *closure) { return makeHeader(rpmSpecSourceHeader(s->spec)); }
bool ModuleMap::saveCachedMap(DataBuffer& mapBuffer, const GenericMap* theMap, uint32 loadMapRequestType, uint32 mapVersion, uint32 generatorVersion, bool update, byte zoomlevel) { uint32 mapID = theMap->getMapID(); MC2String finalFileName( ModuleMap::getCacheFilename(mapID, loadMapRequestType, zoomlevel) ); if ( update && cacheIsUpToDate(theMap->getMapID(), theMap->getFilename(), loadMapRequestType, zoomlevel) ){ return true; } const char* fileName = finalFileName.c_str(); MC2String tmpDir = ModuleMap::getCachePath(); if ( tmpDir[0] == '\0' ) { mc2log << info << "[ModuleMap]: No cachepath set - will not save " << "map 0x" << hex << mapID << dec << endl; return false; } else { mc2log << info << "[ModuleMap]: Will try to save " << MC2CITE(fileName) << endl; } char tempTemplate[1024]; sprintf(tempTemplate, "%scachingXXXXXX", tmpDir.c_str()); int tmpDesc = mkstemp(tempTemplate); MC2String tempName = MC2String(tempTemplate); // Remove the old file if there is one ( to make space for new map ) mc2dbg << "[ModuleMap]: Removing " << MC2CITE(fileName) << " if it exists" << endl; unlink(fileName); int headerSize; byte* header = makeHeader( headerSize, mapID, mapVersion, generatorVersion); FILE* writeFile = NULL; if ( tmpDesc < 0 ) { mc2dbg << "[ModuleMap]: Could not make tempfile" << endl; writeFile = NULL; return false; } else { writeFile = fdopen(tmpDesc, "w"); if ( header ) { if ( fwrite(header, headerSize, 1, writeFile) != 1 ) { mc2dbg << "[ModuleMap]: Could not write header: " << strerror(errno) << endl; fclose(writeFile); unlink(tempName.c_str()); writeFile = NULL; return false; } } else { mc2log << "[ModuleMap]: Header is NULL" << endl; return false; } } delete [] header; MC2_ASSERT( writeFile != NULL ); // Now the header should be written. if ( fwrite(mapBuffer.getBufferAddress(), mapBuffer.getBufferSize(), 1, writeFile) != 1 ) { fclose(writeFile); unlink(tempName.c_str()); writeFile = NULL; mc2dbg << "[ModuleMap]: Could not write map data" << endl; return false; } else { rename(tempName.c_str(), fileName); chmod (fileName, (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) ); fclose(writeFile); mc2log << info << "[ModuleMap]: Map 0x" << hex << mapID << dec << " saved." << endl; return true; } }
int main(int argc, char *argv[]) { fd_set master; fd_set read_fds; struct sockaddr_in serveraddr; struct sockaddr_in clientaddr; char buf[1024]; int fdmax, listener, newfd, nbytes, i, j, addrlen, rc; int yes = 1; int ClientID = 0; int win_num[10]; for (i = 0; i < 100; i++) win_num[i] = 0; //this array stores the bet generated by every client, it is initialized to zero int WinningNumber = GenerateWinningNumber(BEGASEP_NUM_MIN, BEGASEP_NUM_MAX); //at the start of a program a winning nnumber is generated and after every timeout a new winning number is generated struct timeval timeout; /* clear the master sets */ FD_ZERO(&master); FD_ZERO(&read_fds); /* get the listener */ if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Server-socket() error!"); exit(1); } printf("Server-socket() is OK...\n"); //address already in use error message , although I have set this option but still sometimes the program is giving this error if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("Server-setsockopt() error lol!"); exit(1); } printf("Server-setsockopt() is OK...\n"); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = INADDR_ANY; serveraddr.sin_port = htons(2222); memset(&(serveraddr.sin_zero), '\0', 8); if (bind(listener, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) == -1) { perror("Server-bind() Error!"); exit(1); } printf("Server-bind() is OK...\n"); if (listen(listener, 10) == -1) { perror("Server-listen() Error!"); exit(1); } printf("Server-listen() is OK...\n"); // add the listener to the master set FD_SET(listener, &master); // keep track of the biggest file descriptor fdmax = listener; for (;;) { read_fds = master; timeout.tv_sec = 15; //set the timeout for the select statement as 15 seconds timeout.tv_usec = 0; rc = (select(fdmax + 1, &read_fds, NULL, NULL, &timeout)); if (rc < 0) { perror("Server-select() error !"); //if there is some error in the select the program will exit exit(1); } if (rc == 0) //rc is set to 0 , whenever time out takes place, in our case it is 15 secs { printf("Time Out\n"); for (i = 1; i <= fdmax; i++) { if (i == listener) { } else { if (win_num[i] == -1) { //this is a case for the client who did submitted a bet but it was invalid. close(i); FD_CLR(i, &master); } else //this case is for the client who did submit a bet { Begasep_ResultMsg ResultMessage; if (WinningNumber == win_num[i]) ResultMessage.ResultStatus = 1; //if the submitted bet is equal to the winning number else ResultMessage.ResultStatus = 0; //the final BEGASEP_RESULT message is sent to all connected client who did submit a reques Begasep_CommonHeader SendHeader; ResultMessage.WinningNumber = WinningNumber; makeHeader(PROTOCOL_VERSION, BEGASEP_RESULT, sizeof(SendHeader) + sizeof(ResultMessage), i, &SendHeader); if (send(i, (Begasep_CommonHeader*) &SendHeader, sizeof(SendHeader), 0) == -1) { } else { if (send(i, (Begasep_ResultMsg*) &ResultMessage, sizeof(ResultMessage), 0) == -1) { } else { printf( "\n\nServer Sends time out msg **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", SendHeader.ProtocolVersion, SendHeader.PacketType, SendHeader.PacketLength, i); printf( " **** |Bet Status %d | Winning number %d | \n", ResultMessage.ResultStatus, ResultMessage.WinningNumber); close(i); FD_CLR(i, &master); WinningNumber = GenerateWinningNumber( BEGASEP_NUM_MIN, BEGASEP_NUM_MAX); //at the end of every time out a new winning number is generated for the next session } } } } } } for (i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) //now one by one we check all the descriptors as if they are set or not. { //printf("socket %d %d is set \n",i,fdmax); if (i == listener) { /* handle new connections */ addrlen = sizeof(clientaddr); if ((newfd = accept(listener, (struct sockaddr *) &clientaddr, &addrlen)) == -1) perror("Server-accept() !"); else { printf("Server-accept() is OK...\n"); FD_SET(newfd, &master); /* add to master set */ if (newfd > fdmax) { fdmax = newfd; } printf("%s: New connection from %s on socket %d\n", argv[0], inet_ntoa(clientaddr.sin_addr), newfd); } } else { Begasep_CommonHeader RecvHeader; Begasep_CommonHeader SendHeader; if ((recv(i, &RecvHeader, sizeof(RecvHeader), 0)) <= 0) { //this call receives a header and based on the type of packet value present in the header, choose a case to be executed perror("recv"); ; close(i); FD_CLR(i, &master); } else { printf( "\n\nServer Receives **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", RecvHeader.ProtocolVersion, RecvHeader.PacketType, RecvHeader.PacketLength, RecvHeader.ClientId); switch ((unsigned) (RecvHeader.PacketType)) { case BEGASEP_OPEN: //if the packet type field in the header is BEGASEP_OPEN then this case is selected { ClientID = i; //the client ID is set as the unique socket descriptor of that connection, that way the uniquness of the ID is automatically handled Begasep_AcceptMsg AcceptMessage; AcceptMessage.LowerEndofNumber = BEGASEP_NUM_MIN; AcceptMessage.UpperEndofNumber = BEGASEP_NUM_MAX; //header for BEGASEP_ACCEPT is created makeHeader(PROTOCOL_VERSION, BEGASEP_ACCEPT, sizeof(SendHeader) + sizeof(AcceptMessage), ClientID, &SendHeader); //header for the BEGASEP_ACCEPT is sent to the client if (send(i, (Begasep_CommonHeader*) &SendHeader, sizeof(SendHeader), 0) == -1) perror("send"); //in response BEGASEP_ACCEPT is sent to the client if (send(i, (Begasep_AcceptMsg*) &AcceptMessage, sizeof(AcceptMessage), 0) == -1) perror("send"); printf( "\n\nServer Sends **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", SendHeader.ProtocolVersion, SendHeader.PacketType, SendHeader.PacketLength, SendHeader.ClientId); printf( " **** | Minimum Limit = %d | Maximum Limit %d | \n", AcceptMessage.LowerEndofNumber, AcceptMessage.UpperEndofNumber); break; } case BEGASEP_BET: //he packet type field in the header is BEGASEP_BET then this case is selected printf(""); Begasep_BetMsg BetMessage; if ((recv(i, &BetMessage, sizeof(BetMessage), 0)) <= 0) { perror("recv"); exit(1); } printf(" **** |Bet made = %d |\n", BetMessage.ClientBet); //this is a case if the bet made by the client is not within the specified limit so the socket si simply closed if (BetMessage.ClientBet <= BEGASEP_NUM_MIN || BetMessage.ClientBet >= BEGASEP_NUM_MAX) { printf("Bet made was not within the limit\n"); win_num[i] = -1; close(i); FD_CLR(i, &master); } else { printf("Client made a valid Bet\n"); Begasep_ResultMsg ResultMessage; win_num[i] = BetMessage.ClientBet; } break; } } } } } } printf("I am going to close too \n"); return 0; }
void appendFile(int fd, char *fName){ int fdSource; char *buffer; int fileLen; char *fileBuffer = NULL; int num_read; int i; struct ar_hdr header; fdSource = open(fName, O_RDONLY); if (fdSource < 0) { perror("Error while opening file to add to the archive."); exit(EXIT_FAILURE); } makeHeader(&header, fdSource, fName); //read file into memory fileLen = (int)atoi(header.ar_size); fileBuffer = (char*)malloc(fileLen); num_read = read(fdSource, fileBuffer, fileLen); if (num_read < 0) { close(fdSource); perror("Error while reading the file to add to the archive.\n"); exit(EXIT_FAILURE); } buffer = (char*)malloc(60); for(i = 0;i<60;i++)//clear the buffer buffer[i] = ' '; for(i = 0;i<60;i++) buffer[i] = header.ar_name[i]; //write header to archive num_read = write(fd, buffer, 60); if (num_read < 0) { close(fd); perror("Error while writing the archive file.\n"); exit(EXIT_FAILURE); } //fileBuffer = strcat(fileBuffer, (char *)buffer); //write file to archive num_read = write(fd, fileBuffer, fileLen); if (num_read < 0) { close(fd); perror("Error while writing the archive file.\n"); exit(EXIT_FAILURE); } //if odd file lenght write newline to end of archive if(fileLen%2!=0){ buffer[0] = '\n'; num_read = write(fd, buffer , 1); if (num_read < 0) { close(fd); perror("Error while writing the archive file.\n"); exit(EXIT_FAILURE); } } free(buffer); free(fileBuffer); close(fdSource); }
return &(((struct sockaddr_in6*) sa)->sin6_addr); } int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[1024]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; if (argc != 2) { fprintf(stderr, "usage: client hostname\n"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can./client 127.0.0.1 for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *) p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure Begasep_CommonHeader SendHeader; Begasep_CommonHeader RecvHeader; makeHeader(PROTOCOL_VERSION, BEGASEP_OPEN, sizeof(SendHeader), 0, &SendHeader); if (send(sockfd, (Begasep_CommonHeader*) &SendHeader, sizeof(SendHeader), 0) == -1) perror("send"); printf( "Client Sends **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", SendHeader.ProtocolVersion, SendHeader.PacketType, SendHeader.PacketLength, SendHeader.ClientId); int ResultReceived = 0; while (1) { if ((recv(sockfd, &RecvHeader, sizeof(RecvHeader), 0)) <= 0) { perror("recv invalid Bet"); close(sockfd); exit(1); } printf( "\n\nClient Receives **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", RecvHeader.ProtocolVersion, RecvHeader.PacketType, RecvHeader.PacketLength, RecvHeader.ClientId); switch (RecvHeader.PacketType) { case BEGASEP_ACCEPT: printf(""); Begasep_AcceptMsg AcceptMessage; if ((recv(sockfd, &AcceptMessage, sizeof(AcceptMessage), 0)) <= 0) { perror("recv"); exit(1); } printf( " **** |Minimum Limit = %d | Maximum Limit %d | \n", AcceptMessage.LowerEndofNumber, AcceptMessage.UpperEndofNumber); Begasep_BetMsg BetMessage; printf("\n\nEnter the bet you want to make beteen %d and %d = ", BEGASEP_NUM_MIN, BEGASEP_NUM_MAX); scanf("%d", &(BetMessage.ClientBet)); makeHeader(PROTOCOL_VERSION, BEGASEP_BET, sizeof(SendHeader) + sizeof(BetMessage), RecvHeader.ClientId, &SendHeader); if (send(sockfd, (Begasep_CommonHeader*) &SendHeader, sizeof(SendHeader), 0) == -1) perror("send"); if (send(sockfd, (Begasep_BetMsg*) &BetMessage, sizeof(BetMessage), 0) == -1) perror("send"); printf( "\n\nClient Sends **** |Version = %2u | Packet Type = %2u | Packet Length = %d | ClientID = %d | **** \n", SendHeader.ProtocolVersion, SendHeader.PacketType, SendHeader.PacketLength, SendHeader.ClientId); printf(" **** |Bet made = %d |\n", BetMessage.ClientBet); break; case BEGASEP_RESULT: printf(""); Begasep_ResultMsg ResultMessage; if ((recv(sockfd, &ResultMessage, sizeof(ResultMessage), 0)) <= 0) { perror("recv"); exit(1); } printf( " **** |Bet Status %d | Winning number %d | \n", ResultMessage.ResultStatus, ResultMessage.WinningNumber); if (ResultMessage.ResultStatus == 1) printf("***wow you won the bet***\n"); else printf("***:( you lost the bet***\n"); ResultReceived = 1; break; } if (ResultReceived == 1) break; }
Instances *ThresholdCurve::getCurve(std::vector<Prediction*> predictions, const int classIndex) { if ((predictions.size() == 0) || ((static_cast<NominalPrediction*>(predictions.at(0)))->distribution().size() <= classIndex)) { return nullptr; } double totPos = 0, totNeg = 0; double_array probs = getProbabilities(predictions, classIndex); // Get distribution of positive/negatives for (int i = 0; i < probs.size(); i++) { NominalPrediction *pred = static_cast<NominalPrediction*>(predictions.at(i)); if (pred->actual() == Prediction::MISSING_VALUE) { std::cout << " Skipping prediction with missing class value"; continue; } if (pred->weight() < 0) { std::cout << " Skipping prediction with negative weight"; continue; } if (pred->actual() == classIndex) { totPos += pred->weight(); } else { totNeg += pred->weight(); } } Instances *insts = makeHeader(); int_array sorted = Utils::Sort(probs); TwoClassStats *tc = new TwoClassStats(totPos, totNeg, 0, 0); double threshold = 0; double cumulativePos = 0; double cumulativeNeg = 0; for (int i = 0; i < sorted.size(); i++) { if ((i == 0) || (probs[sorted[i]] > threshold)) { tc->setTruePositive(tc->getTruePositive() - cumulativePos); tc->setFalseNegative(tc->getFalseNegative() + cumulativePos); tc->setFalsePositive(tc->getFalsePositive() - cumulativeNeg); tc->setTrueNegative(tc->getTrueNegative() + cumulativeNeg); threshold = probs[sorted[i]]; insts->add(*makeInstance(tc, threshold)); cumulativePos = 0; cumulativeNeg = 0; if (i == sorted.size() - 1) { break; } } NominalPrediction *pred = static_cast<NominalPrediction*>(predictions.at(sorted[i])); if (pred->actual() == Prediction::MISSING_VALUE) { std::cout << " Skipping prediction with missing class value"; continue; } if (pred->weight() < 0) { std::cout << " Skipping prediction with negative weight"; continue; } if (pred->actual() == classIndex) { cumulativePos += pred->weight(); } else { cumulativeNeg += pred->weight(); } } // make sure a zero point gets into the curve if (tc->getFalseNegative() != totPos || tc->getTrueNegative() != totNeg) { tc = new TwoClassStats(0, 0, totNeg, totPos); threshold = probs[sorted[sorted.size() - 1]] + 10e-6; insts->add(*makeInstance(tc, threshold)); } return insts; }
YY_ACTION(void) yy_1_declaration(GREG *G, char *yytext, int yyleng, yythunk *thunk, YY_XTYPE YY_XVAR) { yyprintf((stderr, "do yy_1_declaration\n")); makeHeader(yytext); ; }
Readable* ModuleMap::getMapLoadingReadable(uint32 mapID, uint32 loadMapRequestType, const char* handshake, byte zoomlevel, MapSafeVector* loadedMaps ) { FileUtils::FilePtr file; MC2String cacheFileName = getCacheFilename(mapID, loadMapRequestType, zoomlevel); mc2dbg << "[ModuleMap]: Filename would be \"" << cacheFileName << '"' << endl ; bool useCache = cacheFileName.length(); if ( useCache ) { // If the cache filename exists we should try the cache. file.reset( fopen( cacheFileName.c_str(), "r" ) ); } TCPSocket* tcpsock = NULL; uint32 mapVersion = MAX_UINT32; uint32 generatorVersion = MAX_UINT32; if ( file.get() != NULL ) { mc2dbg << "[ModuleMap]: Cached map found" << endl; // Check versions of map in file. ScopedArray<byte> headerBuf( new byte[CACHED_MAP_HEADER_SIZE] ); uint32 fileMapVersion = MAX_UINT32; uint32 fileGeneratorVersion = MAX_UINT32; uint32 fileMapID = MAX_UINT32; if ( fread( headerBuf.get(), CACHED_MAP_HEADER_SIZE, 1, file.get() ) == 1 ) { DataBuffer dataBuf(headerBuf.get(), CACHED_MAP_HEADER_SIZE); uint32 first = dataBuf.readNextLong(); first = first; fileMapID = dataBuf.readNextLong(); fileMapVersion = dataBuf.readNextLong(); fileGeneratorVersion = dataBuf.readNextLong(); if ( fileMapID == mapID ) { mapVersion = fileMapVersion; generatorVersion = fileGeneratorVersion; } else { mc2dbg << "[ModuleMap]: Wrong mapid in file - was " << fileMapID << " should be " << mapID << endl; } } headerBuf.reset( NULL ); mc2dbg << "[ModuleMap]: Version from file 0x" << hex << fileMapVersion << ":" << dec << fileGeneratorVersion << endl; tcpsock = getMapLoadingSocket(mapID, loadMapRequestType, handshake, zoomlevel, loadedMaps, &mapVersion, &generatorVersion); mc2dbg << "[ModuleMap]: Version from getMapLoadingSocket " << hex << "0x" << mapVersion << dec << ":" << generatorVersion << endl; if ( (tcpsock == NULL ) && ( mapVersion == fileMapVersion ) && ( generatorVersion == fileGeneratorVersion ) ) { mc2dbg << "[ModuleMap]: Cached file OK" << endl; return new FileReadable(file.release()); } else { if ( tcpsock != NULL ) { mc2dbg << "[ModuleMap]: Versions differ (file/MM)." << endl; } else { mc2dbg << "[ModuleMap]: Wrong version or no socket." << endl; } } } else { mc2dbg << "[ModuleMap]: No cache file" << endl; // Just get the socket and load. tcpsock = getMapLoadingSocket(mapID, loadMapRequestType, handshake, zoomlevel, loadedMaps, &mapVersion, &generatorVersion); } if ( tcpsock != NULL && useCache ) { mc2dbg << "[ModuleMap]: Will write to cache" << endl; // We do not have the map cached or it may have been the wrong // version. int headerSize = 0; ScopedArray<byte> header( makeHeader( headerSize, mapID, mapVersion, generatorVersion) ); TCPSocketReadable* tsockRead = new TCPSocketReadable( tcpsock ); return new AutoWritingReadable( tsockRead, cacheFileName.c_str(), header.get(), headerSize ); } else if ( tcpsock ) { mc2dbg << "[ModuleMap]: Will not write to cache" << endl; return new TCPSocketReadable(tcpsock); } else { mc2dbg << "[ModuleMap]: No socket" << endl; // Loading failed return NULL; } }
YY_ACTION(void) yy_1_declaration(char *yytext, int yyleng) { yyprintf((stderr, "do yy_1_declaration\n")); makeHeader(yytext); ; }
static PyObject * specpkg_get_header(specPkgObject *s, void *closure) { return makeHeader(rpmSpecPkgHeader(s->pkg)); }