예제 #1
0
 //-------------------------------------------------------------------------
 void Settings::SetPath( const WCHAR* path )
 {
     wcscpy_s( _path, COUNT(_path), path );
 }
예제 #2
0
파일: metro.c 프로젝트: seorc/metro-mx
/**
 * Constructs a net representing the Metro de la Ciudad de Mexico
 */
net *create_net() {
	net *n; 

	char *stations[] = {
		"Observatorio",					/* 0 */
		"Tacubaya",
		"Juanacatlan",
		"Chapultepec",
		"Sevilla",
		"Insurgentes",					/* 5 */
		"Cuauhtemoc",
		"Balderas",
		"Salto del Agua",
		"Isabel la Catolica",			
		"Pino Suarez",					/* 10 */
		"Merced",
		"Candelaria",
		"San Lazaro",
		"Moctezuma",
		"Balbuena",						/* 15 */
		"Boulevard Puerto Aereo",
		"Gomez Farias",
		"Zaragoza",
		"Pantitlan",					
		"Cuatro Caminos",				/* 20 */
		"Panteones",
		"Tacuba",
		"Cuitlahuac",
		"Popotla",
		"Colegio Militar",				/* 25 */
		"Normal",
		"San Cosme",
		"Revolucion",
		"Hidalgo",
		"Bellas Artes",					/* 30 */
		"Allende",
		"Zocalo",
		"San Antonio Abad",
		"Chabacano",
		"Viaducto",						/* 35 */
		"Xola",
		"Villa de Cortes",
		"Nativitas",
		"Portales",
		"Ermita",						/* 40 */
		"General Anaya",
		"Tasquena",
		"Indios Verdes",
		"Deportivo 18 de Mayo",
		"Potrero",						/* 45 */
		"La Raza",
		"Tlatelolco",
		"Guerrero",
		"Juarez",
		"Ninos Heroes",					/* 50 */
		"Hospital General",
		"Centro Medico",
		"Etiopia",
		"Eugenia",
		"Division del Norte",			/* 55 */
		"Zapata",
		"Coyoacan",
		"Viveros",
		"Miguel Angel de Quevedo",
		"Copilco",						/* 60 */
		"Universidad",
		"Martín Carrera",
		"Talismán",
		"Bondojito",
		"Consulado",					/* 65 */
		"Canal del Norte",
		"Morelos",
		"Fray Servando",
		"Jamaica",
		"Santa Anita",					/* 70 */
		"Hangares",
		"Terminal Aérea",
		"Oceania",
		"Aragón",
		"Eduardo Molina",				/* 75 */
		"Valle Gomez",
		"Misterios",
		"Autobuses Norte",
		"Instituto del Petróleo",
		"Politecnico",					/* 80 */
		"El Rosario",
		"Tezozómoc",
		"Azcapotzalco",
		"Ferrería",
		"Norte 45",						/* 85 */
		"Vallejo",
		"Lindavista",
		"La Villa-Basílica",
		"Aquiles Serdán",
		"Camarones",					/* 90 */
		"Refinería",
		"San Joaquín",
		"Polanco",
		"Auditorio",
		"Constituyentes",				/* 95 */
		"San Pedro de los Pinos",
		"San Antonio",
		"Mixcoac",
		"Barranca del Muerto",
		"Garibaldi", 					/* 100 */
		"San Juan de Letrán",
		"Doctores",
		"Obrera",
		"La Viga",
		"Coyuya",						/* 105 */
		"Iztacalco",
		"Apatlaco",
		"Aculco",
		"Escuadrón 201",
		"Atlalilco",					/* 110 */
		"Iztapalapa",
		"Cerro de la Estrella",
		"UAM-I",
		"Constitución de 1917",
		"Patriotismo",					/* 115 */
		"Chilpancingo",
		"Lázaro Cárdenas",
		"Mixiuhca",
		"Velódromo",
		"Ciudad Deportiva",				/* 120 */
		"Puebla",
		"Agricola Oriental",
		"Canal de San Juan",
		"Tepalcates",
		"Guelatao",						/* 125 */
		"Peñon Viejo",
		"Acatitla",
		"Santa Marta",
		"Los Reyes",
		"La Paz",						/* 130 */
		"Ciudad Azteca",
		"Plaza Aragón",
		"Olimpica",
		"Ecatepec",
		"Múzquiz",						/* 135 */
		"Río de los Remedios",
		"Impulsora",
		"Nezahualcóyotl",
		"Villa de Aragón",
		"Bosque de Aragón",				/* 140 */
		"Deportivo Oceanía",
		"Romero Rubio",
		"R. Flores Magón",
		"Tepito",
		"Lagunilla",					/* 145 */
		"Buenavista"
	};

	int l_1[] = {
		0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
		17, 18, 19
	};
	int l_2[] = {
		20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 10, 33, 34,
		35, 36, 37, 38, 39, 40, 41, 42
	};
	int l_3[] = {
		43, 44, 45, 46, 47, 48, 29, 49, 7, 50, 51, 52, 53, 54, 55, 56, 57, 58,
		59, 60, 61
	};
	int l_4[] = { 62, 63, 64, 65, 66, 67, 12, 68, 69, 70 };
	int l_5[] = { 19, 71, 72, 73, 74, 75, 65, 76, 77, 46, 78, 79, 80 };
	int l_6[] = { 81, 82, 83, 84, 85, 86, 79, 87, 44, 88, 62 };
	int l_7[] = { 81, 89, 90, 91, 22, 92, 93, 94, 95, 1, 96, 97, 98, 99};
	int l_8[] = {
		100, 30, 101, 8, 102, 103, 34, 104, 70, 105, 106, 107, 108, 109,
		110, 111, 112, 113, 114
	};
	int l_9[] = { 1, 115, 116, 52, 117, 34, 69, 118, 119, 120, 121, 19 };
	int l_a[] = { 19, 122, 123, 124, 125, 126, 127, 128,129, 130 };
	int l_b[] = {
		131, 132, 133, 134 ,135, 136, 137, 138, 139, 140, 141,
		73, 142, 143, 13, 67, 144, 145, 100, 48, 146
	};

	n = new_net(COUNT(stations), 11);
	net_create_stations(n, stations);
	net_create_line(n, "1", l_1, COUNT(l_1), 18660);
	net_create_line(n, "2", l_2, COUNT(l_2), 23431);
	net_create_line(n, "3", l_3, COUNT(l_3), 23609);
	net_create_line(n, "4", l_4, COUNT(l_4), 10747);
	net_create_line(n, "5", l_5, COUNT(l_5), 15675);
	net_create_line(n, "6", l_6, COUNT(l_6), 13947);
	net_create_line(n, "7", l_7, COUNT(l_7), 18784);
	net_create_line(n, "8", l_8, COUNT(l_8), 20078);
	net_create_line(n, "9", l_9, COUNT(l_9), 15375);
	net_create_line(n, "A", l_a, COUNT(l_a), 17192);
	net_create_line(n, "B", l_b, COUNT(l_b), 23722);

	return n;
}
예제 #3
0
파일: rc5speed.c 프로젝트: Henauxg/minix
int main(int argc, char **argv)
{
    long count;
    static unsigned char buf[BUFSIZE];
    static unsigned char key[] = {
        0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
        0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
    };
    RC5_32_KEY sch;
    double a, b, c, d;
#ifndef SIGALRM
    long ca, cb, cc;
#endif

#ifndef TIMES
    printf("To get the most accurate results, try to run this\n");
    printf("program when this computer is idle.\n");
#endif

#ifndef SIGALRM
    printf("First we calculate the approximate speed ...\n");
    RC5_32_set_key(&sch, 16, key, 12);
    count = 10;
    do {
        long i;
        RC5_32_INT data[2];

        count *= 2;
        Time_F(START);
        for (i = count; i; i--)
            RC5_32_encrypt(data, &sch);
        d = Time_F(STOP);
    } while (d < 3.0);
    ca = count / 512;
    cb = count;
    cc = count * 8 / BUFSIZE + 1;
    printf("Doing RC5_32_set_key %ld times\n", ca);
# define COND(d) (count != (d))
# define COUNT(d) (d)
#else
# define COND(c) (run)
# define COUNT(d) (count)
    signal(SIGALRM, sig_done);
    printf("Doing RC5_32_set_key for 10 seconds\n");
    alarm(10);
#endif

    Time_F(START);
    for (count = 0, run = 1; COND(ca); count += 4) {
        RC5_32_set_key(&sch, 16, key, 12);
        RC5_32_set_key(&sch, 16, key, 12);
        RC5_32_set_key(&sch, 16, key, 12);
        RC5_32_set_key(&sch, 16, key, 12);
    }
    d = Time_F(STOP);
    printf("%ld RC5_32_set_key's in %.2f seconds\n", count, d);
    a = ((double)COUNT(ca)) / d;

#ifdef SIGALRM
    printf("Doing RC5_32_encrypt's for 10 seconds\n");
    alarm(10);
#else
    printf("Doing RC5_32_encrypt %ld times\n", cb);
#endif
    Time_F(START);
    for (count = 0, run = 1; COND(cb); count += 4) {
        RC5_32_INT data[2];

        RC5_32_encrypt(data, &sch);
        RC5_32_encrypt(data, &sch);
        RC5_32_encrypt(data, &sch);
        RC5_32_encrypt(data, &sch);
    }
    d = Time_F(STOP);
    printf("%ld RC5_32_encrypt's in %.2f second\n", count, d);
    b = ((double)COUNT(cb) * 8) / d;

#ifdef SIGALRM
    printf("Doing RC5_32_cbc_encrypt on %ld byte blocks for 10 seconds\n",
           BUFSIZE);
    alarm(10);
#else
    printf("Doing RC5_32_cbc_encrypt %ld times on %ld byte blocks\n", cc,
           BUFSIZE);
#endif
    Time_F(START);
    for (count = 0, run = 1; COND(cc); count++)
        RC5_32_cbc_encrypt(buf, buf, BUFSIZE, &sch, &(key[0]), RC5_ENCRYPT);
    d = Time_F(STOP);
    printf("%ld RC5_32_cbc_encrypt's of %ld byte blocks in %.2f second\n",
           count, BUFSIZE, d);
    c = ((double)COUNT(cc) * BUFSIZE) / d;

    printf("RC5_32/12/16 set_key       per sec = %12.2f (%9.3fuS)\n", a,
           1.0e6 / a);
    printf("RC5_32/12/16 raw ecb bytes per sec = %12.2f (%9.3fuS)\n", b,
           8.0e6 / b);
    printf("RC5_32/12/16 cbc     bytes per sec = %12.2f (%9.3fuS)\n", c,
           8.0e6 / c);
    exit(0);
#if defined(LINT) || defined(OPENSSL_SYS_MSDOS)
    return (0);
#endif
}
예제 #4
0
파일: cec.c 프로젝트: asmalldev/linux
int cec_add_elem(u64 pfn)
{
	struct ce_array *ca = &ce_arr;
	unsigned int to;
	int count, ret = 0;

	/*
	 * We can be called very early on the identify_cpu() path where we are
	 * not initialized yet. We ignore the error for simplicity.
	 */
	if (!ce_arr.array || ce_arr.disabled)
		return -ENODEV;

	ca->ces_entered++;

	mutex_lock(&ce_mutex);

	if (ca->n == MAX_ELEMS)
		WARN_ON(!del_lru_elem_unlocked(ca));

	ret = find_elem(ca, pfn, &to);
	if (ret < 0) {
		/*
		 * Shift range [to-end] to make room for one more element.
		 */
		memmove((void *)&ca->array[to + 1],
			(void *)&ca->array[to],
			(ca->n - to) * sizeof(u64));

		ca->array[to] = (pfn << PAGE_SHIFT) |
				(DECAY_MASK << COUNT_BITS) | 1;

		ca->n++;

		ret = 0;

		goto decay;
	}

	count = COUNT(ca->array[to]);

	if (count < count_threshold) {
		ca->array[to] |= (DECAY_MASK << COUNT_BITS);
		ca->array[to]++;

		ret = 0;
	} else {
		u64 pfn = ca->array[to] >> PAGE_SHIFT;

		if (!pfn_valid(pfn)) {
			pr_warn("CEC: Invalid pfn: 0x%llx\n", pfn);
		} else {
			/* We have reached max count for this page, soft-offline it. */
			pr_err("Soft-offlining pfn: 0x%llx\n", pfn);
			memory_failure_queue(pfn, 0, MF_SOFT_OFFLINE);
			ca->pfns_poisoned++;
		}

		del_elem(ca, to);

		/*
		 * Return a >0 value to denote that we've reached the offlining
		 * threshold.
		 */
		ret = 1;

		goto unlock;
	}

decay:
	ca->decay_count++;

	if (ca->decay_count >= CLEAN_ELEMS)
		do_spring_cleaning(ca);

unlock:
	mutex_unlock(&ce_mutex);

	return ret;
}
예제 #5
0
파일: p_hyper.c 프로젝트: Vulcanior/IUP
static void
pdf_write_outline_dict(PDF *p, int entry)
{
    pdf_outline *outline = &p->outlines[entry];
    pdc_id act_idlist[PDF_MAX_EVENTS];

    /* write action objects */
    if (outline->action)
        pdf_parse_and_write_actionlist(p, event_bookmark, act_idlist,
                                       (const char *) outline->action);

    pdc_begin_obj(p->out, OBJ_ID(entry));   /* outline object */
    pdc_begin_dict(p->out);

    pdc_objref(p->out, "/Parent", OBJ_ID(PARENT(entry)));

    /* outline destination */
    if (outline->dest)
    {
        pdc_puts(p->out, "/Dest");
        pdf_write_destination(p, outline->dest);
    }

    /* write Action entries */
    else if (outline->action)
        pdf_write_action_entries(p, event_bookmark, act_idlist);

    pdc_puts(p->out, "/Title"); /* outline text */
    pdf_put_hypertext(p, outline->text);
    pdc_puts(p->out, "\n");

    if (PREV(entry))
        pdc_objref(p->out, "/Prev", OBJ_ID(PREV(entry)));
    if (NEXT(entry))
        pdc_objref(p->out, "/Next", OBJ_ID(NEXT(entry)));

    if (FIRST(entry)) {
        pdc_objref(p->out, "/First", OBJ_ID(FIRST(entry)));
        pdc_objref(p->out, "/Last", OBJ_ID(LAST(entry)));
    }
    if (COUNT(entry)) {
        if (OPEN(entry))
            pdc_printf(p->out, "/Count %d\n", COUNT(entry));    /* open */
        else
            pdc_printf(p->out, "/Count %d\n", -COUNT(entry));/* closed */
    }

    /* Color */
    if (outline->textcolor[0] != 0.0 ||
        outline->textcolor[1] != 0.0 ||
        outline->textcolor[2] != 0.0)
        pdc_printf(p->out, "/C[%f %f %f]\n", outline->textcolor[0],
                                              outline->textcolor[1],
                                              outline->textcolor[2]);

    /* FontStyle */
    if (outline->fontstyle != fnt_Normal)
    {
        int fontstyle = 0;
        if (outline->fontstyle == fnt_Bold)
            fontstyle = 2;
        if (outline->fontstyle == fnt_Italic)
            fontstyle = 1;
        if (outline->fontstyle == fnt_BoldItalic)
            fontstyle = 3;
        pdc_printf(p->out, "/F %d\n", fontstyle);
    }

    pdc_end_dict(p->out);
    pdc_end_obj(p->out);                        /* outline object */
}
예제 #6
0
PR_IMPLEMENT(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb)
{
    PLArena *a;   
    char *rp;     /* returned pointer */

    PR_ASSERT((nb & pool->mask) == 0);
    
    nb = (PRUword)PL_ARENA_ALIGN(pool, nb); /* force alignment */

    /* attempt to allocate from arenas at pool->current */
    {
        a = pool->current;
        do {
            if ( a->avail +nb <= a->limit )  {
                pool->current = a;
                rp = (char *)a->avail;
                a->avail += nb;
                return rp;
            }
        } while( NULL != (a = a->next) );
    }

    /* attempt to allocate from arena_freelist */
    {
        PLArena *p; /* previous pointer, for unlinking from freelist */

        /* lock the arena_freelist. Make access to the freelist MT-Safe */
        if ( PR_FAILURE == LockArena())
            return(0);

        for ( a = arena_freelist, p = NULL; a != NULL ; p = a, a = a->next ) {
            if ( a->base +nb <= a->limit )  {
                if ( p == NULL )
                    arena_freelist = a->next;
                else
                    p->next = a->next;
                UnlockArena();
                a->avail = a->base;
                rp = (char *)a->avail;
                a->avail += nb;
                /* the newly allocated arena is linked after pool->current 
                *  and becomes pool->current */
                a->next = pool->current->next;
                pool->current->next = a;
                pool->current = a;
                if ( NULL == pool->first.next )
                    pool->first.next = a;
                return(rp);
            }
        }
        UnlockArena();
    }

    /* attempt to allocate from the heap */ 
    {  
        PRUint32 sz = PR_MAX(pool->arenasize, nb);
        sz += sizeof *a + pool->mask;  /* header and alignment slop */
        a = (PLArena*)PR_MALLOC(sz);
        if ( NULL != a )  {
            a->limit = (PRUword)a + sz;
            a->base = a->avail = (PRUword)PL_ARENA_ALIGN(pool, a + 1);
            rp = (char *)a->avail;
            a->avail += nb;
            /* the newly allocated arena is linked after pool->current 
            *  and becomes pool->current */
            a->next = pool->current->next;
            pool->current->next = a;
            pool->current = a;
            if ( NULL == pool->first.next )
                pool->first.next = a;
            PL_COUNT_ARENA(pool,++);
            COUNT(pool, nmallocs);
            return(rp);
        }
    }
예제 #7
0
static void	quick_sort(List *l,
		/*List_Iterator *first,
		List_Iterator *last,*/
		list_cmp_fct cmpf)
{
/*	
	A LITTLE MORE OPTIMIZED BUT BUGGED VERSION

	List_Iterator *pivot = last;
	List_Iterator *it = first;
	List_Iterator *next = NULL;
	void *data = NULL;
	last = NULL;

	if (!it || !pivot || it == pivot || !pivot->prev || !it->next)
	{
		return;
	}

	while (it != pivot)
	{
		next = it->next;
		if (cmpf(it->data, pivot->data) <= 0)
		{
			if (it == first)
				first = it->next;
			data = List_remove_it(l, it);
			assert(data);
			assert(List_insert_after_it(l, pivot, data));
			if (last == NULL)
				last = pivot->next;
		}
		it = next;
	}
	quick_sort(l, first, pivot->prev, cmpf);
	quick_sort(l, pivot->next, last, cmpf);*/

	void *pivot;
	int cmp = 0;
	List *less = NEW(List);
	List *greater = NEW(List);
	List *equal = NEW(List);
	List_Iterator *it;

	if (!less || !greater || !equal)
	{
		perror("malloc");
		return ;
	}
	if (COUNT(l) <= 1)
		return ;

	it = List_get_it(l, (COUNT(l)/2 - 1));
	pivot = it->data;
	List_remove_it(l, it);
	while (COUNT(l))
	{
		it = List_pop_first_it(l);
		cmp = cmpf(it->data, pivot);
		if (cmp > 0)
			List_append_it(less, it);
		else if (cmp < 0)
			List_append_it(greater, it);
		else
			List_append_it(equal, it);

	}
	// SUBLISTS
	if (COUNT(less)) {
		quick_sort(less, cmpf);
		List_concat(l, less);
	}
	else
		free(less);

	// 
	List_append(l, pivot);
	
	if (COUNT(equal)) {
		List_concat(l, equal);
	}
	else
		free(equal);


	if (COUNT(greater)) {
		quick_sort(greater, cmpf);
		List_concat(l, greater);
	}
	else
		free(greater);

}
예제 #8
0
INT_PTR CALLBACK DlgLuaScriptDialog(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	RECT r;
	RECT r2;
	int dx1, dy1, dx2, dy2;

	switch (msg) {

	case WM_INITDIALOG:
	{
		// remove the 30000 character limit from the console control
		SendMessage(GetDlgItem(hDlg, IDC_LUACONSOLE),EM_LIMITTEXT,0,0);

		GetWindowRect(GUI.hWnd, &r);
		dx1 = (r.right - r.left) / 2;
		dy1 = (r.bottom - r.top) / 2;

		GetWindowRect(hDlg, &r2);
		dx2 = (r2.right - r2.left) / 2;
		dy2 = (r2.bottom - r2.top) / 2;

		int windowIndex = 0;//std::find(LuaScriptHWnds.begin(), LuaScriptHWnds.end(), hDlg) - LuaScriptHWnds.begin();
		int staggerOffset = windowIndex * 24;
		r.left += staggerOffset;
		r.right += staggerOffset;
		r.top += staggerOffset;
		r.bottom += staggerOffset;

		// push it away from the main window if we can
		const int width = (r.right-r.left); 
		const int width2 = (r2.right-r2.left); 
		if(r.left+width2 + width < GetSystemMetrics(SM_CXSCREEN))
		{
			r.right += width;
			r.left += width;
		}
		else if((int)r.left - (int)width2 > 0)
		{
			r.right -= width2;
			r.left -= width2;
		}

		SetWindowPos(hDlg, NULL, r.left, r.top, NULL, NULL, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW);

		RECT r3;
		GetClientRect(hDlg, &r3);
		windowInfo.width = r3.right - r3.left;
		windowInfo.height = r3.bottom - r3.top;
		for(int i = 0; i < numControlLayoutInfos; i++) {
			ControlLayoutState& layoutState = windowInfo.layoutState[i];
			layoutState.valid = false;
		}

		DragAcceptFiles(hDlg, true);
		SetDlgItemText(hDlg, IDC_EDIT_LUAPATH, S9xGetLuaScriptName());

		SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(LOGFONT), &LuaConsoleLogFont, 0); // reset with an acceptable font
		return true;
	}	break;

	case WM_SIZE:
	{
		// resize or move controls in the window as necessary when the window is resized

		//LuaPerWindowInfo& windowInfo = LuaWindowInfo[hDlg];
		int prevDlgWidth = windowInfo.width;
		int prevDlgHeight = windowInfo.height;

		int dlgWidth = LOWORD(lParam);
		int dlgHeight = HIWORD(lParam);

		int deltaWidth = dlgWidth - prevDlgWidth;
		int deltaHeight = dlgHeight - prevDlgHeight;

		for(int i = 0; i < numControlLayoutInfos; i++)
		{
			ControlLayoutInfo layoutInfo = controlLayoutInfos[i];
			ControlLayoutState& layoutState = windowInfo.layoutState[i];

			HWND hCtrl = GetDlgItem(hDlg,layoutInfo.controlID);

			int x,y,width,height;
			if(layoutState.valid)
			{
				x = layoutState.x;
				y = layoutState.y;
				width = layoutState.width;
				height = layoutState.height;
			}
			else
			{
				RECT r;
				GetWindowRect(hCtrl, &r);
				POINT p = {r.left, r.top};
				ScreenToClient(hDlg, &p);
				x = p.x;
				y = p.y;
				width = r.right - r.left;
				height = r.bottom - r.top;
			}

			switch(layoutInfo.horizontalLayout)
			{
				case ControlLayoutInfo::RESIZE_END: width += deltaWidth; break;
				case ControlLayoutInfo::MOVE_START: x += deltaWidth; break;
				default: break;
			}
			switch(layoutInfo.verticalLayout)
			{
				case ControlLayoutInfo::RESIZE_END: height += deltaHeight; break;
				case ControlLayoutInfo::MOVE_START: y += deltaHeight; break;
				default: break;
			}

			SetWindowPos(hCtrl, 0, x,y, width,height, 0);

			layoutState.x = x;
			layoutState.y = y;
			layoutState.width = width;
			layoutState.height = height;
			layoutState.valid = true;
		}

		windowInfo.width = dlgWidth;
		windowInfo.height = dlgHeight;

		RedrawWindow(hDlg, NULL, NULL, RDW_INVALIDATE);
	}	break;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
			case IDOK:
			case IDCANCEL: {
				EndDialog(hDlg, true); // goto case WM_CLOSE;
			}	break;

			case IDC_BUTTON_LUARUN:
			{
				char filename[MAX_PATH];
				GetDlgItemText(hDlg, IDC_EDIT_LUAPATH, filename, MAX_PATH);
				S9xLoadLuaCode(filename);
			}	break;

			case IDC_BUTTON_LUASTOP:
			{
				S9xLuaStop();
			}	break;

			case IDC_BUTTON_LUAEDIT:
			{
				char Str_Tmp [1024]; // shadow added because the global one is unreliable
				SendDlgItemMessage(hDlg,IDC_EDIT_LUAPATH,WM_GETTEXT,(WPARAM)512,(LPARAM)Str_Tmp);
				// tell the OS to open the file with its associated editor,
				// without blocking on it or leaving a command window open.
				if((int)ShellExecute(NULL, "edit", Str_Tmp, NULL, NULL, SW_SHOWNORMAL) == SE_ERR_NOASSOC)
					if((int)ShellExecute(NULL, "open", Str_Tmp, NULL, NULL, SW_SHOWNORMAL) == SE_ERR_NOASSOC)
						ShellExecute(NULL, NULL, "notepad", Str_Tmp, NULL, SW_SHOWNORMAL);
			}	break;

			case IDC_BUTTON_LUABROWSE:
			{
				OPENFILENAME  ofn;
				char  szFileName[MAX_PATH];

				strcpy(szFileName, S9xGetFilenameRel("lua"));

				ZeroMemory( (LPVOID)&ofn, sizeof(OPENFILENAME) );
				ofn.lStructSize = sizeof(OPENFILENAME);
				ofn.hwndOwner = hDlg;
				ofn.lpstrFilter = "Lua Script (*.lua)" "\0*.lua\0" FILE_INFO_ANY_FILE_TYPE "\0*.*\0\0";
				ofn.lpstrFile = szFileName;
				ofn.lpstrDefExt = "lua";
				ofn.nMaxFile = MAX_PATH;
				ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST; // hide previously-ignored read-only checkbox (the real read-only box is in the open-movie dialog itself)
				if(GetOpenFileName( &ofn ))
				{
					SetWindowText(GetDlgItem(hDlg, IDC_EDIT_LUAPATH), szFileName);
				}
				//SetCurrentDirectory(movieDirectory);
				return true;
			}	break;

			case IDC_EDIT_LUAPATH:
			{
				char filename[MAX_PATH];
				GetDlgItemText(hDlg, IDC_EDIT_LUAPATH, filename, MAX_PATH);
				FILE* file = fopen(filename, "rb");
				EnableWindow(GetDlgItem(hDlg, IDOK), file != NULL);
				if(file)
					fclose(file);
			}	break;

			case IDC_LUACONSOLE_CHOOSEFONT:
			{
				CHOOSEFONT cf;

				ZeroMemory(&cf, sizeof(cf));
				cf.lStructSize = sizeof(CHOOSEFONT);
				cf.hwndOwner = hDlg;
				cf.lpLogFont = &LuaConsoleLogFont;
				cf.Flags = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT;
				if (ChooseFont(&cf)) {
					if (hFont) {
						DeleteObject(hFont);
						hFont = NULL;
					}
					hFont = CreateFontIndirect(&LuaConsoleLogFont);
					if (hFont)
						SendDlgItemMessage(hDlg, IDC_LUACONSOLE, WM_SETFONT, (WPARAM)hFont, 0);
				}
			}	break;

			case IDC_LUACONSOLE_CLEAR:
			{
				SetWindowText(GetDlgItem(hDlg, IDC_LUACONSOLE), "");
			}	break;
		}
		break;

	case WM_CLOSE: {
		S9xLuaStop();
		DragAcceptFiles(hDlg, FALSE);
		if (hFont) {
			DeleteObject(hFont);
			hFont = NULL;
		}
		LuaConsoleHWnd = NULL;
	}	break;

	case WM_DROPFILES: {
		HDROP hDrop;
		//UINT fileNo;
		UINT fileCount;
		char filename[PATH_MAX];

		hDrop = (HDROP)wParam;
		fileCount = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
		if (fileCount > 0) {
			DragQueryFile(hDrop, 0, filename, COUNT(filename));
			SetWindowText(GetDlgItem(hDlg, IDC_EDIT_LUAPATH), filename);
		}
		DragFinish(hDrop);
		return true;
	}	break;

	}

	return false;

}
예제 #9
0
#include "fun_head_fast.h"


MODELBEGIN


EQUATION("Init")
/*
Model initialization
*/

v[0] = V("N");
v[1] = V("C0");
v[2] = V("Q0");
v[3] = COUNT("Firm");

for (i = v[3] + 1; i <= v[0]; ++i)
	ADDOBJ("Firm");				// add missing objects

i = 1;
CYCLE(cur, "Firm")				// set initial conditions (t=0)
{
	WRITELS(cur, "Convenience", v[1], 0);
	WRITELS(cur, "Quality", v[2], 0);
	WRITELS(cur, "Prob", 0, 0);
	WRITELS(cur, "sigma", 0, 0);
	WRITELS(cur, "ms", 1 / v[0], 0);
}

PARAMETER;
int
char_ioctl_arg(struct trace_proc * proc, unsigned long req, void * ptr,
	int dir)
{
	minix_i2c_ioctl_exec_t *iie;
	struct fb_var_screeninfo *fbvs;
	struct volume_level *level;
	struct inout_ctrl *inout;
	struct termios *tc;
	struct ptmget *pm;
	struct winsize *ws;
	struct kio_bell *bell;
	struct kio_leds *leds;
	struct pciio_cfgreg *pci_cfgreg;
	struct pciio_bdf_cfgreg *pci_bdf_cfgreg;
	struct pciio_businfo *pci_businfo;
	struct pciio_map *pci_iomap;
	struct pciio_acl *pci_acl;

	switch (req) {
	case MINIX_I2C_IOCTL_EXEC:
		if ((iie = (minix_i2c_ioctl_exec_t *)ptr) == NULL)
			return IF_OUT; /* we print only the request for now */

		put_i2c_op(proc, "iie_op", iie->iie_op);
		put_value(proc, "iie_addr", "0x%04x", iie->iie_addr);
		return 0; /* TODO: print command/data/result */

	case FBIOGET_VSCREENINFO:
		if ((fbvs = (struct fb_var_screeninfo *)ptr) == NULL)
			return IF_IN;

		put_value(proc, "xres", "%"PRIu32, fbvs->xres);
		put_value(proc, "yres", "%"PRIu32, fbvs->yres);
		put_value(proc, "xres_virtual", "%"PRIu32, fbvs->xres_virtual);
		put_value(proc, "yres_virtual", "%"PRIu32, fbvs->yres_virtual);
		put_value(proc, "xoffset", "%"PRIu32, fbvs->xoffset);
		put_value(proc, "yoffset", "%"PRIu32, fbvs->yoffset);
		put_value(proc, "bits_per_pixel", "%"PRIu32,
		    fbvs->bits_per_pixel);
		return 0;

	case FBIOPUT_VSCREENINFO:
	case FBIOPAN_DISPLAY:
		if ((fbvs = (struct fb_var_screeninfo *)ptr) == NULL)
			return IF_OUT;

		put_value(proc, "xoffset", "%"PRIu32, fbvs->xoffset);
		put_value(proc, "yoffset", "%"PRIu32, fbvs->yoffset);
		return 0;

	case DSPIORATE:
	case DSPIOSTEREO:
	case DSPIOSIZE:
	case DSPIOBITS:
	case DSPIOSIGN:
	case DSPIOMAX:
	case DSPIOFREEBUF:
	case DSPIOSAMPLESINBUF:
		if (ptr == NULL)
			return dir;

		put_value(proc, NULL, "%u", *(unsigned int *)ptr);
		return IF_ALL;

	case MIXIOGETVOLUME:
		if ((level = (struct volume_level *)ptr) == NULL)
			return dir;

		if (dir == IF_OUT)
			put_sound_device(proc, "device", level->device);
		else {
			put_value(proc, "left", "%d", level->left);
			put_value(proc, "right", "%d", level->right);
		}
		return IF_ALL;

	case MIXIOSETVOLUME:
		/* Print the corrected volume levels only with verbosity on. */
		if ((level = (struct volume_level *)ptr) == NULL)
			return IF_OUT | ((verbose > 0) ? IF_IN : 0);

		if (dir == IF_OUT)
			put_sound_device(proc, "device", level->device);
		put_value(proc, "left", "%d", level->left);
		put_value(proc, "right", "%d", level->right);
		return IF_ALL;

	case MIXIOGETINPUTLEFT:
	case MIXIOGETINPUTRIGHT:
	case MIXIOGETOUTPUT:
		if ((inout = (struct inout_ctrl *)ptr) == NULL)
			return dir;

		if (dir == IF_OUT)
			put_sound_device(proc, "device", inout->device);
		else {
			put_sound_state(proc, "left", inout->left);
			put_sound_state(proc, "right", inout->right);
		}
		return IF_ALL;

	case MIXIOSETINPUTLEFT:
	case MIXIOSETINPUTRIGHT:
	case MIXIOSETOUTPUT:
		if ((inout = (struct inout_ctrl *)ptr) == NULL)
			return IF_OUT;

		put_sound_device(proc, "device", inout->device);
		put_sound_state(proc, "left", inout->left);
		put_sound_state(proc, "right", inout->right);
		return IF_ALL;

	case TIOCFLUSH:
		if (ptr == NULL)
			return IF_OUT;

		put_flags(proc, NULL, flush_flags, COUNT(flush_flags), "0x%x",
		    *(int *)ptr);
		return IF_ALL;

	case TIOCGETA:
	case TIOCSETA:
	case TIOCSETAW:
	case TIOCSETAF:
		if ((tc = (struct termios *)ptr) == NULL)
			return dir;

		/*
		 * These are fairly common IOCTLs, so printing everything by
		 * default would create a lot of noise.  By default we limit
		 * ourselves to printing the field that contains what I
		 * consider to be the most important flag: ICANON.
		 * TODO: see if we can come up with a decent format for
		 * selectively printing (relatively important) flags.
		 */
		if (verbose > 0) {
			put_flags(proc, "c_iflag", tc_iflags, COUNT(tc_iflags),
			    "0x%x", tc->c_iflag);
			put_flags(proc, "c_oflag", tc_oflags, COUNT(tc_oflags),
			    "0x%x", tc->c_oflag);
			put_flags(proc, "c_cflag", tc_cflags, COUNT(tc_cflags),
			    "0x%x", tc->c_cflag);
		}
		put_flags(proc, "c_lflag", tc_lflags, COUNT(tc_lflags), "0x%x",
			tc->c_lflag);
		if (verbose > 0) {
			put_value(proc, "c_ispeed", "%d", tc->c_ispeed);
			put_value(proc, "c_ospeed", "%d", tc->c_ospeed);
		}
		return 0; /* TODO: print the c_cc fields */

	case TIOCGETD:
	case TIOCSETD:
		if (ptr == NULL)
			return dir;

		put_tty_disc(proc, NULL, *(int *)ptr);
		return IF_ALL;

	case TIOCGLINED:
	case TIOCSLINED:
		if (ptr == NULL)
			return dir;

		put_buf(proc, NULL, PF_LOCADDR | PF_STRING, (vir_bytes)ptr,
		    sizeof(linedn_t));
		return IF_ALL;

	case TIOCGPGRP:
	case TIOCSPGRP:
	case TIOCOUTQ:
	case TIOCPKT:
	case TIOCREMOTE:
	case TIOCUCNTL:
	case TIOCSTAT:		/* argument seems unused? */
	case TIOCGSID:
	case TIOCCONS:		/* argument seems unused? */
	case TIOCEXT:
	case TIOCSQSIZE:
	case TIOCGQSIZE:
		/* Print a simple integer. */
		if (ptr == NULL)
			return dir;

		put_value(proc, NULL, "%d", *(int *)ptr);
		return IF_ALL;

	case TIOCPTSNAME:
		if ((pm = (struct ptmget *)ptr) == NULL)
			return IF_IN;

		put_buf(proc, "sn", PF_LOCADDR | PF_STRING, (vir_bytes)pm->sn,
		    sizeof(pm->sn));
		return IF_ALL;

	case TIOCSTI:
		if (ptr == NULL)
			return dir;

		if (!valuesonly)
			put_value(proc, NULL, "'%s'",
			    get_escape(*(char *)ptr));
		else
			put_value(proc, NULL, "%u", *(char *)ptr);
		return IF_ALL;

	case TIOCGWINSZ:
	case TIOCSWINSZ:
		if ((ws = (struct winsize *)ptr) == NULL)
			return dir;

		/* This is a stupid order, but we follow the struct layout. */
		put_value(proc, "ws_row", "%u", ws->ws_row);
		put_value(proc, "ws_col", "%u", ws->ws_col);
		if (verbose > 0) {
			put_value(proc, "ws_xpixel", "%u", ws->ws_xpixel);
			put_value(proc, "ws_ypixel", "%u", ws->ws_ypixel);
		}
		return (verbose > 0) ? IF_ALL : 0;

	case KIOCBELL:
		if ((bell = (struct kio_bell *)ptr) == NULL)
			return IF_OUT;

		put_value(proc, "kb_pitch", "%u", bell->kb_pitch);
		put_value(proc, "kb_volume", "%lu", bell->kb_volume);
		put_struct_timeval(proc, "kb_duration", PF_LOCADDR,
		    (vir_bytes)&bell->kb_duration);

		return IF_ALL;

	case KIOCSLEDS:
		if ((leds = (struct kio_leds *)ptr) == NULL)
			return IF_OUT;

		put_flags(proc, "kl_bits", kbd_leds, COUNT(kbd_leds), "0x%x",
		    leds->kl_bits);
		return IF_ALL;

	case PCI_IOC_CFGREAD:
		if ((pci_cfgreg = (struct pciio_cfgreg *)ptr) == NULL)
			return IF_IN;

		put_ptr(proc, "reg", (vir_bytes)pci_cfgreg->reg);
		put_value(proc, "val", "%08x", pci_cfgreg->val);
		return IF_ALL;

	case PCI_IOC_CFGWRITE:
		if ((pci_cfgreg = (struct pciio_cfgreg *)ptr) == NULL)
			return IF_OUT;

		put_ptr(proc, "reg", (vir_bytes)pci_cfgreg->reg);
		put_value(proc, "val", "%08x", pci_cfgreg->val);
		return IF_ALL;

	case PCI_IOC_BDF_CFGREAD:
		if ((pci_bdf_cfgreg = (struct pciio_bdf_cfgreg *)ptr) == NULL)
			return IF_IN;

		put_value(proc, "bus", "%u", pci_bdf_cfgreg->bus);
		put_value(proc, "device", "%u", pci_bdf_cfgreg->device);
		put_value(proc, "function", "%u", pci_bdf_cfgreg->function);
		put_ptr(proc, "cfgreg.reg", (vir_bytes)pci_bdf_cfgreg->cfgreg.reg);
		put_value(proc, "cfgreg.val", "%08x", pci_bdf_cfgreg->cfgreg.val);
		return IF_ALL;

	case PCI_IOC_BDF_CFGWRITE:
		if ((pci_bdf_cfgreg = (struct pciio_bdf_cfgreg *)ptr) == NULL)
			return IF_OUT;

		put_value(proc, "bus", "%u", pci_bdf_cfgreg->bus);
		put_value(proc, "device", "%u", pci_bdf_cfgreg->device);
		put_value(proc, "function", "%u", pci_bdf_cfgreg->function);
		put_ptr(proc, "cfgreg.reg", (vir_bytes)pci_bdf_cfgreg->cfgreg.reg);
		put_value(proc, "cfgreg.val", "%08x", pci_bdf_cfgreg->cfgreg.val);
		return IF_ALL;

	case PCI_IOC_BUSINFO:
		if ((pci_businfo = (struct pciio_businfo *)ptr) == NULL)
			return IF_IN;

		put_value(proc, "busno", "%u", pci_businfo->busno);
		put_value(proc, "maxdevs", "%u", pci_businfo->maxdevs);
		return IF_ALL;

	case PCI_IOC_MAP:
		if ((pci_iomap = (struct pciio_map *)ptr) == NULL)
			return IF_OUT|IF_IN;

		put_value(proc, "flags", "%x", pci_iomap->flags);
		put_value(proc, "phys_offset", "%08x", pci_iomap->phys_offset);
		put_value(proc, "size", "%zu", pci_iomap->size);
		put_value(proc, "readonly", "%x", pci_iomap->readonly);

		if (IF_IN == dir)
			put_ptr(proc, "vaddr_ret", (vir_bytes)pci_iomap->vaddr_ret);

		return IF_ALL;

	case PCI_IOC_UNMAP:
		if ((pci_iomap = (struct pciio_map *)ptr) == NULL)
			return IF_OUT;

		put_ptr(proc, "vaddr", (vir_bytes)pci_iomap->vaddr);

		return IF_ALL;

	case PCI_IOC_RESERVE:
		if ((pci_acl = (struct pciio_acl *)ptr) == NULL)
			return IF_OUT;

		put_value(proc, "domain", "%u", pci_acl->domain);
		put_value(proc, "bus", "%u", pci_acl->bus);
		put_value(proc, "device", "%u", pci_acl->device);
		put_value(proc, "function", "%u", pci_acl->function);

		return IF_ALL;
	case PCI_IOC_RELEASE:
		if ((pci_acl = (struct pciio_acl *)ptr) == NULL)
			return IF_OUT;

		put_value(proc, "domain", "%u", pci_acl->domain);
		put_value(proc, "bus", "%u", pci_acl->bus);
		put_value(proc, "device", "%u", pci_acl->device);
		put_value(proc, "function", "%u", pci_acl->function);

		return IF_ALL;

	default:
		return 0;
	}
}
예제 #11
0
static __inline void
sharelock(struct thread *td, struct lock *lkp, int incr) {
	lkp->lk_flags |= LK_SHARE_NONZERO;
	lkp->lk_sharecount += incr;
	COUNT(td, incr);
}
예제 #12
0
void Config_ResetDefault() {
  float tmp1[] = DEFAULT_AXIS_STEPS_PER_UNIT;
  float tmp2[] = DEFAULT_MAX_FEEDRATE;
  long tmp3[] = DEFAULT_MAX_ACCELERATION;
  for (uint8_t i = 0; i < NUM_AXIS; i++) {
    axis_steps_per_unit[i] = tmp1[i];
    max_feedrate[i] = tmp2[i];
    max_acceleration_units_per_sq_second[i] = tmp3[i];
    #if ENABLED(SCARA)
      if (i < COUNT(axis_scaling))
        axis_scaling[i] = 1;
    #endif
  }

  // steps per sq second need to be updated to agree with the units per sq second
  reset_acceleration_rates();

  acceleration = DEFAULT_ACCELERATION;
  retract_acceleration = DEFAULT_RETRACT_ACCELERATION;
  travel_acceleration = DEFAULT_TRAVEL_ACCELERATION;
  minimumfeedrate = DEFAULT_MINIMUMFEEDRATE;
  minsegmenttime = DEFAULT_MINSEGMENTTIME;
  mintravelfeedrate = DEFAULT_MINTRAVELFEEDRATE;
  max_xy_jerk = DEFAULT_XYJERK;
  max_z_jerk = DEFAULT_ZJERK;
  max_e_jerk = DEFAULT_EJERK;
  home_offset[X_AXIS] = home_offset[Y_AXIS] = home_offset[Z_AXIS] = 0;

  #if ENABLED(MESH_BED_LEVELING)
    mbl.active = 0;
  #endif

  #if ENABLED(AUTO_BED_LEVELING_FEATURE)
    zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  #endif

  #if ENABLED(DELTA)
    endstop_adj[X_AXIS] = endstop_adj[Y_AXIS] = endstop_adj[Z_AXIS] = 0;
    delta_radius =  DELTA_RADIUS;
    delta_diagonal_rod =  DELTA_DIAGONAL_ROD;
    delta_segments_per_second =  DELTA_SEGMENTS_PER_SECOND;
    delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1;
    delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2;
    delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3;
    recalc_delta_settings(delta_radius, delta_diagonal_rod);
  #elif ENABLED(Z_DUAL_ENDSTOPS)
    z_endstop_adj = 0;
  #endif

  #if ENABLED(ULTIPANEL)
    plaPreheatHotendTemp = PLA_PREHEAT_HOTEND_TEMP;
    plaPreheatHPBTemp = PLA_PREHEAT_HPB_TEMP;
    plaPreheatFanSpeed = PLA_PREHEAT_FAN_SPEED;
    absPreheatHotendTemp = ABS_PREHEAT_HOTEND_TEMP;
    absPreheatHPBTemp = ABS_PREHEAT_HPB_TEMP;
    absPreheatFanSpeed = ABS_PREHEAT_FAN_SPEED;
  #endif

  #if ENABLED(HAS_LCD_CONTRAST)
    lcd_contrast = DEFAULT_LCD_CONTRAST;
  #endif

  #if ENABLED(PIDTEMP)
    #if ENABLED(PID_PARAMS_PER_EXTRUDER)
      for (uint8_t e = 0; e < EXTRUDERS; e++)
    #else
      int e = 0; UNUSED(e); // only need to write once
    #endif
    {
      PID_PARAM(Kp, e) = DEFAULT_Kp;
      PID_PARAM(Ki, e) = scalePID_i(DEFAULT_Ki);
      PID_PARAM(Kd, e) = scalePID_d(DEFAULT_Kd);
      #if ENABLED(PID_ADD_EXTRUSION_RATE)
        PID_PARAM(Kc, e) = DEFAULT_Kc;
      #endif
    }
    #if ENABLED(PID_ADD_EXTRUSION_RATE)
      lpq_len = 20; // default last-position-queue size
    #endif
    // call updatePID (similar to when we have processed M301)
    updatePID();
  #endif // PIDTEMP

  #if ENABLED(PIDTEMPBED)
    bedKp = DEFAULT_bedKp;
    bedKi = scalePID_i(DEFAULT_bedKi);
    bedKd = scalePID_d(DEFAULT_bedKd);
  #endif

  #if ENABLED(FWRETRACT)
    autoretract_enabled = false;
    retract_length = RETRACT_LENGTH;
    #if EXTRUDERS > 1
      retract_length_swap = RETRACT_LENGTH_SWAP;
    #endif
    retract_feedrate = RETRACT_FEEDRATE;
    retract_zlift = RETRACT_ZLIFT;
    retract_recover_length = RETRACT_RECOVER_LENGTH;
    #if EXTRUDERS > 1
      retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
    #endif
    retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  #endif

  volumetric_enabled = false;
  for (uint8_t q = 0; q < COUNT(filament_size); q++)
    filament_size[q] = DEFAULT_NOMINAL_FILAMENT_DIA;
  calculate_volumetric_multipliers();

  SERIAL_ECHO_START;
  SERIAL_ECHOLNPGM("Hardcoded Default Settings Loaded");
}
예제 #13
0
static int Unfreeze()
{
   // notaz: overflowing the damn Symbian stack again
   char buffer [16];
   char rom_filename [512];
   int result;

   int version;

   unsigned int len = strlen(SNAPSHOT_MAGIC) + 1 + 4 + 1;
   if (statef_read(buffer, len) != (int)len)
      return (WRONG_FORMAT);
   if (strncmp(buffer, SNAPSHOT_MAGIC, strlen(SNAPSHOT_MAGIC)) != 0)
      return (WRONG_FORMAT);
   if ((version = atoi(&buffer [strlen(SNAPSHOT_MAGIC) + 1])) > SNAPSHOT_VERSION)
      return (WRONG_VERSION);

   if ((result = UnfreezeBlock("NAM", (uint8*) rom_filename, 512)) != SUCCESS)
      return (result);

   if (strcasecmp(rom_filename, Memory.ROMFilename) != 0 &&
         strcasecmp(S9xBasename(rom_filename), S9xBasename(Memory.ROMFilename)) != 0)
   {
      S9xMessage(S9X_WARNING, S9X_FREEZE_ROM_NAME,
                 "Current loaded ROM image doesn't match that required by freeze-game file.");
   }



   uint32 old_flags = CPU.Flags;
#ifdef USE_SA1
   uint32 sa1_old_flags = SA1.Flags;
#endif
   S9xReset();
   S9xSetSoundMute(TRUE);

   if ((result = UnfreezeStruct("CPU", &CPU, SnapCPU,
                                COUNT(SnapCPU))) != SUCCESS)
      return (result);


   FixROMSpeed();
   CPU.Flags |= old_flags & (DEBUG_MODE_FLAG | TRACE_FLAG |
                             SINGLE_STEP_FLAG | FRAME_ADVANCE_FLAG);
   if ((result = UnfreezeStruct("REG", &Registers, SnapRegisters, COUNT(SnapRegisters))) != SUCCESS)
      return (result);
   if ((result = UnfreezeStruct("PPU", &PPU, SnapPPU, COUNT(SnapPPU))) != SUCCESS)
      return (result);


   IPPU.ColorsChanged = TRUE;
   IPPU.OBJChanged = TRUE;
   CPU.InDMA = FALSE;
   // Restore colors from PPU
   unsigned int i;
   for (i = 0; i < 256; i++)
   {
      IPPU.Red[i] = PPU.CGDATA[i] & 0x1f;
      IPPU.Green[i] = (PPU.CGDATA[i] >> 5) & 0x1f;
      IPPU.Blue[i] = (PPU.CGDATA[i] >> 10) & 0x1f;
   }

   S9xFixColourBrightness();
   IPPU.RenderThisFrame = FALSE;

   if ((result = UnfreezeStruct("DMA", DMA, SnapDMA,
                                COUNT(SnapDMA))) != SUCCESS)
      return (result);

   if ((result = UnfreezeBlock("VRA", Memory.VRAM, 0x10000)) != SUCCESS)
      return (result);

   if ((result = UnfreezeBlock("RAM", Memory.RAM, 0x20000)) != SUCCESS)
      return (result);

   if ((result = UnfreezeBlock("SRA", SRAM, 0x20000)) != SUCCESS)
      return (result);

   if ((result = UnfreezeBlock("FIL", Memory.FillRAM, 0x8000)) != SUCCESS)
      return (result);

   // Restore graphics shadow registers
   GFX.r212c_s = Memory.FillRAM[0x212c];
   GFX.r212d_s = Memory.FillRAM[0x212d];
   GFX.r212e_s = Memory.FillRAM[0x212e];
   GFX.r212f_s = Memory.FillRAM[0x212f];
   GFX.r2130_s = Memory.FillRAM[0x2130];
   GFX.r2131_s = Memory.FillRAM[0x2131];

   if (UnfreezeStruct("APU", &APU, SnapAPU, COUNT(SnapAPU)) == SUCCESS)
   {
      SAPURegisters spcregs;
      if ((result = UnfreezeStruct("ARE", &spcregs, SnapAPURegisters,
                                   COUNT(SnapAPURegisters))) != SUCCESS)
         return (result);
      // reload all SPC700 regs from savestate compatible struct
      IAPU.P = spcregs.P;
      IAPU.YA.W = spcregs.YA.W;
      IAPU.X = spcregs.X;
      IAPU.S = spcregs.S;
      IAPU.PC = IAPU.RAM + spcregs.PC;

      if ((result = UnfreezeBlock("ARA", IAPU.RAM, 0x10000)) != SUCCESS)
         return (result);

      if ((result = UnfreezeStruct("SOU", &SoundData, SnapSoundData,
                                   COUNT(SnapSoundData))) != SUCCESS)
         return (result);

      // notaz: just to be sure
      int u;
      for (u = 0; u < 8; u++)
      {
         SoundData.channels[u].env_ind_attack &= 0xf;
         SoundData.channels[u].env_ind_decay  &= 0x7;
         SoundData.channels[u].env_ind_sustain &= 0x1f;
      }

      S9xSetSoundMute(FALSE);
      S9xAPUUnpackStatus();
      if (APUCheckDirectPage())
         IAPU.DirectPage = IAPU.RAM + 0x100;
      else
         IAPU.DirectPage = IAPU.RAM;
      Settings.APUEnabled = TRUE;
      /*IAPU.APUExecuting*/CPU.APU_APUExecuting = TRUE;
   }
   else
   {
      Settings.APUEnabled = FALSE;
      /*IAPU.APUExecuting*/CPU.APU_APUExecuting = FALSE;
      S9xSetSoundMute(TRUE);
   }
#ifdef USE_SA1
   if ((result = UnfreezeStruct("SA1", &SA1, SnapSA1,
                                COUNT(SnapSA1))) == SUCCESS)
   {
      if ((result = UnfreezeStruct("SAR", &SA1Registers,
                                   SnapSA1Registers, COUNT(SnapSA1Registers))) != SUCCESS)
         return (result);

      S9xFixSA1AfterSnapshotLoad();
      SA1.Flags |= sa1_old_flags & (TRACE_FLAG);
   }
#endif
   S9xFixSoundAfterSnapshotLoad();
   ICPU.ShiftedPB = Registers.PB << 16;
   ICPU.ShiftedDB = Registers.DB << 16;
   S9xSetPCBase(ICPU.ShiftedPB + Registers.PC);

#ifndef ASMCPU
   S9xUnpackStatus();  // not needed
   S9xFixCycles();  // also not needed?
#endif
   S9xReschedule();

   S9xSRTCPostLoadState();
   if (Settings.SDD1)  S9xSDD1PostLoadState();

   return (SUCCESS);
}
예제 #14
0
int main(void)
{
    clock_t tic,toc;

    double signal[] = { 3,4,5,6,7,8,9,10};
    double filter[] = { 2,1 };
    //double result[COUNT(signal) + COUNT(filter) - 1] = NULL;
    double* result = (double *) calloc(COUNT(signal) + COUNT(filter) - 1, sizeof(double));

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
    tic = clock();
    convolve(signal, COUNT(signal), filter, COUNT(filter), result);
    toc = clock();
    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
*/
    int j;/*
    printf("Resultado Final:\n");
    for( j=0; j<(COUNT(signal) + COUNT(filter) - 1); j++ ) {
        printf("%f ",result[j]);
    }
    printf("\n");
*/
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    result = (double *) calloc(COUNT(signal) + COUNT(filter) - 1, sizeof(double));

    tic = clock();
    //convolve_index(signal,0, COUNT(signal), filter, COUNT(filter), result);

    convNormalIndex(signal,0, COUNT(signal), filter, COUNT(filter), result);

    toc = clock();
    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);

    //printf("Resultado Final:\n");
    for( j=0; j<(COUNT(signal) + COUNT(filter) - 1); j++ ) {
        printf("%f ",result[j]);
    }
    printf("\n");

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    result = (double *) calloc(COUNT(signal) + COUNT(filter) - 1, sizeof(double));

    int block_size = 4;
    int l_localBuffer = nextpw2(block_size+COUNT(filter)-1);
    double* localBuffer = (double *) calloc(l_localBuffer, sizeof(double));
    printf("size = %d\n",l_localBuffer);

    tic = clock();
    for( j=0; j<(COUNT(signal)/block_size); j++ ) {
        //printf("Bucle externo j: %d\n",j);
        //que empiece enl puntero en el inicio del vector signal o result pero en (j*block_size)
        convOverlapAdd(&signal[j*block_size], block_size, localBuffer, l_localBuffer, filter, COUNT(filter), &result[j*block_size]);
    }

    toc = clock();
    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
    free(localBuffer);
    printf("Resultado Final:\n");
    for( j=0; j<(COUNT(signal) + COUNT(filter) - 1); j++ ) {
        printf("%f ",result[j]);
    }
    printf("\n");

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    printf("%d\n",(int)resultLength);

    double *A = malloc( resultLength*sizeof(double) );
    //double *B = malloc( resultLength*sizeof(double) );
    //double *C = (double *) calloc(resultLength, sizeof(double));


    /* datos aleatorios */
    /*    printf("[");
    int j;
    for( j=0; j<signalLength; j++ ) {
        A[j] = ((double) rand()/ RAND_MAX);
        printf("%f, ",A[j]);
    }
    printf("]\n");
     */
/*
    tic = clock();
    convolve(soundRandom, signalLength, H_1, filterLength, A);
    toc = clock();
    printf("Elapsed: %f miliseconds\n", (double)(toc - tic)*1000 / CLOCKS_PER_SEC);


    int block_size2 = 512;
    int l_localBuffer2 = nextpw2(block_size2+filterLength-1);
    double *localBuffer2 = (double *) calloc(l_localBuffer2, sizeof(double));
    printf("size = %d\n",l_localBuffer2);

    tic = clock();
    for( j=0; j<(signalLength/block_size2); j++ ) {
        printf("Bucle externo j: %d, indice:%d\n",j,j*block_size2);
        //que empiece enl puntero en el inicio del vector signal o result pero en (j*block_size)
        //convOverlapAdd(&soundRandom[j*block_size], block_size2, localBuffer2, l_localBuffer2, H_1, filterLength, &C[j*block_size]);
    }


    toc = clock();
    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
*/

/*
    printf("A\tB\tC\n");
    //int j;
    for( j=0; j<resultLength; j++ ) {
        if(A[j]-C[j] != 0){
            printf("%f\t%f\n ",A[j],C[j]);
        }
    }
*/
/*
    printf("[");
    int j;
    for( j=0; j<resultLength; j++ ) {
        if (j == resultLength-1){
            printf("%f ",C[j]);
        }else{
            printf("%f, ",C[j]);
        }
    }
    printf("]\n");
*/
    return 0;
}
예제 #15
0
void vram_init()
{
    menu_add("VRAM", vram_menus, COUNT(vram_menus));
    old_buffer_pos = YUV422_LV_BUFFER_1;
}
예제 #16
0
void model1::em_loop(int it,Perplexity& perp, sentenceHandler& sHandler1, bool seedModel1, 
		     bool dump_alignment, const char* alignfile, Dictionary& dict, bool useDict, Perplexity& viterbi_perp, bool test)
{
  WordIndex i, j, l, m ;
  double cross_entropy;
  int pair_no=0 ;
  perp.clear();
  viterbi_perp.clear();
  ofstream of2;
  // for each sentence pair in the corpus
  if (dump_alignment||FEWDUMPS)
    of2.open(alignfile);
  cerr <<" number of French (target) words = " << noFrenchWords << endl;
  PROB uniform = 1.0/noFrenchWords ;
  cerr << "initial unifrom prob = " << uniform << endl;
  sentPair sent ;
  sHandler1.rewind();
  while(sHandler1.getNextSentence(sent)){
    Vector<WordIndex>& es = sent.eSent;
    Vector<WordIndex>& fs = sent.fSent;
    const float so  = sent.getCount(); // number of times sentence occurs in corpus
    //std::cerr << "\n\nNEW sentence (#" << (pair_no + 1) << ") with count = " << so << endl;
    l = es.size() - 1;  // source length
    m = fs.size() - 1;  // target length
    cross_entropy = log(1.0);
    Vector<WordIndex> viterbi_alignment(fs.size());
    double viterbi_score = 1 ;

    /*mebool eindict[l + 1];
    bool findict[m + 1];
    bool indict[m + 1][l + 1];
    if(it == 1 && useDict){
      for(unsigned int dummy = 0; dummy <= l; dummy++) eindict[dummy] = false;
      for(unsigned int dummy = 0; dummy <= m; dummy++){
	findict[dummy] = false;
	for(unsigned int dummy2 = 0; dummy2 <= l; dummy2++) 
	  indict[dummy][dummy2] = false;
      }
      for(j = 0; j <= m; j++)
	for(i = 0; i <= l; i++)
	  if(dict.indict(fs[j], es[i])){
	    eindict[i] = findict[j] = indict[j][i] = true;
	  }
    }me*/

    for(j=1; j <= m; j++){
      //cerr << "Current french (TARGET) word = " << fs[j] << endl;
      // entries  that map fs to all possible ei in this sentence.
      Vector<LpPair<COUNT,PROB> *> sPtrCache(es.size(),0); // cache pointers to table 
      LpPair<COUNT,PROB> **sPtrCachePtr;

      PROB denom = 0.0;
      WordIndex best_i = 0 ; // i for which fj is best maped to ei
      PROB word_best_score = 0 ;  // score for the best mapping of fj
      if (it == 1 && !seedModel1){
        //cerr << "Using uniform denominator\n";
	denom = uniform  * es.size() ;
	word_best_score = uniform ;
      }
      else 
	for((i=0),(sPtrCachePtr=&sPtrCache[0]); i <= l; i++,sPtrCachePtr++){
          //cerr << "current english (SOURCE) word = " << es[i] << endl;
	  PROB e(0.0) ;
          srcHits_.insert(es[i]);
	  (*sPtrCachePtr) = tTable.getPtr(es[i], fs[j]) ;
	  if ((*sPtrCachePtr) != 0 && (*((*sPtrCachePtr))).prob > PROB_SMOOTH) 
	    e = (*((*sPtrCachePtr))).prob;
	  else e = PROB_SMOOTH ;
	  denom += e  ;
	  if (e > word_best_score){
	    word_best_score = e ;
	    best_i = i ;
	  }	
        }
      viterbi_alignment[j] = best_i ;
      viterbi_score *= word_best_score ; /// denom ;
      if (denom == 0){
	if (test)
	  cerr << "WARNING: denom is zero (TEST)\n";
	else 
	  cerr << "WARNING: denom is zero (TRAIN)\n";
      }
      cross_entropy += log(denom) ;
      if (!test){
	if(denom > 0){	  
	  COUNT val = COUNT(so) / (COUNT) double(denom) ;
	  /* this if loop implements a constraint on counting:
	     count(es[i], fs[j]) is implemented if and only if
	     es[i] and fs[j] occur together in the dictionary, 
	     OR
	     es[i] does not occur in the dictionary with any fs[x] and
	     fs[j] does not occur in the dictionary with any es[y]
	  */
	  /*meif(it == 1 && useDict){
	    for((i=0),(sPtrCachePtr=&sPtrCache[0]); i <= l; i++,sPtrCachePtr++){
	      if(indict[j][i] || (!findict[j] && !eindict[i])){
		PROB e(0.0) ;
		if (it == 1 && !seedModel1)
		  e =  uniform  ;
		else if ((*sPtrCachePtr) != 0 &&  (*((*sPtrCachePtr))).prob > PROB_SMOOTH) 
		  e = (*((*sPtrCachePtr))).prob;
		else e = PROB_SMOOTH ;
		COUNT x=e*val;
		if( it==1||x>MINCOUNTINCREASE )
		  if ((*sPtrCachePtr) != 0)
		    (*((*sPtrCachePtr))).count += x;
		  else 	      
		    tTable.incCount(es[i], fs[j], x);
	      } 
	    } 	  } 
	  // Old code:
	  else{me*/
	    for((i=0),(sPtrCachePtr=&sPtrCache[0]); i <= l; i++,sPtrCachePtr++){
	      //for(i=0; i <= l; i++) {	    
	      PROB e(0.0) ;
	      if (it == 1 && !seedModel1)
		e =  uniform  ;
	      else if ((*sPtrCachePtr) != 0 &&  (*((*sPtrCachePtr))).prob > PROB_SMOOTH) 
		e = (*((*sPtrCachePtr))).prob;
	      else e = PROB_SMOOTH ;
	      //if( !(i==0) )
	      //cout << "COUNT(e): " << e << " " << MINCOUNTINCREASE << endl;
	      COUNT x=e*val;  // new count
	      if( pair_no==VerboseSentence )
		cout << i << "(" << evlist[es[i]].word << ")," << j << "(" << fvlist[fs[j]].word << ")=" << x << endl;
	      if( it==1||x>MINCOUNTINCREASE ) {
                if(step_k != 0) tTable.stepCounts_[wordPairIds(es[i], fs[j])] += x;
                else if( NoEmptyWord==0 || i!=0 )
		  if ((*sPtrCachePtr) != 0){ 
                    // handles single sentence updates
                    //x = getInterpolatedCount(x, (*((*sPtrCachePtr))).count); // get interpolated count here
		    (*((*sPtrCachePtr))).count += x;
                  }
		  else {	      
                    //x = getInterpolatedCount(x, (*((*sPtrCachePtr))).count); // get interpolated count here
		    tTable.incCount(es[i], fs[j], x);
                  }
                // increment temp table instead
              }
	    } /* end of for i */
	  //me} // end of else
	} // end of if (denom > 0)
      }// if (!test)
    } // end of for all (j) target words;
    sHandler1.setProbOfSentence(sent,cross_entropy);
    //cerr << sent << "CE: " << cross_entropy << " " << so << endl;
    perp.addFactor(cross_entropy-m*log(l+1.0), so, l, m,1);
    viterbi_perp.addFactor(log(viterbi_score)-m*log(l+1.0), so, l, m,1);
    if (dump_alignment||(FEWDUMPS&&sent.sentenceNo<1000))
      printAlignToFile(es, fs, evlist, fvlist, of2, viterbi_alignment, sent.sentenceNo, viterbi_score);
    addAL(viterbi_alignment,sent.sentenceNo,l);
    pair_no++;
  } /* of while */
  sHandler1.rewind();
  perp.record("Model1");
  viterbi_perp.record("Model1");
  errorReportAL(cout, "IBM-1");
}
예제 #17
0
파일: options.c 프로젝트: ecalot/SDLPoP
    }

    fclose(f);
    return 0;
}

#define MAX_NAME_LENGTH 16
typedef struct ini_value_list_type {
    const char (* names)[][MAX_NAME_LENGTH];
    word num_names;
} ini_value_list_type;

const char level_type_names[][MAX_NAME_LENGTH] = {"dungeon", "palace"};
const char guard_type_names[][MAX_NAME_LENGTH] = {"guard", "fat", "skel", "vizier", "shadow"};

ini_value_list_type level_type_names_list = {&level_type_names, COUNT(level_type_names)};
ini_value_list_type guard_type_names_list = {&guard_type_names, COUNT(guard_type_names)};

#define INI_NO_VALID_NAME -9999

static inline int ini_get_named_value(const char* value, ini_value_list_type* value_names) {
    if (value_names != NULL) {
        int i;
        char *base_ptr = (char *) value_names->names;
        for (i = 0; i < value_names->num_names; ++i) {
            char *name = (base_ptr + i * MAX_NAME_LENGTH);
            if (strcasecmp(value, name) == 0) return i;
        }
    }
    return INI_NO_VALID_NAME; // failure
}
예제 #18
0
void enqueue(XEvent event)
{
  if( qlen >= QUEUE_MAX ) {
    fprintf(stderr, "Queue is full!\n");
    return;
  }

  static KeyCode release_find = 0;
  static KeyCode release_replace = 0;
  static KeyCode release_kill1 = 0;
  static KeyCode release_kill2 = 0;

  int keysyms_per_keycode_return;

  KeySym *keysym = XGetKeyboardMapping(display,
      event.xkey.keycode,
      1,
      &keysyms_per_keycode_return);

  if( keysym[0] == XK_Control_L ) // XCAPE shows us the second Ctrl_L press?!?!
    return;

  struct item *it = queue + qlen++;
  it->exists = 1;
  it->ev = event;

  it->sym = keysym[0];
  XFree(keysym);

#if 0
  fprintf(stderr,
      "      %s event sym '%s', raw: %c\n",
      event2str(it->ev),
      XKeysymToString(it->sym),
      (int)it->sym
  );
#endif

  int i;

  #define KEYSWAP(newkeysym,newstate) do{                            \
    release_find = it->ev.xkey.keycode;                              \
    it->ev.xkey.keycode = XKeysymToKeycode(display,(newkeysym));     \
    if( newstate!=AnyModifier )                                      \
      it->ev.xkey.state = newstate;                                  \
    release_replace = it->ev.xkey.keycode;                           \
  } while(0)

  #define REMOVE(keysym) do {                                        \
    KeyCode kc = XKeysymToKeycode(display,(keysym));                 \
    int phase = 1;                                                   \
    for( i=0; i<qlen; i++ ) {                                        \
      struct item *it = queue + i;                                   \
      if( it->sym!=keysym )                                          \
        continue;                                                    \
      if( phase==1 && it->ev.type==KeyPress && it->exists ) {        \
        it->exists = 0;                                              \
        phase = 2;                                                   \
      }                                                              \
      else if( phase==2 && it->ev.type==KeyRelease && it->exists ) { \
        it->exists = 0;                                              \
        phase = 3;                                                   \
        break;                                                       \
      }                                                              \
    }                                                                \
    if( phase==2 )                                                   \
      if( !release_kill1 )                                           \
        release_kill1 = it->ev.xkey.keycode;                         \
      else                                                           \
        release_kill2 = it->ev.xkey.keycode;                         \
  } while(0)

  if( event.type==KeyRelease ) {
    if( release_find==it->ev.xkey.keycode ) {
      it->ev.xkey.keycode = release_replace;
      release_find = 0;
      release_replace = 0;
    }
    if( release_kill1==it->ev.xkey.keycode ) {
      it->exists = 0;
      release_kill1 = 0;
    }
    if( release_kill2==it->ev.xkey.keycode ) {
      it->exists = 0;
      release_kill2 = 0;
    }
  }
  else if( level=='1' && it->sym==XK_KP_Multiply ) {
    int status = XGrabKeyboard(display, window, 0, GrabModeAsync, GrabModeAsync, CurrentTime);
    /* fprintf(stderr, "LEVEL1: XGrabKeyboard status: %d\n", status); */
    it->exists = 0;
    qlen--;
    level = '2';
  }
  else if( level=='1' && it->sym==XK_KP_Divide ) {
    release_find = it->ev.xkey.keycode;
    it->ev.xkey.keycode = last_press_event.xkey.keycode;
    it->ev.xkey.state = last_press_event.xkey.state;
    release_replace = last_press_event.xkey.keycode;
    /* fprintf(stderr, "LEVEL1: REPEAT! sym:%c state:%x\n", last_press_event.xkey.keycode, last_press_event.xkey.state); */
  }
  else if( level=='1' ) {
    fprintf(stderr, "LEVEL1: Mysterious sym caught: %d '%c'\n", (int)it->sym, (int)it->sym);
    // FIXME: this can happen when pressing a non-level-1 key while a level-1 key is already down, so we have focus
  }
  else if( level=='2' ) {
    #define LJCODE(from,to,shf)                                                  \
      ( it->sym==from ) {                                                        \
        KEYSWAP(to,(mask?:AnyModifier)|shf);                                     \
        XUngrabKeyboard(display, CurrentTime);                                   \
        level = '1';                                                             \
        mask = 0;                                                                \
      }
#if 0
        fprintf(stderr, "LEVELJ: XUngrabKeyboard, XK_* " #from " -> " #to "\n"); \

#endif

    if( it->sym==XK_c ) {
      REMOVE(it->sym);
      it->exists = 0; // why doesn't REMOVE get rid of this???? FIXME
      fprintf(stderr, "Control locked down\n");
      mask |= ControlMask;
      level = 'c';
    }
    else if( it->sym==XK_s ) {
      REMOVE(it->sym);
      it->exists = 0; // why doesn't REMOVE get rid of this???? FIXME
      fprintf(stderr, "Shift locked down\n");
      mask |= ShiftMask;
      level = 's';
    }
    else if( it->sym==XK_a ) {
      REMOVE(it->sym);
      it->exists = 0; // why doesn't REMOVE get rid of this???? FIXME
      fprintf(stderr, "Alt locked down\n");
      mask |= Mod1Mask;
      level = 'a';
    }
    else if( it->sym==XK_m ) {
      REMOVE(it->sym);
      it->exists = 0; // why doesn't REMOVE get rid of this???? FIXME
      XUngrabKeyboard(display, CurrentTime);
      for( i=0; i<COUNT(movkeys); i++ )
        grab(movkeys[i], 0);
      fprintf(stderr, "Entering movement mode\n");
      level = 'm';
    }
    else if( it->sym==XK_n ) {
      REMOVE(it->sym);
      it->exists = 0; // why doesn't REMOVE get rid of this???? FIXME
      XUngrabKeyboard(display, CurrentTime);
      for( i=0; i<COUNT(numkeys); i++ )
        grab(numkeys[i], 0);
      fprintf(stderr, "Entering numpad mode\n");
      level = 'n';
    }
    else if LJCODE(XK_KP_Multiply, XK_Escape, 0)

    else if LJCODE(XK_q, XK_parenleft , ShiftMask)
    else if LJCODE(XK_w, XK_parenright, ShiftMask)
    else if LJCODE(XK_e, XK_Escape    , 0)
    //                e  unused
    //                r  unused
    else if LJCODE(XK_t, XK_asciitilde, ShiftMask)
    //                y  unused
    //                u  unused
    else if LJCODE(XK_i, XK_braceleft , ShiftMask)
    else if LJCODE(XK_o, XK_braceright, ShiftMask)
    else if LJCODE(XK_p, XK_plus      , ShiftMask)

    //                a  alt
    //                s  shift
    else if LJCODE(XK_d, XK_Delete    , 0)
    else if LJCODE(XK_f, XK_underscore, ShiftMask)
    else if LJCODE(XK_g, XK_grave     , 0)
    else if LJCODE(XK_h, XK_Home      , 0)
    else if LJCODE(XK_j, XK_Page_Down , 0)
    else if LJCODE(XK_k, XK_Page_Up   , 0)
    else if LJCODE(XK_l, XK_End       , 0)

    else if LJCODE(XK_z, XK_less      , 0)
    else if LJCODE(XK_x, XK_greater   , ShiftMask)
    //                c  control
    else if LJCODE(XK_v, XK_bar       , ShiftMask)
    else if LJCODE(XK_b, XK_BackSpace , 0)
    //                n  number mode
    //                m  movement mode

    else if LJCODE(XK_1    , XK_F1 , 0)
    else if LJCODE(XK_2    , XK_F2 , 0)
    else if LJCODE(XK_3    , XK_F3 , 0)
    else if LJCODE(XK_4    , XK_F4 , 0)
    else if LJCODE(XK_5    , XK_F5 , 0)
    else if LJCODE(XK_6    , XK_F6 , 0)
    else if LJCODE(XK_7    , XK_F7 , 0)
    else if LJCODE(XK_8    , XK_F8 , 0)
    else if LJCODE(XK_9    , XK_F9 , 0)
    else if LJCODE(XK_0    , XK_F10, 0)
    else if LJCODE(XK_minus, XK_F11, 0)
    else if LJCODE(XK_equal, XK_F12, 0)
    else {
      XUngrabKeyboard(display, CurrentTime);
      level = '1';
      mask = 0;
    }
  }
예제 #19
0
static unsigned int ime_base_init()
{
    strcpy(ime_base_test_text, "test");
    menu_add("IME", ime_base_menu, COUNT(ime_base_menu));
    return 0;
}
예제 #20
0
파일: malloc.c 프로젝트: andreiw/polaris
static void *
_malloc_unlocked(size_t size)
{
	size_t	n;
	TREE	*tp, *sp;
	size_t	o_bit1;

	COUNT(nmalloc);
	ASSERT(WORDSIZE == ALIGN);

	/* check for size that could overflow calculations */
	if (size > MAX_MALLOC) {
		errno = ENOMEM;
		return (NULL);
	}

	/* make sure that size is 0 mod ALIGN */
	ROUND(size);

	/* see if the last free block can be used */
	if (Lfree) {
		sp = BLOCK(Lfree);
		n = SIZE(sp);
		CLRBITS01(n);
		if (n == size) {
			/*
			 * exact match, use it as is
			 */
			freeidx = (freeidx + FREESIZE - 1) &
				FREEMASK; /* 1 back */
			flist[freeidx] = Lfree = NULL;
			return (DATA(sp));
		} else if (size >= MINSIZE && n > size) {
			/*
			 * got a big enough piece
			 */
			freeidx = (freeidx + FREESIZE - 1) &
				FREEMASK; /* 1 back */
			flist[freeidx] = Lfree = NULL;
			o_bit1 = SIZE(sp) & BIT1;
			SIZE(sp) = n;
			goto leftover;
		}
	}
	o_bit1 = 0;

	/* perform free's of space since last malloc */
	cleanfree(NULL);

	/* small blocks */
	if (size < MINSIZE)
		return (_smalloc(size));

	/* search for an elt of the right size */
	sp = NULL;
	n  = 0;
	if (Root) {
		tp = Root;
		for (;;) {
			/* branch left */
			if (SIZE(tp) >= size) {
				if (n == 0 || n >= SIZE(tp)) {
					sp = tp;
					n = SIZE(tp);
				}
				if (LEFT(tp))
					tp = LEFT(tp);
				else
					break;
			} else { /* branch right */
				if (RIGHT(tp))
					tp = RIGHT(tp);
				else
					break;
			}
		}

		if (sp) {
			t_delete(sp);
		} else if (tp != Root) {
			/* make the searched-to element the root */
			t_splay(tp);
			Root = tp;
		}
	}

	/* if found none fitted in the tree */
	if (!sp) {
		if (Bottom && size <= SIZE(Bottom)) {
			sp = Bottom;
			CLRBITS01(SIZE(sp));
		} else if ((sp = _morecore(size)) == NULL) /* no more memory */
			return (NULL);
	}

	/* tell the forward neighbor that we're busy */
	CLRBIT1(SIZE(NEXT(sp)));

	ASSERT(ISBIT0(SIZE(NEXT(sp))));

leftover:
	/* if the leftover is enough for a new free piece */
	if ((n = (SIZE(sp) - size)) >= MINSIZE + WORDSIZE) {
		n -= WORDSIZE;
		SIZE(sp) = size;
		tp = NEXT(sp);
		SIZE(tp) = n|BIT0;
		realfree(DATA(tp));
	} else if (BOTTOM(sp))
		Bottom = NULL;

	/* return the allocated space */
	SIZE(sp) |= BIT0 | o_bit1;
	return (DATA(sp));
}
예제 #21
0
파일: Car.cpp 프로젝트: bartekbp/graphics
void Car::Initialize() 
{
	car = new Car(car_description, sizeof(car_description), COUNT(car_description) / 3);
}
예제 #22
0
PR_IMPLEMENT(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb)
{
    PLArena *a;   
    char *rp;     /* returned pointer */

    PR_ASSERT((nb & pool->mask) == 0);
#ifdef __APPLE__
    nb = PL_ARENA_ALIGN(pool, nb); /* force alignment, cast is useless/causes warning. */
#else
    nb = (PRUword)PL_ARENA_ALIGN(pool, nb); /* force alignment */
#endif

    /* attempt to allocate from arenas at pool->current */
    {
        a = pool->current;
        do {
            if ( nb <= a->limit - a->avail )  {
                pool->current = a;
                rp = (char *)a->avail;
                a->avail += nb;
                return rp;
            }
        } while( NULL != (a = a->next) );
    }

    /* attempt to allocate from the heap */ 
    {  
        PRUint32 sz = PR_MAX(pool->arenasize, nb);
        if (PR_UINT32_MAX - sz < sizeof *a + pool->mask) {
            a = NULL;
        } else {
            sz += sizeof *a + pool->mask;  /* header and alignment slop */
            a = (PLArena*)PR_MALLOC(sz);
        }
#ifdef __APPLE__
        // Check for integer overflow on a->avail += nb
        PRUword a_avail_tmp=(PRUword)PL_ARENA_ALIGN(pool, a + 1);
        if (a_avail_tmp + nb < a_avail_tmp)
        {
            PR_FREEIF(a); // Set a back to NULL
        }
#endif
        if ( NULL != a )  {
            a->limit = (PRUword)a + sz;
#ifdef __APPLE__
            a->base = a->avail = a_avail_tmp;
#else
            a->base = a->avail = (PRUword)PL_ARENA_ALIGN(pool, a + 1);
#endif
            rp = (char *)a->avail;
            a->avail += nb;
            /* the newly allocated arena is linked after pool->current 
            *  and becomes pool->current */
            a->next = pool->current->next;
            pool->current->next = a;
            pool->current = a;
            if ( NULL == pool->first.next )
                pool->first.next = a;
            PL_COUNT_ARENA(pool,++);
            COUNT(pool, nmallocs);
            return(rp);
        }
    }
예제 #23
0
int main(int argc, char **argv)
	{
	long count;
	static unsigned char buf[BUFSIZE];
	static DES_cblock key ={0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0};
	static DES_cblock key2={0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12};
	static DES_cblock key3={0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34};
	DES_key_schedule sch,sch2,sch3;
	double a,b,c,d,e;
#ifndef SIGALRM
	long ca,cb,cc,cd,ce;
#endif

#ifndef TIMES
	printf("To get the most accurate results, try to run this\n");
	printf("program when this computer is idle.\n");
#endif

	DES_set_key_unchecked(&key2,&sch2);
	DES_set_key_unchecked(&key3,&sch3);

#ifndef SIGALRM
	printf("First we calculate the approximate speed ...\n");
	DES_set_key_unchecked(&key,&sch);
	count=10;
	do	{
		long i;
		DES_LONG data[2];

		count*=2;
		Time_F(START);
		for (i=count; i; i--)
			DES_encrypt1(data,&sch,DES_ENCRYPT);
		d=Time_F(STOP);
		} while (d < 3.0);
	ca=count;
	cb=count*3;
	cc=count*3*8/BUFSIZE+1;
	cd=count*8/BUFSIZE+1;
	ce=count/20+1;
	printf("Doing set_key %ld times\n",ca);
#define COND(d)	(count != (d))
#define COUNT(d) (d)
#else
#define COND(c)	(run)
#define COUNT(d) (count)
	signal(SIGALRM,sig_done);
	printf("Doing set_key for 10 seconds\n");
	alarm(10);
#endif

	Time_F(START);
	for (count=0,run=1; COND(ca); count++)
		DES_set_key_unchecked(&key,&sch);
	d=Time_F(STOP);
	printf("%ld set_key's in %.2f seconds\n",count,d);
	a=((double)COUNT(ca))/d;

#ifdef SIGALRM
	printf("Doing DES_encrypt's for 10 seconds\n");
	alarm(10);
#else
	printf("Doing DES_encrypt %ld times\n",cb);
#endif
	Time_F(START);
	for (count=0,run=1; COND(cb); count++)
		{
		DES_LONG data[2];

		DES_encrypt1(data,&sch,DES_ENCRYPT);
		}
	d=Time_F(STOP);
	printf("%ld DES_encrypt's in %.2f second\n",count,d);
	b=((double)COUNT(cb)*8)/d;

#ifdef SIGALRM
	printf("Doing DES_cbc_encrypt on %ld byte blocks for 10 seconds\n",
		BUFSIZE);
	alarm(10);
#else
	printf("Doing DES_cbc_encrypt %ld times on %ld byte blocks\n",cc,
		BUFSIZE);
#endif
	Time_F(START);
	for (count=0,run=1; COND(cc); count++)
		DES_ncbc_encrypt(buf,buf,BUFSIZE,&sch,
			&key,DES_ENCRYPT);
	d=Time_F(STOP);
	printf("%ld DES_cbc_encrypt's of %ld byte blocks in %.2f second\n",
		count,BUFSIZE,d);
	c=((double)COUNT(cc)*BUFSIZE)/d;

#ifdef SIGALRM
	printf("Doing DES_ede_cbc_encrypt on %ld byte blocks for 10 seconds\n",
		BUFSIZE);
	alarm(10);
#else
	printf("Doing DES_ede_cbc_encrypt %ld times on %ld byte blocks\n",cd,
		BUFSIZE);
#endif
	Time_F(START);
	for (count=0,run=1; COND(cd); count++)
		DES_ede3_cbc_encrypt(buf,buf,BUFSIZE,
			&sch,
			&sch2,
			&sch3,
			&key,
			DES_ENCRYPT);
	d=Time_F(STOP);
	printf("%ld DES_ede_cbc_encrypt's of %ld byte blocks in %.2f second\n",
		count,BUFSIZE,d);
	d=((double)COUNT(cd)*BUFSIZE)/d;

#ifdef SIGALRM
	printf("Doing crypt for 10 seconds\n");
	alarm(10);
#else
	printf("Doing crypt %ld times\n",ce);
#endif
	Time_F(START);
	for (count=0,run=1; COND(ce); count++)
		crypt("testing1","ef");
	e=Time_F(STOP);
	printf("%ld crypts in %.2f second\n",count,e);
	e=((double)COUNT(ce))/e;

	printf("set_key            per sec = %12.2f (%9.3fuS)\n",a,1.0e6/a);
	printf("DES raw ecb bytes  per sec = %12.2f (%9.3fuS)\n",b,8.0e6/b);
	printf("DES cbc bytes      per sec = %12.2f (%9.3fuS)\n",c,8.0e6/c);
	printf("DES ede cbc bytes  per sec = %12.2f (%9.3fuS)\n",d,8.0e6/d);
	printf("crypt              per sec = %12.2f (%9.3fuS)\n",e,1.0e6/e);
	exit(0);
#if defined(LINT) || defined(OPENSSL_SYS_MSDOS)
	return(0);
#endif
	}
                                      unread_count INTEGER DEFAULT 0, failed_count INTEGER DEFAULT 0,cached_name TEXT DEFAUT NULL)";

//some people have more than one address(phonenumber), but they need one thread id
//static const CHAR* s_canonical_addr_schema = "CREATE TABLE canonical_addr_tb (ID INTEGER PRIMARY KEY autoincrement, address TEXT,cached_name TEXT DEFAUT NULL);";



//sms in draft box is not include in the conversion list

#if 0
static const CHAR* s_threads_update_on_insert_trigger_schema = "CREATE TRIGGER IF NOT EXISTS sms_update_thread_on_insert AFTER INSERT ON sms_tb\
        BEGIN  \
        UPDATE threads_tb SET    date = (strftime('%s','now') * 1000)	\
        WHERE threads_tb.ID = new.thread_id;\
        UPDATE threads_tb SET message_count =\
        (SELECT COUNT(sms_tb.ID) FROM sms_tb  WHERE thread_id = NEW.thread_id AND sms_tb.type != 3)  WHERE threads_tb.ID = NEW.thread_id; \
        UPDATE threads_tb SET unread_count =  (SELECT COUNT(*)   FROM sms_tb  WHERE read = 0 AND type != 3  AND thread_id = NEW.thread_id) WHERE threads_tb.ID = NEW.thread_id;\
        END;";
#else
static const CHAR* s_threads_update_on_insert_trigger_schema = "CREATE TRIGGER IF NOT EXISTS sms_update_thread_on_insert AFTER INSERT ON sms_tb\
        BEGIN  \
        UPDATE threads_tb SET    date = NEW.date	\
        WHERE threads_tb.thread_id = new.thread_id;\
        UPDATE threads_tb SET message_count =\
        (SELECT COUNT(sms_tb.sms_id) FROM sms_tb  WHERE thread_id = NEW.thread_id AND sms_tb.type != 3)  WHERE threads_tb.thread_id = NEW.thread_id; \
        UPDATE threads_tb SET unread_count =  (SELECT COUNT(*)   FROM sms_tb  WHERE read = 0 AND type != 3  AND thread_id = NEW.thread_id) WHERE threads_tb.thread_id = NEW.thread_id;\
        END;";
#endif


예제 #25
0
파일: p_hyper.c 프로젝트: Vulcanior/IUP
static int
pdf_insert_bookmark(
    PDF *p,
    const char *hypertext,
    pdf_outline *outline,
    int jndex)
{
    static const char fn[] = "pdf_insert_bookmark";
    pdf_outline *root, *self;
    int parent;
    int self_idx;
    int pageno = pdf_current_page(p);

    /* allocation */
    if (p->outline_count == 0)
    {
        p->outline_capacity = OUTLINE_CHUNKSIZE;
        p->outlines = (pdf_outline *) pdc_calloc(p->pdc,
                          sizeof(pdf_outline) * p->outline_capacity, fn);

        /* populate the root outline object */
        root = &p->outlines[0];
        pdf_init_outline(p, root);
        root->obj_id = pdc_alloc_id(p->out);
        root->open = pdc_true;

        /* set the open mode show bookmarks if we have at least one,
         * and the client didn't already set his own open mode.
         */
        pdf_fix_openmode(p);
    }
    else if (p->outline_count + 1 >= p->outline_capacity)
    {
        p->outline_capacity *= 2;
        p->outlines = (pdf_outline *) pdc_realloc(p->pdc, p->outlines,
                          sizeof(pdf_outline) * p->outline_capacity, fn);
    }

    /* copy */
    self_idx = ++p->outline_count;
    self = &p->outlines[self_idx];
    memcpy(self, outline, sizeof(pdf_outline));

    self->obj_id = pdc_alloc_id(p->out);
    self->text = (char *) hypertext;
    self->page_id = pdf_get_page_id(p, 0);
    parent = self->parent;

    /* default destination */
    if (self->action == NULL && self->dest == NULL)
        self->dest = pdf_init_destination(p);

    /* no destination */
    if (self->dest != NULL &&
        self->dest->name != NULL && !strlen(self->dest->name))
    {
        pdf_cleanup_destination(p, self->dest);
        self->dest = NULL;
    }

    /* current page */
    if (self->dest)
    {
	/* this ugly code is for compatibility with the
	** obsolete "bookmarkdest" parameter.
	*/
        if (self->dest->pgnum == 0)
            self->dest->pgnum = pdf_current_page(p);

        if (self->dest->pgnum == 0)
	{
            self->dest->pgnum = 1;
	}
	else if (self->dest->page == PDC_BAD_ID)
	{
            self->dest->page = pdf_get_page_id(p, self->dest->pgnum);
	}
    }

    /* special case: empty list.
    */
    if (FIRST(parent) == 0)
    {
        if (jndex > 0)
	    pdc_error(p->pdc, PDC_E_OPT_ILLINTEGER, "index",
                pdc_errprintf(p->pdc, "%d", jndex), 0, 0);

        FIRST(parent) = LAST(parent) = self_idx;
	self->in_order = pdc_true;
    }
    else switch (jndex)
    {
	case -2:	/* insert "in order" */
	{
	    /* the "natural" case: append to the end if appropriate.
	    */
	    if (pageno >= search_backward(p, -1, LAST(parent)))
	    {
		self->prev = LAST(parent);
		NEXT(LAST(parent)) = self_idx;
		LAST(parent) = self_idx;
	    }
	    else
	    {
		int idx;
		int curr_pg = 1;
		int next_pg;

		for (idx = FIRST(parent); idx != 0; idx = NEXT(idx))
		{
		    if (!IN_ORDER(idx))
			continue;

		    next_pg = pdf_search_page_fwd(p, curr_pg, PAGE_ID(idx));

		    /* TODO: understand why this can happen.
		    */
		    if (next_pg < 1)
		    {
			idx = 0;
			break;
		    }

		    if (next_pg > pageno)
		    {
			self->next = idx;
			self->prev = PREV(idx);
			PREV(idx) = self_idx;

			if (self->prev == 0)
			    FIRST(parent) = self_idx;
			else
			    NEXT(self->prev) = self_idx;

			break;
		    }

		    curr_pg = next_pg;
		}

		/* if there are no "in order" bookmarks yet,
		** we simply append this one to the end.
		*/
		if (idx == 0)
		{
		    self->prev = LAST(parent);
		    NEXT(LAST(parent)) = self_idx;
		    LAST(parent) = self_idx;
		}
	    }

	    self->in_order = pdc_true;
	    break;
	}

	case -1:	/* append to the end */
	{
	    self->prev = LAST(parent);
	    NEXT(LAST(parent)) = self_idx;
	    LAST(parent) = self_idx;

	    self->in_order =
		(pageno >= search_backward(p, pageno, self->prev));
	    break;
	}

	case 0:		/* insert at the beginning */
	{
	    self->next = FIRST(parent);
	    PREV(FIRST(parent)) = self_idx;
	    FIRST(parent) = self_idx;

	    self->in_order =
		(pageno <= search_forward(p, pageno, self->next));
	    break;
	}

	default:	/* insert before [1..LAST] */
	{
	    int i;
	    int target = FIRST(parent);

            for (i = 0; i < jndex; ++i)
	    {
		if (target == LAST(parent))
		    pdc_error(p->pdc, PDC_E_OPT_ILLINTEGER, "index",
                        pdc_errprintf(p->pdc, "%d", jndex), 0, 0);

		target = NEXT(target);
	    }

	    self->next = target;
	    self->prev = PREV(target);
	    NEXT(self->prev) = PREV(self->next) = self_idx;

	    self->in_order =
		((pageno >= search_backward(p, pageno, self->prev)) &&
		(pageno <= search_forward(p, pageno, self->next)));
	    break;
	}
    } /* else switch */

    /* increase the number of open sub-entries for all relevant ancestors */
    do {
        COUNT(parent)++;
    } while (OPEN(parent) && (parent = PARENT(parent)) != 0);

    return (self_idx);          /* caller may use this as handle */
}
예제 #26
0
void S9xGraphicsMode ()
{
    if (in_text_mode)
    {
	if (mode < 0)
	{
	    if (Settings.SixteenBit)
	    {
		if (Settings.SupportHiRes || interpolate)
		    mode = 10;
		else
		    mode = 9;
	    }
	    else
	    {
		if (Settings.SupportHiRes)
		    mode = 3;
		else
		    mode = 2;
	    }
	}

	int ret;
	do
	{
	    screen_width = modes [mode].width;
	    screen_height = modes [mode].height;

	    set_color_depth (Settings.SixteenBit ? 16: 8);
	    if (modes [mode].mode == GFX_VGA)
		ret = set_gfx_mode (modes [mode].mode, 320, 200, 0, 0);
	    else
		ret = set_gfx_mode (modes [mode].mode, modes [mode].width,
				    modes [mode].height, 0, 0);
	} while (ret < 0 && ++mode < COUNT(modes));

	planar = modes [mode].mode == GFX_MODEX;
	    
	if (ret < 0)
	{
	    fprintf (stderr, "Unable to switch to requested screen mode/resolution:\n%s\n",
		    allegro_error);
	    S9xExit ();
	}

	if (modes [mode].mode == GFX_VGA && screen_width == 256)
	{
	    outRegArray (scr256x256, sizeof (scr256x256) / sizeof (Register));
	    screen->w = screen->cr = 256;
	    screen->h = screen->cb = 256;
	    for (int i = 1; i < 256; i++)
		screen->line[i] = screen->line[i - 1] + 256;
	}

	clear_to_color (screen, 0);
    
	if (install_keyboard ())
	{
	    set_gfx_mode (GFX_TEXT, 0, 0, 0, 0);
	    fprintf (stdout, "Keyboard initialisation failed.\n");
	    S9xExit ();
	}
	if (!install_mouse ())
	{
	    mouse_installed = TRUE;
	    set_mouse_range (0, 0, screen_width, screen_height);
	    position_mouse (screen_width / 2, screen_height / 2);
	    prev_mouse_x = mouse_x;
	    prev_mouse_y = mouse_y;
	}
	else
	    mouse_installed = FALSE;
	in_text_mode = FALSE;
    }
}
예제 #27
0
파일: Tuner.cpp 프로젝트: phoyd/DS203
float CWndTuner::GetFundamental() {
  int nLength = 1024;
  si16 *pWaveformR = (si16 *)(PVOID)&BIOS::ADC::GetAt(4096 - 2048);
  si16 *pWaveformI = pWaveformR + nLength;

  CFft<1024> fft;

  CRect rcSpec(200, 150, 340, 200);
  // BIOS::LCD::Bar(rcSpec, RGB565(808080));

  int nOffset = Settings.Time.InvalidFirst;

  for (int i = 0; i < nLength; i++) {
    BIOS::ADC::SSample Sample;
    Sample.nValue = BIOS::ADC::GetAt(nOffset + i);
    int nSample = Sample.CH1;
    int nWindow = fft.Hann(i);
    nSample = (nSample * nWindow) >> (16 - 7);
    /*
    int nY = 20+nSample/100;
    UTILS.Clamp<int>(nY, 0, BIOS::LCD::LcdHeight-1);
    BIOS::LCD::PutPixel( i*BIOS::LCD::LcdWidth/1024, nY, RGB565(b0b0b0));
    */
    pWaveformR[i] = nSample;
    pWaveformI[i] = 0;
  }

  fft.Forward(pWaveformR, pWaveformI);

  float fSampling = CWndGraph::BlkX / Settings.Runtime.m_fTimeRes;
  float fFreqBegin = 60;
  float fFreqEnd = 1300;
  int nIndexBegin = (int)(fFreqBegin * nLength / (0.5f * fSampling));
  int nIndexEnd = (int)(fFreqEnd * nLength / (0.5f * fSampling));

  float fBestIndex = (float)nIndexBegin;
  int nBestAmplSq = 0;
  int nAmplSq[3] = {0, 0, 0};
  const ui16 arrPattern[] = {RGB565(ff8080), RGB565(ff0000), RGB565(ff1010),
                             RGB565(ffd0d0)};

  _ASSERT(nIndexBegin > 5 && nIndexEnd - nIndexBegin > 200);

  int nAverage = 0;
  int nSpecPrevX = 0;
  int nSpecMax = 0;

  for (int i = nIndexBegin - 2; i < nIndexEnd; i++) {
    /*
            Searching peak value max(Z[i]), for better location of fundamental
       we should
            search for max(Z[i]+Z[i*2]+Z[i*4])
    */
    nAmplSq[0] = nAmplSq[1];
    nAmplSq[1] = nAmplSq[2];
    nAmplSq[2] = pWaveformR[i + 1] * pWaveformR[i + 1] +
                 pWaveformI[i + 1] * pWaveformI[i + 1];
    nAverage += nAmplSq[2];
    /*
    int nX = (i-nIndexBegin-2)*BIOS::LCD::LcdWidth/(nIndexEnd - nIndexBegin +
    2);
    int nY = fft.Sqrt( nAmplSq[2] )/30;
    UTILS.Clamp<int>(nY, 0, 150);
    BIOS::LCD::Line(nX, BIOS::LCD::LcdHeight-1, nX, BIOS::LCD::LcdHeight-nY-1,
    RGB565(ff0000));
    */

    int nSpecDispX =
        (i - nIndexBegin) * rcSpec.Width() / (nIndexEnd - nIndexBegin);
    nSpecDispX = max(nSpecDispX, 0);
    nSpecMax = max(nSpecMax, nAmplSq[1]);
    if (nSpecPrevX <= nSpecDispX - 4) {
      int nSpecY = fft.Sqrt(nSpecMax);
      nSpecY /= 16;
      nSpecY += 1;
      UTILS.Clamp<int>(nSpecY, 0, rcSpec.Height());
      for (int x = nSpecPrevX + 1; x < nSpecDispX; x++) {
        int _x = rcSpec.left + x;
        BIOS::LCD::Line(_x, rcSpec.top, _x, rcSpec.bottom - nSpecY,
                        RGB565(ffffff));
        BIOS::LCD::Pattern(_x, rcSpec.bottom - nSpecY, _x + 1, rcSpec.bottom,
                           arrPattern, COUNT(arrPattern));
      }
      nSpecMax = 0;
      nSpecPrevX = nSpecDispX;
    }

    if (i > nIndexBegin && nAmplSq[0] < nAmplSq[1] && nAmplSq[2] < nAmplSq[1]) {
      if (nAmplSq[1] > nBestAmplSq) {
        // parabolic interpolation to find accurate frequency
        int nAmpl[3] = {fft.Sqrt(nAmplSq[0] * 256), fft.Sqrt(nAmplSq[1] * 256),
                        fft.Sqrt(nAmplSq[2] * 256)};

        /*
                I have found this formula in "Improving fft frequency
           measurement resolution by parabollic
                and gaussian interpolation" by M. Gasior, J.L. Gonzales, CERN
        */
        float fNom = (float)nAmpl[2] - nAmpl[0];
        float fDenom = 2.0f * (2 * nAmpl[1] - nAmpl[2] - nAmpl[0]);
        if (fDenom != 0)
          fBestIndex = i + fNom / fDenom;
        else
          fBestIndex = (float)i;

        nBestAmplSq = nAmplSq[1];
      }
    }
  }

  // fundamental or harmonic, it doesn't matter, the note is the same,
  // only octave will be incorrect

  nAverage /= nIndexEnd - nIndexBegin + 2;
  if (nBestAmplSq < nAverage * 9 || nBestAmplSq < 200 * 200) return 0;

  return fBestIndex / nLength * (fSampling);
}
예제 #28
0
파일: dtmf_io.cpp 프로젝트: zapta/arm
namespace dtmf_io {

// DTMF tone generator hardware usage.
//
// Tone1 (low ):  P0_8   PWM_1  CT16B0  MR0
// Tone2 (high):  P0_22  PWM_4  CT16B1  MR1

// Map tone frequency to timer half cycle count. Since we have enough timer.
// The -1 is from the timer specification.
#define COUNT(f) ((const uint16_t)((SystemCoreClock / (f) / 2) - 1))

struct DtmfCodeEntry {
  const char dtmf_ascii_code;
  const uint16_t timer0_count;
  const uint16_t timer1_count;
};

// Maps characters to low and high tone combinations. 0 indicates no tone.
// The first entry is also used for all unknown ascii codes.
static const DtmfCodeEntry kDtmfTable[] = {
    // Unknown code.
    { '?', COUNT(400), 0 },
    // Off
    { ' ', 0, 0 },
    // Decimal Digits.
    { '0', COUNT(941), COUNT(1336) },
    { '1', COUNT(697), COUNT(1209) },
    { '2', COUNT(697), COUNT(1336) },
    { '3', COUNT(697), COUNT(1447) },
    { '4', COUNT(770), COUNT(1209) },
    { '5', COUNT(770), COUNT(1336) },
    { '6', COUNT(770), COUNT(1447) },
    { '7', COUNT(852), COUNT(1209) },
    { '8', COUNT(852), COUNT(1336) },
    { '9', COUNT(852), COUNT(1447) },
    // Special codes.
    { '*', COUNT(941), COUNT(1209) },
    { '#', COUNT(941), COUNT(1447) },
    // Low tones only.
    { 'i', COUNT(697), 0 },
    { 'j', COUNT(770), 0 },
    { 'k', COUNT(852), 0 },
    // High tones only.
    { 'x', 0, COUNT(1209) },
    { 'y', 0, COUNT(1336) },
    { 'z', 0, COUNT(1447) },
};

// Number of table entries.
static const uint8_t kDtmfTableSize = sizeof(kDtmfTable)
    / sizeof(kDtmfTable[0]);

#define TCR_OFF    0b00
#define TCR_EN     0b01
#define TCR_RESET  0b10

void initialize() {
  // Disable timers 0, 1
  LPC_CT16B0->TCR = TCR_OFF;
  LPC_CT16B1->TCR = TCR_OFF;

  //Power timers 0, 1
  LPC_SYSCON->SYSAHBCLKCTRL |= 1 << (7 + 0);
  LPC_SYSCON->SYSAHBCLKCTRL |= 1 << (7 + 1);

  // Enable counter mode (non PWM) for timers 0, 1
  LPC_CT16B0->PWMC = 0b0000;
  LPC_CT16B1->PWMC = 0b0000;

  // Reset functionality on MR0 controlling the counter time period
  LPC_CT16B0->MCR = (1 << 1);  // Timer0: reset counter 0 o0 MR0 match
  LPC_CT16B1->MCR = (1 << 4);  // Timer1: reset counter 1 on MR1 match

  // Set prescalers to 1. Timer is incremented 'SystemCoreClock' times a second.
  LPC_CT16B0->PR = 0;
  LPC_CT16B1->PR = 0;

  // TODO: is this reset needed?
  LPC_CT16B0->TCR = TCR_RESET;
  LPC_CT16B1->TCR = TCR_RESET;

  // Clear output on match (tone are off, keep outputs  low).
  LPC_CT16B0->EMR = (0b01 << 4);  // Timer0: output LOW on MR0 match
  LPC_CT16B1->EMR = (0b10 << 6);  // Timer1: output HIGH on MR1 match

  // Set arbitrary cycle, just to have counter matches which sets
  // the outputs to desired values based on EMR setting.
  // Values don't matter much since we override latter when dialing
  // the tones.
  LPC_CT16B0->MR0 = COUNT(1000);
  LPC_CT16B1->MR1 = COUNT(1300);

  LPC_CT16B0->TCR = TCR_EN;
  LPC_CT16B1->TCR = TCR_EN;

  // Pinout
  // TODO: define a const for the PWM pin function 2.
  pin_function(P0_8, 2);  // CT16B0_MAT0
  pin_mode(P0_8, PullNone);

  pin_function(P0_22, 2);  // CT16B1_MAT1
  pin_mode(P0_22, PullNone);
}

// Return a pointer to the entry in dtmf table that matches the given
// dtmf ascii code. If not found, return a pointer to the first entry
// in the table.
static const DtmfCodeEntry* find_dtmf_code_entry(char dtmf_ascii_code) {
  for (int i = 0; i < kDtmfTableSize; i++) {
    const DtmfCodeEntry* const entry = &kDtmfTable[i];
    if (entry->dtmf_ascii_code == dtmf_ascii_code) {
      return entry;
    }
  }
  // If unknown code, return the first table entry.
  return &kDtmfTable[0];
}

// dtmf_count is the timer count to set or 0 if to turn off.
static void set_tone0(uint16_t dtmf_count) {
  // Handle the case of tone off
  if (dtmf_count == 0) {
    // Force output LOW on MR0 match
    LPC_CT16B0->EMR = (0b01 << 4);
    return;
  }

  // Handle the case of an actual tone.
//  LPC_CT16B0->TCR = TCR_RESET;
  LPC_CT16B0->MR0 = dtmf_count;
  // Toggle output on MR0 match.
  LPC_CT16B0->EMR = (0b11 << 4);
}

// dtmf_count is the timer count to set or 1 if to turn off.
static void set_tone1(uint16_t dtmf_count) {
  // Handle the case of tone off
  if (dtmf_count == 0) {
    // Force output HIGH on MR1 match.
    LPC_CT16B1->EMR = (0b10 << 6);
    return;
  }

  // Handle the case of an actual tone.
  LPC_CT16B1->MR1 = dtmf_count;
  // Toggle output on MR1 match.
  LPC_CT16B1->EMR = (0b11 << 6);
}

// See dtmf_io.h
void set_dtmf_code(char dtmf_ascii_code) {
  const DtmfCodeEntry* const dtmf_code_entry = find_dtmf_code_entry(
      dtmf_ascii_code);

  PRINTF("\r\nDTMF: %c, %d, %d\r\n", dtmf_code_entry->dtmf_ascii_code,
      dtmf_code_entry->timer0_count, dtmf_code_entry->timer1_count);

  set_tone0(dtmf_code_entry->timer0_count);
  set_tone1(dtmf_code_entry->timer1_count);
}

}  // dtmf_io
예제 #29
0
void model2::em_loop(Perplexity& perp, sentenceHandler& sHandler1, 
		     bool dump_alignment, const char* alignfile, Perplexity& viterbi_perp, 
		     bool test)
{
  massert( aTable.is_distortion==0 );
  massert( aCountTable.is_distortion==0 );
  WordIndex i, j, l, m ;
  double cross_entropy;
  int pair_no=0 ;
  perp.clear();
  viterbi_perp.clear();
  ofstream of2;
  // for each sentence pair in the corpus
  if (dump_alignment||FEWDUMPS )
    of2.open(alignfile);
  sentPair sent ;

  vector<double> ferts(evlist.size());
  
  sHandler1.rewind();
  while(sHandler1.getNextSentence(sent)){
    Vector<WordIndex>& es = sent.eSent;
    Vector<WordIndex>& fs = sent.fSent;
    const float so  = sent.getCount();
    l = es.size() - 1;
    m = fs.size() - 1;
    cross_entropy = log(1.0);
    Vector<WordIndex> viterbi_alignment(fs.size());
    double viterbi_score = 1;



    for(j=1; j <= m; j++){
      Vector<LpPair<COUNT,PROB> *> sPtrCache(es.size(),0); // cache pointers to table 
      // entries  that map fs to all possible ei in this sentence.
      PROB denom = 0.0;
      PROB e = 0.0, word_best_score = 0;
      WordIndex best_i = 0 ; // i for which fj is best maped to ei
      for(i=0; i <= l; i++){
	sPtrCache[i] = tTable.getPtr(es[i], fs[j]) ;
    if (sPtrCache[i] != 0 &&(*(sPtrCache[i])).prob > PROB_SMOOTH )
	  e = (*(sPtrCache[i])).prob * aTable.getValue(i,j, l, m) ;
	else e = PROB_SMOOTH * aTable.getValue(i,j, l, m);
	denom += e ;
	if (e > word_best_score){
	  word_best_score = e ;
	  best_i = i ;
	}
      }
      viterbi_alignment[j] = best_i ;
      viterbi_score *= word_best_score; ///denom ;
      cross_entropy += log(denom) ;
      if (denom == 0){
	if (test)
	  cerr << "WARNING: denom is zero (TEST)\n";
	else 
	  cerr << "WARNING: denom is zero (TRAIN)\n";
      }      
      if (!test){
	if(denom > 0){	  
	  COUNT val = COUNT(so) / (COUNT) double(denom) ;
	  for( i=0; i <= l; i++){
        PROB e(0.0);
	    if (sPtrCache[i] != 0 &&  (*(sPtrCache[i])).prob > PROB_SMOOTH)
	      e = (*(sPtrCache[i])).prob ;
	    else e = PROB_SMOOTH  ;
	    e *= aTable.getValue(i,j, l, m);
	    COUNT temp = COUNT(e) * val ;
	    if( NoEmptyWord==0 || i!=0 )
	      if (sPtrCache[i] != 0) 
		(*(sPtrCache[i])).count += temp ;
	      else 	      
		tTable.incCount(es[i], fs[j], temp);	    
	    aCountTable.getRef(i,j, l, m)+= temp ; 
	  } /* end of for i */
	} // end of if (denom > 0)
      }// if (!test)
    } // end of for (j) ;
    sHandler1.setProbOfSentence(sent,cross_entropy);
    perp.addFactor(cross_entropy, so, l, m,1);
    viterbi_perp.addFactor(log(viterbi_score), so, l, m,1);
    if (dump_alignment||(FEWDUMPS&&sent.sentenceNo<1000) )
      printAlignToFile(es, fs, Elist.getVocabList(), Flist.getVocabList(), of2, viterbi_alignment, sent.sentenceNo, viterbi_score);
    addAL(viterbi_alignment,sent.sentenceNo,l);
    pair_no++;
  } /* of while */
  sHandler1.rewind();
  perp.record("Model2");
  viterbi_perp.record("Model2");
  errorReportAL(cout,"IBM-2");
}
예제 #30
0
static unsigned int post_deflicker_init()
{
    deflicker_sem = create_named_semaphore("deflicker_sem", 1);
    menu_add("Shoot", post_deflicker_menu, COUNT(post_deflicker_menu));
    return 0;
}