bool ThreadInfo::recalcUsage(int sampleTimeDiff) { cpuUsage = -1; totalCpuTimeMs = -1; HANDLE thread_handle = getThreadHandle(); if (thread_handle == NULL) return false; FILETIME CreationTime, ExitTime, KernelTime, UserTime; if (!GetThreadTimes( thread_handle, &CreationTime, &ExitTime, &KernelTime, &UserTime )) return false; __int64 kernel_diff = getDiff(prevKernelTime, KernelTime); __int64 user_diff = getDiff(prevUserTime, UserTime); prevKernelTime = KernelTime; prevUserTime = UserTime; if (sampleTimeDiff > 0) { __int64 total_diff = ((kernel_diff + user_diff) / 10000) * 100; cpuUsage = static_cast<int>(total_diff / sampleTimeDiff); } totalCpuTimeMs = (getTotal(KernelTime) + getTotal(UserTime)) / 10000; return true; }
int deposito(DStack* stack, Cliente* cliente){ float value = -1; printf("valor na conta: R$ %.2f\n",getTotal(cliente)); while(value<0){ printf("digite um valor ou 0 para cancelar: "); scanf("%f",&value); } if(value==0){ printf("operacao de deposito cancelada\n"); return 1; } setTempDeposito(cliente,value); dStackPush(stack,senha); int result = dStackExecuteTopElement(stack,cliente); dStackPop(stack); if(!result){ printf("senha nao confere\n"); printf("operacao de deposito nao foi bem sucedida\n"); return 0; } setTotal(cliente,getTotal(cliente)+value); setTempDeposito(cliente,0); printf("operacao de deposito bem sucedida\n"); return 1; }
void Transfer::getParams(const UserConnection& aSource, StringMap& params) { params["userNI"] = aSource.getUser()->getNick(); params["userI4"] = aSource.getRemoteIp(); params["hub"] = aSource.getUser()->getClientName(); params["hubURL"] = aSource.getUser()->getClientUrl(); params["fileSI"] = Util::toString(getSize()); params["fileSIshort"] = Util::formatBytes(getSize()); params["fileSIchunk"] = Util::toString(getTotal()); params["fileSIchunkshort"] = Util::formatBytes(getTotal()); params["fileSIactual"] = Util::toString(getActual()); params["fileSIactualshort"] = Util::formatBytes(getActual()); params["speed"] = Util::formatBytes(getAverageSpeed()) + "/s"; params["time"] = Util::formatSeconds((GET_TICK() - getStart()) / 1000); params["fileTR"] = getTTH().toBase32(); }
int main(int argc, const char * argv[]) { FILE * revenue = NULL, * lost = NULL, * save = NULL; char * save_path = calloc(1, STRLEN), * bk = calloc(1, STRLEN); save_path = firstOpen_update(save); bk = strdup(save_path); if (save_path == '\0') updateSavePath(); else { revenue = fopen(strcat(save_path, "/revenue.json"), "r"); strcpy(save_path, bk); lost = fopen(strcat(bk, "/lost.json"), "r"); } createRevenueMovementList(revenue); createLostMovementList(lost); fclose(revenue); fclose(lost); strcpy(bk, save_path); getTotal(bk); selection(save_path); return 0; }
Weight& Weight::operator*=(const double & b) { int total = (this->lbs * 16 + this->ozs) * b; ozs = (total); getTotal(); return *this; }
bool House::isHitting() const{ if (getTotal() > 17) return false; else return true; }
unsigned int SHMIntHashIndex_AX::malloc() { if(m_iLastTotal != (*m_piTotal)) { SHMAccess::reopen(); m_iLastTotal = (*m_piTotal); } if( ( getCount()*100/getTotal() ) > 98 ){ expandMem(); } unsigned int j=0; if (*m_piUsed <= *m_piTotal) { (*m_piUsed)++; j = *m_piHead; if( *m_piUsed == 1+(*m_piTotal) ){ *m_piHead = 0; *m_piTail = 0; }else{ *m_piHead = m_poList[j].m_iNext; } } else { //##空间不够 THROW(MBC_SHMIntHashIndex+1); } #ifdef DEBUG_TEST printf("分配到偏移为%u。 ", j); #endif return j; }
void ScoreKeeper::printDebugScores() { int longest_weight_id = 0; for (unsigned int i = 0; i < weight_ids.size(); i++) { if (weight_ids[i].length() > longest_weight_id) longest_weight_id = weight_ids[i].length(); } float total = getTotal(); std::cout << "--------------------" << std::endl; std::cout << "Total: " << total << std::endl; for (unsigned int i = 0; i < weight_ids.size(); i++) { float percent_of_total = (scores[i] * weights[i]) / total * 100; std::cout << " - " << std::setw(longest_weight_id + 1) << std::left << weight_ids[i] << " Weighted Score: " << std::setw(10) << std::left << (scores[i] * weights[i]) << " Orig Score: " << std::setw(10) << std::left << scores[i] << " (" << percent_of_total << "% of total)" << std::endl; } std::cout << "--------------------" << std::endl; }
Weight& Weight::operator-=(const Weight& b) { int totalB = (b.lbs * 16 + b.ozs); int total = (this->lbs * 16 + this->ozs); this->ozs = (total - totalB); getTotal(); return *this; }
int main() { myGreet(); double myTotal = 0.0; double hourlyPay = getHourlyPay(); int hoursWkd = getHoursWkd(); getTotal(hoursWkd, hourlyPay, myTotal); myDisplay(myTotal); return 0; }
int saque(DStack* stack,Cliente* cliente){ float value = -1; printf("valor na conta: R$ %.2f\n",getTotal(cliente)); if(getTotal(cliente)<=0){ printf("nao possui saldo suficiente\n"); return 0; } while(value<0){ printf("escolha o valor ou digite 0 para cancelar: "); scanf("%f",&value); } if(value==0){ printf("operacao cancelada\n"); return 1; } setTempSaque(cliente,value); dStackPush(stack,checkValue); int result = dStackExecuteTopElement(stack,cliente); dStackPop(stack); if(!result){ printf("operacao de saque nao foi bem sucedida\n"); return 0; } setTotal(cliente,getTotal(cliente)-getTempSaque(cliente)); setTempSaque(cliente,0); printf("operacao de saque bem sucedida\n"); return result; }
int checkValue(DStack* stack,Cliente* cliente){ if(getTempSaque(cliente) > getTotal(cliente)){ printf("nao possui saldo suficiente\n"); return 0; } dStackPush(stack,senha); int result = dStackExecuteTopElement(stack,cliente); dStackPop(stack); if(!result){ printf("senha nao confere\n"); return 0; } return 1; }
//Punt0 4 (20) mostrar la lista void showList(char (*_nombres)[MAX_CHARACTER_NAME], float *_salarios, float *_total){ int i=0; if(enlisted_employees==0){ printf("No se han ingresado datos aún.\n"); return; } //Listar empleados printf("\n\tLista de trabajadores\n"); printf("|%-15s|%-15s|\n","Emprendedor S:A", "Nit: 80808080"); printf("|%-15s|%-15s|\n", "Nombre", "Salario"); for(i=0; i<enlisted_employees; i++){ printf("|%-15s|%-15.2f|\n", *(_nombres+i), *(_salarios+i)); } //Listar el total printf("|%-15s|", "Total"); getTotal(_salarios, _total); }
void Transfer::updateRunningAverage() { time_t tick = GET_TICK(); // Update 4 times/sec at most if(tick > (lastTick + 250)) { time_t diff = tick - lastTick; int64_t tot = getTotal(); if( ((tick - getStart()) < AVG_PERIOD) ) { runningAverage = getAverageSpeed(); } else { int64_t bdiff = tot - last; int64_t avg = bdiff * (int64_t)1000 / diff; if(diff > AVG_PERIOD) { runningAverage = avg; } else { // Weighted average... runningAverage = ((avg * diff) + (runningAverage*(AVG_PERIOD-diff)))/AVG_PERIOD; } } last = tot; } lastTick = tick; }
string Assessment::toString(int n) { stringstream outString; for (int i = 0; i < n; i++) { outString << "---"; } outString << name << " : " << getPercentage() << "% : " << getMark() << "/" << getTotal() << " : " << getWeightedMark() << "/" << getWeight() << endl; for (iter = opps.begin(); iter != opps.end(); iter++) { outString << (*iter)->toString(n + 1); } //for (int i = 0; i < n; i++) //{ // outString << "---"; //} //outString << "_______________________________\n"; return outString.str(); }
PaletteIndex ColorCount::getRandomColor() const { if(m_should_recalc) { recalc(m_quantity_by_color, m_number_of_colors, getTotal(), m_minimal_chance, m_cumuliative_percent_chance); m_should_recalc = false; } // Get the random color PaletteIndex random_color(0); { float rand = my_utility::random(); for(float*chance_iter=m_cumuliative_percent_chance; chance_iter!=m_cumuliative_percent_chance+m_number_of_colors; ++chance_iter,++random_color) { if(rand<*chance_iter) { break; } } } return random_color; }
int main() { int i; int seed = 1000; int numPlayer = 2; int maxBonus = 10; int p, r, handCount; int bonus; struct gameState G; int maxHandCount = 5; int k[10] = {adventurer, council_room, feast, gardens, mine, remodel, smithy, village, baron, great_hall}; // arrays of all coppers, silvers, and golds int coppers[MAX_HAND]; int silvers[MAX_HAND]; int golds[MAX_HAND]; int rand_hand[MAX_HAND]; int treasures[3] = {copper, silver, gold}; for (i = 0; i < MAX_HAND; i++) { coppers[i] = copper; silvers[i] = silver; golds[i] = gold; } printf ("TESTING updateCoins():\n"); for (p = 0; p < numPlayer; p++){ for (handCount = 1; handCount <= maxHandCount; handCount++){ for (bonus = 0; bonus <= maxBonus; bonus++){ int total; // generate a random hand to check for(i = 0; i < MAX_HAND; i++){ int n = rand() % 3; rand_hand[i] = treasures[n]; } //printf("Test player %d with %d treasure card(s) and %d bonus.\n", p, handCount, bonus); memset(&G, '-', sizeof(struct gameState)); // clear the game state r = initializeGame(numPlayer, k, seed, &G); // initialize a new game G.handCount[p] = handCount; // set the number of cards on hand // get the total that we should see. This is kind pointless since it just // re-creates the updateCoins function but whatev total = getTotal(rand_hand, handCount); memcpy(G.hand[p], coppers, sizeof(int) * handCount); // set all the cards to copper r = updateCoins(p, &G, bonus); assert(r == 0); //printf("G.coins = %d, expected = %d\n", G.coins, handCount * 1 + bonus); assert(G.coins == handCount * 1 + bonus); // check if the number of coins is correct memcpy(G.hand[p], silvers, sizeof(int) * handCount); // set all the cards to silver r = updateCoins(p, &G, bonus); assert(r == 0); //printf("G.coins = %d, expected = %d\n", G.coins, handCount * 2 + bonus); assert(G.coins == handCount * 2 + bonus); // check if the number of coins is correct memcpy(G.hand[p], golds, sizeof(int) * handCount); // set all the cards to gold r = updateCoins(p, &G, bonus); assert(r == 0); //printf("G.coins = %d, expected = %d\n", G.coins, handCount * 3 + bonus); assert(G.coins == handCount * 3 + bonus); // check if the number of coins is correct memcpy(G.hand[p], rand_hand, sizeof(int) * handCount); // test a random hand r = updateCoins(p, &G, bonus); assert(r == 0); //printf("G.coins = %d, expected = %d\n", G.coins, total+bonus); assert(G.coins == total + bonus); // check if the number of coins is correct } } } printf("All tests passed!\n"); return 0; }
/* Main function. */ int main(int argc, char *argv[]) { /* Local variables. */ char option = 'x'; int exitValue; char *fileName; FILE *employeeFile; employee *employees; float total = 0; // Validation: Number of arguments from console. if (argc != 2) { printf("Error: Numero de parametros invalido.\nDebe iniciar asi: ./taller.out <archivo.csv>\n"); exit(0); } fileName = argv[1]; employeeFile = fopen(fileName, "r"); if(employeeFile == NULL) { printf("No se pudo abrir el archivo\n"); exit(0); } numEmployees = getNumEmployees(employeeFile); if (numEmployees <= 0) { printf("Error: No hay trabajadores en el archivo\n"); exit(0); } printf("Hay %d trabajadores en el archivo\n", numEmployees); employees = (employee *)malloc(sizeof(employee) * numEmployees); do { getOption(&option); switch (option) { case 'a': registerEmployees(employees, employeeFile); break; case 'b': showEmployees(employees); break; case 'c': total = getTotal(employees); printf("TOTAL: %.2f", total); break; case 'q': printf("Saliendo del programa...\n"); break; default: printf("La opcion '%c' no es valida. Volviendo al menu.\n", option); break; } } while(option != 'q'); exitValue = fclose(employeeFile); if(exitValue == 0) { printf("se cerro el archivo\n"); } /* Free memory. */ free(employees); return 0; }
int main(int argc, char *argv[]) { librdf_world* world; librdf_parser* parser; librdf_serializer* serializer; librdf_storage *storage; librdf_model* model; librdf_node *source, *arc, *target, *node; librdf_node *subject, *predicate, *object; librdf_node* context_node=NULL; librdf_stream* stream; librdf_iterator* iterator; librdf_uri *uri; librdf_uri *base_uri=NULL; librdf_query *query; librdf_query_results *results; librdf_hash *options; int count; int rc; int transactions=0; const char* storage_name; const char* storage_options; const char* context; const char* identifier; const char* results_format; librdf_statement* statement=NULL; char* query_cmd=NULL; char* s; /* * Initialize */ storage_name="virtuoso"; results_format="xml"; context=DEFAULT_CONTEXT; identifier=DEFAULT_IDENTIFIER; /* * Get connection options */ if(argc == 2 && argv[1][0] != '\0') storage_options=argv[1]; else if((s=getenv ("VIRTUOSO_STORAGE_OPTIONS")) != NULL) storage_options=s; else storage_options=DEFAULT_STORAGE_OPTIONS; world=librdf_new_world(); librdf_world_set_logger(world, world, log_handler); librdf_world_open(world); options=librdf_new_hash(world, NULL); librdf_hash_open(options, NULL, 0, 1, 1, NULL); librdf_hash_put_strings(options, "contexts", "yes"); transactions=1; librdf_hash_from_string(options, storage_options); storage=librdf_new_storage_with_options(world, storage_name, identifier, options); if(!storage) { fprintf(stderr, ": Failed to open %s storage '%s'\n", storage_name, identifier); return(1); } model=librdf_new_model(world, storage, NULL); if(!model) { fprintf(stderr, ": Failed to create model\n"); return(1); } if(transactions) librdf_model_transaction_start(model); /* Do this or gcc moans */ stream=NULL; iterator=NULL; parser=NULL; serializer=NULL; source=NULL; arc=NULL; target=NULL; subject=NULL; predicate=NULL; object=NULL; uri=NULL; node=NULL; query=NULL; results=NULL; context_node=librdf_new_node_from_uri_string(world, (const unsigned char *)context); /**** Test 1 *******/ startTest(1, " Remove all triples in <%s> context\n", context); { rc=librdf_model_context_remove_statements(model, context_node); if(rc) endTest(0, " failed to remove context triples from the graph\n"); else endTest(1, " removed context triples from the graph\n"); } /**** Test 2 *******/ startTest(2, " Add triples to <%s> context\n", context); { rc=0; rc |= add_triple(world, context_node, model, "aa", "bb", "cc"); rc |= add_triple(world, context_node, model, "aa", "bb1", "cc"); rc |= add_triple(world, context_node, model, "aa", "a2", "_:cc"); rc |= add_triple_typed(world, context_node, model, "aa", "a2", "cc"); rc |= add_triple_typed(world, context_node, model, "mm", "nn", "Some long literal with language@en"); rc |= add_triple_typed(world, context_node, model, "oo", "pp", "12345^^<http://www.w3.org/2001/XMLSchema#int>"); if(rc) endTest(0, " failed add triple\n"); else endTest(1, " add triple to context\n"); } /**** Test 3 *******/ startTest(3, " Print all triples in <%s> context\n", context); { raptor_iostream* iostr = raptor_new_iostream_to_file_handle(librdf_world_get_raptor(world), stdout); librdf_model_write(model, iostr); raptor_free_iostream(iostr); endTest(1, "\n"); } /***** Test 4 *****/ startTest(4, " Count of triples in <%s> context\n", context); { count=librdf_model_size(model); if(count >= 0) endTest(1, " graph has %d triples\n", count); else endTest(0, " graph has unknown number of triples\n"); } /***** Test 5 *****/ startTest(5, " Exec: ARC aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); node=librdf_model_get_target(model, subject, predicate); librdf_free_node(subject); librdf_free_node(predicate); if(!node) { endTest(0, " Failed to get arc\n"); } else { print_node(stdout, node); librdf_free_node(node); endTest(1, "\n"); } } /***** Test 6 *****/ startTest(6, " Exec: ARCS aa cc \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); iterator=librdf_model_get_arcs(model, subject, object); librdf_free_node(subject); librdf_free_node(object); if(!iterator) { endTest(0, " Failed to get arcs\n"); } else { print_nodes(stdout, iterator); endTest(1, "\n"); } } /***** Test 7 *****/ startTest(7, " Exec: ARCS-IN cc \n"); { object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); iterator=librdf_model_get_arcs_in(model, object); librdf_free_node(object); if(!iterator) { endTest(0, " Failed to get arcs in\n"); } else { int ok=1; count=0; while(!librdf_iterator_end(iterator)) { context_node=(librdf_node*)librdf_iterator_get_context(iterator); node=(librdf_node*)librdf_iterator_get_object(iterator); /*returns SHARED pointer */ if(!node) { ok=0; endTest(ok, " librdf_iterator_get_next returned NULL\n"); break; } fputs("Matched arc: ", stdout); librdf_node_print(node, stdout); if(context_node) { fputs(" with context ", stdout); librdf_node_print(context_node, stdout); } fputc('\n', stdout); count++; librdf_iterator_next(iterator); } librdf_free_iterator(iterator); endTest(ok, " matching arcs: %d\n", count); } } /***** Test 8 *****/ startTest(8, " Exec: ARCS-OUT aa \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); iterator=librdf_model_get_arcs_out(model, subject); librdf_free_node(subject); if(!iterator) endTest(0, " Failed to get arcs out\n"); else { int ok=1; count=0; while(!librdf_iterator_end(iterator)) { context_node=(librdf_node*)librdf_iterator_get_context(iterator); node=(librdf_node*)librdf_iterator_get_object(iterator); if(!node) { ok=0; endTest(ok, " librdf_iterator_get_next returned NULL\n"); break; } fputs("Matched arc: ", stdout); librdf_node_print(node, stdout); if(context_node) { fputs(" with context ", stdout); librdf_node_print(context_node, stdout); } fputc('\n', stdout); count++; librdf_iterator_next(iterator); } librdf_free_iterator(iterator); endTest(ok, " matching arcs: %d\n", count); } } /***** Test 9 *****/ startTest(9, " Exec: CONTAINS aa bb1 cc \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb1"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); statement=librdf_new_statement(world); librdf_statement_set_subject(statement, subject); librdf_statement_set_predicate(statement, predicate); librdf_statement_set_object(statement, object); if(librdf_model_contains_statement(model, statement)) endTest(1, " the graph contains the triple\n"); else endTest(0, " the graph does not contain the triple\n"); librdf_free_statement(statement); } /***** Test 10 *****/ startTest(10, " Exec: FIND aa - - \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); statement=librdf_new_statement(world); librdf_statement_set_subject(statement, subject); stream=librdf_model_find_statements_in_context(model, statement, context_node); if(!stream) { endTest(0, " FIND returned no results (NULL stream)\n"); } else { librdf_node* ctxt_node=NULL; int ok=1; count=0; while(!librdf_stream_end(stream)) { librdf_statement *stmt=librdf_stream_get_object(stream); ctxt_node=(librdf_node*)librdf_stream_get_context(stream); if(!stmt) { ok=0; endTest(ok, " librdf_stream_next returned NULL\n"); break; } fputs("Matched triple: ", stdout); librdf_statement_print(stmt, stdout); if(context) { fputs(" with context ", stdout); librdf_node_print(ctxt_node, stdout); } fputc('\n', stdout); count++; librdf_stream_next(stream); } librdf_free_stream(stream); endTest(ok, " matching triples: %d\n", count); } librdf_free_statement(statement); } /***** Test 11 *****/ startTest(11, " Exec: HAS-ARC-IN cc bb \n"); { predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); if(librdf_model_has_arc_in(model, object, predicate)) endTest(1, " the graph contains the arc\n"); else endTest(0, " the graph does not contain the arc\n"); librdf_free_node(predicate); librdf_free_node(object); } /***** Test 12 *****/ startTest(12, " Exec: HAS-ARC-OUT aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); if(librdf_model_has_arc_out(model, subject, predicate)) endTest(1, " the graph contains the arc\n"); else endTest(0, " the graph does not contain the arc\n"); librdf_free_node(predicate); librdf_free_node(subject); } /***** Test 13 *****/ startTest(13, " Exec: SOURCE aa cc \n"); { predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); node=librdf_model_get_source(model, predicate, object); librdf_free_node(predicate); librdf_free_node(object); if(!node) { endTest(0, " Failed to get source\n"); } else { print_node(stdout, node); librdf_free_node(node); endTest(1, "\n"); } } /***** Test 14 *****/ startTest(14, " Exec: SOURCES bb cc \n"); { predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); iterator=librdf_model_get_sources(model, predicate, object); librdf_free_node(predicate); librdf_free_node(object); if(!iterator) { endTest(0, " Failed to get sources\n"); } else { print_nodes(stdout, iterator); endTest(1, "\n"); } } /***** Test 15 *****/ startTest(15, " Exec: TARGET aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); node=librdf_model_get_target(model, subject, predicate); librdf_free_node(subject); librdf_free_node(predicate); if(!node) { endTest(0, " Failed to get target\n"); } else { print_node(stdout, node); librdf_free_node(node); endTest(1, "\n"); } } /***** Test 16 *****/ startTest(16, " Exec: TARGETS aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); iterator=librdf_model_get_targets(model, subject, predicate); librdf_free_node(subject); librdf_free_node(predicate); if(!iterator) { endTest(0, " Failed to get targets\n"); } else { print_nodes(stdout, iterator); endTest(1, "\n"); } } /***** Test 17 *****/ startTest(17, " Exec: REMOVE aa bb1 cc \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb1"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); statement=librdf_new_statement(world); librdf_statement_set_subject(statement, subject); librdf_statement_set_predicate(statement, predicate); librdf_statement_set_object(statement, object); if(librdf_model_context_remove_statement(model, context_node, statement)) endTest(0, " failed to remove triple from the graph\n"); else endTest(1, " removed triple from the graph\n"); librdf_free_statement(statement); } /***** Test 18 *****/ query_cmd=(char *)"CONSTRUCT {?s ?p ?o} FROM <http://red> WHERE {?s ?p ?o}"; startTest(18, " Exec: QUERY \"%s\" \n", query_cmd); { query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL); if(!(results=librdf_model_query_execute(model, query))) { endTest(0, " Query of model with '%s' failed\n", query_cmd); librdf_free_query(query); query=NULL; } else { stream=librdf_query_results_as_stream(results); if(!stream) { endTest(0, " QUERY returned no results (NULL stream)\n"); } else { librdf_node* ctxt=NULL; count=0; while(!librdf_stream_end(stream)) { librdf_statement *stmt=librdf_stream_get_object(stream); /*returns SHARED pointer */ ctxt=(librdf_node*)librdf_stream_get_context(stream); if(!stmt) { endTest(0, " librdf_stream_next returned NULL\n"); break; } fputs("Matched triple: ", stdout); librdf_statement_print(stmt, stdout); if(ctxt) { fputs(" with context ", stdout); librdf_node_print(ctxt, stdout); } fputc('\n', stdout); count++; librdf_stream_next(stream); } librdf_free_stream(stream); endTest(1, " matching triples: %d\n", count); librdf_free_query_results(results); } } librdf_free_query(query); } /***** Test 19 *****/ query_cmd=(char *)"SELECT * WHERE {graph <http://red> { ?s ?p ?o }}"; startTest(19, " Exec1: QUERY_AS_BINDINGS \"%s\" \n", query_cmd); { query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL); if(!(results=librdf_model_query_execute(model, query))) { endTest(0, " Query of model with '%s' failed\n", query_cmd); librdf_free_query(query); query=NULL; } else { raptor_iostream *iostr; librdf_query_results_formatter *formatter; fprintf(stderr, "**: Formatting query result as '%s':\n", results_format); iostr = raptor_new_iostream_to_file_handle(librdf_world_get_raptor(world), stdout); formatter = librdf_new_query_results_formatter2(results, results_format, NULL /* mime type */, NULL /* format_uri */); base_uri = librdf_new_uri(world, (const unsigned char*)"http://example.org/"); librdf_query_results_formatter_write(iostr, formatter, results, base_uri); librdf_free_query_results_formatter(formatter); raptor_free_iostream(iostr); librdf_free_uri(base_uri); endTest(1, "\n"); librdf_free_query_results(results); } librdf_free_query(query); } /***** Test 20 *****/ query_cmd=(char *)"SELECT * WHERE {graph <http://red> { ?s ?p ?o }}"; startTest(20, " Exec2: QUERY_AS_BINDINGS \"%s\" \n", query_cmd); { query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL); if(!(results=librdf_model_query_execute(model, query))) { endTest(0, " Query of model with '%s' failed\n", query_cmd); librdf_free_query(query); query=NULL; } else { if(print_query_results(world, model, results)) endTest(0, "\n"); else endTest(1, "\n"); librdf_free_query_results(results); } librdf_free_query(query); } getTotal(); if(transactions) librdf_model_transaction_commit(model); librdf_free_node(context_node); librdf_free_node(context_node); librdf_free_hash(options); librdf_free_model(model); librdf_free_storage(storage); librdf_free_world(world); #ifdef LIBRDF_MEMORY_DEBUG librdf_memory_report(stderr); #endif /* keep gcc -Wall happy */ return(0); }
int verificarSaldo(DStack* stack,Cliente* cliente){ printf("valor atual na conta: R$ %.2f\n",getTotal(cliente)); return 1; }
double UAMean::predictUtility(double u) const { double nextU = getTotal() + u; int nextC = getCount() + 1; return nextU / nextC; }
void main(int argc, char** argvs) { struct NODE* listBuy = NULL; struct NODE* listSell = NULL; FILE* fileIn = NULL; FILE* fileOut = NULL; char strLine[BUFFER]; int iTargetSize = 0; char* strCommand; char* strOderID; char* strSide; int iTime; double dPrice; int iSize; double dTotalB = 0; double dTotalS = 0; /** * Check arguments, if number of arguments is wrong then * print help and return. */ if (argc != 4) { printf("The Pricer program using 3 arguments:\n"); printf("<target-size> <file-in> <file-out>\n"); return; } fileIn = fopen(argvs[2], "r"); if (fileIn) { iTargetSize = atoi(argvs[1]); fileOut = fopen(argvs[3], "w"); while (!feof(fileIn)) { strLine[0] = NULL;//Clear line before get new line; fgets(strLine, BUFFER, fileIn); if (strlen(strLine) == 0) break; char* context = NULL; iTime = atoi(strtok(strLine, " ")); strCommand = strtok(NULL, " "); strOderID = strtok(NULL, " "); //Handle for command 'A' Add Order to Book if (strcmp(strCommand, "A")==0) { strSide = strtok(NULL, " "); dPrice = toDouble(strtok(NULL, " ")); iSize = atoi(strtok(NULL, " ")); //Add Order to Book by side 'B' if (strcmp(strSide, "B") == 0) { addList(&listBuy, makeNode(strOderID, dPrice, iSize), false); double dTotal = getTotal(listBuy, iTargetSize); if (dTotal > 0) { if (!compareDoubles(dTotal, dTotalS)) { dTotalS = dTotal; printf("%d S %0.2f\n", iTime, dTotalS); fprintf(fileOut, "%d S %0.2f\n", iTime, dTotalS); } } } //Add Order to Book by side 'S' else if (strcmp(strSide, "S") == 0) { addList(&listSell, makeNode(strOderID, dPrice, iSize), true); double dTotal = getTotal(listSell, iTargetSize); if (dTotal > 0) { if (!compareDoubles(dTotal, dTotalB)) { dTotalB = dTotal; printf("%d B %0.2f\n", iTime, dTotalB); fprintf(fileOut, "%d B %0.2f\n", iTime, dTotalB); } } } } //Handle for command 'R' Add Order to Book else if (strcmp(strCommand, "R") == 0) { iSize = atoi(strtok(NULL, " ")); if (reduceSize(&listBuy, strOderID, iSize)) { double dTotal = getTotal(listBuy, iTargetSize); if (dTotal > 0) { if (!compareDoubles(dTotalS, dTotal)) { dTotalS = dTotal; printf("%d S %0.2f\n", iTime, dTotalS); fprintf(fileOut, "%d S %0.2f\n", iTime, dTotalS); } } else if (dTotalS > 0) { printf("%d S NA\n", iTime); fprintf(fileOut, "%d S NA\n", iTime); dTotalS = 0; } } if (reduceSize(&listSell, strOderID, iSize)) { double dTotal = getTotal(listSell, iTargetSize); if (dTotal > 0) { if (!compareDoubles(dTotalB, dTotal)) { dTotalB = dTotal; printf("%d B %0.2f\n", iTime, dTotalB); fprintf(fileOut, "%d B %0.2f\n", iTime, dTotalB); } } else if (dTotalB > 0) { printf("%d B NA\n", iTime); fprintf(fileOut,"%d B NA\n", iTime); dTotalB = 0; } } } } fclose(fileIn); fclose(fileOut); removeList(listBuy); removeList(listSell); } else { printf("Could not find file: %s\n", argvs[2]); return; } }
bool GameScene::init(){ if (!Layer::init()) { return false; } //游戏数据初始化 card_num = 0; debt_num = 0; //先添加桌面背景,在最下面 auto * table = Sprite::create("table.png"); this->addChild(table); auto screenSize = Director::getInstance()->getWinSize();//获取屏幕尺寸 table->setPosition(screenSize.width/2,screenSize.height/2-30); table->setScale(1.1);//设置缩放级别 //add buttons //按钮上的文字后期用ps来制作 auto giveUpMenuItem = MenuItemImage::create( "button01.png", "button02.png", CC_CALLBACK_1(GameScene::button_giveUp, this)); giveUpMenuItem->setPosition(Point(60, 40)); auto genZhuMenuItem = MenuItemImage::create( "button01.png", "button02.png", CC_CALLBACK_1(GameScene::button_xiaZhu, this)); genZhuMenuItem->setPosition(Point(190, 40)); auto yiLvMenuItem = MenuItemImage::create( "button01.png", "button02.png", CC_CALLBACK_1(GameScene::button_jiaZhu, this)); yiLvMenuItem->setPosition(Point(320, 40)); auto starMenu = Menu::create(giveUpMenuItem, genZhuMenuItem,yiLvMenuItem,NULL); starMenu->setPosition(Point::ZERO); this->addChild(starMenu, 1); //按钮上添加文字(暂时的功能,后期完善可以删掉) auto button_label01 = Label::createWithSystemFont("giveUp", "Arial", 17); button_label01->setPosition(Point(60, 40)); this->addChild(button_label01,2); //按钮上添加文字(暂时的功能,后期完善可以删掉) auto button_label02 = Label::createWithSystemFont("xiaZhu", "Arial", 17); button_label02->setPosition(Point(190, 40)); this->addChild(button_label02,2); //按钮上添加文字(暂时的功能,后期完善可以删掉) auto button_label03 = Label::createWithSystemFont("jiaZhu", "Arial", 17); button_label03->setPosition(Point(320, 40)); this->addChild(button_label03,2); // your codes here /* char str[] = "poker_pic/13.png"; auto test_card = Sprite::create(str); this->addChild(test_card); test_card->setPosition(screenSize.width / 2, screenSize.height -400); test_card->setScale(0.6); auto my_testCard = Card::create("roomgirl.png"); // auto == Card my_testCard->setPosition(screenSize.width / 2, screenSize.height - 200); my_testCard->setScale(0.6); my_testCard->setCardID(23); this->addChild(my_testCard); CCLOG("my_testCard->ID = %d .", my_testCard->getCardID());//会得到log:my_testCard->ID = 23 . */ //test_end //显示玩家头像,玩家筹码等信息,荷官的片, auto roomgirl = Sprite::create("roomgirl.png"); this->addChild(roomgirl); roomgirl->setPosition(screenSize.width/2, screenSize.height-70); roomgirl->setScale(1); player_num = 2;//设置为2名玩家 //添加游戏玩家(other players) auto player01 = addNewPlayer("player01", 50000); int my_total = 50000; char *my_name = "player_me"; //添加自己的游戏数据======== player_me = Player::create("default_player.png");//创建纹理,并且显示在屏幕的正下方 player_me->setPhoto("default_player.png"); player_me->setPosition(screenSize.width/2,170); player_me->setDebt(0); //set to 0 player_me->setTotal(my_total); player_me->setOnTable(true); this->addChild(player_me); player01->setPlayerName(my_name); player01->setTotal(my_total); //show player name auto player_me_name = Label::createWithSystemFont(my_name, "Arial", 17); player_me_name->setPosition(screenSize.width/2, 215); this->addChild(player_me_name); //show player total money char tmp[9]; sprintf(tmp, "%d",my_total); auto player_me_total = Label::createWithSystemFont(tmp, "Arial", 17); player_me_total->setPosition(screenSize.width/2,120); this->addChild(player_me_total); //下底注(后期可以用ps来制作一张图来支持中文) //show tips auto tips = Sprite::create("show_tips.png"); tips->setScale(0.3); tips->setPosition(screenSize.width / 2, screenSize.height / 2); tips->setOpacity(200); this->addChild(tips, 0, 100);// set tag 100 auto tips_label = Label::createWithSystemFont("XiaDiZhu", "SimSun", 30); tips_label->setPosition(screenSize.width / 2, screenSize.height / 2); tips_label->setColor(ccc3(0, 0, 0));//color black this->addChild(tips_label, 0, 101);// set tag 101 this->scheduleOnce(schedule_selector(GameScene::showTips), 1);//调用回调函数来删掉刚刚创建的tips player01->addDebt(DIZHU); player_me->addDebt(DIZHU); debt_num = DIZHU * 2; //CCLOG为调试信息 CCLOG("player01.debt = %d ,total = %d", player01->getDebt(), player01->getTotal()); CCLOG("player_me.debt = %d ,total = %d", player_me->getDebt(), player_me->getTotal()); //发底牌(2张底牌)保证不相同 srand((unsigned)time(NULL)); //初始化随机数种子 int t1 = getOneNumber();//两名玩家共4张底牌 int t2 = getOneNumber(); int t3 = getOneNumber(); int t4 = getOneNumber(); CCLOG("DIPAI == %d %d %d %d",t1,t2,t3,t4); player01->setCards(t1,t2); player_me->setCards(t3,t4); //CCLOG("PLAYER01 c1 = %d, c2 = %d ,PLAYER_ME c3 = %d, c4 =%d ", player01->getCard01(), player01->getCard02(), player_me->getCard01(), player_me->getCard02()); //显示玩家得到的底牌(可以添加动画效果) char poker_file_name[20]="poker_pic/"; char temp[9]; sprintf(temp, "%d", player_me->getCard01()); strcat(poker_file_name,temp); strcat(poker_file_name, ".png"); //CCLOG("poker_file_name 1 = %s", poker_file_name); auto dipai01 = Card::create(poker_file_name); dipai01->setRotation(-13);//旋转角度 dipai01->setScale(0.5); dipai01->setPosition(320, 165); this->addChild(dipai01); //重新创建一个变量 char poker_file_name2[20] = "poker_pic/"; sprintf(temp, "%d", player_me->getCard02()); strcat(poker_file_name2, temp); strcat(poker_file_name2, ".png"); //CCLOG("poker_file_name 2 = %s", poker_file_name2); auto dipai02 = Card::create(poker_file_name2); dipai02->setRotation(9);//旋转角度 dipai02->setScale(0.5); dipai02->setPosition(340, 165); this->addChild(dipai02); //添加背面的牌: auto hand_card_R = Sprite::create("hand_card_back.png"); hand_card_R->setScale(0.6); hand_card_R->setPosition(22, 470); this->addChild(hand_card_R); //刚发过底牌,设置一个标签,来定义玩到了什么进度 game_round = 1;//刚发过底牌,设置为1 //若不弃牌,则下注,下注之后可选加注 //庄家下注,玩家跟注?加注? //发第一张公共牌 //发第二张公共牌 //... //...直到发最后一张公共牌,是否加注?判断游戏输赢 //以上内容写在了按钮中,通过读取变量值来知道是第几个回合 return true;//init函数执行成功,返回真 }
/* Main function. */ int main(int argc, char *argv[]) { /* Variables locales. */ char option = 'x'; char (*nombres)[MAX_CHARACTER_NAME];//arreglo de caracteres de tamaño 50 x posición float *salarios;//arreglo de salarios float total = 0;//total de salarios /* Obtener informacion. */ /* Hacer operaciones. */ // Validación: Número de argumentos traídos de consola. if (argc != 2) { printf("\nError: Numero de parametros invalido.\nDebe iniciar asi: ./taller.out <numero maximo de trabajadores>\n"); exit(0); } // Obtengo el argumento y lo convierto a número max_employees = atoi(argv[1]);//convierte lo que recibe a número setbuf(stdin, NULL); //limpiar el bufer printf("\nEl valor ingresado fue: %d\n", max_employees); /* Obtener espacio dinámico en memoria. */ nombres = (char (*)[MAX_CHARACTER_NAME]) malloc(sizeof(char[MAX_CHARACTER_NAME]) * max_employees); salarios = (float *) malloc(sizeof(float) * max_employees); //Validar que el número ingresado sea positivo if(max_employees<=0){ printf("\nError: El número de empleados ingresado no es válido,\ndebe ser un número mayor a cero.\n"); exit(0); }else{ printf("La lista tendrá una cantidad máxima de %d trabajadores\n", max_employees); do{ getOption(&option); printf("\nLa opción escogida fue %c\n", option); switch (option){ case 'a': registerEmployees(nombres, salarios); break; case 'b': printf("El salario total es: "); getTotal(salarios, &total); break; case 'c': showList(nombres, salarios, &total); break; case 'q': printf("\nSaliendo del programa..\n\n"); break; default: printf("La opción %c escogida no es válida, seleccione de nuevo.\n", option); } }while(option !='q'); } /* Liberar memoria. */ free(nombres); free(salarios); /* Mostrar resultados. */ return 0; }
Weight::Weight(int a, int b) { lbs = a; ozs = b; getTotal(); }
XObjectPtr FunctionSubstring::execute( XPathExecutionContext& executionContext, XalanNode* /* context */, const XObjectPtr arg1, const XObjectPtr arg2, const XObjectPtr arg3, const LocatorType* /* locator */) const { assert(arg1.null() == false && arg2.null() == false); const XalanDOMString& theSourceString = arg1->str(); const XalanDOMString::size_type theSourceStringLength = length(theSourceString); if (theSourceStringLength == 0) { return createEmptyString(executionContext); } else { // Get the value of the second argument... const double theSecondArgValue = DoubleSupport::round(arg2->num()); // XPath indexes from 1, so this is the first XPath index.... const XalanDOMString::size_type theStartIndex = getStartIndex(theSecondArgValue, theSourceStringLength); if (theStartIndex >= theSourceStringLength) { return createEmptyString(executionContext); } else { const double theTotal = getTotal(theSourceStringLength, theSecondArgValue, arg3); if (DoubleSupport::isNaN(theSecondArgValue) == true || DoubleSupport::isNaN(theTotal) == true || DoubleSupport::isNegativeInfinity(theTotal) == true || theTotal == 0.0 || theTotal < double(theStartIndex)) { return createEmptyString(executionContext); } else { const XalanDOMString::size_type theSubstringLength = getSubstringLength( theSourceStringLength, theStartIndex, theTotal); XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext); XalanDOMString& theString = theResult.get(); assign( theString, toCharArray(theSourceString) + theStartIndex, theSubstringLength); return executionContext.getXObjectFactory().createString(theResult); } } } }
void print() const { ::printf("total %.06f count %zu avg %.06f max %.06f min %.06f\n", getTotal(), getCount(), getAverage(), getMax(), getMin()); }