예제 #1
0
파일: util.c 프로젝트: Berticus/powaur
void print_aurpkg_list(alpm_list_t *list)
{
	alpm_list_t *i;
	struct aurpkg_t *pkg;
	const char *pkgname, *pkgver;
	size_t cols, curcols, pkglen;

	cols = getcols();
	curcols = 0;

	for (i = list; i; i = i->next) {
		pkg = i->data;
		pkgname = pkg->name;
		pkgver = pkg->version;

		pkglen = strlen(pkgname) + 1 + strlen(pkgver);
		if (curcols + pkglen > cols) {
			printf("\n");
			curcols = 0;
		}

		if (curcols == 0) {
			printf("%s %s", pkgname, pkgver);
			curcols = pkglen;
		} else {
			printf("  %s %s", pkgname, pkgver);
			curcols += pkglen + 2;
		}
	}

	printf("\n");
}
예제 #2
0
파일: util.c 프로젝트: Berticus/powaur
void print_list(alpm_list_t *list)
{
	alpm_list_t *i;
	size_t curcols, newlen;
	size_t cols = getcols();
	if (!list) {
		printf("None\n");
		return;
	}

	curcols = 0;
	for (i = list; i; i = i->next) {
		/* There's a bug here which I'm not gonna fix. */
		newlen = curcols + 2 + strlen(i->data);
		if (newlen > cols) {
			printf("\n");
			curcols = 0;
		}

		if (curcols == 0) {
			printf("%s", i->data);
			curcols += strlen(i->data);
			continue;
		}

		curcols = newlen;
		printf("  %s", i->data);
	}

	printf("\n");
}
예제 #3
0
/*
void mkbound(pelement otmasuk[], pelement where, int* len){
	otmasuk[0]->parent = where;  where->left = otmasuk[0];
	otmasuk++;
	(*len)--;
	otmasuk[0]->parent = where;  where->right = otmasuk[0];
	where->value = where->left->value + where->right->value;
	otmasuk[0] = where;
	somesort(otmasuk, *len);
}
*/
void printtree(pelement viska, pelement cur){
	printf("%sНаше дерево Хаффмана%s\n", cyan, none);
	int wid = getcols();
	pelement a[256];
	pelement b[256];
	pelement* vivodar=a;
	pelement* subvivodar=b;
	pelement* tmp;
	vivodar[0] = viska;
	for (int q=1; q<=256; q*=2){
		for (int z=0; z<q; z++){
			for (int i=0; i<wid/q/2-2; i++) printf(" ");
			if (vivodar[z] == cur) printf("%s", red);
			printf("%4i", vivodar[z]->value);
			printf("%s", none);
			if (z!=q-1) for (int i=0; i<wid/q/2; i++) printf(" ");
		}
		printf("\n----------------\n");
		for (int i=0; i<q; i++){
			if (i >= 128) break;
			subvivodar[i*2] = vivodar[i]->left;
			subvivodar[i*2+1] = vivodar[i]->right;
		}
		tmp = vivodar;
		vivodar = subvivodar;
		subvivodar = tmp;

	}
	printf("%sГотово%s\n", green, none);
}
예제 #4
0
파일: util.c 프로젝트: ava1ar/package-query
static void indent (const char *str)
{
	const char *c=NULL, *c1=NULL;
	int cur_col=INDENT, cols;
	if (!str)
		return;
	cols=getcols();
	if (!cols)
	{
		fprintf (stdout, "%*s%s\n", INDENT, "", str);
		return;
	}
	c=str;
	fprintf (stdout, "%*s", INDENT, "");
	while ((c1=strchr (c, ' ')) != NULL)
	{
		int len = (c1-c);
		cur_col+=len+1;
		if (cur_col >= cols)
		{
			fprintf (stdout, "\n%*s%.*s ", INDENT, "", len, c);
			cur_col=INDENT+len+1;
		}
		else
			fprintf (stdout, "%.*s ", len, c);
		c=&c1[1];
	}
	cur_col+=strlen (c);
	if (cur_col >= cols && c!=str)
		fprintf (stdout, "\n%*s%s\n", INDENT, "", c);
	else
		fprintf (stdout, "%s\n", c);
}
예제 #5
0
파일: util.c 프로젝트: Berticus/powaur
void print_list_color(alpm_list_t *list, const char *wcolor)
{
	alpm_list_t *i;
	size_t curcols, newlen;
	size_t cols = getcols();
	if (!list) {
		printf("None\n");
		return;
	}

	curcols = 0;
	for (i = list; i; i = i->next) {
		newlen = curcols + 2 + strlen(i->data);
		if (newlen > cols) {
			printf("\n");
			curcols = 0;
		}

		if (curcols == 0) {
			printf("%s%s%s", wcolor, i->data, color.nocolor);
			curcols += strlen(i->data);
			continue;
		}

		curcols = newlen;
		printf("  %s%s%s", wcolor, i->data, color.nocolor);
	}

	printf("\n");
}
예제 #6
0
파일: ali.c 프로젝트: ssvlab/esbmc-gpu
static void
ali_print_name_list (mu_list_t list, int off)
{
  mu_iterator_t itr;
  char *item;
  
  mu_list_get_iterator (list, &itr);
  
  if (list_mode)
    {
      mu_iterator_first (itr);
      mu_iterator_current (itr, (void **)&item);
      printf ("%s\n", item);
      for (mu_iterator_next (itr); !mu_iterator_is_done (itr); mu_iterator_next (itr))
	{
	  int len;
	  mu_iterator_current (itr, (void **)&item);
	  len = off + strlen (item);
	  printf ("%*.*s\n", len, len, item);
	}
    }
  else
    {
      int ncol = getcols ();
      int n = off;
      
      mu_iterator_first (itr);

      for (;;)
	{
	  int len;

	  mu_iterator_current (itr, (void **)&item);
	  len = strlen (item) + 2;
	  if (n + len > ncol)
	    n = printf ("\n ");

	  len = printf ("%s", item);
	  mu_iterator_next (itr);
	  if (!mu_iterator_is_done (itr))
	    len += printf (", ");
	  else
	    break;
	  n += len;
	}
      printf ("\n");
    }
  mu_iterator_destroy (&itr);
}
예제 #7
0
파일: util.c 프로젝트: Berticus/powaur
/* Print dependencies */
void print_list_deps(alpm_list_t *list, const char *prefix)
{
	alpm_list_t *i;
	size_t indent, cols, curcols, newlen;
	size_t depstrlen;
	char *depstr;

	printf("%s%s%s ", color.bold, prefix, color.nocolor);
	if (!list) {
		printf("None\n");
		return;
	}

	cols = getcols();
	indent = strlen(prefix) + 1;
	curcols = indent;

	for (i = list; i; i = i->next) {
		/* Compute dep string */
		depstr = alpm_dep_compute_string(i->data);
		if (!depstr) {
			continue;
		}

		depstrlen = strlen(depstr);
		newlen = curcols + 2 + depstrlen;

		if (newlen > cols) {
			printf("\n");
			printf("%*s", indent, "");
			curcols = indent;
		}

		if (curcols == indent) {
			printf("%s", depstr);
			curcols += depstrlen;
		} else {
			printf("  %s", depstr);
			curcols += 2 + depstrlen;
		}

		free(depstr);
	}

	printf("\n");
}
예제 #8
0
파일: util.c 프로젝트: Berticus/powaur
void print_list_prefix(alpm_list_t *list, const char *prefix)
{
	alpm_list_t *i;
	size_t len = strlen(prefix);
	size_t indent, curcols, newlen;

	size_t cols = getcols();
	printf("%s%s%s ", color.bold, prefix, color.nocolor);

	if (!list) {
		printf("None\n");
		return;
	}

	indent = len + 1;
	curcols = indent;
	for (i = list; i; i = i->next) {
		/* There's a bug here which I'm not gonna fix. */
		newlen = curcols + 2 + strlen(i->data);
		if (newlen > cols) {
			printf("\n");
			printf("%*s", indent, "");
			curcols = indent;
		}

		if (curcols == indent) {
			printf("%s", i->data);
			curcols += strlen(i->data);
			continue;
		}

		curcols = newlen;
		printf("  %s", i->data);
	}

	printf("\n");
}
예제 #9
0
파일: mynano.c 프로젝트: mtawaken/gits
void do_outputchar(char* chars)
{
  int charslen=strlen(chars); //not mblen,maybe望文
  int i;
  int len = curline->pdata_x-curline->data;
  //curline->data
     //如果写成realloc(p) 则当输入10个字母时,数据突然丢失
     //并且应该相应改动pdata_x? 需要改动相关的指针吗? 
  char* data2 = curline->data = 
      realloc(curline->data, strlen(curline->data)+charslen+1);
  char* data_x2 = curline->pdata_x=curline->data+len;  
 
  memmove(data_x2+charslen,
          data_x2,
          strlen(data_x2) + 1);
  memcpy(data_x2,  chars,charslen);
  
  //curline->data_x
  curline->pdata_x+=charslen;

  //output 
  curline->win_x+=getcols(chars);  
  sub_outputline(curline);
}
void car_module::putinfo()
{
	printf("mac=%d\n",mac);
	printf("sumcar=%2d spendcar=%2d\n",sumcar,spendcar);
	printf("rows=%2d cols=%2d\n",rows,cols);
	printf("speed_rows=%.3lf speed_cols=%.3lf\n",speed_rows,speed_cols);

	printf("\n");
	for(int i=rows-1;i>=0;i--)
	{
		for(int j=0;j<cols;j++)
		{
			printf("%2d ",i*cols+j);
		}
		printf("\n");
	}
	printf("\n");

	for(i=0;i<rows*cols;i++)
	{
		printf("rows=%2d cols=%2d id=%2d free=%2d time=%.3lf\n",getrows(map_queue[i].id),getcols(map_queue[i].id),map_queue[i].id,map_queue[i].idle,map_queue[i].time);
	}
	printf("\n");
}
예제 #11
0
/* callback to handle questions from libalpm transactions (yes/no) */
void cb_question(alpm_question_t *question)
{
	if(config->print) {
		if(question->type == ALPM_QUESTION_INSTALL_IGNOREPKG) {
			question->any.answer = 1;
		} else {
			question->any.answer = 0;
		}
		return;
	}
	switch(question->type) {
		case ALPM_QUESTION_INSTALL_IGNOREPKG:
			{
				alpm_question_install_ignorepkg_t *q = &question->install_ignorepkg;
				if(!config->op_s_downloadonly) {
					q->install = yesno(_("%s is in IgnorePkg/IgnoreGroup. Install anyway?"),
							alpm_pkg_get_name(q->pkg));
				} else {
					q->install = 1;
				}
			}
			break;
		case ALPM_QUESTION_REPLACE_PKG:
			{
				alpm_question_replace_t *q = &question->replace;
				q->replace = yesno(_("Replace %s with %s/%s?"),
						alpm_pkg_get_name(q->oldpkg),
						alpm_db_get_name(q->newdb),
						alpm_pkg_get_name(q->newpkg));
			}
			break;
		case ALPM_QUESTION_CONFLICT_PKG:
			{
				alpm_question_conflict_t *q = &question->conflict;
				/* print conflict only if it contains new information */
				if(strcmp(q->conflict->package1, q->conflict->reason->name) == 0
						|| strcmp(q->conflict->package2, q->conflict->reason->name) == 0) {
					q->remove = noyes(_("%s and %s are in conflict. Remove %s?"),
							q->conflict->package1,
							q->conflict->package2,
							q->conflict->package2);
				} else {
					q->remove = noyes(_("%s and %s are in conflict (%s). Remove %s?"),
							q->conflict->package1,
							q->conflict->package2,
							q->conflict->reason->name,
							q->conflict->package2);
				}
			}
			break;
		case ALPM_QUESTION_REMOVE_PKGS:
			{
				alpm_question_remove_pkgs_t *q = &question->remove_pkgs;
				alpm_list_t *namelist = NULL, *i;
				size_t count = 0;
				for(i = q->packages; i; i = i->next) {
					namelist = alpm_list_add(namelist,
							(char *)alpm_pkg_get_name(i->data));
					count++;
				}
				colon_printf(_n(
							"The following package cannot be upgraded due to unresolvable dependencies:\n",
							"The following packages cannot be upgraded due to unresolvable dependencies:\n",
							count));
				list_display("     ", namelist, getcols());
				printf("\n");
				q->skip = noyes(_n(
							"Do you want to skip the above package for this upgrade?",
							"Do you want to skip the above packages for this upgrade?",
							count));
				alpm_list_free(namelist);
			}
			break;
		case ALPM_QUESTION_SELECT_PROVIDER:
			{
				alpm_question_select_provider_t *q = &question->select_provider;
				size_t count = alpm_list_count(q->providers);
				char *depstring = alpm_dep_compute_string(q->depend);
				colon_printf(_n("There is %zd provider available for %s\n",
						"There are %zd providers available for %s:\n", count),
						count, depstring);
				free(depstring);
				select_display(q->providers);
				q->use_index = select_question(count);
			}
			break;
		case ALPM_QUESTION_CORRUPTED_PKG:
			{
				alpm_question_corrupted_t *q = &question->corrupted;
				q->remove = yesno(_("File %s is corrupted (%s).\n"
							"Do you want to delete it?"),
						q->filepath,
						alpm_strerror(q->reason));
			}
			break;
		case ALPM_QUESTION_IMPORT_KEY:
			{
				alpm_question_import_key_t *q = &question->import_key;
				char created[12];
				time_t time = (time_t)q->key->created;
				strftime(created, 12, "%Y-%m-%d", localtime(&time));

				if(q->key->revoked) {
					q->import = yesno(_("Import PGP key %d%c/%s, \"%s\", created: %s (revoked)?"),
							q->key->length, q->key->pubkey_algo, q->key->fingerprint, q->key->uid, created);
				} else {
					q->import = yesno(_("Import PGP key %d%c/%s, \"%s\", created: %s?"),
							q->key->length, q->key->pubkey_algo, q->key->fingerprint, q->key->uid, created);
				}
			}
			break;
	}
	if(config->noask) {
		if(config->ask & question->type) {
			/* inverse the default answer */
			question->any.answer = !question->any.answer;
		}
	}
}
예제 #12
0
파일: util.c 프로젝트: sandsmark/pacman
/* prepare a list of pkgs to display */
static void _display_targets(alpm_list_t *targets, int verbose)
{
	char *str;
	const char *label;
	double size;
	off_t isize = 0, rsize = 0, dlsize = 0;
	unsigned short cols;
	alpm_list_t *i, *rows = NULL, *names = NULL;

	if(!targets) {
		return;
	}

	/* gather package info */
	for(i = targets; i; i = alpm_list_next(i)) {
		pm_target_t *target = i->data;

		if(target->install) {
			dlsize += alpm_pkg_download_size(target->install);
			isize += alpm_pkg_get_isize(target->install);
		}
		if(target->remove) {
			/* add up size of all removed packages */
			rsize += alpm_pkg_get_isize(target->remove);
		}
	}

	/* form data for both verbose and non-verbose display */
	for(i = targets; i; i = alpm_list_next(i)) {
		pm_target_t *target = i->data;

		rows = alpm_list_add(rows, create_verbose_row(target));
		if(target->install) {
			pm_asprintf(&str, "%s-%s", alpm_pkg_get_name(target->install),
					alpm_pkg_get_version(target->install));
		} else if(isize == 0) {
			pm_asprintf(&str, "%s-%s", alpm_pkg_get_name(target->remove),
					alpm_pkg_get_version(target->remove));
		} else {
			pm_asprintf(&str, "%s-%s [removal]", alpm_pkg_get_name(target->remove),
					alpm_pkg_get_version(target->remove));
		}
		names = alpm_list_add(names, str);
	}

	/* print to screen */
	pm_asprintf(&str, _("Packages (%d):"), alpm_list_count(targets));
	printf("\n");

	cols = getcols(fileno(stdout));
	if(verbose) {
		alpm_list_t *header = create_verbose_header();
		if(table_display(str, header, rows, cols) != 0) {
			/* fallback to list display if table wouldn't fit */
			list_display(str, names, cols);
		}
		alpm_list_free(header);
	} else {
		list_display(str, names, cols);
	}
	printf("\n");

	/* rows is a list of lists of strings, free inner lists here */
	for(i = rows; i; i = alpm_list_next(i)) {
		alpm_list_t *lp = i->data;
		FREELIST(lp);
	}
	alpm_list_free(rows);
	FREELIST(names);
	free(str);

	if(dlsize > 0 || config->op_s_downloadonly) {
		size = humanize_size(dlsize, 'M', 2, &label);
		printf(_("Total Download Size:    %.2f %s\n"), size, label);
	}
	if(!config->op_s_downloadonly) {
		if(isize > 0) {
			size = humanize_size(isize, 'M', 2, &label);
			printf(_("Total Installed Size:   %.2f %s\n"), size, label);
		}
		if(rsize > 0 && isize == 0) {
			size = humanize_size(rsize, 'M', 2, &label);
			printf(_("Total Removed Size:     %.2f %s\n"), size, label);
		}
		/* only show this net value if different from raw installed size */
		if(isize > 0 && rsize > 0) {
			size = humanize_size(isize - rsize, 'M', 2, &label);
			printf(_("Net Upgrade Size:       %.2f %s\n"), size, label);
		}
	}
}
예제 #13
0
파일: callback.c 프로젝트: mineo/pacman
/* callback to handle display of download progress */
void cb_dl_progress(const char *filename, off_t file_xfered, off_t file_total)
{
	int infolen;
	int filenamelen;
	char *fname, *p;
	/* used for wide character width determination and printing */
	int len, wclen, wcwid, padwid;
	wchar_t *wcfname;

	int totaldownload = 0;
	off_t xfered, total;
	double rate = 0.0, timediff = 0.0;
	unsigned int eta_h = 0, eta_m = 0, eta_s = 0;
	double rate_human, xfered_human;
	const char *rate_label, *xfered_label;
	int file_percent = 0, total_percent = 0;

	const int cols = getcols();

	if(config->noprogressbar || cols == 0 || file_total == -1) {
		if(file_xfered == 0) {
			printf(_("downloading %s...\n"), filename);
			fflush(stdout);
		}
		return;
	}

	infolen = cols * 6 / 10;
	if(infolen < 50) {
		infolen = 50;
	}
	/* explanation of magic 28 number at the end */
	filenamelen = infolen - 28;

	/* only use TotalDownload if enabled and we have a callback value */
	if(config->totaldownload && list_total) {
		/* sanity check */
		if(list_xfered + file_total <= list_total) {
			totaldownload = 1;
		} else {
			/* bogus values : don't enable totaldownload and reset */
			list_xfered = 0;
			list_total = 0;
		}
	}

	if(totaldownload) {
		xfered = list_xfered + file_xfered;
		total = list_total;
	} else {
		xfered = file_xfered;
		total = file_total;
	}

	/* bogus values : stop here */
	if(xfered > total) {
		return;
	}

	/* this is basically a switch on xfered: 0, total, and
	 * anything else */
	if(file_xfered == 0) {
		/* set default starting values, ensure we only call this once
		 * if TotalDownload is enabled */
		if(!totaldownload || (totaldownload && list_xfered == 0)) {
			gettimeofday(&initial_time, NULL);
			xfered_last = (off_t)0;
			rate_last = 0.0;
			get_update_timediff(1);
		}
	} else if(file_xfered == file_total) {
		/* compute final values */
		struct timeval current_time;
		double diff_sec, diff_usec;

		gettimeofday(&current_time, NULL);
		diff_sec = current_time.tv_sec - initial_time.tv_sec;
		diff_usec = current_time.tv_usec - initial_time.tv_usec;
		timediff = diff_sec + (diff_usec / 1000000.0);
		rate = xfered / timediff;

		/* round elapsed time to the nearest second */
		eta_s = (int)(timediff + 0.5);
	} else {
		/* compute current average values */
		timediff = get_update_timediff(0);

		if(timediff < UPDATE_SPEED_SEC) {
			/* return if the calling interval was too short */
			return;
		}
		rate = (xfered - xfered_last) / timediff;
		/* average rate to reduce jumpiness */
		rate = (rate + 2 * rate_last) / 3;
		eta_s = (total - xfered) / rate;
		rate_last = rate;
		xfered_last = xfered;
	}

	file_percent = (file_xfered * 100) / file_total;

	if(totaldownload) {
		total_percent = ((list_xfered + file_xfered) * 100) /
			list_total;

		/* if we are at the end, add the completed file to list_xfered */
		if(file_xfered == file_total) {
			list_xfered += file_total;
		}
	}

	/* fix up time for display */
	eta_h = eta_s / 3600;
	eta_s -= eta_h * 3600;
	eta_m = eta_s / 60;
	eta_s -= eta_m * 60;

	fname = strdup(filename);
	/* strip package or DB extension for cleaner look */
	if((p = strstr(fname, ".pkg")) || (p = strstr(fname, ".db"))) {
			*p = '\0';
	}
	/* In order to deal with characters from all locales, we have to worry
	 * about wide characters and their column widths. A lot of stuff is
	 * done here to figure out the actual number of screen columns used
	 * by the output, and then pad it accordingly so we fill the terminal.
	 */
	/* len = filename len + null */
	len = strlen(filename) + 1;
	wcfname = calloc(len, sizeof(wchar_t));
	wclen = mbstowcs(wcfname, fname, len);
	wcwid = wcswidth(wcfname, wclen);
	padwid = filenamelen - wcwid;
	/* if padwid is < 0, we need to trim the string so padwid = 0 */
	if(padwid < 0) {
		int i = filenamelen - 3;
		wchar_t *wcp = wcfname;
		/* grab the max number of char columns we can fill */
		while(i > 0 && wcwidth(*wcp) < i) {
			i -= wcwidth(*wcp);
			wcp++;
		}
		/* then add the ellipsis and fill out any extra padding */
		wcscpy(wcp, L"...");
		padwid = i;

	}

	rate_human = humanize_size((off_t)rate, '\0', 0, &rate_label);
	xfered_human = humanize_size(xfered, '\0', 0, &xfered_label);

	/* 1 space + filenamelen + 1 space + 7 for size + 1 + 7 for rate + 2 for /s + 1 space + 8 for eta */
	printf(" %ls%-*s %6.1f%s %#6.1f%s/s %02u:%02u:%02u", wcfname,
			padwid, "", xfered_human, xfered_label, rate_human, rate_label,
			eta_h, eta_m, eta_s);

	free(fname);
	free(wcfname);

	if(totaldownload) {
		fill_progress(file_percent, total_percent, cols - infolen);
	} else {
		fill_progress(file_percent, file_percent, cols - infolen);
	}
	return;
}
예제 #14
0
파일: callback.c 프로젝트: 7799/pacman
/* TODO this is one of the worst ever functions written. void *data ? wtf */
void cb_question(alpm_question_t event, void *data1, void *data2,
                   void *data3, int *response)
{
	if(config->print) {
		if(event == ALPM_QUESTION_INSTALL_IGNOREPKG) {
			*response = 1;
		} else {
			*response = 0;
		}
		return;
	}
	switch(event) {
		case ALPM_QUESTION_INSTALL_IGNOREPKG:
			if(!config->op_s_downloadonly) {
				*response = yesno(_("%s is in IgnorePkg/IgnoreGroup. Install anyway?"),
								alpm_pkg_get_name(data1));
			} else {
				*response = 1;
			}
			break;
		case ALPM_QUESTION_REPLACE_PKG:
			*response = yesno(_("Replace %s with %s/%s?"),
					alpm_pkg_get_name(data1),
					(char *)data3,
					alpm_pkg_get_name(data2));
			break;
		case ALPM_QUESTION_CONFLICT_PKG:
			/* data parameters: target package, local package, conflict (strings) */
			/* print conflict only if it contains new information */
			if(strcmp(data1, data3) == 0 || strcmp(data2, data3) == 0) {
				*response = noyes(_("%s and %s are in conflict. Remove %s?"),
						(char *)data1,
						(char *)data2,
						(char *)data2);
			} else {
				*response = noyes(_("%s and %s are in conflict (%s). Remove %s?"),
						(char *)data1,
						(char *)data2,
						(char *)data3,
						(char *)data2);
			}
			break;
		case ALPM_QUESTION_REMOVE_PKGS:
			{
				alpm_list_t *unresolved = data1;
				alpm_list_t *namelist = NULL, *i;
				size_t count = 0;
				for(i = unresolved; i; i = i->next) {
					namelist = alpm_list_add(namelist,
							(char *)alpm_pkg_get_name(i->data));
					count++;
				}
				colon_printf(_n(
							"The following package cannot be upgraded due to unresolvable dependencies:\n",
							"The following packages cannot be upgraded due to unresolvable dependencies:\n",
							count));
				list_display("     ", namelist, getcols(fileno(stdout)));
				printf("\n");
				*response = noyes(_n(
							"Do you want to skip the above package for this upgrade?",
							"Do you want to skip the above packages for this upgrade?",
							count));
				alpm_list_free(namelist);
			}
			break;
		case ALPM_QUESTION_SELECT_PROVIDER:
			{
				alpm_list_t *providers = data1;
				size_t count = alpm_list_count(providers);
				char *depstring = alpm_dep_compute_string((alpm_depend_t *)data2);
				colon_printf(_("There are %zd providers available for %s:\n"), count,
						depstring);
				free(depstring);
				select_display(providers);
				*response = select_question(count);
			}
			break;
		case ALPM_QUESTION_CORRUPTED_PKG:
			*response = yesno(_("File %s is corrupted (%s).\n"
						"Do you want to delete it?"),
					(char *)data1,
					alpm_strerror(*(alpm_errno_t *)data2));
			break;
		case ALPM_QUESTION_IMPORT_KEY:
			{
				alpm_pgpkey_t *key = data1;
				char created[12];
				time_t time = (time_t)key->created;
				strftime(created, 12, "%Y-%m-%d", localtime(&time));

				if(key->revoked) {
					*response = yesno(_("Import PGP key %d%c/%s, \"%s\", created: %s (revoked)?"),
							key->length, key->pubkey_algo, key->fingerprint, key->uid, created);
				} else {
					*response = yesno(_("Import PGP key %d%c/%s, \"%s\", created: %s?"),
							key->length, key->pubkey_algo, key->fingerprint, key->uid, created);
				}
			}
			break;
	}
	if(config->noask) {
		if(config->ask & event) {
			/* inverse the default answer */
			*response = !*response;
		}
	}
}
예제 #15
0
파일: package.c 프로젝트: gtmanfred/pacman
/**
 * Display the details of a search.
 * @param db the database we're searching
 * @param targets the targets we're searching for
 * @param show_status show if the package is also in the local db
 */
int dump_pkg_search(alpm_db_t *db, alpm_list_t *targets, int show_status)
{
    int freelist = 0;
    alpm_db_t *db_local;
    alpm_list_t *i, *searchlist;
    unsigned short cols;
    const colstr_t *colstr = &config->colstr;

    if(show_status) {
        db_local = alpm_get_localdb(config->handle);
    }

    /* if we have a targets list, search for packages matching it */
    if(targets) {
        searchlist = alpm_db_search(db, targets);
        freelist = 1;
    } else {
        searchlist = alpm_db_get_pkgcache(db);
        freelist = 0;
    }
    if(searchlist == NULL) {
        return 1;
    }

    cols = getcols(fileno(stdout));
    for(i = searchlist; i; i = alpm_list_next(i)) {
        alpm_list_t *grp;
        alpm_pkg_t *pkg = i->data;

        if(config->quiet) {
            fputs(alpm_pkg_get_name(pkg), stdout);
        } else {
            printf("%s%s/%s%s %s%s%s", colstr->repo, alpm_db_get_name(db),
                   colstr->title, alpm_pkg_get_name(pkg),
                   colstr->version, alpm_pkg_get_version(pkg), colstr->nocolor);

            if((grp = alpm_pkg_get_groups(pkg)) != NULL) {
                alpm_list_t *k;
                printf(" %s(", colstr->groups);
                for(k = grp; k; k = alpm_list_next(k)) {
                    const char *group = k->data;
                    fputs(group, stdout);
                    if(alpm_list_next(k)) {
                        /* only print a spacer if there are more groups */
                        putchar(' ');
                    }
                }
                printf(")%s", colstr->nocolor);
            }

            if(show_status) {
                print_installed(db_local, pkg);
            }

            /* we need a newline and initial indent first */
            fputs("\n    ", stdout);
            indentprint(alpm_pkg_get_desc(pkg), 4, cols);
        }
        fputc('\n', stdout);
    }

    /* we only want to free if the list was a search list */
    if(freelist) {
        alpm_list_free(searchlist);
    }

    return 0;
}
예제 #16
0
파일: util.c 프로젝트: JohnFrazier/pacman
/* prepare a list of pkgs to display */
static void _display_targets(alpm_list_t *targets, int verbose)
{
	char *str;
	off_t isize = 0, rsize = 0, dlsize = 0;
	unsigned short cols;
	alpm_list_t *i, *names = NULL, *header = NULL, *rows = NULL;

	if(!targets) {
		return;
	}

	/* gather package info */
	for(i = targets; i; i = alpm_list_next(i)) {
		pm_target_t *target = i->data;

		if(target->install) {
			dlsize += alpm_pkg_download_size(target->install);
			isize += alpm_pkg_get_isize(target->install);
		}
		if(target->remove) {
			/* add up size of all removed packages */
			rsize += alpm_pkg_get_isize(target->remove);
		}
	}

	/* form data for both verbose and non-verbose display */
	for(i = targets; i; i = alpm_list_next(i)) {
		pm_target_t *target = i->data;

		if(verbose) {
			rows = alpm_list_add(rows, create_verbose_row(target));
		}

		if(target->install) {
			pm_asprintf(&str, "%s-%s", alpm_pkg_get_name(target->install),
					alpm_pkg_get_version(target->install));
		} else if(isize == 0) {
			pm_asprintf(&str, "%s-%s", alpm_pkg_get_name(target->remove),
					alpm_pkg_get_version(target->remove));
		} else {
			pm_asprintf(&str, "%s-%s [%s]", alpm_pkg_get_name(target->remove),
					alpm_pkg_get_version(target->remove), _("removal"));
		}
		names = alpm_list_add(names, str);
	}

	/* print to screen */
	pm_asprintf(&str, "%s (%zd)", _("Packages"), alpm_list_count(targets));
	printf("\n");

	cols = getcols(fileno(stdout));
	if(verbose) {
		header = create_verbose_header(alpm_list_count(targets));
		if(table_display(header, rows, cols) != 0) {
			/* fallback to list display if table wouldn't fit */
			list_display(str, names, cols);
		}
	} else {
		list_display(str, names, cols);
	}
	printf("\n");

	table_free(header, rows);
	FREELIST(names);
	free(str);
	rows = NULL;

	if(dlsize > 0 || config->op_s_downloadonly) {
		add_transaction_sizes_row(&rows, _("Total Download Size:"), dlsize);
	}
	if(!config->op_s_downloadonly) {
		if(isize > 0) {
			add_transaction_sizes_row(&rows, _("Total Installed Size:"), isize);
		}
		if(rsize > 0 && isize == 0) {
			add_transaction_sizes_row(&rows, _("Total Removed Size:"), rsize);
		}
		/* only show this net value if different from raw installed size */
		if(isize > 0 && rsize > 0) {
			add_transaction_sizes_row(&rows, _("Net Upgrade Size:"), isize - rsize);
		}
	}
	table_display(NULL, rows, cols);
	table_free(NULL, rows);
}
예제 #17
0
/* callback to handle display of transaction progress */
void cb_progress(alpm_progress_t event, const char *pkgname, int percent,
                       size_t howmany, size_t current)
{
	static int prevpercent;
	static size_t prevcurrent;
	/* size of line to allocate for text printing (e.g. not progressbar) */
	int infolen;
	int digits, textlen;
	size_t tmp;
	char *opr = NULL;
	/* used for wide character width determination and printing */
	int len, wclen, wcwid, padwid;
	wchar_t *wcstr;

	const unsigned short cols = getcols();

	if(config->noprogressbar || cols == 0) {
		return;
	}

	if(percent == 0) {
		get_update_timediff(1);
	} else if(percent == 100) {
		/* no need for timediff update, but unconditionally continue unless we
		 * already completed on a previous call */
		if(prevpercent == 100) {
			return;
		}
	} else {
		if(current != prevcurrent) {
			/* update always */
		} else if(!pkgname || percent == prevpercent ||
				get_update_timediff(0) < UPDATE_SPEED_MS) {
			/* only update the progress bar when we have a package name, the
			 * percentage has changed, and it has been long enough. */
			return;
		}
	}

	prevpercent = percent;
	prevcurrent = current;

	/* set text of message to display */
	switch(event) {
		case ALPM_PROGRESS_ADD_START:
			opr = _("installing");
			break;
		case ALPM_PROGRESS_UPGRADE_START:
			opr = _("upgrading");
			break;
		case ALPM_PROGRESS_DOWNGRADE_START:
			opr = _("downgrading");
			break;
		case ALPM_PROGRESS_REINSTALL_START:
			opr = _("reinstalling");
			break;
		case ALPM_PROGRESS_REMOVE_START:
			opr = _("removing");
			break;
		case ALPM_PROGRESS_CONFLICTS_START:
			opr = _("checking for file conflicts");
			break;
		case ALPM_PROGRESS_DISKSPACE_START:
			opr = _("checking available disk space");
			break;
		case ALPM_PROGRESS_INTEGRITY_START:
			opr = _("checking package integrity");
			break;
		case ALPM_PROGRESS_KEYRING_START:
			opr = _("checking keys in keyring");
			break;
		case ALPM_PROGRESS_LOAD_START:
			opr = _("loading package files");
			break;
		default:
			return;
	}

	infolen = cols * 6 / 10;
	if(infolen < 50) {
		infolen = 50;
	}

	/* find # of digits in package counts to scale output */
	digits = 1;
	tmp = howmany;
	while((tmp /= 10)) {
		++digits;
	}
	/* determine room left for non-digits text [not ( 1/12) part] */
	textlen = infolen - 3 /* (/) */ - (2 * digits) - 1 /* space */;

	/* In order to deal with characters from all locales, we have to worry
	 * about wide characters and their column widths. A lot of stuff is
	 * done here to figure out the actual number of screen columns used
	 * by the output, and then pad it accordingly so we fill the terminal.
	 */
	/* len = opr len + pkgname len (if available) + space + null */
	len = strlen(opr) + ((pkgname) ? strlen(pkgname) : 0) + 2;
	wcstr = calloc(len, sizeof(wchar_t));
	/* print our strings to the alloc'ed memory */
#if defined(HAVE_SWPRINTF)
	wclen = swprintf(wcstr, len, L"%s %s", opr, pkgname);
#else
	/* because the format string was simple, we can easily do this without
	 * using swprintf, although it is probably not as safe/fast. The max
	 * chars we can copy is decremented each time by subtracting the length
	 * of the already printed/copied wide char string. */
	wclen = mbstowcs(wcstr, opr, len);
	wclen += mbstowcs(wcstr + wclen, " ", len - wclen);
	wclen += mbstowcs(wcstr + wclen, pkgname, len - wclen);
#endif
	wcwid = wcswidth(wcstr, wclen);
	padwid = textlen - wcwid;
	/* if padwid is < 0, we need to trim the string so padwid = 0 */
	if(padwid < 0) {
		int i = textlen - 3;
		wchar_t *p = wcstr;
		/* grab the max number of char columns we can fill */
		while(i - wcwidth(*p) > 0) {
			i -= wcwidth(*p);
			p++;
		}
		/* then add the ellipsis and fill out any extra padding */
		wcscpy(p, L"...");
		padwid = i;

	}

	printf("(%*ld/%*ld) %ls%-*s", digits, (unsigned long)current,
			digits, (unsigned long)howmany, wcstr, padwid, "");

	free(wcstr);

	/* call refactored fill progress function */
	fill_progress(percent, percent, cols - infolen);

	if(percent == 100) {
		alpm_list_t *i = NULL;
		on_progress = 0;
		fflush(stdout);
		for(i = output; i; i = i->next) {
			fputs((const char *)i->data, stderr);
		}
		fflush(stderr);
		FREELIST(output);
	} else {
		on_progress = 1;
	}
}
예제 #18
0
파일: package.c 프로젝트: gtmanfred/pacman
/**
 * Display the details of a package.
 * Extra information entails 'required by' info for sync packages and backup
 * files info for local packages.
 * @param pkg package to display information for
 * @param from the type of package we are dealing with
 * @param extra should we show extra information
 */
void dump_pkg_full(alpm_pkg_t *pkg, int extra)
{
    unsigned short cols;
    time_t bdate, idate;
    alpm_pkgfrom_t from;
    double size;
    char bdatestr[50] = "", idatestr[50] = "";
    const char *label, *reason;
    alpm_list_t *validation = NULL, *requiredby = NULL, *optionalfor = NULL;

    from = alpm_pkg_get_origin(pkg);

    /* set variables here, do all output below */
    bdate = (time_t)alpm_pkg_get_builddate(pkg);
    if(bdate) {
        strftime(bdatestr, 50, "%c", localtime(&bdate));
    }
    idate = (time_t)alpm_pkg_get_installdate(pkg);
    if(idate) {
        strftime(idatestr, 50, "%c", localtime(&idate));
    }

    switch(alpm_pkg_get_reason(pkg)) {
    case ALPM_PKG_REASON_EXPLICIT:
        reason = _("Explicitly installed");
        break;
    case ALPM_PKG_REASON_DEPEND:
        reason = _("Installed as a dependency for another package");
        break;
    default:
        reason = _("Unknown");
        break;
    }

    alpm_pkgvalidation_t v = alpm_pkg_get_validation(pkg);
    if(v) {
        if(v & ALPM_PKG_VALIDATION_NONE) {
            validation = alpm_list_add(validation, _("None"));
        } else {
            if(v & ALPM_PKG_VALIDATION_MD5SUM) {
                validation = alpm_list_add(validation, _("MD5 Sum"));
            }
            if(v & ALPM_PKG_VALIDATION_SHA256SUM) {
                validation = alpm_list_add(validation, _("SHA256 Sum"));
            }
            if(v & ALPM_PKG_VALIDATION_SIGNATURE) {
                validation = alpm_list_add(validation, _("Signature"));
            }
        }
    } else {
        validation = alpm_list_add(validation, _("Unknown"));
    }

    if(extra || from == ALPM_PKG_FROM_LOCALDB) {
        /* compute this here so we don't get a pause in the middle of output */
        requiredby = alpm_pkg_compute_requiredby(pkg);
        optionalfor = alpm_pkg_compute_optionalfor(pkg);
    }

    cols = getcols(fileno(stdout));

    /* actual output */
    if(from == ALPM_PKG_FROM_SYNCDB) {
        string_display(_("Repository     :"),
                       alpm_db_get_name(alpm_pkg_get_db(pkg)), cols);
    }
    string_display(_("Name           :"), alpm_pkg_get_name(pkg), cols);
    string_display(_("Version        :"), alpm_pkg_get_version(pkg), cols);
    string_display(_("Description    :"), alpm_pkg_get_desc(pkg), cols);
    string_display(_("Architecture   :"), alpm_pkg_get_arch(pkg), cols);
    string_display(_("URL            :"), alpm_pkg_get_url(pkg), cols);
    list_display(_("Licenses       :"), alpm_pkg_get_licenses(pkg), cols);
    list_display(_("Groups         :"), alpm_pkg_get_groups(pkg), cols);
    deplist_display(_("Provides       :"), alpm_pkg_get_provides(pkg), cols);
    deplist_display(_("Depends On     :"), alpm_pkg_get_depends(pkg), cols);
    optdeplist_display(pkg, cols);

    if(extra || from == ALPM_PKG_FROM_LOCALDB) {
        list_display(_("Required By    :"), requiredby, cols);
        list_display(_("Optional For   :"), optionalfor, cols);
    }
    deplist_display(_("Conflicts With :"), alpm_pkg_get_conflicts(pkg), cols);
    deplist_display(_("Replaces       :"), alpm_pkg_get_replaces(pkg), cols);

    size = humanize_size(alpm_pkg_get_size(pkg), '\0', 2, &label);
    if(from == ALPM_PKG_FROM_SYNCDB) {
        printf("%s%s%s %6.2f %s\n", config->colstr.title, _("Download Size  :"),
               config->colstr.nocolor, size, label);
    } else if(from == ALPM_PKG_FROM_FILE) {
        printf("%s%s%s %6.2f %s\n", config->colstr.title, _("Compressed Size:"),
               config->colstr.nocolor, size, label);
    } else {
        // autodetect size for "Installed Size"
        label = "\0";
    }

    size = humanize_size(alpm_pkg_get_isize(pkg), label[0], 2, &label);
    printf("%s%s%s %6.2f %s\n", config->colstr.title, _("Installed Size :"),
           config->colstr.nocolor, size, label);

    string_display(_("Packager       :"), alpm_pkg_get_packager(pkg), cols);
    string_display(_("Build Date     :"), bdatestr, cols);
    if(from == ALPM_PKG_FROM_LOCALDB) {
        string_display(_("Install Date   :"), idatestr, cols);
        string_display(_("Install Reason :"), reason, cols);
    }
    if(from == ALPM_PKG_FROM_FILE || from == ALPM_PKG_FROM_LOCALDB) {
        string_display(_("Install Script :"),
                       alpm_pkg_has_scriptlet(pkg) ?  _("Yes") : _("No"), cols);
    }

    if(from == ALPM_PKG_FROM_SYNCDB && extra) {
        const char *base64_sig = alpm_pkg_get_base64_sig(pkg);
        alpm_list_t *keys = NULL;
        if(base64_sig) {
            unsigned char *decoded_sigdata = NULL;
            size_t data_len;
            alpm_decode_signature(base64_sig, &decoded_sigdata, &data_len);
            alpm_extract_keyid(config->handle, alpm_pkg_get_name(pkg),
                               decoded_sigdata, data_len, &keys);
        } else {
            keys = alpm_list_add(keys, _("None"));
        }

        string_display(_("MD5 Sum        :"), alpm_pkg_get_md5sum(pkg), cols);
        string_display(_("SHA256 Sum     :"), alpm_pkg_get_sha256sum(pkg), cols);
        list_display(_("Signatures     :"), keys, cols);
    } else {
        list_display(_("Validated By   :"), validation, cols);
    }

    if(from == ALPM_PKG_FROM_FILE) {
        alpm_siglist_t siglist;
        int err = alpm_pkg_check_pgp_signature(pkg, &siglist);
        if(err && alpm_errno(config->handle) == ALPM_ERR_SIG_MISSING) {
            string_display(_("Signatures     :"), _("None"), cols);
        } else if(err) {
            string_display(_("Signatures     :"),
                           alpm_strerror(alpm_errno(config->handle)), cols);
        } else {
            signature_display(_("Signatures     :"), &siglist, cols);
        }
        alpm_siglist_cleanup(&siglist);
    }

    /* Print additional package info if info flag passed more than once */
    if(from == ALPM_PKG_FROM_LOCALDB && extra) {
        dump_pkg_backups(pkg);
    }

    /* final newline to separate packages */
    printf("\n");

    FREELIST(requiredby);
    alpm_list_free(validation);
}
예제 #19
0
/* callback to handle display of download progress */
void cb_dl_progress(const char *filename, off_t file_xfered, off_t file_total)
{
	static double rate_last;
	static off_t xfered_last;
	static int64_t initial_time = 0;
	int infolen;
	int filenamelen;
	char *fname, *p;
	/* used for wide character width determination and printing */
	int len, wclen, wcwid, padwid;
	wchar_t *wcfname;

	int totaldownload = 0;
	off_t xfered, total;
	double rate = 0.0;
	unsigned int eta_h = 0, eta_m = 0, eta_s = 0;
	double rate_human, xfered_human;
	const char *rate_label, *xfered_label;
	int file_percent = 0, total_percent = 0;

	const unsigned short cols = getcols();

	if(config->noprogressbar || cols == 0 || file_total == -1) {
		if(file_xfered == 0) {
			printf(_("downloading %s...\n"), filename);
			fflush(stdout);
		}
		return;
	}

	infolen = cols * 6 / 10;
	if(infolen < 50) {
		infolen = 50;
	}
	/* only use TotalDownload if enabled and we have a callback value */
	if(config->totaldownload && list_total) {
		/* sanity check */
		if(list_xfered + file_total <= list_total) {
			totaldownload = 1;
		} else {
			/* bogus values : don't enable totaldownload and reset */
			list_xfered = 0;
			list_total = 0;
		}
	}

	if(totaldownload) {
		xfered = list_xfered + file_xfered;
		total = list_total;
	} else {
		xfered = file_xfered;
		total = file_total;
	}

	/* bogus values : stop here */
	if(xfered > total || xfered < 0) {
		return;
	}

	/* this is basically a switch on xfered: 0, total, and
	 * anything else */
	if(file_xfered == 0) {
		/* set default starting values, ensure we only call this once
		 * if TotalDownload is enabled */
		if(!totaldownload || (totaldownload && list_xfered == 0)) {
			initial_time = get_time_ms();
			xfered_last = (off_t)0;
			rate_last = 0.0;
			get_update_timediff(1);
		}
	} else if(file_xfered == file_total) {
		/* compute final values */
		int64_t timediff = get_time_ms() - initial_time;
		if(timediff > 0) {
			rate = (double)xfered / (timediff / 1000.0);
			/* round elapsed time (in ms) to the nearest second */
			eta_s = (unsigned int)(timediff + 500) / 1000;
		} else {
			eta_s = 0;
		}
	} else {
		/* compute current average values */
		int64_t timediff = get_update_timediff(0);

		if(timediff < UPDATE_SPEED_MS) {
			/* return if the calling interval was too short */
			return;
		}
		rate = (double)(xfered - xfered_last) / (timediff / 1000.0);
		/* average rate to reduce jumpiness */
		rate = (rate + 2 * rate_last) / 3;
		if(rate > 0.0) {
			eta_s = (total - xfered) / rate;
		} else {
			eta_s = UINT_MAX;
		}
		rate_last = rate;
		xfered_last = xfered;
	}

	if(file_total) {
		file_percent = (file_xfered * 100) / file_total;
	} else {
		file_percent = 100;
	}

	if(totaldownload) {
		total_percent = ((list_xfered + file_xfered) * 100) /
			list_total;

		/* if we are at the end, add the completed file to list_xfered */
		if(file_xfered == file_total) {
			list_xfered += file_total;
		}
	}

	/* fix up time for display */
	eta_h = eta_s / 3600;
	eta_s -= eta_h * 3600;
	eta_m = eta_s / 60;
	eta_s -= eta_m * 60;

	len = strlen(filename);
	fname = malloc(len + 1);
	memcpy(fname, filename, len);
	/* strip package or DB extension for cleaner look */
	if((p = strstr(fname, ".pkg")) || (p = strstr(fname, ".db")) || (p = strstr(fname, ".files"))) {
		/* tack on a .sig suffix for signatures */
		if(memcmp(&filename[len - 4], ".sig", 4) == 0) {
			memcpy(p, ".sig", 4);

			/* adjust length for later calculations */
			len = p - fname + 4;
		} else {
			len = p - fname;
		}
	}
	fname[len] = '\0';

	/* 1 space + filenamelen + 1 space + 6 for size + 1 space + 3 for label +
	 * + 2 spaces + 4 for rate + 1 for label + 2 for /s + 1 space +
	 * 8 for eta, gives us the magic 30 */
	filenamelen = infolen - 30;
	/* see printf() code, we omit 'HH:' in these conditions */
	if(eta_h == 0 || eta_h >= 100) {
		filenamelen += 3;
	}

	/* In order to deal with characters from all locales, we have to worry
	 * about wide characters and their column widths. A lot of stuff is
	 * done here to figure out the actual number of screen columns used
	 * by the output, and then pad it accordingly so we fill the terminal.
	 */
	/* len = filename len + null */
	wcfname = calloc(len + 1, sizeof(wchar_t));
	wclen = mbstowcs(wcfname, fname, len);
	wcwid = wcswidth(wcfname, wclen);
	padwid = filenamelen - wcwid;
	/* if padwid is < 0, we need to trim the string so padwid = 0 */
	if(padwid < 0) {
		int i = filenamelen - 3;
		wchar_t *wcp = wcfname;
		/* grab the max number of char columns we can fill */
		while(i > 0 && wcwidth(*wcp) < i) {
			i -= wcwidth(*wcp);
			wcp++;
		}
		/* then add the ellipsis and fill out any extra padding */
		wcscpy(wcp, L"...");
		padwid = i;

	}

	rate_human = humanize_size((off_t)rate, '\0', -1, &rate_label);
	xfered_human = humanize_size(xfered, '\0', -1, &xfered_label);

	printf(" %ls%-*s ", wcfname, padwid, "");
	/* We will show 1.62M/s, 11.6M/s, but 116K/s and 1116K/s */
	if(rate_human < 9.995) {
		printf("%6.1f %3s  %4.2f%c/s ",
				xfered_human, xfered_label, rate_human, rate_label[0]);
	} else if(rate_human < 99.95) {
		printf("%6.1f %3s  %4.1f%c/s ",
				xfered_human, xfered_label, rate_human, rate_label[0]);
	} else {
		printf("%6.1f %3s  %4.f%c/s ",
				xfered_human, xfered_label, rate_human, rate_label[0]);
	}
	if(eta_h == 0) {
		printf("%02u:%02u", eta_m, eta_s);
	} else if(eta_h < 100) {
		printf("%02u:%02u:%02u", eta_h, eta_m, eta_s);
	} else {
		fputs("--:--", stdout);
	}

	free(fname);
	free(wcfname);

	if(totaldownload) {
		fill_progress(file_percent, total_percent, cols - infolen);
	} else {
		fill_progress(file_percent, file_percent, cols - infolen);
	}
	return;
}
예제 #20
0
파일: marq.c 프로젝트: smart-facility/srp
/*********************************************************************************
 *                                                                               *
 *                           G A T E W A Y   R O U T I N E                       *
 *                                                                               *
 *********************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  /*
   >>>>>>>>>>>>>>>>>>           VARIABLE DECLARATIONS          <<<<<<<<<<<<<<<<<<<
   */
   matrix *PI_vector;
   matrix *NetDef, *W1, *W2, *PHI, *Y, *L_hidden, *H_hidden;
   double *M, lambda;
   int iter, hidden, inputs, outputs, a, n, decays;
   trparmstruct *trparms;
   mxArray  *Matmatrix;
   char *infolevelstr[] = {"infolevel", "Infolevel", "INFOLEVEL", "InfoLevel"};
   char *maxiterstr[] = {"maxiter", "MAXITER", "Maxiter", "MaxIter"};
   char *critminstr[] = {"critmin", "Critmin", "CRITMIN", "CritMin"};
   char *crittermstr[] = {"critterm", "Critterm", "CRITTERM", "CritTerm"};
   char *gradtermstr[] = {"gradterm", "Gradterm", "GRADTERM", "GradTerm"};
   char *paramtermstr[] = {"paramterm", "Paramterm", "PARAMTERM", "ParamTerm"};
   char *Dstr[] = {"D", "d"};
   char *lambdastr[] = {"lambda", "Lambda", "LAMBDA"};
   char *skipstr[] = {"skip", "Skip", "SKIP"};


  /*
   >>>>>>>>>>>>>>>>      CHECK FOR PROPER NUMBER OF ARGUMENTS      <<<<<<<<<<<<<<<
   */
   if (nrhs<5 || nrhs>6)
   { 
       mexErrMsgTxt("Wrong number of input arguments");
   }
   else if (nlhs > 5)
   {
       mexErrMsgTxt("Too many output arguments");
   }


  /*
   >>>>>>>>>>>>>>>>>     CONVERT INPUT ARGUMENTS TO SM FORMAT     <<<<<<<<<<<<<<<<
   */
  NetDef  = matstring2sm(prhs[0]);
  PHI     = mat2sm(prhs[3]);
  Y       = mat2sm(prhs[4]);

  inputs  = mxGetM(prhs[3]);
  outputs = mxGetM(prhs[4]);
  L_hidden = neuvector(NetDef,1,'L');      /* Location of linear hidden units      */
  H_hidden = neuvector(NetDef,1,'H');      /* Location of tanh hidden units        */  
  hidden   = L_hidden->row*L_hidden->col + H_hidden->row*H_hidden->col;
  if(mxGetM(prhs[1])==0 || mxGetN(prhs[1])==0 || mxGetM(prhs[2])==0\
                         || mxGetN(prhs[2])==0){
   	W1 = mmake(hidden,inputs+1);
   	W2 = mmake(outputs,hidden+1);
   	mrand(W1); smul(W1,W1,0.5);
   	mrand(W2); smul(W2,W2,0.5);
  }
  else{
   	if(mxGetM(prhs[1])!=hidden) mexErrMsgTxt("W1 has the wrong dimension");
   	if(mxGetN(prhs[1])!=inputs+1) mexErrMsgTxt("W1 has the wrong dimension");
   	if(mxGetM(prhs[2])!=outputs) mexErrMsgTxt("W2 has the wrong dimension");
   	if(mxGetN(prhs[2])!=hidden+1) mexErrMsgTxt("W2 has the wrong dimension");
   	W1 = mat2sm(prhs[1]);     /* Input-to-hidden layer weights */
   	W2 = mat2sm(prhs[2]);     /* Hidden-to-output layer weights */
  }
 trparms = (trparmstruct*)malloc(sizeof(trparmstruct)); 
 a = 5;
 if (nrhs==6){
    /* INFOLEVEL */
    trparms->infolevel   = TRDINFOLEVEL;    
    for(n=0;n<4;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, infolevelstr[n]))!=NULL){
           trparms->infolevel=(int)(*mxGetPr(Matmatrix));
           break;
        }
    }

    /* MAXITER */
    trparms->maxiter   = TRDMAXITER;    
    for(n=0;n<4;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, maxiterstr[n]))!=NULL){
           trparms->maxiter=(int)(*mxGetPr(Matmatrix));
           break;
        }
    }

    /* CRITMIN */
    trparms->critmin   = TRDCRITMIN;    
    for(n=0;n<4;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, critminstr[n]))!=NULL){
           trparms->critmin=(double)(*mxGetPr(Matmatrix));
           break;
        }
    }

    
    /* CRITTERM */
    trparms->critterm   = TRDCRITTERM;    
    for(n=0;n<4;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, crittermstr[n]))!=NULL){
           trparms->critterm=(double)(*mxGetPr(Matmatrix));
           break;
        }
    }

    /* GRADTERM */
    trparms->gradterm   = TRDGRADTERM;    
    for(n=0;n<4;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, gradtermstr[n]))!=NULL){
           trparms->gradterm=(double)(*mxGetPr(Matmatrix));
           break;
        }
    }

    /* PARAMTERM */
    trparms->paramterm   = TRDPARAMTERM;    
    for(n=0;n<4;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, paramtermstr[n]))!=NULL){
           trparms->paramterm=(double)(*mxGetPr(Matmatrix));
           break;
        }
    }

    /* Lambda */
    trparms->lambda   = TRDLAMBDA;    
    for(n=0;n<3;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, lambdastr[n]))!=NULL){
           trparms->lambda=(double)(*mxGetPr(Matmatrix));
           break;
        }
    }

    /* D */
    for(n=0;n<2;n++){
        if ((Matmatrix=mxGetField(prhs[a], 0, Dstr[n]))!=NULL){
           decays = mxGetM(Matmatrix)*mxGetN(Matmatrix);
           trparms->D         = mmake(1,decays);
           M    = mxGetPr(Matmatrix);
           for(n=0;n<decays;n++){
              rvput(trparms->D,n,M[n]);
           }
           break;
        }
    }
    if(Matmatrix==NULL){
       trparms->D         = mmake(1,1);
       put_val(trparms->D,0,0,TRDD);
    }
}
  else
  {
    trparms->infolevel = TRDINFOLEVEL;
    trparms->maxiter   = TRDMAXITER;
    trparms->critmin   = TRDCRITMIN;
    trparms->critterm  = TRDCRITTERM;
    trparms->gradterm  = TRDGRADTERM;
    trparms->paramterm = TRDPARAMTERM;
    trparms->D         = mmake(1,1);
    put_val(trparms->D,0,0,TRDD);
    trparms->lambda    = TRDLAMBDA;
    trparms->skip      = TRDSKIP;
  }


  /*
   >>>>>>>>>>>>>>>>>>>>>>         CALL THE C-ROUTINE         <<<<<<<<<<<<<<<<<<<<<
   */
  marqc(&PI_vector, &iter, &lambda, NetDef, W1, W2, PHI, Y, trparms);


  /*
   >>>>>>>>>>>>>>>>>>>         CREATE OUTPUT MATICES            <<<<<<<<<<<<<<<<<<
   */
  plhs[0] = mxCreateDoubleMatrix(getrows(W1),getcols(W1),mxREAL);
  plhs[1] = mxCreateDoubleMatrix(getrows(W2),getcols(W2),mxREAL);
  plhs[2] = mxCreateDoubleMatrix(getrows(PI_vector),getcols(PI_vector),mxREAL);
  plhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);
  plhs[4] = mxCreateDoubleMatrix(1,1,mxREAL);

  sm2mat(plhs[0],W1);
  sm2mat(plhs[1],W2);
  sm2mat(plhs[2],PI_vector);
  M = mxGetPr(plhs[3]); M[0] = (double)iter;
  M = mxGetPr(plhs[4]); M[0] = (double)lambda;

  /*
   >>>>>>>>>>>>>>>>>>>>        FREE ARGUMENT MATRICES        <<<<<<<<<<<<<<<<<<<<<
   */
  mfree(NetDef); mfree(PHI); mfree(Y); mfree(L_hidden); mfree(H_hidden);
  mfree(trparms->D);
  free(trparms); 
}