Example #1
0
uint QGLContext::colorIndex( const QColor& c ) const
{
    int screen = ((XVisualInfo *)vi)->screen;
    if ( isValid() ) {
	if ( format().plane()
	     && c.pixel( screen ) == overlayTransparentColor().pixel( screen ) )
	    return c.pixel( screen );		// Special; don't look-up
	if ( ((XVisualInfo*)vi)->visualid ==
	     XVisualIDFromVisual( (Visual*)QPaintDevice::x11AppVisual( screen ) ) )
	    return c.pixel( screen );		// We're using QColor's cmap

	XVisualInfo *info = (XVisualInfo *) vi;
	CMapEntry *x = cmap_dict->find( (long) info->visualid + ( info->screen * 256 ) );
	if ( x && !x->alloc) {		// It's a standard colormap
	    int rf = (int)(((float)c.red() * (x->scmap.red_max+1))/256.0);
	    int gf = (int)(((float)c.green() * (x->scmap.green_max+1))/256.0);
	    int bf = (int)(((float)c.blue() * (x->scmap.blue_max+1))/256.0);
	    uint p = x->scmap.base_pixel
		     + ( rf * x->scmap.red_mult )
		     + ( gf * x->scmap.green_mult )
		     + ( bf * x->scmap.blue_mult );
	    return p;
	} else {
	    if (!qglcmap_dict) {
		qglcmap_dict = new QIntDict< QMap<int, QRgb> >;
	    }
	    QMap<int, QRgb> *cmap;
	    if ((cmap = qglcmap_dict->find((long) info->visualid)) == 0) {
		cmap = new QMap<int, QRgb>;
		qglcmap_dict->insert((long) info->visualid, cmap);
	    }

	    // already in the map?
	    QRgb target = c.rgb();
	    QMap<int, QRgb>::Iterator it = cmap->begin();
	    for (; it != cmap->end(); ++it) {
		if ((*it) == target)
		    return it.key();
	    }

	    // need to alloc color
	    unsigned long plane_mask[2];
	    unsigned long color_map_entry;
	    if (!XAllocColorCells (QPaintDevice::x11AppDisplay(), x->cmap, TRUE, plane_mask, 0,
				   &color_map_entry, 1))
		return c.pixel(screen);

	    XColor col;
	    col.flags = DoRed | DoGreen | DoBlue;
	    col.pixel = color_map_entry;
	    col.red   = (ushort)((qRed(c.rgb()) / 255.0) * 65535.0 + 0.5);
	    col.green = (ushort)((qGreen(c.rgb()) / 255.0) * 65535.0 + 0.5);
	    col.blue  = (ushort)((qBlue(c.rgb()) / 255.0) * 65535.0 + 0.5);
	    XStoreColor(QPaintDevice::x11AppDisplay(), x->cmap, &col);

	    cmap->insert(color_map_entry, target);
	    return color_map_entry;
	}
    }
    return 0;
}
Example #2
0
		ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
	}

	/* we do NOT need to copy the \0! */
	memcpy(pThis->pBuf, sz, pThis->iStrLen);

	*ppThis = pThis;

finalize_it:
	RETiRet;
}


/* a helper function for rsCStr*Strf()
 */
static rsRetVal rsCStrConstructFromszStrv(cstr_t **ppThis, const char *fmt, va_list ap) __attribute__((format(printf,2, 0)));
static rsRetVal
rsCStrConstructFromszStrv(cstr_t **ppThis, const char *fmt, va_list ap)
{
	DEFiRet;
	cstr_t *pThis;
	va_list ap2;
	int len;

	va_copy(ap2, ap);
	len = vsnprintf(NULL, 0, (char*)fmt, ap2);
	va_end(ap2);

	if(len < 0)
		ABORT_FINALIZE(RS_RET_ERR);
Example #3
0
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
    return format(unit, amount, plussign) + QString(" ") + name(unit);
}
Example #4
0
static void display_resistance_panel(const struct player_flag_record *resists,
									size_t size, const region *bounds) 
{
	size_t i;
	int j;
	int col = bounds->col;
	int row = bounds->row;
	Term_putstr(col, row++, RES_COLS, TERM_WHITE, "      @abcdefghijklmnopqrstuvwxyz{|}");
	for (i = 0; i < size-3; i++, row++)
	{
		byte name_attr = TERM_WHITE;
		Term_gotoxy(col+6, row);
		/* repeated extraction of flags is inefficient but more natural */
		for (j = INVEN_WIELD - 1; j < INVEN_TOTAL; j++)
		{
			if (((j >= INVEN_WIELD) && (j < INVEN_WIELD + rp_ptr->melee_slots))
			||	((j >= INVEN_BOW) && (j < INVEN_BOW + rp_ptr->range_slots))
			||	((j >= INVEN_FINGER) && (j < INVEN_FINGER + rp_ptr->ring_slots))
			||	((j >= INVEN_NECK) && (j < INVEN_NECK + rp_ptr->amulet_slots))
			||	((j >= INVEN_LIGHT) && (j < INVEN_LIGHT + rp_ptr->light_slots))
			||	((j >= INVEN_BODY) && (j < INVEN_BODY + rp_ptr->body_slots))
			||	((j >= INVEN_OUTER) && (j < INVEN_OUTER + rp_ptr->cloak_slots))
			||	((j >= INVEN_ARM) && (j < INVEN_ARM + rp_ptr->shield_slots))
			||	((j >= INVEN_HEAD) && (j < INVEN_HEAD + rp_ptr->helm_slots))
			||	((j >= INVEN_HANDS) && (j < INVEN_HANDS + rp_ptr->glove_slots))
			||	((j >= INVEN_FEET) && (j < INVEN_FEET + rp_ptr->boot_slots))
			||	(j == INVEN_WIELD - 1))
			{
				object_type *o_ptr = &p_ptr->inventory[j];
				bitflag f[OF_SIZE];

				byte attr = TERM_WHITE | (j % 2) * 8; /* alternating columns */
				char sym = '.';

				bool res, imm, vuln;

				/* Wipe flagset */
				of_wipe(f);

				if (j < INVEN_WIELD)
				{
					player_flags(f);

					/* If the race has innate infravision/digging, force the corresponding flag
					   here.  If we set it in player_flags(), then all callers of that
					   function will think the infravision is caused by equipment. */
					if (rp_ptr->infra > 0)
						of_on(f, OF_INFRA);
					if (rp_ptr->r_skills[SKILL_DIGGING] > 0)
						of_on(f, OF_TUNNEL);
				}
				else if (j < INVEN_TOTAL && o_ptr->k_idx)
				{
					object_flags_known(o_ptr, f);
				}

				res = of_has(f, resists[i].res_flag);
				imm = of_has(f, resists[i].im_flag);
				vuln = of_has(f, resists[i].vuln_flag);

				if (imm) name_attr = TERM_GREEN;
				else if (res && name_attr == TERM_WHITE) name_attr = TERM_L_BLUE;

				if (vuln) sym = '-';
				else if (imm) sym = '*';
				else if (res) sym = '+';
				else if ((j < INVEN_TOTAL) && o_ptr->k_idx && 
					!object_flag_is_known(o_ptr, resists[i].res_flag)) sym = '?';
				Term_addch(attr, sym);
			}
		}
		Term_putstr(col, row, 6, name_attr, format("%5s:", resists[i].name));
	}
	Term_putstr(col, row++, RES_COLS, TERM_WHITE, "      @abcdefghijklmnopqrstuvwxyz{|}");
	/* Equippy */
	display_player_equippy(row++, col+7);
}
Example #5
0
int main(int argc, char *argv[]) {

  /* initialize Madagascar */
  sf_init(argc, argv);

  Logger::instance().init("serial-fwi");

  FwiParams &params = FwiParams::instance();

  std::vector<float> dobs(params.ns * params.nt * params.ng); /* observed data */
  std::vector<float> cg(params.nz * params.nx, 0);    /* conjugate gradient */
  std::vector<float> g0(params.nz * params.nx, 0);    /* gradient at previous step */
  std::vector<float> wlt(params.nt); /* ricker wavelet */
  std::vector<float> objval(params.niter, 0); /* objective/misfit function */

  /* initialize wavelet */
  rickerWavelet(&wlt[0], params.nt, params.fm, params.dt, params.amp);

  ShotPosition allSrcPos(params.szbeg, params.sxbeg, params.jsz, params.jsx, params.ns, params.nz);
  ShotPosition allGeoPos(params.gzbeg, params.gxbeg, params.jgz, params.jgx, params.ng, params.nz);

  // read velocity
  Velocity v0 = SfVelocityReader::read(params.vinit, params.nx, params.nz);

  // read observed data
  ShotDataReader::serialRead(params.shots, &dobs[0], params.ns, params.nt, params.ng);

  EnquistAbc2d fmMethod(params.dt, params.dx, params.dz);
  Velocity vel = fmMethod.expandDomain(v0);

  float obj0 = 0;
  for (int iter = 0; iter < params.niter; iter++) {
    boost::timer::cpu_timer timer;
    std::vector<float> g1(params.nz * params.nx, 0);    /* gradient at curret step */
    std::vector<float> derr(params.ns * params.ng * params.nt, 0); /* residual/error between synthetic and observation */
    std::vector<float> illum(params.nz * params.nx, 0); /* illumination of the source wavefield */
    Velocity vtmp = vel;  /* temporary velocity computed with epsil */

    fmMethod.bindVelocity(vel);

    /**
     * calculate local objective function & derr & illum & g1(gradient)
     */
    float obj = cal_obj_derr_illum_grad(params, &derr[0], &illum[0], &g1[0], &wlt[0], &dobs[0], fmMethod, allSrcPos, allGeoPos);

    DEBUG() << format("sum_derr %f, sum_illum %f, sum_g1 %f") % sum(derr) % sum(illum) % sum(g1);
    objval[iter] = iter == 0 ? obj0 = obj, 1.0 : obj / obj0;

    float epsil = 0;
    float beta = 0;
    sf_floatwrite(&illum[0], params.nz * params.nx, params.illums);

    scale_gradient(&g1[0], &vel.dat[0], &illum[0], params.nz, params.nx, params.precon);
    bell_smoothz(&g1[0], &illum[0], params.rbell, params.nz, params.nx);
    bell_smoothx(&illum[0], &g1[0], params.rbell, params.nz, params.nx);
    sf_floatwrite(&g1[0], params.nz * params.nx, params.grads);

    DEBUG() << format("before beta: sum_g0: %f, sum_g1: %f, sum_cg: %f") % sum(g0) % sum(g1) % sum(cg);
    beta = iter == 0 ? 0.0 : cal_beta(&g0[0], &g1[0], &cg[0], params.nz, params.nx);

    cal_conjgrad(&g1[0], &cg[0], beta, params.nz, params.nx);
    epsil = cal_epsilon(&vel.dat[0], &cg[0], params.nz, params.nx);
    cal_vtmp(&vtmp.dat[0], &vel.dat[0], &cg[0], epsil, params.nz, params.nx);

    std::swap(g1, g0); // let g0 be the previous gradient

    fmMethod.bindVelocity(vtmp);
    float alpha = calVelUpdateStepLen(params, &wlt[0], &dobs[0], &derr[0], epsil, fmMethod, allSrcPos, allGeoPos);

    update_vel(&vel.dat[0], &cg[0], alpha, params.nz, params.nx);

    sf_floatwrite(&vel.dat[0], params.nz * params.nx, params.vupdates);

    // output important information at each FWI iteration
    INFO() << format("iteration %d obj=%f  beta=%f  epsil=%f  alpha=%f") % (iter + 1) % obj % beta % epsil % alpha;
//    INFO() << timer.format(2);

  } /// end of iteration

  sf_floatwrite(&objval[0], params.niter, params.objs);

  sf_close();

  return 0;
}
Example #6
0
Common::Error GroovieEngine::run() {
	if (_gameDescription->version == kGroovieV2 && getPlatform() == Common::kPlatformMacintosh) {
		// Load the Mac installer with the lowest priority (in case the user has installed
		// the game and has the MIDI folder present; faster to just load them)
		Common::Archive *archive = createStuffItArchive("The 11th Hour Installer");

		if (archive)
			SearchMan.add("The 11th Hour Installer", archive);
	}

	_script = new Script(this, _gameDescription->version);

	// Initialize the graphics
	switch (_gameDescription->version) {
	case kGroovieV2: {
		// Request the mode with the highest precision available
		Graphics::PixelFormat format(4, 8, 8, 8, 8, 24, 16, 8, 0);
		initGraphics(640, 480, true, &format);

		if (_system->getScreenFormat() != format)
			return Common::kUnsupportedColorMode;

		// Save the enabled mode
		_pixelFormat = format;
		break;
	}
	case kGroovieT7G:
		initGraphics(640, 480, true);
		_pixelFormat = Graphics::PixelFormat::createFormatCLUT8();
		break;
	}

	// Create debugger. It requires GFX to be initialized
	_debugger = new Debugger(this);
	_script->setDebugger(_debugger);

	// Create the graphics manager
	_graphicsMan = new GraphicsMan(this);

	// Create the resource and cursor managers and the video player
	// Prepare the font too
	switch (_gameDescription->version) {
	case kGroovieT7G:
		if (getPlatform() == Common::kPlatformMacintosh) {
			_macResFork = new Common::MacResManager();
			if (!_macResFork->open(_gameDescription->desc.filesDescriptions[0].fileName))
				error("Could not open %s as a resource fork", _gameDescription->desc.filesDescriptions[0].fileName);
			// The Macintosh release used system fonts. We use GUI fonts.
			_font = FontMan.getFontByUsage(Graphics::FontManager::kBigGUIFont);
		} else {
			Common::File fontfile;
			if (!fontfile.open("sphinx.fnt")) {
				error("Couldn't open sphinx.fnt");
				return Common::kNoGameDataFoundError;
			} else if (!_sphinxFont.load(fontfile)) {
				error("Error loading sphinx.fnt");
				return Common::kUnknownError;
			}
			fontfile.close();
			_font = &_sphinxFont;
		}

		_resMan = new ResMan_t7g(_macResFork);
		_grvCursorMan = new GrvCursorMan_t7g(_system, _macResFork);
		_videoPlayer = new VDXPlayer(this);
		break;
	case kGroovieV2:
		_resMan = new ResMan_v2();
		_grvCursorMan = new GrvCursorMan_v2(_system);
#ifdef ENABLE_GROOVIE2
		_videoPlayer = new ROQPlayer(this);
#endif
		break;
	}

	// Detect ScummVM Music Enhancement Project presence (T7G only)
	if (Common::File::exists("gu16.ogg") && _gameDescription->version == kGroovieT7G) {
		// Load player for external files
		_musicPlayer = new MusicPlayerIOS(this);
	} else {
		// Create the music player
		switch (getPlatform()) {
		case Common::kPlatformMacintosh:
			if (_gameDescription->version == kGroovieT7G)
				_musicPlayer = new MusicPlayerMac_t7g(this);
			else
				_musicPlayer = new MusicPlayerMac_v2(this);
			break;
		case Common::kPlatformIOS:
			_musicPlayer = new MusicPlayerIOS(this);
			break;
		default:
			_musicPlayer = new MusicPlayerXMI(this, _gameDescription->version == kGroovieT7G ? "fat" : "sample");
			break;
		}
	}

	// Load volume levels
	syncSoundSettings();

	// Get the name of the main script
	Common::String filename = _gameDescription->desc.filesDescriptions[0].fileName;
	if (_gameDescription->version == kGroovieT7G) {
		// Run The 7th Guest's demo if requested
		if (ConfMan.hasKey("demo_mode") && ConfMan.getBool("demo_mode"))
			filename = "demo.grv";
		else if (getPlatform() == Common::kPlatformMacintosh)
			filename = "script.grv"; // Stored inside the executable's resource fork
	} else if (_gameDescription->version == kGroovieV2) {
		// Open the disk index
		Common::File disk;
		if (!disk.open(filename)) {
			error("Couldn't open %s", filename.c_str());
			return Common::kNoGameDataFoundError;
		}

		// Search the entry
		bool found = false;
		int index = 0;
		while (!found && !disk.eos()) {
			Common::String line = disk.readLine();
			if (line.hasPrefix("title: ")) {
				// A new entry
				index++;
			} else if (line.hasPrefix("boot: ") && index == _gameDescription->indexEntry) {
				// It's the boot of the entry we're looking for,
				// get the script filename
				filename = line.c_str() + 6;
				found = true;
			}
		}

		// Couldn't find the entry
		if (!found) {
			error("Couldn't find entry %d in %s", _gameDescription->indexEntry, filename.c_str());
			return Common::kUnknownError;
		}
	}

	// Check the script file extension
	if (!filename.hasSuffix(".grv")) {
		error("%s isn't a valid script filename", filename.c_str());
		return Common::kUnknownError;
	}

	// Load the script
	if (!_script->loadScript(filename)) {
		error("Couldn't load the script file %s", filename.c_str());
		return Common::kUnknownError;
	}

	// Should I load a saved game?
	if (ConfMan.hasKey("save_slot")) {
		// Get the requested slot
		int slot = ConfMan.getInt("save_slot");
		_script->directGameLoad(slot);
	}

	// Game timer counter
	uint16 tmr = 0;

	// Check that the game files and the audio tracks aren't together run from
	// the same cd
	if (getPlatform() != Common::kPlatformIOS) {
		checkCD();

		// Initialize the CD
		int cd_num = ConfMan.getInt("cdrom");
		if (cd_num >= 0)
			_system->getAudioCDManager()->openCD(cd_num);
	}

	while (!shouldQuit()) {
		// Give the debugger a chance to act
		_debugger->onFrame();

		// Handle input
		Common::Event ev;
		while (_eventMan->pollEvent(ev)) {
			switch (ev.type) {
			case Common::EVENT_KEYDOWN:
				// CTRL-D: Attach the debugger
				if ((ev.kbd.flags & Common::KBD_CTRL) && ev.kbd.keycode == Common::KEYCODE_d)
					_debugger->attach();

				// Send the event to the scripts
				_script->setKbdChar(ev.kbd.ascii);

				// Continue the script execution to handle the key
				_waitingForInput = false;
				break;

			case Common::EVENT_MAINMENU:
				// Closing the GMM
			case Common::EVENT_MOUSEMOVE:
				// Continue the script execution, the mouse pointer
				// may fall inside a different hotspot now
				_waitingForInput = false;
				break;

			case Common::EVENT_LBUTTONDOWN:
				// Send the event to the scripts
				_script->setMouseClick(1);

				// Continue the script execution to handle
				// the click
				_waitingForInput = false;
				break;

			case Common::EVENT_RBUTTONDOWN:
				// Send the event to the scripts (to skip the video)
				_script->setMouseClick(2);
				break;

			case Common::EVENT_QUIT:
				quitGame();
				break;

			default:
				break;
			}
		}

		// The event loop may have triggered the quit status. In this case,
		// stop the execution.
		if (shouldQuit()) {
			continue;
		}

		if (_waitingForInput) {
			// Still waiting for input, just update the mouse, game timer and then wait a bit more
			_grvCursorMan->animate();
			_system->updateScreen();
			tmr++;
			// Wait a little bit between increments.  While mouse is moving, this triggers
			// only negligably slower.
			if (tmr > 4) {
				_script->timerTick();
				tmr = 0;
			}

			_system->delayMillis(50);
		} else if (_graphicsMan->isFading()) {
			// We're waiting for a fading to end, let the CPU rest
			// for a while and continue
			_system->delayMillis(30);
		} else {
			// Everything's fine, execute another script step
			_script->step();
		}

		// Update the screen if required
		_graphicsMan->update();
	}

	return Common::kNoError;
}
Example #7
0
		comment += " ";
	}
#endif		
	assem::OPER *sink1 = _aOPER5("", "", alive_regs, TempList(), "@def " + comment);
	assem::OPER *sink2 = _aOPER5("", "", TempList(), alive_regs, "@use " + comment);
	
	assem::Instruction *funcLabel = body.front();
	assert(funcLabel->isLABEL());
	newbody.push_back(funcLabel);
	
	newbody.push_back(sink1);
	std::copy(body.begin()+1, body.end(), std::back_inserter(newbody));
	
	//insert end label
	assert(endFuncLabel);
	std::string assem = format("%s:", endFuncLabel->toString().c_str());
	assem::LABEL *end_lab = _aLABEL(assem, endFuncLabel);
	newbody.push_back(end_lab);

	newbody.push_back(sink2);

	return newbody;
}

TempList
X86Frame::findRegsInBody(const assem::InstructionList &body)
{
	TempList used;
	BOOST_FOREACH(assem::Instruction *inst, body) {
		TempList def = inst->def();
		BOOST_FOREACH(Temp *t, def) {
void callback_state::output(uint64_t value)
{
    output(format("%1%") % value);
}
Example #9
0
void String2DateTimeFilter::writeExtraAttributes(QXmlStreamWriter * writer) const
{
	writer->writeAttribute("format", format());
}
void callback_state::error(const std::string& message)
{
    error(format(message));
}
void callback_state::output(const std::string& message)
{
    output(format(message));
}
Example #12
0
void zdl::append_data_to(std::string & s) const
{
	append(s, to_string(time_to_point_));
	append(s, format(distance_, 1));
	append(s, to_string(type_point_));
}
Example #13
0
bool wxClipboard::GetData( wxDataObject& data )
{
    wxCHECK_MSG( m_open, FALSE, wxT("clipboard not open") );

    /* get formats from wxDataObjects */
    wxDataFormat *array = new wxDataFormat[ data.GetFormatCount() ];
    data.GetAllFormats( array );

    for (size_t i = 0; i < data.GetFormatCount(); i++)
    {
        wxDataFormat format( array[i] );

        wxLogTrace( TRACE_CLIPBOARD,
                    wxT("wxClipboard::GetData: requested format: %s"),
                    format.GetId().c_str() );

        /* is data supported by clipboard ? */

        /* store requested format to be asked for by callbacks */
        m_targetRequested = format;

        wxCHECK_MSG( m_targetRequested, FALSE, wxT("invalid clipboard format") );

        m_formatSupported = FALSE;

       /* perform query. this will set m_formatSupported to
          TRUE if m_targetRequested is supported.
          also, we have to wait for the "answer" from the
          clipboard owner which is an asynchronous process.
          therefore we set m_waiting = TRUE here and wait
          until the callback "targets_selection_received"
          sets it to FALSE */

        m_waiting = TRUE;

#if 0
        gtk_selection_convert( m_targetsWidget,
                           m_usePrimary ? (GdkAtom)GDK_SELECTION_PRIMARY
                                        : g_clipboardAtom,
                           g_targetsAtom,
                           (guint32) GDK_CURRENT_TIME );

        while (m_waiting) gtk_main_iteration();
#endif

        if (!m_formatSupported) continue;

        /* store pointer to data object to be filled up by callbacks */
        m_receivedData = &data;

        /* store requested format to be asked for by callbacks */
        m_targetRequested = format;

        wxCHECK_MSG( m_targetRequested, FALSE, wxT("invalid clipboard format") );

        /* start query */
        m_formatSupported = FALSE;

        /* ask for clipboard contents.  this will set
           m_formatSupported to TRUE if m_targetRequested
           is supported.
           also, we have to wait for the "answer" from the
           clipboard owner which is an asynchronous process.
           therefore we set m_waiting = TRUE here and wait
           until the callback "targets_selection_received"
           sets it to FALSE */

        m_waiting = TRUE;

        wxLogTrace( TRACE_CLIPBOARD,
                    wxT("wxClipboard::GetData: format found, start convert") );

#if 0
        gtk_selection_convert( m_clipboardWidget,
                               m_usePrimary ? (GdkAtom)GDK_SELECTION_PRIMARY
                                            : g_clipboardAtom,
                               m_targetRequested,
                               (guint32) GDK_CURRENT_TIME );

        while (m_waiting) gtk_main_iteration();
#endif

        /* this is a true error as we checked for the presence of such data before */
        wxCHECK_MSG( m_formatSupported, FALSE, wxT("error retrieving data from clipboard") );

        /* return success */
        delete[] array;
        return TRUE;
    }

    wxLogTrace( TRACE_CLIPBOARD,
                wxT("wxClipboard::GetData: format not found") );

    /* return failure */
    delete[] array;
    return FALSE;
}
Example #14
0
void wr_artifacts(void)
{
    size_t i;
    u16b tmp16u;

    /* Record the total number of artifacts. */
    tmp16u = z_info->a_max;
    wr_u16b(tmp16u);
  
    /* Record the first random artifact index. */
    tmp16u = ART_MIN_RANDOM;
    wr_u16b(tmp16u);
  
  
    /* Write the artifact info. */
    for (i = 0; i < ART_MIN_RANDOM; i++)
    {
	artifact_type *a_ptr = &a_info[i];
	
	wr_byte(a_ptr->created);
	wr_byte(a_ptr->seen);
	/* Store set completion info */
	wr_byte(a_ptr->set_bonus ? 1 : 0);
	
	/* Expansion */
	wr_u32b(0);
    }

    /* Random artifacts are specific to each player. */
    for (i = ART_MIN_RANDOM; i < z_info->a_max; i++)
    {
	artifact_type *a_ptr = &a_info[i];
	size_t j;

	wr_string(format("%s", a_ptr->name));
	
	wr_byte(a_ptr->tval);
	wr_byte(a_ptr->sval);
	wr_u16b(a_ptr->pval);
	
	wr_u16b(a_ptr->to_h);
	wr_u16b(a_ptr->to_d);
	wr_u16b(a_ptr->to_a);
	
	wr_byte(a_ptr->dd);
	wr_byte(a_ptr->ds);
	  
	wr_u16b(a_ptr->ac);
	wr_u16b(a_ptr->weight);
	  
	wr_u32b(a_ptr->cost);
	  
	for (j = 0; j < OF_SIZE; j++)
	    wr_byte(a_ptr->flags_obj[j]);
	for (j = 0; j < CF_SIZE; j++)
	    wr_byte(a_ptr->flags_curse[j]);
	  
	wr_byte(a_ptr->level);
	wr_byte(a_ptr->rarity);
	  
	wr_byte(a_ptr->created);
	wr_byte(a_ptr->seen);
	wr_byte(a_ptr->effect);
	wr_u16b(a_ptr->time.base);
	wr_u16b(a_ptr->time.dice);
	wr_u16b(a_ptr->time.sides);
	wr_u16b(a_ptr->charge.base);
	wr_u16b(a_ptr->charge.dice);
	wr_u16b(a_ptr->charge.sides);

	/* Resists, bonuses, multiples -NRM- */
	for (j = 0; j < MAX_P_RES; j++)
	    wr_byte(a_ptr->percent_res[j]);
	for (j = 0; j < A_MAX; j++)
	    wr_byte(a_ptr->bonus_stat[j]);
	for (j = 0; j < MAX_P_BONUS; j++)
	    wr_byte(a_ptr->bonus_other[j]);
	for (j = 0; j < MAX_P_SLAY; j++)
	    wr_byte(a_ptr->multiple_slay[j]);
	for (j = 0; j < MAX_P_BRAND; j++)
	    wr_byte(a_ptr->multiple_brand[j]);
	  
	/* Add some filler space for later expansion. */
	wr_u32b(0);
    }
}
Example #15
0
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
############################################################################## */

#include "jliball.hpp"
#include "jhtree.hpp"
#include "ctfile.hpp"

void fatal(const char *format, ...) __attribute__((format(printf, 1, 2)));
void fatal(const char *format, ...)
{
    va_list      args;

    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);
    fflush(stderr);
    releaseAtoms();
    ExitModuleObjects();
    _exit(2);
}

bool optHex = false;
bool optRaw = false;
Example #16
0
	va_start (argptr,error);
	Q_vsnprintf (string, sizeof(string), error, argptr);
	va_end (argptr);

	Sys_ErrorDialog( string );

	Sys_Exit( 3 );
}

#if 0
/*
=================
Sys_Warn
=================
*/
static __attribute__ ((format (printf, 1, 2))) void Sys_Warn( char *warning, ... )
{
	va_list argptr;
	char    string[1024];

	va_start (argptr,warning);
	Q_vsnprintf (string, sizeof(string), warning, argptr);
	va_end (argptr);

	CON_Print( va( "Warning: %s", string ) );
}
#endif

/*
============
Sys_FileTime
Example #17
0
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with libqb.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "os_base.h"

#include <qb/qbdefs.h>
#include <qb/qbutil.h>
#include <qb/qblog.h>

extern size_t qb_vsnprintf_serialize(char *serialize, size_t max_len, const char *fmt, va_list ap);

static void
store_this_qb(const char *fmt, ...) __attribute__((format(printf, 1, 2)));

static void
store_this_snprintf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));

typedef void (*snprintf_like_func)(const char *fmt, ...)  __attribute__((format(printf, 1, 2)));


static void
store_this_qb(const char *fmt, ...)
{
	char buf[QB_LOG_MAX_LEN];
	va_list ap;

	va_start(ap, fmt);
	qb_vsnprintf_serialize(buf, QB_LOG_MAX_LEN, fmt, ap);
Example #18
0
//RUN: clang-cc -fsyntax-only -verify %s

#include <stdarg.h>

void a(const char *a, ...) __attribute__((format(printf, 1,2))); // no-error
void b(const char *a, ...) __attribute__((format(printf, 1,1))); // expected-error {{'format' attribute parameter 3 is out of bounds}}
void c(const char *a, ...) __attribute__((format(printf, 0,2))); // expected-error {{'format' attribute parameter 2 is out of bounds}}
void d(const char *a, int c) __attribute__((format(printf, 1,2))); // expected-error {{format attribute requires variadic function}}
void e(char *str, int c, ...) __attribute__((format(printf, 2,3))); // expected-error {{format argument not a string type}}

typedef const char* xpto;
void f(xpto c, va_list list) __attribute__((format(printf, 1, 0))); // no-error
void g(xpto c) __attribute__((format(printf, 1, 0))); // no-error

void y(char *str) __attribute__((format(strftime, 1,0))); // no-error
void z(char *str, int c, ...) __attribute__((format(strftime, 1,2))); // expected-error {{strftime format attribute requires 3rd parameter to be 0}}

int (*f_ptr)(char*,...) __attribute__((format(printf, 1,2))); // no-error
int (*f2_ptr)(double,...) __attribute__((format(printf, 1, 2))); // expected-error {{format argument not a string type}}

struct _mystruct {
  int (*printf)(const char *format, ...) __attribute__((__format__(printf, 1, 2))); // no-error
  int (*printf2)(double format, ...) __attribute__((__format__(printf, 1, 2))); // expected-error {{format argument not a string type}}
};

typedef int (*f3_ptr)(char*,...) __attribute__((format(printf,1,0))); // no-error

// <rdar://problem/6623513>
int rdar6623513(void *, const char*, const char*, ...)
  __attribute__ ((format (printf, 3, 0)));
Example #19
0
  vnet_main_t * vnet_main;
} l2_patch_main_t;

typedef struct {
  u32 rx_sw_if_index;
  u32 tx_sw_if_index;
} l2_patch_trace_t;

/* packet trace format function */
static u8 * format_l2_patch_trace (u8 * s, va_list * args)
{
  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
  l2_patch_trace_t * t = va_arg (*args, l2_patch_trace_t *);
  
  s = format (s, "L2_PATCH: rx %d tx %d", t->rx_sw_if_index,
              t->tx_sw_if_index);
  return s;
}

l2_patch_main_t l2_patch_main;

static vlib_node_registration_t l2_patch_node;

#define foreach_l2_patch_error			\
_(PATCHED, "L2 patch packets")			\
_(DROPPED, "L2 patch misconfigured drops")

typedef enum {
#define _(sym,str) L2_PATCH_ERROR_##sym,
  foreach_l2_patch_error
#undef _
Example #20
0
template<class PerturbedT> bool perturbed_ratio(RawArray<Quantized> result, void(*const ratio)(RawArray<mp_limb_t,2>,RawArray<const Vector<Exact<1>,PerturbedT::m>>), const int degree, RawArray<const PerturbedT> X, const bool take_sqrt) {
  const int m = PerturbedT::m;
  typedef Vector<Exact<1>,m> EV;
  const int n = X.size();
  const int r = result.size();

  if (verbose)
    cout << "perturbed_ratio:\n  degree = "<<degree<<"\n  X = "<<X<<endl;

  // Check if the ratio is nonsingular before perturbation
  const auto Z = GEODE_RAW_ALLOCA(n,EV);
  const int precision = degree*Exact<1>::ratio;
  {
    for (int i=0;i<n;i++)
      Z[i] = EV(to_exact(X[i].value()));
    const auto R = GEODE_RAW_ALLOCA((r+1)*precision,mp_limb_t).reshape(r+1,precision);
    ratio(R,Z);
    if (const int sign = mpz_sign(R[r])) {
      snap_divs(result,R,take_sqrt);
      return sign>0;
    }
  }

  // Check the first perturbation level with specialized code
  vector<Vector<ExactInt,m>> Y(n); // perturbations
  {
    // Compute the first level of perturbations
    for (int i=0;i<n;i++)
      Y[i] = perturbation<m>(1,X[i].seed());
    if (verbose)
      cout << "  Y = "<<Y<<endl;

    // Evaluate polynomial at epsilon = 1, ..., degree
    const int scaled_precision = precision+factorial_limbs(degree);
    const auto values = GEODE_RAW_ALLOCA(degree*(r+1)*scaled_precision,mp_limb_t).reshape(degree,r+1,scaled_precision);
    for (int j=0;j<degree;j++) {
      for (int i=0;i<n;i++)
        Z[i] = EV(to_exact(X[i].value())+(j+1)*Y[i]);
      ratio(values[j],Z);
      if (verbose)
        cout << "  ratio("<<Z<<") = "<<mpz_str(values[j])<<endl;
    }

    // Find interpolating polynomials, overriding the input with the result.
    for (int k=0;k<=r;k++) {
      scaled_univariate_in_place_interpolating_polynomial(values.sub<1>(k));
      if (verbose)
        cout << "  coefs "<<k<<" = "<<mpz_str(values.sub<1>(k))<<endl;
    }

    // Find the largest (lowest degree) nonzero denominator coefficient.  If we detect an infinity during this process, explode.
    for (int j=0;j<degree;j++) {
      if (const int sign = mpz_sign(values(j,r))) { // We found a nonzero, now compute the rounded ratio
        snap_divs(result,values[j],take_sqrt);
        return sign>0;
      } else
        for (int k=0;k<r;k++)
          if (mpz_nonzero(values(j,k)))
            throw OverflowError(format("perturbed_ratio: infinite result in l'Hopital expansion: %s/0",mpz_str(values(j,k))));
    }
  }

  {
    // Add one perturbation level after another until we hit a nonzero denominator.  Our current implementation duplicates
    // work from one iteration to the next for simplicity, which is fine since the first interation suffices almost always.
    for (int d=2;;d++) {
      // Compute the next level of perturbations
      Y.resize(d*n);
      for (int i=0;i<n;i++)
        Y[(d-1)*n+i] = perturbation<m>(d,X[i].seed());

      // Evaluate polynomial at every point in an "easy corner"
      const auto lambda = monomials(degree,d);
      const Array<mp_limb_t,3> values(lambda.m,r+1,precision,uninit);
      for (int j=0;j<lambda.m;j++) {
        for (int i=0;i<n;i++)
          Z[i] = EV(to_exact(X[i].value())+lambda(j,0)*Y[i]);
        for (int v=1;v<d;v++)
          for (int i=0;i<n;i++)
            Z[i] += EV(lambda(j,v)*Y[v*n+i]);
        ratio(values[j],Z);
      }

      // Find interpolating polynomials, overriding the input with the result.
      for (int k=0;k<=r;k++)
        in_place_interpolating_polynomial(degree,lambda,values.sub<1>(k));

      // Find the largest nonzero denominator coefficient
      int sign = 0;
      int nonzero = -1;
      for (int j=0;j<lambda.m;j++)
        if (const int s = mpz_sign(values(j,r))) {
          if (check) // Verify that a term which used to be zero doesn't become nonzero
            GEODE_ASSERT(lambda(j,d-1));
          if (nonzero<0 || monomial_less(lambda[nonzero],lambda[j])) {
            sign = s;
            nonzero = j;
          }
        }

      // Verify that numerator coefficients are zero for all large monomials
      for (int j=0;j<lambda.m;j++)
        if (nonzero<0 || monomial_less(lambda[nonzero],lambda[j]))
          for (int k=0;k<r;k++)
            if (mpz_nonzero(values(j,k)))
              throw OverflowError(format("perturbed_ratio: infinite result in l'Hopital expansion: %s/0",str(values(j,k))));

      // If we found a nonzero, compute the result
      if (nonzero >= 0) {
        snap_divs(result,values[nonzero],take_sqrt);
        return sign>0;
      }

      // If we get through two levels without fixing the degeneracy, run a fast, strict identity test to make sure we weren't handed an impossible problem.
      if (d==2)
        assert_last_nonzero(ratio,values[0],X,"perturbed_ratio: identically zero denominator");
    }
  }
}
Example #21
0
/*
 * Recursive file perusal.
 *
 * Return FALSE on "?", otherwise TRUE.
 *
 * This function could be made much more efficient with the use of "seek"
 * functionality, especially when moving backwards through a file, or
 * forwards through a file by less than a page at a time.  XXX XXX XXX
 */
bool show_file(cptr name, cptr what, int line, int mode)
{
	int i, k, n;

	char ch;

	/* Number of "real" lines passed by */
	int next = 0;

	/* Number of "real" lines in the file */
	int size;

	/* Backup value for "line" */
	int back = 0;

	/* This screen has sub-screens */
	bool menu = FALSE;

	/* Case sensitive search */
	bool case_sensitive = FALSE;

	/* Current help file */
	ang_file *fff = NULL;

	/* Find this string (if any) */
	char *find = NULL;

	/* Jump to this tag */
	cptr tag = NULL;

	/* Hold a string to find */
	char finder[80] = "";

	/* Hold a string to show */
	char shower[80] = "";

	/* Filename */
	char filename[1024];

	/* Describe this thing */
	char caption[128] = "";

	/* Path buffer */
	char path[1024];

	/* General buffer */
	char buf[1024];

	/* Lower case version of the buffer, for searching */
	char lc_buf[1024];

	/* Sub-menu information */
	char hook[26][32];

	int wid, hgt;



	/* Wipe the hooks */
	for (i = 0; i < 26; i++) hook[i][0] = '\0';

	/* Get size */
	Term_get_size(&wid, &hgt);

	/* Copy the filename */
	my_strcpy(filename, name, sizeof(filename));

	n = strlen(filename);

	/* Extract the tag from the filename */
	for (i = 0; i < n; i++)
	{
		if (filename[i] == '#')
		{
			filename[i] = '\0';
			tag = filename + i + 1;
			break;
		}
	}

	/* Redirect the name */
	name = filename;


	/* Hack XXX XXX XXX */
	if (what)
	{
		my_strcpy(caption, what, sizeof(caption));

		my_strcpy(path, name, sizeof(path));
		fff = file_open(path, MODE_READ, -1);
	}

	/* Look in "help" */
	if (!fff)
	{
		strnfmt(caption, sizeof(caption), "Help file '%s'", name);

		path_build(path, sizeof(path), reposband_DIR_HELP, name);
		fff = file_open(path, MODE_READ, -1);
	}

	/* Look in "info" */
	if (!fff)
	{
		strnfmt(caption, sizeof(caption), "Info file '%s'", name);

		path_build(path, sizeof(path), reposband_DIR_INFO, name);
		fff = file_open(path, MODE_READ, -1);
	}

	/* Oops */
	if (!fff)
	{
		/* Message */
		msg_format("Cannot open '%s'.", name);
		message_flush();

		/* Oops */
		return (TRUE);
	}


	/* Pre-Parse the file */
	while (TRUE)
	{
		/* Read a line or stop */
		if (!file_getl(fff, buf, sizeof(buf))) break;

		/* XXX Parse "menu" items */
		if (prefix(buf, "***** "))
		{
			char b1 = '[', b2 = ']';

			/* Notice "menu" requests */
			if ((buf[6] == b1) && isalpha((unsigned char)buf[7]) &&
			    (buf[8] == b2) && (buf[9] == ' '))
			{
				/* This is a menu file */
				menu = TRUE;

				/* Extract the menu item */
				k = A2I(buf[7]);

				/* Store the menu item (if valid) */
				if ((k >= 0) && (k < 26))
					my_strcpy(hook[k], buf + 10, sizeof(hook[0]));
			}
			/* Notice "tag" requests */
			else if (buf[6] == '<')
			{
				if (tag)
				{
					/* Remove the closing '>' of the tag */
					buf[strlen(buf) - 1] = '\0';

					/* Compare with the requested tag */
					if (streq(buf + 7, tag))
					{
						/* Remember the tagged line */
						line = next;
					}
				}
			}

			/* Skip this */
			continue;
		}

		/* Count the "real" lines */
		next++;
	}

	/* Save the number of "real" lines */
	size = next;



	/* Display the file */
	while (TRUE)
	{
		/* Clear screen */
		Term_clear();


		/* Restrict the visible range */
		if (line > (size - (hgt - 4))) line = size - (hgt - 4);
		if (line < 0) line = 0;


		/* Re-open the file if needed */
		if (next > line)
		{
			/* Close it */
			file_close(fff);

			/* Hack -- Re-Open the file */
			fff = file_open(path, MODE_READ, -1);
			if (!fff) return (TRUE);

			/* File has been restarted */
			next = 0;
		}


		/* Goto the selected line */
		while (next < line)
		{
			/* Get a line */
			if (!file_getl(fff, buf, sizeof(buf))) break;

			/* Skip tags/links */
			if (prefix(buf, "***** ")) continue;

			/* Count the lines */
			next++;
		}


		/* Dump the next lines of the file */
		for (i = 0; i < hgt - 4; )
		{
			/* Hack -- track the "first" line */
			if (!i) line = next;

			/* Get a line of the file or stop */
			if (!file_getl(fff, buf, sizeof(buf))) break;

			/* Hack -- skip "special" lines */
			if (prefix(buf, "***** ")) continue;

			/* Count the "real" lines */
			next++;

			/* Make a copy of the current line for searching */
			my_strcpy(lc_buf, buf, sizeof(lc_buf));

			/* Make the line lower case */
			if (!case_sensitive) string_lower(lc_buf);

			/* Hack -- keep searching */
			if (find && !i && !strstr(lc_buf, find)) continue;

			/* Hack -- stop searching */
			find = NULL;

			/* Dump the line */
			Term_putstr(0, i+2, -1, TERM_WHITE, buf);

			/* Highlight "shower" */
			if (shower[0])
			{
				cptr str = lc_buf;

				/* Display matches */
				while ((str = strstr(str, shower)) != NULL)
				{
					int len = strlen(shower);

					/* Display the match */
					Term_putstr(str-lc_buf, i+2, len, TERM_YELLOW, &buf[str-lc_buf]);

					/* Advance */
					str += len;
				}
			}

			/* Count the printed lines */
			i++;
		}

		/* Hack -- failed search */
		if (find)
		{
			bell("Search string not found!");
			line = back;
			find = NULL;
			continue;
		}


		/* Show a general "title" */
		prt(format("[%s %s, %s, Line %d-%d/%d]", VERSION_NAME, VERSION_STRING,
		           caption, line, line + hgt - 4, size), 0, 0);


		/* Prompt -- menu screen */
		if (menu)
		{
			/* Wait for it */
			prt("[Press a Number, or ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- small files */
		else if (size <= hgt - 4)
		{
			/* Wait for it */
			prt("[Press ESC to exit.]", hgt - 1, 0);
		}

		/* Prompt -- large files */
		else
		{
			/* Wait for it */
			prt("[Press Space to advance, or ESC to exit.]", hgt - 1, 0);
		}

		/* Get a keypress */
		ch = inkey();

		/* Exit the help */
		if (ch == '?') break;

		/* Toggle case sensitive on/off */
		if (ch == '!')
		{
			case_sensitive = !case_sensitive;
		}

		/* Try showing */
		if (ch == '&')
		{
			/* Get "shower" */
			prt("Show: ", hgt - 1, 0);
			(void)askfor_aux(shower, sizeof(shower), NULL);

			/* Make the "shower" lowercase */
			if (!case_sensitive) string_lower(shower);
		}

		/* Try finding */
		if (ch == '/')
		{
			/* Get "finder" */
			prt("Find: ", hgt - 1, 0);
			if (askfor_aux(finder, sizeof(finder), NULL))
			{
				/* Find it */
				find = finder;
				back = line;
				line = line + 1;

				/* Make the "finder" lowercase */
				if (!case_sensitive) string_lower(finder);

				/* Show it */
				my_strcpy(shower, finder, sizeof(shower));
			}
		}

		/* Go to a specific line */
		if (ch == '#')
		{
			char tmp[80] = "0";

			prt("Goto Line: ", hgt - 1, 0);
			if (askfor_aux(tmp, sizeof(tmp), NULL))
				line = atoi(tmp);
		}

		/* Go to a specific file */
		if (ch == '%')
		{
			char ftmp[80] = "help.hlp";

			prt("Goto File: ", hgt - 1, 0);
			if (askfor_aux(ftmp, sizeof(ftmp), NULL))
			{
				if (!show_file(ftmp, NULL, 0, mode))
					ch = ESCAPE;
			}
		}

		/* Back up one line */
		if (ch == ARROW_UP || ch == '8')
		{
			line = line - 1;
		}

		/* Back up one full page */
		if ((ch == '9') || (ch == '-'))
		{
			line = line - (hgt - 4);
		}

		/* Back to the top */
		if (ch == '7')
		{
			line = 0;
		}

		/* Advance one line */
		if ((ch == ARROW_DOWN) || (ch == '2') || (ch == '\n') || (ch == '\r'))
		{
			line = line + 1;
		}

		/* Advance one full page */
		if ((ch == '3') || (ch == ' '))
		{
			line = line + (hgt - 4);
		}

		/* Advance to the bottom */
		if (ch == '1')
		{
			line = size;
		}

		/* Recurse on letters */
		if (menu && isalpha((unsigned char)ch))
		{
			/* Extract the requested menu item */
			k = A2I(ch);

			/* Verify the menu item */
			if ((k >= 0) && (k <= 25) && hook[k][0])
			{
				/* Recurse on that file */
				if (!show_file(hook[k], NULL, 0, mode)) ch = ESCAPE;
			}
		}

		/* Exit on escape */
		if (ch == ESCAPE) break;
	}

	/* Close the file */
	file_close(fff);

	/* Done */
	return (ch != '?');
}
Example #22
0
// end_header
void end_header(Val stream, const char16* pwszFileName)
{
    format(stream, L"~%#endif // ~A~%", encode_file_name(pwszFileName));
    close(stream);
} // end_stream
Example #23
0
#if !defined(__APPLE__) && !defined(__WIN32__)
typedef void(dt_signal_handler_t)(int);
// static dt_signal_handler_t *_dt_sigill_old_handler = NULL;
static dt_signal_handler_t *_dt_sigsegv_old_handler = NULL;

// deer graphicsmagick, please stop messing with the stuff that you should not be touching at all.
// based on GM's InitializeMagickSignalHandlers() and MagickSignalHandlerMessage()
static const int _signals_to_preserve[] = { SIGHUP,  SIGINT,  SIGQUIT, SIGILL,  SIGABRT, SIGBUS, SIGFPE,
                                            SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGXCPU, SIGXFSZ };
#define _NUM_SIGNALS_TO_PRESERVE (sizeof(_signals_to_preserve) / sizeof(_signals_to_preserve[0]))
static dt_signal_handler_t *_orig_sig_handlers[_NUM_SIGNALS_TO_PRESERVE] = { NULL };
#endif

#if(defined(__FreeBSD_version) && (__FreeBSD_version < 800071)) || (defined(OpenBSD) && (OpenBSD < 201305))       \
    || defined(__SUNOS__)
static int dprintf(int fd, const char *fmt, ...) __attribute__((format(printf, 2, 3)))
{
  va_list ap;
  FILE *f = fdopen(fd, "a");
  va_start(ap, fmt);
  int rc = vfprintf(f, fmt, ap);
  fclose(f);
  va_end(ap);
  return rc;
}
#endif

#if !defined(__APPLE__) && !defined(__WIN32__)
static void _dt_sigsegv_handler(int param)
{
  pid_t pid;
Example #24
0
	char *base;
	base = strrchr (file_name, '/');
	if (base) {
		return base + 1;
	}

	return file_name;
}

static void
_logsys_log_printf(int level, int subsys,
		const char *function_name,
		const char *file_name,
		int file_line,
		const char *format,
		...) __attribute__((format(printf, 6, 7)));

static void
_logsys_log_printf(int level, int subsys,
		const char *function_name,
		const char *file_name,
		int file_line,
		const char *format, ...)
{
	va_list ap;

	va_start(ap, format);
	qb_log_from_external_source_va(function_name, corosync_basename(file_name),
				    format, level, file_line,
				    subsys, ap);
	va_end(ap);
Example #25
0
void 
PIXAPI pix_str_inf(pix_str str, pix_inf inf)
{
  format(*str->str, *inf->inf);
}
Example #26
0
static const unsigned char *program_name = "";
static const unsigned char *ejudge_xml_path = 0;
static const unsigned char *src_plugin_name = 0;
static const unsigned char *dst_plugin_name = 0;

static int contest_id = 0;

static struct ejudge_cfg *config = 0;
static const struct contest_desc *cnts = 0;
static clarlog_state_t src_clarlog = 0;
static clarlog_state_t dst_clarlog = 0;

static void
die(const char *format, ...)
  __attribute__((format(printf, 1, 2), noreturn));
static void
die(const char *format, ...)
{
  va_list args;
  char buf[1024];

  va_start(args, format);
  vsnprintf(buf, sizeof(buf), format, args);
  va_end(args);

  fprintf(stderr, "%s: %s\n", program_name,
          buf);
  exit(1);
}
Example #27
0
    printf( "h-lang end\n\n" );
    */

    create_global_env();
    g_env = g_global;

    yyparse();

    return 0;
}



__attribute__ ((noreturn)) 
__attribute__((format (printf, 1, 2)))
void
error( const char *fmt, ... )
{
    va_list ap;
    va_start( ap, fmt );
    fprintf( stderr, "ERROR: " );
    vfprintf( stderr, fmt, ap );
    fprintf( stderr, "\n" );
    va_end( ap );

    exit( 1 );
}


Example #28
0
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign, SeparatorStyle separators)
{
    return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
Example #29
0
 static std::string format(
     llvm::StringRef Code,
     const FormatStyle &Style = getGoogleStyle(FormatStyle::LK_Java)) {
   return format(Code, 0, Code.size(), Style);
 }
Example #30
0
bool QGLContext::chooseContext( const QGLContext* shareContext )
{
    Display* disp = d->paintDevice->x11Display();
    vi = chooseVisual();
    if ( !vi )
	return FALSE;

    if ( deviceIsPixmap() &&
	 (((XVisualInfo*)vi)->depth != d->paintDevice->x11Depth() ||
	  ((XVisualInfo*)vi)->screen != d->paintDevice->x11Screen()) )
    {
	XFree( vi );
	XVisualInfo appVisInfo;
	memset( &appVisInfo, 0, sizeof(XVisualInfo) );
	appVisInfo.visualid = XVisualIDFromVisual( (Visual*)d->paintDevice->x11Visual() );
	appVisInfo.screen = d->paintDevice->x11Screen();
	int nvis;
	vi = XGetVisualInfo( disp, VisualIDMask | VisualScreenMask, &appVisInfo, &nvis );
	if ( !vi )
	    return FALSE;

	int useGL;
	glXGetConfig( disp, (XVisualInfo*)vi, GLX_USE_GL, &useGL );
	if ( !useGL )
	    return FALSE;	//# Chickening out already...
    }
    int res;
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_LEVEL, &res );
    glFormat.setPlane( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_DOUBLEBUFFER, &res );
    glFormat.setDoubleBuffer( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_DEPTH_SIZE, &res );
    glFormat.setDepth( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_RGBA, &res );
    glFormat.setRgba( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_ALPHA_SIZE, &res );
    glFormat.setAlpha( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_ACCUM_RED_SIZE, &res );
    glFormat.setAccum( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_STENCIL_SIZE, &res );
    glFormat.setStencil( res );
    glXGetConfig( disp, (XVisualInfo*)vi, GLX_STEREO, &res );
    glFormat.setStereo( res );

    Bool direct = format().directRendering() ? True : False;

    if ( shareContext &&
	 ( !shareContext->isValid() || !shareContext->cx ) ) {
#if defined(QT_CHECK_NULL)
	    qWarning("QGLContext::chooseContext(): Cannot share with invalid context");
#endif
	    shareContext = 0;
    }

    // 1. Sharing between rgba and color-index will give wrong colors.
    // 2. Contexts cannot be shared btw. direct/non-direct renderers.
    // 3. Pixmaps cannot share contexts that are set up for direct rendering.
    if ( shareContext && (format().rgba() != shareContext->format().rgba() ||
			  (deviceIsPixmap() &&
			   glXIsDirect( disp, (GLXContext)shareContext->cx ))))
	shareContext = 0;

    cx = 0;
    if ( shareContext ) {
	cx = glXCreateContext( disp, (XVisualInfo *)vi,
			       (GLXContext)shareContext->cx, direct );
	if ( cx )
	    d->sharing = TRUE;
    }
    if ( !cx )
	cx = glXCreateContext( disp, (XVisualInfo *)vi, None, direct );
    if ( !cx )
	return FALSE;
    glFormat.setDirectRendering( glXIsDirect( disp, (GLXContext)cx ) );
    if ( deviceIsPixmap() ) {
#if defined(GLX_MESA_pixmap_colormap) && defined(QGL_USE_MESA_EXT)
	gpm = glXCreateGLXPixmapMESA( disp, (XVisualInfo *)vi,
				      d->paintDevice->handle(),
				      choose_cmap( disp, (XVisualInfo *)vi ) );
#else
	gpm = (Q_UINT32)glXCreateGLXPixmap( disp, (XVisualInfo *)vi,
					    d->paintDevice->handle() );
#endif
	if ( !gpm )
	    return FALSE;
    }
    return TRUE;
}