void FileExplorer_Main() { dir[6] = '\0'; //Reset the file path count = file_list(dir, &files); //------------------------------------ INPUT ---------------------------------------- //Both touch and buttons input supported if ((posX > 0 && posX < 158) && (posY > 240 - 24 && posY < 240)) mode = 2; //Close //Buttons item selection if (input & KEY_UP) FileExplorer_PrevSelection(); else if (input & KEY_DOWN) FileExplorer_NextSelection(); else if (input & KEY_A) FileExplorer_Select(); //Touch item selection if ((posX > 32 && posX < 266) && (posY > 10 && posY < 240 - 24 - 40 - (10 - itemShown)*fontBlack.height)) { //If tap on file manager item int selectedItem = (posY - 19) / fontBlack.height + beginning; if (pointer == selectedItem)FileExplorer_Select(); else pointer = selectedItem; } if (((posX > 11 && posX < 30) && (posY > 62 && posY < 129)) && beginning != 0) pointer = beginning - 1;//Prev FM page if (((posX > 289 && posX < 312) && (posY > 62 && posY < 129)) && count > beginning + 10) pointer = beginning + 10;//Next FM page if (pointer - beginning == 10)beginning += 10; if (pointer < beginning)beginning -= 10; }
static ERROR program_link(const struct stage *stage) { const char *out_fn = "a.out"; const char *main_fn = "a.out.c"; FILE *run = fopen(main_fn, "w"); if (run == NULL) { THROWF(errno, "Cannot open output file '%s'", main_fn); } fprintf(run, "int _$Nmain(void);\n" "void _$Nprelude(int *argc, char ***argv, char ***env);\n" "int _$Ninvoke_main(void);\n" "extern int n$builtins$last_exit_code;\n" "void _$Npostlude(int *ret);\n"); fprintf(run, "int main(int argc, char **argv, char **env) {\n" "_$Nprelude(&argc, &argv, &env);\n" "n$builtins$last_exit_code = _$Ninvoke_main();\n" "return n$builtins$last_exit_code;\n" "}\n"); fclose(run); char *inputs = file_list((const struct module **)stage->sorted, stage->sorted_count, o_filename); error e = clink(stage, out_fn, inputs, main_fn); free(inputs); EXCEPT(e); return 0; }
// get the files in the directory and add them to the output collection File_Bag process_directory(std::string arg) { File_Bag files; auto bag = file_list(arg); for (auto file = bag.cbegin(); file != bag.cend(); ++file) files.insert(*file); return files; }
struct variable *sys_file_list(struct context *context) { struct variable *arguments = (struct variable*)stack_pop(context->operand_stack); struct variable *path = array_get(arguments->list.ordered, 1); const char *path2 = hal_doc_path(path->str); struct variable *result = variable_new_list(context, NULL); struct file_list_context flc = {context, result}; file_list(path2, &file_list_callback, &flc); return flc.result; }
void myPicture::show_picture() { label_pic_dis->setPixmap(picmap[k]->scaled(label_pic_dis->width(),label_pic_dis->height())); k++; if(k >= listlen) k = 0; if(valchanged == 1) { file_list(); valchanged = 0; } }
static ERROR run_examples(const struct stage *stage) { static const char *out_fn = "a.out.examples"; static const char *main_fn = "a.out.examples.c"; FILE *run = fopen(main_fn, "w"); if (run == NULL) { THROWF(errno, "Cannot open output file '%s'", main_fn); } for (size_t n = 0; n < stage->sorted_count; ++n) { const struct module *mod = stage->sorted[n]; fprintf(run, "void "); print_c_runexamples_name(run, mod); fprintf(run, "(void);\n"); } fprintf(run, "void _$Nprelude(int *argc, char ***argv, char ***env);\n" "extern int n$builtins$last_exit_code;\n" "void _$Npostlude(int *ret);\n"); fprintf(run, "int main(int argc, char **argv, char **env) {\n" "_$Nprelude(&argc, &argv, &env);\n"); for (size_t n = 0; n < stage->sorted_count; ++n) { const struct module *mod = stage->sorted[n]; print_c_runexamples_name(run, mod); fprintf(run, "();\n"); } fprintf(run, "n$builtins$last_exit_code = 0;\n" "return n$builtins$last_exit_code;\n" "}\n"); fclose(run); char *inputs = file_list((const struct module **)stage->sorted, stage->sorted_count, o_filename); error e = clink(stage, out_fn, inputs, main_fn); free(inputs); EXCEPT(e); static const char *fmt = "%s ./%s%s"; const char *runner = ""; const char *ext = ""; if (strcmp(g_opt.compiler, "emcc") == 0) { runner = "d8"; ext = ".js"; } char *cmd = calloc(strlen(fmt) + strlen(runner) + strlen(main_fn) + strlen(ext) + 1, sizeof(char)); sprintf(cmd, fmt, runner, out_fn, ext); e = sh(cmd); free(cmd); EXCEPTF(e, "examples failed"); return 0; }
/** * recover_all -- Iterates over all core tables in enumerated order for recovery from * journal files (.jnl). * The parm 'lastn' is the number of journal files needed to be recovered. * Hardcoded to only find MAXFILES. * * e.g. * 25 journal files are present for the 'acc' table, however you only * want to restore the latest 3; so lastn=3. */ int recover_all(int lastn) { lnode_p n, h; tbl_cache_p _tbc = tables; if(MAXFILES < lastn) return 1; if(!schema_dir) { fprintf(stderr, "[recover_all]: null path to schema files.\n"); return 1; } if(!db_home) { fprintf(stderr, "[recover_all]: null path to db_home.\n"); return 1; } while(_tbc) { int j; if(_tbc->dtp) h = file_list(db_home, _tbc->dtp->name); n = h; /*lastn; move to the oldest of the N*/ for(j=1;j<lastn;j++) if(n && (n->next != NULL) ) n = n->next; while(n) { printf("[recover_all] recovering file: %s\n",n->p); if(recover(n->p)) fprintf(stderr, "[recover_all]: Error while recovering: [%s]\n. Continuing..\n",n->p); n = n->prev; } while(h) /*free mem*/ { n = h->next; free(h->p); free(h); h = n; } _tbc = _tbc->next; } return 0; }
myPicture::myPicture(QWidget *parent) :QLabel(parent) { k = 0; listlen = 0; valchanged = 0; file_list(); label_pic_dis = new QLabel(parent); label_pic_dis->setGeometry(569, 139, 240, 261); show_picture(); QTimer *timer1 = new QTimer(parent); QObject::connect(timer1,SIGNAL(timeout()),this,SLOT(show_picture())); timer1->stop(); timer1->start(2000); }
t_err autocomplete_file(char *arg, t_autocomp *autoc) { int i; int len; len = my_strlen(arg); i = len; while (--i >= 0 && arg[i] != '/'); if (i == -1) { autoc->buf = my_strdup(arg); return (file_list(autoc, NULL)); } else return (autocomplete_path(i, autoc, arg)); }
t_err autocomplete_path(int i, t_autocomp *autoc, char *arg) { char **pathes; t_err err; if (!(pathes = malloc(sizeof(char *) * 2)) || !(pathes[0] = my_strndup(arg, i))) return (print_error(ERROR_MALLOC_FAILED)); pathes[1] = NULL; if (arg[i + 1]) { if (!(autoc->buf = my_strdup(&arg[i + 1]))) return (print_error(ERROR_MALLOC_FAILED)); } else autoc->buf = NULL; if ((err = file_list(autoc, pathes))) return (err); free(pathes[0]); free(pathes); return (0); }
///递归遍历指定文件夹,并输出所有文件 void file_list(const char*fileName,int layer){ DIR *pRec = opendir(fileName); if(pRec){ struct dirent *pDir; while( (pDir = readdir(pRec)) ){ char path[PATH_MAX+1]; memset(path,'\0',PATH_MAX+1); int len = strlen(fileName);//without '\0' strncpy(path,fileName,len); strcat(path,"/"); strcat(path,pDir->d_name); //1 表示是目录,0表示是文件 int type = get_file_type(path); if(type){ //当不是.和..时才进入下一级目录 if(strcmp(pDir->d_name,".") && strcmp(pDir->d_name,"..")){ //show_file(pDir->d_name,layer); file_list(path,++layer); }else{ //printf("test:%s\n",pDir->d_name); //show_file(pDir->d_name,layer); } }else{ //show_file(pDir->d_name,layer); //直接删除文件 dele_file(path); } } //此时文件夹中的文件已经全部被删除 dele_dir(fileName); }else{ //show_file(fileName,--layer); // Since file_suc is not equal to zero that means the specify path // is legal. if(!file_suc){ printf("Specify path is illegal,please check again.\n"); } } }
int main() { struct sockaddr_in server; struct sockaddr_in dest; int socket_fd, client_fd,num; socklen_t size; SSL_CTX *ctx; /******* START SSL ***************/ /* http://mooon.blog.51cto.com/1246491/909932 */ /* SSL Libraries Init */ SSL_library_init(); /* add all SSL algorithms */ OpenSSL_add_all_algorithms(); /* add all SSL ciphers */ OpenSSL_add_all_ciphers(); /* add all digests */ OpenSSL_add_all_digests(); /* load all SSL errors */ SSL_load_error_strings(); /* Build SSL_CTX -> SSL Content Text * SSLv2_server_method() or SSLv3_server_method() relative to SSL V2 * and SSL V3 */ ctx = SSL_CTX_new(SSLv23_server_method()); if(ctx == NULL){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the server certificate into the SSL_CTX structure */ if(SSL_CTX_use_certificate_file(ctx,RSA_SERVER_CERT,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Load the private-key corresponding to the server certificate */ if(SSL_CTX_use_PrivateKey_file(ctx,RSA_SERVER_KEY,SSL_FILETYPE_PEM) <= 0){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /* Check if the server certificate and private-key matches */ if(!SSL_CTX_check_private_key(ctx)){ ERR_print_errors_fp(stdout); exit(EXIT_FAILURE); } /*********** END SSL ****************/ int yes =1; /* Open a socket to listen */ if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(EXIT_FAILURE); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } /* init memory for server and dest */ memset(&server, 0, sizeof(server)); memset(&dest,0,sizeof(dest)); server.sin_family = AF_INET; //same to PF_INET server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; /* BIND SOCKET */ if ((bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(EXIT_FAILURE); } /* START LISTENING */ if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(EXIT_FAILURE); } while(1) { SSL *ssl; size = sizeof(struct sockaddr_in); /* Waiting for client to connect */ if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) { perror("accept"); continue; //exit(EXIT_FAILURE); } else{ printf("Server got connection from client %s, port %d, socket %d\n", inet_ntoa(dest.sin_addr),ntohs(dest.sin_port),client_fd); } /* /connection complete */ /* create a new ssl based on ctx */ ssl = SSL_new(ctx); /* add socket : client_fd to SSL */ SSL_set_fd(ssl,client_fd); /* Build up SSL connection */ if(SSL_accept(ssl) == -1){ perror("accept"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } /******* START PROCESSING DATA *************/ /* read header - then do action based on header parsing */ char header_buf[HEADER_SIZE]; int len = HEADER_SIZE; if ((num = recv_all(ssl, (unsigned char *)header_buf, &len))== -1) { printf("Read header failed\n"); perror("recv"); SSL_shutdown(ssl); SSL_free(ssl); close(client_fd); continue; //exit(EXIT_FAILURE); } char *hr = NULL; hr = malloc(3); SSL_read(ssl, hr, sizeof(hr)); if(strcmp("100",hr)){ printf("Header receiving failed\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } else{ printf("Header received successfully\n"); } /* unpack header string */ header h; if (unpack_header_string(header_buf, &h) == -1) { fprintf(stderr, "[SERVER] Could not unpack header information from client\n"); h.action = FAIL_ERROR; //exit(EXIT_FAILURE); } if (h.action == FAIL_ERROR) { printf("Header action is FAIL ERROR\n"); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } //inform client header unpacked successfully SSL_write(ssl,"100",strlen("100")); printf("Header unpacked successfully\n"); // header part end // if client requests to uplaod file if (h.action == ADD_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Adding file %s\n", target); receive_file(ssl, target, h.file_size); free(target); } else if (h.action == FETCH_FILE) { char *target = NULL; target = malloc(BLOCK_SIZE); sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); printf("[SERVER] Fetching file %s\n", target); FILE *fp; if (!(fp = fopen(target, "r"))) { perror("fopen"); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } free(target); // get file's protection rating to compare to // client's requested circumference int protectionRating = getProtectionRating(h.file_name); header h_send; if (protectionRating >= h.circ) { h_send.action = ADD_FILE; } else { h_send.action = FAIL_ERROR; // client will fail out } h_send.file_size = get_file_size(fp); h_send.file_name = h.file_name; h_send.certificate = " "; send_header(ssl, h_send); if (protectionRating >= h.circ) send_file(ssl, fp); fclose(fp); } else if (h.action == UPLOAD_CERT) { char target[MAXSIZE]; sprintf(target, "%s/%s_crt.pem", SERVER_CERT_DIR, h.file_name); printf("Receiving cert and storing: %s\n", target); receive_file(ssl, target, h.file_size); }// if client requests to list files else if (h.action == LIST_FILE) { char **files; size_t count; unsigned int i; count = file_list(SERVER_FILE_DIR, &files); for (i = 0; i < count; i++) { char *send_str = NULL; send_str = malloc(MAXSIZE); int protectionRating = getProtectionRating(files[i]); if (protectionRating >= h.circ) { sprintf(send_str, "Protected (c = %i): %s",protectionRating,files[i]); } else { sprintf(send_str, "Unprotected (c = %i): %s",protectionRating,files[i]); } send_message(ssl, send_str); free(send_str); } printf("File list transmitting completed.\n"); close(client_fd); printf("Client connection closed.\n"); } /* if client requires to vouch a file * https://gitorious.org/random_play/random_play/source/b9f19d4d9e8d4a9ba0ef55a6b0e2113d1c6a5587:openssl_sign.c */ else if (h.action == VOUCH_FILE){ // vouch for this file const char *clearTextFileName = h.file_name; int isCertFile = isNameCertFile(clearTextFileName); // vouch using this certificate char *certificate_file_name = h.certificate; char *cert_loc = NULL; cert_loc = malloc(MAXSIZE); sprintf(cert_loc, "%s/%s", SERVER_CERT_DIR, certificate_file_name); if (!check_if_file_exists(cert_loc)) { char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Unable to locate %s certificate on the server. Please upload using -a\n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; // should notify client here somehow } else{ char *message = NULL; message = malloc(MAXSIZE); sprintf(message, "Located %s certificate on the server. \n", cert_loc); SSL_write(ssl, message,strlen(message)); free(message); } free(cert_loc); char *target = NULL; target = malloc(MAXSIZE); if (isCertFile) { sprintf(target, "%s/%s", SERVER_CERT_DIR, h.file_name); } else { sprintf(target, "%s/%s", SERVER_FILE_DIR, h.file_name); } unsigned char *md5Value = NULL; md5Value = malloc(MD5_DIGEST_LENGTH); if(hashFile(md5Value, (const char *)target)!=0){ printf("Couldn't open file"); free(target); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; } free(target); send_message(ssl, (char *)md5Value); unsigned char signature[MAXSIZE]; SSL_read(ssl, signature, 128); char *sig_name = NULL; sig_name = malloc(MAXSIZE); // keep certificate signatures with certificates if (isCertFile) { sprintf(sig_name, "%s/%s_%s.sig", SERVER_CERT_DIR, clearTextFileName, certificate_file_name); } else { sprintf(sig_name, "%s/%s_%s.sig", SERVER_SIG_DIR, clearTextFileName, certificate_file_name); } if (writeSig(signature, sig_name) != 0) { fprintf(stderr, "Could not save signature file\n"); free(sig_name); SSL_write(ssl,"-1",strlen("-1")); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); continue; //exit(EXIT_FAILURE); } else{ printf("Sig loc: %s\n", sig_name); SSL_write(ssl,"100",strlen("100")); } free(sig_name); } else if (h.action == VERIFY_FILE){ // test verification of signature files char signatoryCertName[MAXSIZE]; sprintf( signatoryCertName, "%s_crt.pem", h.certificate ); const char *clearText = h.file_name; if(!verifySig(signatoryCertName,clearText)){ printf("Verify failed\n"); } } else if (h.action == FIND_ISSUER){ char certPath[MAXSIZE]; sprintf( certPath, "%s", h.certificate ); } else if (h.action == TEST_RINGOFTRUST) { ringOfTrust(h.file_name); } /********** END DATA PROCESSING **************/ free(h.certificate); free(h.file_name); /* Close SSL Connection */ SSL_shutdown(ssl); /* Release SSL */ SSL_free(ssl); //Close Connection Socket close(client_fd); } //Outer While /* Close listening socket */ close(socket_fd); /* Release CTX */ SSL_CTX_free(ctx); return 0; } //End of main
int generate(int num_samples) { msr::airlib::MultirotorRpcLibClient client; client.confirmConnection(); msr::airlib::ClockBase* clock = msr::airlib::ClockFactory::get(); RandomPointPoseGenerator pose_generator(static_cast<int>(clock->nowNanos())); std::fstream file_list(FileSystem::combine(storage_dir_, "files_list.txt"), std::ios::out | std::ios::in | std::ios_base::app); int sample = getImageCount(file_list); common_utils::ProsumerQueue<ImagesResult> results; std::thread result_process_thread(processImages, & results); try { while(sample < num_samples) { //const auto& collision_info = client.getCollisionInfo(); //if (collision_info.has_collided) { // pose_generator.next(); // client.simSetPose(pose_generator.position, pose_generator.orientation); // std::cout << "Collison at " << VectorMath::toString(collision_info.position) // << "Moving to next pose: " << VectorMath::toString(pose_generator.position) // << std::endl; // continue; //} ++sample; auto start_nanos = clock->nowNanos(); std::vector<ImageRequest> request = { ImageRequest(0, ImageType::Scene), ImageRequest(1, ImageType::Scene), ImageRequest(1, ImageType::DisparityNormalized, true) }; const std::vector<ImageResponse>& response = client.simGetImages(request); if (response.size() != 3) { std::cout << "Images were not recieved!" << std::endl; start_nanos = clock->nowNanos(); continue; } ImagesResult result; result.file_list = &file_list; result.response = response; result.sample = sample; result.render_time = clock->elapsedSince(start_nanos);; result.storage_dir_ = storage_dir_; result.position = pose_generator.position; result.orientation = pose_generator.orientation; results.push(result); pose_generator.next(); client.simSetPose(Pose(pose_generator.position, pose_generator.orientation), true); } } catch (rpc::timeout &t) { // will display a message like // rpc::timeout: Timeout of 50ms while calling RPC function 'sleep' std::cout << t.what() << std::endl; } results.setIsDone(true); result_process_thread.join(); return 0; }
t_err autocomplete_cmd(char *arg, t_autocomp *autoc, char **pathes) { autoc->buf = arg; return (file_list(autoc, pathes)); }
int mymain(int argc, char **argv) { setlocale(LC_ALL, "Russian"); init_dicts(); //if (argc != 4) //{ // throw CExpc ("bad number of arguments"); //} /* читаем малый словарь, который состоит из пар слов отдельно на каждой строке типа "аббат abbot" считается, что если пара попала в этот словарь, то у этой пары хороший вес для перевода. Параллелльно считаем скорость морфологии7 */ std::cerr << "Opening small dictionary\t\t\t\r"; std::ifstream SmallDict("C:\\RML\\Dicts\\SrcBinDict\\shira.txt");//<<<<<CONST assert(SmallDict.is_open()); clock_t MorphTime = 0; while (true){ char buff[2048]; SmallDict.getline(buff, 2047); if (!SmallDict) break; /* на самом деле, здесь возможны словосочетания как с русской, так и с англ. стороны От словосочетания всегда берем только первое слово. */ StringTokenizer tok(buff, " \t"); StringVector vec; const char *word; while ((word = tok())) vec.push_back(word); std::string r, e; if (vec.size() < 2) continue; if (vec.size() == 2){ r = vec[0]; e = vec[1]; } else{ r = vec[0]; int i = 1; // проходим все русские слова while ((unsigned char)vec[i][0] > 128 && i < vec.size()) i++; if (i == vec.size() - 1) e = vec[i]; else continue; } // лемматизируем clock_t ltime1 = clock(); DwordVector r_id, e_id; MorphHolderRus.string_to_ids(r.c_str(), r_id, true); MorphHolderEng.string_to_ids(e.c_str(), e_id, true); clock_t ltime2 = clock(); MorphTime += ltime2 - ltime1; for (int R = 0; R < r_id.size(); R++) for (int E = 0; E < e_id.size(); E++) SmallDictSet.insert(std::make_pair(r_id[R], e_id[E])); } SmallDict.close(); std::cerr << "Done\t" << SmallDictSet.size() << "\t\t\t\n"; if (MorphTime > 0) { MorphTime /= CLOCKS_PER_SEC; if (MorphTime > 0) std::cerr << "Morphology of norm norm/second)\t" << double(SmallDictSet.size() * 2 / MorphTime) << "\t\t\t\n"; }; std::cerr << "Parsing aligned sentences\t\t\t\r"; const char *in_str = "C:\\RML\\Texts\\freq_hud.txt"; const char *out_str = "C:\\RML\\Dicts\\BinDict\\freq_hud.bin"; std::ifstream file_list(in_str); out.open(out_str, std::ios::binary); if (!out.is_open()) { std::cerr << "cannot open output file!" << out_str << std::endl; return -1; }; if (!file_list.is_open()) { std::cerr << "cannot open list-file !" << in_str << std::endl; return -1; }; while (true) { std::string file_name; std::string file; file_list >> file; file_name = "C:/RML/" + file; if (!file_list) break; std::ifstream in(file_name.c_str()); assert(in.is_open()); int sent_no = 0; while (true){ char buff[2][4096]; in.getline(buff[0], 4095); in.getline(buff[1], 4095); if (!in) break; const char *word; StringTokenizer r_tok(buff[0], " \t"); StringTokenizer e_tok(buff[1], " \t"); std::vector<CFormInfo> e_id, r_id; while ((word = r_tok())) { std::vector<CFormInfo> p; string w = word; if (MorphHolderRus.m_pLemmatizer->CreateParadigmCollection(false, w, false, false, p)) r_id.insert(r_id.end(), p.begin(), p.end()); } while ((word = e_tok())) { std::vector<CFormInfo> p; string w = word; if (MorphHolderEng.m_pLemmatizer->CreateParadigmCollection(false, w, false, false, p)) e_id.insert(e_id.end(), p.begin(), p.end()); } for (int r = 0; r < r_id.size(); r++) for (int e = 0; e < e_id.size(); e++) if (BinaryDictionary.HavePair(e_id[e].GetParadigmId(), r_id[r].GetParadigmId())) { word_map[word_pair(e_id[e].GetParadigmId(), r_id[r].GetParadigmId())]++; break; } } in.close(); } /* вычисляю максимальную частоту и увеличиваю частоту пары слов, которая была найдена в малом словаре */ long MaxFreq = 0; std::set<std::pair<long, long> > SmallDictUsed; std::map<word_pair, int>::iterator it = word_map.begin(); for (; it != word_map.end(); ++it) { if (SmallDictSet.count(std::make_pair(it->first.r, it->first.e))) { it->second *= 3; if (it->second < 6) it->second = 6; SmallDictUsed.insert(std::make_pair(it->first.r, it->first.e)); } if (it->second > MaxFreq) MaxFreq = it->second; }; // writting out file and dump int written = 0; std::cout << "Frequence of Pair\tRussian Lemma\tEnglish Lemma"; for (it = word_map.begin(); it != word_map.end(); ++it) { std::string rus = MorphHolderRus.id_to_string(it->first.r); std::string eng = MorphHolderEng.id_to_string(it->first.e); out.write((char*)&(it->first.e), sizeof(long)); out.write((char*)&(it->first.r), sizeof(long)); unsigned short freq = it->second; /* частота не должна превышать USHRT_MAX, поэтому нужно нормализовать частоту */ if (MaxFreq > USHRT_MAX) freq *= USHRT_MAX / MaxFreq; out.write((char*)&(freq), sizeof(unsigned short)); // выводим дамп std::cout << it->second << '\t' << rus.c_str() << '\t' << eng.c_str() << std::endl; written++; } /* проходим по малому словарю, если пара из этого словаря не была записана в выходной файл, пишем с частотой пять берутся только существительные, глаголы, прил. и нар, */ for (std::set<std::pair<long, long> >::iterator shira_it = SmallDictSet.begin(); shira_it != SmallDictSet.end(); ++shira_it) { if (SmallDictUsed.count(*shira_it)) continue; CFormInfo rp = MorphHolderRus.id_to_paradigm(shira_it->first); CFormInfo ep = MorphHolderEng.id_to_paradigm(shira_it->second); BYTE r_pos = MorphHolderRus.m_pGramTab->GetPartOfSpeech(rp.GetAncode(0).c_str()); BYTE e_pos = MorphHolderEng.m_pGramTab->GetPartOfSpeech(ep.GetAncode(0).c_str()); BYTE t_pos = 0xff; if (r_pos == NOUN && e_pos == eNOUN)t_pos = 0; if (r_pos == ADJ_FULL && e_pos == eADJ)t_pos = 2; if (r_pos == ADJ_SHORT && e_pos == eADJ)t_pos = 2; if (r_pos == ADV && e_pos == eADV)t_pos = 3; if (r_pos == PREDK && e_pos == eADV)t_pos = 3; if (r_pos == INFINITIVE && e_pos == eVERB)t_pos = 1; if (t_pos == 0xff) continue; long id = ep.GetParadigmId(); out.write((char*)&(id), sizeof(long)); id = rp.GetParadigmId(); out.write((char*)&(id), sizeof(long)); unsigned short freq = 5; out.write((char*)&(freq), sizeof(unsigned short)); std::string rus = MorphHolderRus.id_to_string(shira_it->first); std::string eng = MorphHolderEng.id_to_string(shira_it->second); if (!BinaryDictionary.HavePair(shira_it->second, shira_it->first)) { std::cerr << rus << " " << rp.GetAncode(0).c_str() << " " << eng; std::cerr << " " << ep.GetAncode(0).c_str() << " " << t_pos << " 0 0 0 0" << std::endl; } std::cout << 5 << '\t' << rus << '\t' << eng << std::endl; written++; } std::cerr << "Written " << written << "\t\t\t" << std::endl; out.close(); file_list.close(); return 0; }
void print::visit (t_extra_dist &n) { file_list (n, "extra_dist"); }
void TypeDependenceChecker::OutputMake(FileSymbol* file_symbol) { // // // const char* name; char* buf = NULL; int length; if (control -> option.directory == NULL) { name = file_symbol -> FileName(); length = file_symbol -> FileNameLength() - (file_symbol -> IsJava() ? FileSymbol::java_suffix_length : FileSymbol::class_suffix_length); } else { name = file_symbol -> Utf8Name(); length = strlen(name); DirectorySymbol* dir_symbol = file_symbol -> OutputDirectory(); char* dir_name = dir_symbol -> DirectoryName(); int dir_length = strlen(dir_name); buf = new char[length + FileSymbol::class_suffix_length + dir_length + 2]; strcpy(buf, dir_name); #ifdef UNIX_FILE_SYSTEM buf[dir_length] = (char)U_SLASH; #elif defined(WIN32_FILE_SYSTEM) buf[dir_length] = (char)U_BACKSLASH; #endif strcpy(&buf[dir_length+1], name); name = buf; length = dir_length + 1 + length; } char* output_name = new char[length + FileSymbol::class_suffix_length + 1]; char* u_name = new char[length + strlen(StringConstant::U8S_DO_u) + 1]; strncpy(output_name, name, length); strncpy(u_name, name, length); strcpy(&output_name[length], FileSymbol::class_suffix); strcpy(&u_name[length], StringConstant::U8S_DO_u); // // // SymbolSet file_set; for (unsigned i = 0; i < file_symbol -> types.Length(); i++) { TypeSymbol* type = file_symbol -> types[i]; TypeSymbol* parent; for (parent = (TypeSymbol*) type -> parents_closure -> FirstElement(); parent; parent = (TypeSymbol*) type -> parents_closure -> NextElement()) { FileSymbol* symbol = parent -> file_symbol; if (symbol && (! symbol -> IsZip())) file_set.AddElement(symbol); } } file_set.RemoveElement(file_symbol); // // // Tuple<FileSymbol*> file_list(file_set.Size()); file_list.Next() = file_symbol; for (FileSymbol* symbol = (FileSymbol*) file_set.FirstElement(); symbol; symbol = (FileSymbol*) file_set.NextElement()) file_list.Next() = symbol; FILE* outfile = SystemFopen(u_name, "w"); if (outfile == NULL) Coutput << "*** Cannot open output Makefile " << u_name << endl; else { OutputMake(outfile, output_name, file_list); fclose(outfile); } delete [] output_name; delete [] u_name; if (control -> option.directory) delete [] buf; }
int main() { //printf("%d\n", SEND_FILE); struct sockaddr_in server; struct sockaddr_in dest; int status,socket_fd, client_fd,num; socklen_t size; //char buffer[1024]; char *buff; // memset(buffer,0,sizeof(buffer)); int yes =1; if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0))== -1) { fprintf(stderr, "Socket failure!!\n"); exit(EXIT_FAILURE); } if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } memset(&server, 0, sizeof(server)); memset(&dest,0,sizeof(dest)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; if ((bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr )))== -1) { //sizeof(struct sockaddr) fprintf(stderr, "Binding Failure\n"); exit(EXIT_FAILURE); } if ((listen(socket_fd, BACKLOG))== -1){ fprintf(stderr, "Listening Failure\n"); exit(EXIT_FAILURE); } while(1) { size = sizeof(struct sockaddr_in); if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) { perror("accept"); exit(EXIT_FAILURE); } printf("Server got connection from client %s\n", inet_ntoa(dest.sin_addr)); char header[1024]; // read header - then do action based on header parsing if ((num = recv(client_fd, header, 1024,0))== -1) { perror("recv"); exit(EXIT_FAILURE); } else if (num == 0) { printf("Connection closed\n"); //So I can now wait for another client continue; } // printf("%s\n", buffer); while(TRUE){ // if client requests to uplaod file if (strcmp(header, "send") == 0) { char *file_name = "written.txt"; // TODO get file_name from header receive_file(client_fd, file_name); } else if (strcmp(header, "list") == 0) { char **files; size_t count; unsigned int i; count = file_list("./", &files); printf("There are %zu files in the directory,transmitting file list.\n", count); for (i = 0; i < count; i++) { send_message(client_fd,files[i]); sleep(1); } printf("File list transmitting completed.\n"); close(client_fd); printf("Client connection closed.\n"); } break; } } //Outer While close(socket_fd); return 0; } //End of main
void print::visit (t_nodist_sources &n) { file_list (n, "nodist_sources"); }
int main(void) { //LCD_begin(); UINT16 i=0,temporary1,temporary2,song_num=0,song_position=0,k,key,key2,key3,key4,sw[17],sw0,sw1,clupsec_num,data_sector; UINT16 back[2]={0},num_lyric,num_music,num_lyrics,time_base,j_base,base,fat_addr,cluster_num; UINT32 j; unsigned int cl[3000]; BYTE Buffer[512]={0}; while(SD_card_init()) // wait for the card to be inserted usleep(500000); LCD_begin(); struct music0 music[30]; struct lyric0 lyric[30]; struct lyrics0 lyrics; char title[2][18]={" Press KEY1 to ", " select a song "}; char text[2][16]={"songs", "lyrics"}; char wait[16]="loading"; file_list(music,lyric,&num_music,&num_lyric,&clupsec_num, &data_sector,&fat_addr); // search and update the database from the SD card sw1=IORD(SW_BASE,0); back[0]=sw1&0x20000; while(1) { IOWR(SEG7_BASE,0,0); sw0=IORD(SW_BASE,0); sw0=sw0&0x07; sw[0]=sw0&0x01; sw[1]=sw0&0x02; sw[2]=sw0&0x04; if(!sw0) { LCD_Init(); LCD_Show_Text(title[0]); lcd_write_command(LCD_BASE,0xC0); LCD_Show_Text(title[1]); while(1) { key=IORD(KEY_BASE,0); // wait till key2 is pressed key2=~key&0x02; if(key2) break; } LCD_Init(); lcd_write_command(LCD_BASE,0x80); usleep(100); lcd_write_data(LCD_BASE,(char)(num_music/10+0x30)); // display the number of wav files usleep(100); lcd_write_data(LCD_BASE,(char)(num_music%10+0x30)); usleep(100); for(i=0;i<5;i++) { lcd_write_data(LCD_BASE,text[0][i]); usleep(100); } lcd_write_command(LCD_BASE,0xc0); usleep(100); lcd_write_data(LCD_BASE,(char)(num_lyric/10+0x30)); // display the number of lysic files usleep(100); lcd_write_data(LCD_BASE,(char)(num_lyric%10+0x30)); usleep(100); for(i=0;i<6;i++) { lcd_write_data(LCD_BASE,text[1][i]); usleep(100); } usleep(1000000); while(1) { show_name(music[song_num].m_name); key=IORD(KEY_BASE,0); key=~key&0x0e; if(key) { key2=key&0x02; key3=key&0x04; key4=key&0x08; if(key2) break; else if(key3) { song_num=(song_num+1)%num_music; // next song } else if(key4) { song_num=(song_num+num_music-1)%num_music; // previous song } else ; } time(0,song_num+1,num_music); } } else if(sw[0]) { song_num=(song_num+1)%num_music; // continuous time(0,song_num+1,num_music); } else if(sw[1]) { song_num+=0; time(0,song_num+1,num_music); // repeat the song } else if(sw[2]) { song_num=(num_lyrics+temporary1+temporary2+music[song_num].m_name[0])%num_music; // random play time(0,song_num+1,num_music); } LCD_Init(); LCD_Show_Text(wait); num_lyrics=read_lyrics(music[song_num].m_name,lyric,&lyrics,num_lyric,&clupsec_num, &data_sector); //lyrics cl[0]=music[song_num].cluster; find_cluster(song_num,fat_addr,cl); for(i=0;cl[i]>1;i++); cluster_num=i; show_name(music[song_num].m_name); // show the name of the song for(song_position=0;song_position<cluster_num;song_position++) { base=(cl[song_position]-2)*clupsec_num+data_sector; j_base=song_position*clupsec_num-base; sw1=IORD(SW_BASE,0); sw[4]=sw1&0x10; sw[5]=sw1&0x20; sw[6]=sw1&0x40; back[1]=sw1&0x20000; if(back[1]!=back[0]) { back[0]=back[1]; break; } if(sw[4]) { song_position=(song_position+4)%cluster_num; time(song_position*clupsec_num,song_num+1,num_music); // fast forward usleep(20000); continue; } else if(sw[6]) { song_position=(song_position+cluster_num-4)%cluster_num; time(song_position*clupsec_num,song_num+1,num_music); // pause usleep(20000); continue; } else if(sw[5]) { song_position=(song_position+cluster_num-1)%cluster_num; // reverse usleep(20000); continue; } for(j=base;j<base+clupsec_num;j++) //j is the section in the cluster { SD_read_lba(Buffer,j,1); // read function from SD card controller.c i=0; while(i<512) { if(!IORD(AUDIO_BASE,0)) { temporary1=((Buffer[i+1]<<8)|Buffer[i]); // read from SD card IOWR(AUDIO_BASE,0,temporary1); i+=2; } } if(j%32==0) { unsigned int x=0; unsigned int y=0xffff; unsigned int z = temporary1; do { x++; z=z<<1; }while((z & 0x8000)==0); y=y>>x; IOWR(LEDR_BASE,0,y); IOWR(LEDG_BASE,0,z); } /********************************************************************/ time(j+j_base,song_num+1,num_music); //display time for(k=0;k<num_lyrics;k++) //display lyric { time_base=j_base-lyrics.time[k]-2; if(j+j_base==lyrics.time[k]) { lcd_write_command(LCD_BASE,0x80); break; } else if(j+j_base==lyrics.time[k]+36) { lcd_write_command(LCD_BASE,0xc0); break; } else if(j%2==0&&(j+j_base>=lyrics.time[k]+2)&&(j+j_base<=lyrics.time[k]+34)) { lcd_write_data(LCD_BASE,lyrics.text[k][(j+time_base)/2]); break; } else if(j%2==0&&(j+j_base>=lyrics.time[k]+38)&&(j+j_base<lyrics.time[k]+70)) { lcd_write_data(LCD_BASE,lyrics.text[k][(j+time_base)/2-2]); break; } } } } }