Beispiel #1
0
void cTextField::handleInput(cKey key) {
	changeMade = true;
	bool select = mod_contains(key.mod, mod_shift);
	bool haveSelection = insertionPoint != selectionPoint;
	key = divineFunction(key);
	TextStyle style;
	style.font = FONT_PLAIN;
	style.pointSize = 12;
	size_t new_ip;
	std::string contents = getText();
	if(current_action && hist_timer.getElapsedTime().asSeconds() > 5.0f)
		history.add(current_action), current_action.reset();
	hist_timer.restart();
	if(!key.spec) {
		if(haveSelection) {
			cKey deleteKey = key;
			deleteKey.spec = true;
			deleteKey.k = key_bsp;
			handleInput(deleteKey);
			contents = getText();
		}
		if(aTextInsert* ins = dynamic_cast<aTextInsert*>(current_action.get()))
			ins->append(key.c);
		else {
			if(current_action) history.add(current_action);
			aTextInsert* new_ins = new aTextInsert(*this, insertionPoint);
			new_ins->append(key.c);
			current_action.reset(new_ins);
		}
		contents.insert(contents.begin() + insertionPoint, char(key.c));
		selectionPoint = ++insertionPoint;
	} else switch(key.k) {
		case key_enter: break; // Shouldn't be receiving this anyway
			// TODO: Implement all the other special keys
		case key_left: case key_word_left:
			if(current_action) history.add(current_action), current_action.reset();
			if(haveSelection && !select) {
				selectionPoint = insertionPoint = std::min(selectionPoint,insertionPoint);
				break;
			}
			new_ip = select ? selectionPoint : insertionPoint;
			if(new_ip == 0) break;
			if(key.k == key_word_left) {
				new_ip--;
				while(new_ip > 0 && contents[new_ip - 1] != ' ')
					new_ip--;
			} else new_ip--;
			(select ? selectionPoint : insertionPoint) = new_ip;
			if(!select) selectionPoint = insertionPoint;
			break;
		case key_right: case key_word_right:
			if(current_action) history.add(current_action), current_action.reset();
			if(haveSelection && !select) {
				selectionPoint = insertionPoint = std::max(selectionPoint,insertionPoint);
				break;
			}
			new_ip = select ? selectionPoint : insertionPoint;
			if(new_ip == contents.length()) break;
			if(key.k == key_word_right) {
				new_ip++;
				while(new_ip < contents.length() && contents[new_ip] != ' ')
					new_ip++;
			} else new_ip++;
			(select ? selectionPoint : insertionPoint) = new_ip;
			if(!select) selectionPoint = insertionPoint;
			break;
		case key_up:
			if(current_action) history.add(current_action), current_action.reset();
			if(haveSelection && !select)
				selectionPoint = insertionPoint = std::min(selectionPoint,insertionPoint);
			if(snippets[ip_row].at.y == snippets[0].at.y) {
				key.k = key_top;
				if(select) key.mod += mod_shift;
				handleInput(key);
			} else {
				int x = snippets[ip_row].at.x + ip_col, y = snippets[ip_row].at.y - 10;
				set_ip(loc(x,y), select ? &cTextField::selectionPoint : &cTextField::insertionPoint);
				if(!select) selectionPoint = insertionPoint;
			}
			break;
		case key_down:
			if(current_action) history.add(current_action), current_action.reset();
			if(haveSelection && !select)
				selectionPoint = insertionPoint = std::max(selectionPoint,insertionPoint);
			if(snippets[ip_row].at.y == snippets.back().at.y) {
				key.k = key_bottom;
				if(select) key.mod += mod_shift;
				handleInput(key);
			} else {
				int x = snippets[ip_row].at.x + ip_col, y = snippets[ip_row].at.y + 20;
				set_ip(loc(x,y), select ? &cTextField::selectionPoint : &cTextField::insertionPoint);
				if(!select) selectionPoint = insertionPoint;
			}
			break;
		case key_bsp: case key_word_bsp:
		case key_del: case key_word_del:
			if(haveSelection) {
				if(key.k == key_word_bsp)
					handleInput({true, key_word_left, mod_shift});
				else if(key.k == key_word_del)
					handleInput({true, key_word_right, mod_shift});
				auto begin = contents.begin() + std::min(selectionPoint, insertionPoint);
				auto end = contents.begin() + std::max(selectionPoint, insertionPoint);
				std::string removed(begin, end);
				auto result = contents.erase(begin, end);
				bool dir = insertionPoint < selectionPoint;
				selectionPoint = insertionPoint = result - contents.begin();
				if(current_action) history.add(current_action), current_action.reset();
				history.add(action_ptr(new aTextDelete(*this, std::min(selectionPoint, insertionPoint), removed, dir)));
			} else if(key.k == key_word_bsp) {
				cKey selectKey = key;
				selectKey.k = key_word_left;
				selectKey.mod = mod_shift;
				key.k = key_bsp;
				handleInput(selectKey);
				if(selectionPoint != insertionPoint)
					handleInput(key);
				return;
			} else if(key.k == key_bsp) {
				if(insertionPoint == 0) break;
				char c = contents[insertionPoint - 1];
				contents.erase(insertionPoint - 1,1);
				selectionPoint = --insertionPoint;
				if(aTextDelete* del = dynamic_cast<aTextDelete*>(current_action.get()))
					del->append_front(c);
				else {
					if(current_action) history.add(current_action);
					aTextDelete* new_del = new aTextDelete(*this, insertionPoint + 1, insertionPoint + 1);
					new_del->append_front(c);
					current_action.reset(new_del);
				}
			} else if(key.k == key_word_del) {
				cKey selectKey = key;
				selectKey.k = key_word_right;
				selectKey.mod = mod_shift;
				key.k = key_del;
				handleInput(selectKey);
				if(selectionPoint != insertionPoint)
					handleInput(key);
				return;
			} else if(key.k == key_del) {
				if(insertionPoint == contents.length()) break;
				char c = contents[insertionPoint];
				contents.erase(insertionPoint,1);
				if(aTextDelete* del = dynamic_cast<aTextDelete*>(current_action.get()))
					del->append_back(c);
				else {
					if(current_action) history.add(current_action);
					aTextDelete* new_del = new aTextDelete(*this, insertionPoint, insertionPoint);
					new_del->append_back(c);
					current_action.reset(new_del);
				}
			}
			break;
		case key_top:
			if(current_action) history.add(current_action), current_action.reset();
			if(!select) insertionPoint = 0;
			selectionPoint = 0;
			break;
		case key_bottom:
			if(current_action) history.add(current_action), current_action.reset();
			if(!select) insertionPoint = contents.length();
			selectionPoint = contents.length();
			break;
		case key_end:
			if(current_action) history.add(current_action), current_action.reset();
			new_ip = snippets[ip_row].at.x + string_length(snippets[ip_row].text, style);
			set_ip(loc(new_ip, snippets[ip_row].at.y), select ? &cTextField::selectionPoint : &cTextField::insertionPoint);
			if(!select) selectionPoint = insertionPoint;
			break;
		case key_home:
			if(current_action) history.add(current_action), current_action.reset();
			set_ip(snippets[ip_row].at, select ? &cTextField::selectionPoint : &cTextField::insertionPoint);
			if(!select) selectionPoint = insertionPoint;
			break;
		case key_pgup:
			if(current_action) history.add(current_action), current_action.reset();
			if(snippets[ip_row].at.y != snippets[0].at.y) {
				int x = snippets[ip_row].at.x + ip_col, y = frame.top + 2;
				set_ip(loc(x,y), select ? &cTextField::selectionPoint : &cTextField::insertionPoint);
				if(!select) selectionPoint = insertionPoint;
			}
			break;
		case key_pgdn:
			if(current_action) history.add(current_action), current_action.reset();
			if(snippets[ip_row].at.y != snippets.back().at.y) {
				int x = snippets[ip_row].at.x + ip_col, y = frame.bottom - 2;
				set_ip(loc(x,y), select ? &cTextField::selectionPoint : &cTextField::insertionPoint);
				if(!select) selectionPoint = insertionPoint;
			}
			break;
		case key_copy:
		case key_cut:
			if(current_action) history.add(current_action), current_action.reset();
			set_clipboard(contents.substr(std::min(insertionPoint,selectionPoint), abs(insertionPoint - selectionPoint)));
			if(key.k == key_cut) {
				cKey deleteKey = key;
				deleteKey.k = key_bsp;
				handleInput(deleteKey);
				contents = getText();
			}
			break;
		case key_paste:
			if(current_action) history.add(current_action), current_action.reset();
			if(!get_clipboard().empty()) {
				if(haveSelection) {
					cKey deleteKey = {true, key_bsp, mod_none};
					handleInput(deleteKey);
				}
				contents = getText();
				std::string toInsert = get_clipboard();
				contents.insert(insertionPoint, toInsert);
				history.add(action_ptr(new aTextInsert(*this, insertionPoint, toInsert)));
				insertionPoint += toInsert.length();
				selectionPoint = insertionPoint;
			}
			break;
		case key_undo:
			if(current_action) history.add(current_action), current_action.reset();
			history.undo();
			return;
		case key_redo:
			if(current_action) history.add(current_action), current_action.reset();
			history.redo();
			return;
		case key_selectall:
			if(current_action) history.add(current_action), current_action.reset();
			selectionPoint = 0;
			insertionPoint = contents.length();
			break;
			// These keys have no function in this context.
		case key_esc:
		case key_tab:
		case key_help:
		case key_insert:
			break;
	}
	// Setting the text normally resets insertion/selection point, but we don't want that here.
	int ip = insertionPoint, sp = selectionPoint;
	setText(contents);
	insertionPoint = ip;
	selectionPoint = sp;
}
Beispiel #2
0
void ShaderProgram::arg(const GLchar * name, const GLfloat value) {
	CHECK_CONTEXT;
    _context->glUniform1f(loc(name),value);
    _context->check_error(string("setting uniform variable: ") + name);
}
Beispiel #3
0
/*
 * Request a "movement" direction (1,2,3,4,6,7,8,9) from the user.
 *
 * Return TRUE if a direction was chosen, otherwise return FALSE.
 *
 * This function should be used for all "repeatable" commands, such as
 * run, walk, open, close, bash, disarm, spike, tunnel, etc, as well
 * as all commands which must reference a grid adjacent to the player,
 * and which may not reference the grid under the player.
 *
 * Directions "5" and "0" are illegal and will not be accepted.
 *
 * This function tracks and uses the "global direction", and uses
 * that as the "desired direction", if it is set.
 */
bool get_rep_dir(int *dp)
{
	int dir = 0;

	ui_event ke;

	/* Initialize */
	(*dp) = 0;

	/* Get a direction */
	while (!dir)
	{
		/* Paranoia XXX XXX XXX */
		message_flush();

		/* Get first keypress - the first test is to avoid displaying the
		   prompt for direction if there's already a keypress queued up
		   and waiting - this just avoids a flickering prompt if there is
		   a "lazy" movement delay. */
		inkey_scan = SCAN_INSTANT;
		ke = inkey_ex();
		inkey_scan = SCAN_OFF;

		if (ke.type == EVT_NONE ||
				(ke.type == EVT_KBRD && target_dir(ke.key) == 0))
		{
			prt("Direction or <click> (Escape to cancel)? ", 0, 0);
			ke = inkey_ex();
		}

		/* Check mouse coordinates */
		if (ke.type == EVT_MOUSE) {
			if (ke.mouse.button == 1) {
				int y = KEY_GRID_Y(ke);
				int x = KEY_GRID_X(ke);
				struct loc from = loc(p_ptr->px, p_ptr->py);
				struct loc to = loc(x, y);

				dir = pathfind_direction_to(from, to);
			} else
			if (ke.mouse.button == 2) {
				/* Clear the prompt */
				prt("", 0, 0);

				return (FALSE);
			}
		}

		/* Get other keypresses until a direction is chosen. */
		else if (ke.type == EVT_KBRD)
		{
			int keypresses_handled = 0;

			while (ke.type == EVT_KBRD && ke.key.code != 0)
			{
				int this_dir;

				if (ke.key.code == ESCAPE) 
				{
					/* Clear the prompt */
					prt("", 0, 0);

					return (FALSE);
				}

				/* XXX Ideally show and move the cursor here to indicate 
				   the currently "Pending" direction. XXX */
				this_dir = target_dir(ke.key);

				if (this_dir)
					dir = dir_transitions[dir][this_dir];

				if (lazymove_delay == 0 || ++keypresses_handled > 1)
					break;

				inkey_scan = lazymove_delay; 
				ke = inkey_ex();
			}

			/* 5 is equivalent to "escape" */
			if (dir == 5)
			{
				/* Clear the prompt */
				prt("", 0, 0);

				return (FALSE);
			}
		}

		/* Oops */
		if (!dir) bell("Illegal repeatable direction!");
	}

	/* Clear the prompt */
	prt("", 0, 0);

	/* Save direction */
	(*dp) = dir;

	/* Success */
	return (TRUE);
}
// -----------------------------------------------------------------------
// Construct a fully qualified table name.
// -----------------------------------------------------------------------
Lng32 AddTableName( const hs_table_type type
                 , const char *table
                 , const char *schema
                 , const char *catalog
                 )
  {
    HSGlobalsClass *hs_globals = GetHSContext();
    
    NAString catName, schName, objName;
    NAString extName;
    NAString defaultCat, defaultSch;
    NAString userLocation;
    Lng32 retcode = 0;

    hs_globals->tableType = type;
    HSLogMan *LM = HSLogMan::Instance();
  
    // SET MPLOC is converted to CQD (setting values for default
    // attributes MP_SYSTEM, MP_VOLUME, MP_SUBVOLUME).  It does not
    // update the global MPLOC value stored in SqlParser_MPLOC.  The
    // following updates the global MPLOC value to be consistent with
    // the default attribute values set by SET MPLOC/CQD.
    ActiveSchemaDB()->getDefaults().getSqlParser_NADefaults();

    if (type == GUARDIAN_TABLE)
      {
        if (*table == '$')
          { // Qualify with system name.
            extName  = SqlParser_MPLOC.getSystemName();
            extName += ".";
            extName += table;
          }
        else
          extName = table;
        hs_globals->tableFormat = SQLMP;
      }
    else
      {
        // When CQD DEFAULT_SCHEMA_ACCESS_ONLY is on, 
        // users cannot update stats on tables not in the default/public schemas.
        if ( schema && 
             ActiveSchemaDB()->getDefaults().getToken(DEFAULT_SCHEMA_ACCESS_ONLY)==DF_ON )
        {
          SchemaName objSchName;
          NAString curSchName(schema);
          NAString curCatName;
          objSchName.setSchemaName(curSchName);
          if (catalog)
          {
            curCatName = catalog;
            objSchName.setCatalogName(curCatName);
          }
          else
            curCatName = ActiveSchemaDB()->getDefaultSchema().getCatalogName();

          // If the schema is neither default nor public,
          // issue inaccessible error.
          if (!objSchName.matchDefaultPublicSchema())
          {
            NAString dataObj(curCatName);
            if (!dataObj.isNull()) dataObj += ".";
            dataObj += curSchName + ".";
            dataObj += table;
            HSFuncMergeDiags(-UERR_OBJECT_INACCESSIBLE, dataObj.data());
            retcode = -1;
            HSHandleError(retcode);
          }
        }

        if (catalog)
          catName = catalog;
        else
          {
            // LCOV_EXCL_START :nsk
            if (SqlParser_NAMETYPE == DF_NSK)
              {
                catName = SqlParser_MPLOC.getSysDotVol();
                hs_globals->tableType = GUARDIAN_TABLE;
                hs_globals->tableFormat = SQLMP;
              }
            else
            // LCOV_EXCL_STOP
              catName = ActiveSchemaDB()->getDefaultSchema().getCatalogName();
          }
  
        if (schema) 
          schName = schema;
        else
          {
            // LCOV_EXCL_START :nsk
            if (SqlParser_NAMETYPE == DF_NSK)
              {
                schName = SqlParser_MPLOC.getSubvolName();
                hs_globals->tableFormat = SQLMP;
              }
            else
            // LCOV_EXCL_STOP
              schName = ActiveSchemaDB()->getDefaultSchema().getSchemaName();
          }
  
        objName = table;
        extName = catName + "." + schName + "." + objName;
      }
  
    // LCOV_EXCL_START :nsk
    if (hs_globals->tableFormat == SQLMP)
      {
        ComMPLoc loc(extName, ComMPLoc::FILE);
        if (loc.getFormat() == ComMPLoc::INVALID)
          {
            HSFuncMergeDiags(-UERR_OBJECT_INACCESSIBLE, extName);
            retcode = -1;
            HSHandleError(retcode);
          }
  
        catName = loc.getSysDotVol();
        schName = loc.getSubvolName();
        objName = loc.getFileName();
      }
    // LCOV_EXCL_STOP

    hs_globals->objDef = NULL;
    
    // Search in volatile schema first. If not found, search in regular cat/sch.
    if ((CmpCommon::context()->sqlSession()->volatileSchemaInUse()) &&
        (type != GUARDIAN_TABLE) &&
        (! catalog))
      {
        // search using the volatile schema name.
        NAString &volCatName = CmpCommon::context()->sqlSession()->volatileCatalogName();
        NAString &volSchName = CmpCommon::context()->sqlSession()->volatileSchemaName();
        NAString volObjName = table;
	
        
        ComObjectName volIntName(volCatName, volSchName, volObjName,
                                 COM_UNKNOWN_NAME, 
                                 ComAnsiNamePart::INTERNAL_FORMAT);
        if (NOT volIntName.isValid())
          {
            LM->Log("***[ERROR] Unable to create an ObjectClass");
            HSFuncMergeDiags(-UERR_OBJECT_INACCESSIBLE, extName);
            retcode = -1;
            HSHandleError(retcode);
          }
	
        if (LM->LogNeeded())
          {
            LM->Log("Searching in volatile schema, since catalog not specified.\n");
            sprintf(LM->msg, "Checking volatile name (volIntName) %s.%s.%s\n",
                    volIntName.getCatalogNamePart().getInternalName().data(),
                    volIntName.getSchemaNamePart().getInternalName().data(),
                    volIntName.getObjectNamePart().getInternalName().data());
            LM->Log(LM->msg);
          }

        hs_globals->objDef = HSTableDef::create(STMTHEAP,
                                                volIntName,
                                                hs_globals->tableType,
                                                hs_globals->nameSpace);

      	if (NOT hs_globals->objDef->objExists(hs_globals->isUpdatestatsStmt))
          {
            // now look into the regular schema
            delete hs_globals->objDef;
            hs_globals->objDef = NULL;
          }
        else 
          {
            // if schema name was specified, validate that it is the
            // current username.
            if (schema)
              {
                QualifiedName qn(volObjName, schName);
                if (NOT CmpCommon::context()->sqlSession()->validateVolatileQualifiedName(qn))
                  {
                    // table was found in the volatile schema but it is
                    // not a valid volatile name.
                    // Look for it in regular schema.
                    // error info was moved to CmpCommon::diags. Clear it.
                    CmpCommon::diags()->clear();
                    delete hs_globals->objDef;
                    hs_globals->objDef = NULL;
                  }
              }
          }
      }      
    
    if (hs_globals->objDef == NULL)
      {
	ComObjectName intName(catName, schName, objName,
			      COM_UNKNOWN_NAME, 
			      ComAnsiNamePart::INTERNAL_FORMAT);
	if (NOT intName.isValid())
	  {
	    LM->Log("***[ERROR] Unable to create an ObjectClass");
	    HSFuncMergeDiags(-UERR_OBJECT_INACCESSIBLE, extName);
	    retcode = -1;
	    HSHandleError(retcode);
	  }
	

       hs_globals->objDef = HSTableDef::create(STMTHEAP,
                                          intName,
                                          hs_globals->tableType,
                                          hs_globals->nameSpace);

       // try public schema if an object is not qualified and not found
       if ((NOT schema) && 
           (NOT hs_globals->objDef->objExists(hs_globals->isUpdatestatsStmt)))
       {
          NAString pubSch = ActiveSchemaDB()->getDefaults().getValue(PUBLIC_SCHEMA_NAME);
          ComSchemaName pubSchema(pubSch);
          if (NOT pubSchema.getSchemaNamePart().isEmpty())
          {
            NAString pubSchName = pubSchema.getSchemaNamePart().getInternalName();
            NAString pubCatName = (pubSchema.getCatalogNamePart().isEmpty() ? 
              catName:pubSchema.getCatalogNamePart().getInternalName());
      	    ComObjectName pubIntName(pubCatName, pubSchName, objName,
                                     COM_UNKNOWN_NAME, ComAnsiNamePart::INTERNAL_FORMAT);
	      
            if (pubIntName.isValid())
	     {
                HSTableDef *pubObjDef = HSTableDef::create(STMTHEAP,
                                                           pubIntName, 
                                                           hs_globals->tableType,
                                                           hs_globals->nameSpace);

                if (pubObjDef->objExists(hs_globals->isUpdatestatsStmt))
                {
                  hs_globals->objDef = pubObjDef;
                }
	     }
          }
       }

      if (NOT hs_globals->objDef->objExists(hs_globals->isUpdatestatsStmt))
      {
         HSFuncMergeDiags(-UERR_OBJECT_INACCESSIBLE, extName);
         retcode = -1;
         HSHandleError(retcode);
      }
    }

    //10-040123-2660 We only support tables. We do not allow views.
    // Tables can be metadata tables.
    if ((hs_globals->objDef->getObjectType() != COM_BASE_TABLE_OBJECT) &&
        (hs_globals->objDef->getObjectType() != COM_MV_OBJECT)) 
      {
        HSFuncMergeDiags(-UERR_INVALID_OBJECT, extName);
        retcode = -1;
        HSHandleError(retcode);
      }
    retcode = hs_globals->objDef->getColumnNames();
    HSFuncExecQuery("CONTROL QUERY DEFAULT DISPLAY_DIVISION_BY_COLUMNS RESET");
    HSHandleError(retcode);

    hs_globals->tableFormat = hs_globals->objDef->getObjectFormat();
    *hs_globals->catSch     = hs_globals->objDef->getPrimaryLoc(HSTableDef::EXTERNAL_FORMAT);
    *hs_globals->user_table = hs_globals->objDef->getObjectFullName();
    hs_globals->tableFormat = hs_globals->objDef->getObjectFormat();
    hs_globals->isHbaseTable = HSGlobalsClass::isHbaseCat(catName);
    hs_globals->isHiveTable = HSGlobalsClass::isHiveCat(catName);

    if (hs_globals->tableFormat == SQLMX)
      {
        // Determine the schema version for this MX table.
        if (LM->LogNeeded())
         {
            sprintf(LM->msg, "\nCHECK SCHEMA VERSION FOR TABLE: %s\n", 
              hs_globals->user_table->data());
            LM->Log(LM->msg);
         }
        HSGlobalsClass::schemaVersion = getTableSchemaVersion(hs_globals->user_table->data());
        // LCOV_EXCL_START :rfi
        if (HSGlobalsClass::schemaVersion == COM_VERS_UNKNOWN)
        {
           HSFuncMergeDiags(-UERR_INTERNAL_ERROR, "GET_SCHEMA_VERSION");
           return -1;
        }
        // LCOV_EXCL_STOP


        if (HSGlobalsClass::schemaVersion >= COM_VERS_2300) 
          HSGlobalsClass::autoInterval = CmpCommon::getDefaultLong(USTAT_AUTOMATION_INTERVAL);
        if (LM->LogNeeded())
         {
            sprintf(LM->msg, "\nUpdateStats: TABLE: %s; SCHEMA VERSION: %d; AUTOMATION INTERVAL: %d\n", 
                  hs_globals->user_table->data(), 
                  HSGlobalsClass::schemaVersion, HSGlobalsClass::autoInterval);
            LM->Log(LM->msg);
         }

        NAString catName(hs_globals->objDef->getCatName());

        *hs_globals->hstogram_table = getHistogramsTableLocation(hs_globals->catSch->data(), FALSE);

        *hs_globals->hsintval_table = getHistogramsTableLocation(hs_globals->catSch->data(), FALSE);

        NABoolean isHbaseOrHive = HSGlobalsClass::isHbaseCat(catName) ||
                                  HSGlobalsClass::isHiveCat(catName);

        if (isHbaseOrHive) {
          hs_globals->hstogram_table->append(".").append(HBASE_HIST_NAME);
          hs_globals->hsintval_table->append(".").append(HBASE_HISTINT_NAME);
        } else {
          hs_globals->hstogram_table->append(".HISTOGRAMS");
          hs_globals->hsintval_table->append(".HISTOGRAM_INTERVALS");
        }
      }
    else
      {
        // LCOV_EXCL_START :nsk
        *hs_globals->hstogram_table = hs_globals->objDef->getCatalogLoc(HSTableDef::EXTERNAL_FORMAT);
        hs_globals->hstogram_table->append(".HISTOGRM");
        
        *hs_globals->hsintval_table = hs_globals->objDef->getCatalogLoc(HSTableDef::EXTERNAL_FORMAT);
        hs_globals->hsintval_table->append(".HISTINTS");        

        // RESET CQDS:
        HSFuncExecQuery("CONTROL QUERY DEFAULT ALLOW_DP2_ROW_SAMPLING RESET");
        HSFuncExecQuery("CONTROL QUERY DEFAULT POS RESET");
        HSFuncExecQuery("CONTROL QUERY DEFAULT POS_NUM_OF_PARTNS RESET");
        // LCOV_EXCL_STOP
      }
  
    return 0;
  }
  // callback for messages
  void PeopleTrackingNode::callbackRcv(const cob_perception_msgs::PositionMeasurement::ConstPtr& message)
  {
    ROS_DEBUG("Tracking node got a people position measurement (%f,%f,%f)",
	      message->pos.x, message->pos.y, message->pos.z);
    // get measurement in fixed frame
    Stamped<tf::Vector3> meas_rel, meas;
    meas_rel.setData(
		     tf::Vector3(message->pos.x, message->pos.y, message->pos.z));
    meas_rel.stamp_ = message->header.stamp;
    meas_rel.frame_id_ = message->header.frame_id;
    robot_state_.transformPoint(fixed_frame_, meas_rel, meas);
    
    // get measurement covariance
    SymmetricMatrix cov(3);
    for (unsigned int i = 0; i < 3; i++)
      for (unsigned int j = 0; j < 3; j++)
	cov(i + 1, j + 1) = message->covariance[3 * i + j];
    
    // ----- LOCKED ------
    boost::mutex::scoped_lock lock(filter_mutex_);

    // update tracker if matching tracker found
    for (list<Tracker*>::iterator it = trackers_.begin(); it != trackers_.end(); it++)
      if ((*it)->getName() == message->object_id) {
	(*it)->updatePrediction(message->header.stamp.toSec());
	(*it)->updateCorrection(meas, cov);
      }
    // check if reliable message with no name should be a new tracker
    if (message->object_id == "" && message->reliability > reliability_threshold_) {
      double closest_tracker_dist = start_distance_min_;
      StatePosVel est;
      for (list<Tracker*>::iterator it = trackers_.begin(); it != trackers_.end(); it++) {
	(*it)->getEstimate(est);
	double dst = sqrt(pow(est.pos_[0] - meas[0], 2) + pow(est.pos_[1] - meas[1], 2));
	if (dst < closest_tracker_dist)
	  closest_tracker_dist = dst;
      }
      // initialize a new tracker
      if (follow_one_person_)
	cout << "Following one person" << endl;
      if (message->initialization == 1 && ((!follow_one_person_ && (closest_tracker_dist >= start_distance_min_)) || (follow_one_person_ && trackers_.empty()))) {
	//if (closest_tracker_dist >= start_distance_min_ || message->initialization == 1){
	//if (message->initialization == 1 && trackers_.empty()){
	ROS_INFO("Passed crazy conditional.");
	tf::Point pt;
	tf::pointMsgToTF(message->pos, pt);
	tf::Stamped<tf::Point> loc(pt, message->header.stamp, message->header.frame_id);
	robot_state_.transformPoint("base_link", loc, loc);
	float cur_dist;
	if ((cur_dist = pow(loc[0], 2.0) + pow(loc[1], 2.0)) < tracker_init_dist) {
	  
	  cout << "starting new tracker" << endl;
	  stringstream tracker_name;
	  StatePosVel prior_sigma(tf::Vector3(sqrt(cov(1, 1)), sqrt(cov(
									2, 2)), sqrt(cov(3, 3))), tf::Vector3(0.0000001, 0.0000001, 0.0000001));
	  tracker_name << "person " << tracker_counter_++;
	  Tracker* new_tracker = new TrackerKalman(tracker_name.str(),
						   sys_sigma_);
	  //Tracker* new_tracker = new TrackerParticle(tracker_name.str(), num_particles_tracker, sys_sigma_);
	  new_tracker->initialize(meas, prior_sigma,
				  message->header.stamp.toSec());
	  trackers_.push_back(new_tracker);
	  ROS_INFO("Initialized new tracker %s", tracker_name.str().c_str());
	}
	else
	  ROS_INFO("Found a person, but he/she is not close enough to start following.  Person is %f away, and must be less than %f away.", cur_dist , tracker_init_dist);
      }
      else
	ROS_INFO("Failed crazy conditional.");
    }
    lock.unlock();
    // ------ LOCKED ------
    

    // visualize measurement
    meas_cloud_.points[0].x = meas[0];
    meas_cloud_.points[0].y = meas[1];
    meas_cloud_.points[0].z = meas[2];
    meas_cloud_.header.frame_id = meas.frame_id_;
    people_tracker_vis_pub_.publish(meas_cloud_);
  }
Beispiel #6
0
  int Q5CG = Q4FU + 0x01;
  loc Q5C0 = loc( Q4FS, Q4FT, Q5CG );
  loc trapLocation = loc( 0x14CB, 0x023C, 0x00 );
  list Q5DQ;
  if(!hasObjVar(this, "working"))
  {
    bark(this, "SOUND EFFECT");
    callback(this, 0x05, 0x01);
    int Q64U = teleport(this, Q5C0);
    messageToRange(trapLocation, 0x0A, "disarm", Q5DQ);
    setObjVar(this, "working", 0x01);
  }
  return(0x01);
}

TRIGGER( callback , 0x01 )()
{
  int Q4FS = getX(getLocation(this));
  int Q4FT = getY(getLocation(this));
  int Q4FU = getZ(getLocation(this));
  int Q5CG = Q4FU - 0x01;
  loc Q5C0 = loc( Q4FS, Q4FT, Q5CG );
  bark(this, "SOUND EFFECT");
  bark(this, "returning");
  if(hasObjVar(this, "working"))
  {
    removeObjVar(this, "working");
  }
  int Q64U = teleport(this, Q5C0);
  return(0x01);
}
//------------------------------------------------------------------------------
// processDetonationPDU() callback --
//------------------------------------------------------------------------------
void NetIO::processDetonationPDU(const DetonationPDU* const pdu)
{

   // Get the Firing Player's ID
   unsigned short fPlayerId = pdu->firingEntityID.ID;
   unsigned short fSiteId = pdu->firingEntityID.simulationID.siteIdentification;
   unsigned short fApplicationId = pdu->firingEntityID.simulationID.applicationIdentification;

   // Ignore our own PDUs
   if (fSiteId == getSiteID() && fApplicationId == getApplicationID()) return;

   // Get the Munition Player's ID
   unsigned short mPlayerId = pdu->munitionID.ID;
   unsigned short mSiteId = pdu->munitionID.simulationID.siteIdentification;
   unsigned short mApplicationId = pdu->munitionID.simulationID.applicationIdentification;

   // Get the Target Player's ID
   unsigned short tPlayerId = pdu->targetEntityID.ID;
   unsigned short tSiteId = pdu->targetEntityID.simulationID.siteIdentification;
   unsigned short tApplicationId = pdu->targetEntityID.simulationID.applicationIdentification;

   // ---
   // 1) Find the target player
   // ---
   Simulation::Player* tPlayer = 0;
   if (tPlayerId != 0 && tSiteId != 0 && tApplicationId != 0) {
      Simulation::Nib* tNib = findDisNib(tPlayerId, tSiteId, tApplicationId, OUTPUT_NIB);
      if (tNib != 0) {
         tPlayer = tNib->getPlayer();
      }
   }
   //std::cout << "Net kill(2) tPlayer = " << tPlayer << std::endl;

   // ---
   // 2) Find the firing player and munitions (networked) IPlayers
   // ---
   Simulation::Player* fPlayer = 0;
   if (fPlayerId != 0 && fSiteId != 0 && fApplicationId != 0) {
      Simulation::Nib* fNib = findDisNib(fPlayerId, fSiteId, fApplicationId, INPUT_NIB);
      if (fNib != 0) {
         fPlayer = fNib->getPlayer();
      }
      else {
         SPtr<Basic::PairStream> players( getSimulation()->getPlayers() );
         fPlayer = getSimulation()->findPlayer(fPlayerId);
      }
   }

   Simulation::Nib* mNib = 0;
   if (mPlayerId != 0 && mSiteId != 0 && mApplicationId != 0) {
      mNib = findDisNib(mPlayerId, mSiteId, mApplicationId, INPUT_NIB);
   }

    //std::cout << "Net kill(3) fNib = " << fNib << ", mNib = " << mNib << std::endl;

   // ---
   // 3) Update the data of the munition's NIB and player
   // ---
   Simulation::Weapon* mPlayer = 0;
   if (mNib != 0) {

      // ---
      // a) Set the munition's NIB to the location of the detonation
      // ---

      // Get the geocentric position, velocity and acceleration from the PDU
      osg::Vec3d geocPos;
      geocPos[Basic::Nav::IX] = pdu->location.X_coord;
      geocPos[Basic::Nav::IY] = pdu->location.Y_coord;
      geocPos[Basic::Nav::IZ] = pdu->location.Z_coord;

      osg::Vec3d geocVel;
      geocVel[Basic::Nav::IX] = pdu->velocity.component[0];
      geocVel[Basic::Nav::IY] = pdu->velocity.component[1];
      geocVel[Basic::Nav::IZ] = pdu->velocity.component[2];

      osg::Vec3d geocAcc(0,0,0);
      osg::Vec3d geocAngles(0,0,0);
      osg::Vec3d arates(0,0,0);

      // (re)initialize the dead reckoning function
      mNib->resetDeadReckoning(
         Simulation::Nib::STATIC_DRM,
         geocPos,
         geocVel,
         geocAcc,
         geocAngles,
         arates);

      // Set the NIB's mode to DETONATED
      mNib->setMode(Simulation::Player::DETONATED);

      // Find the munition player and set its mode, location and target position
      mPlayer = dynamic_cast<Simulation::Weapon*>(mNib->getPlayer());
      if (mPlayer != 0) {

         // Munition's mode
         mPlayer->setMode(Simulation::Player::DETONATED);

         // munition's position, velocity and acceleration at the time of the detonation
         mPlayer->setGeocPosition(geocPos);
         mPlayer->setGeocVelocity(geocVel);
         mPlayer->setGeocAcceleration(geocAcc);

         // detonation results
         mPlayer->setDetonationResults(Simulation::Weapon::Detonation(pdu->detonationResult));

         // Munition's target player and the location of detonation relative to target
         mPlayer->setTargetPlayer(tPlayer,false);
         LCreal x = pdu->locationInEntityCoordinates.component[0];
         LCreal y = pdu->locationInEntityCoordinates.component[1];
         LCreal z = pdu->locationInEntityCoordinates.component[2];
         osg::Vec3 loc(x,y,z);
         mPlayer->setDetonationLocation(loc);

         // Munition's launcher
         if (mPlayer->getLaunchVehicle() == 0 && fPlayer != 0) {
            mPlayer->setLaunchVehicle(fPlayer);
         }
      }
   }

   // ---
   // 4) Check all local players for the effects of the detonation
   // ---
   if (mPlayer != 0) {
      mPlayer->checkDetonationEffect();
   }
}
Beispiel #8
0
	SECTION("Basic header data") {
		CHECK(scen.adjust_diff);
		CHECK(scen.bg_dungeon == 9);
		CHECK(scen.bg_fight == 4);
		CHECK(scen.bg_out == 10);
		CHECK(scen.bg_town == 13);
		CHECK(scen.campaign_id.empty());
		CHECK(scen.custom_graphics.empty());
		CHECK(scen.default_ground == 0);
		CHECK(scen.difficulty == 1);
		CHECK(scen.init_spec == -1);
		CHECK(scen.intro_mess_pic == 27);
		CHECK(scen.intro_pic == 27);
		CHECK(scen.is_legacy);
		CHECK(scen.journal_strs.empty());
		CHECK(scen.last_out_edited == loc(1,1));
		CHECK(scen.last_town_edited == 2);
		CHECK(scen.out_sec_start == loc(4,4));
		CHECK(scen.out_start == loc(1,1));
		CHECK(scen.rating == eContentRating::R);
		CHECK(scen.shops.empty());
		CHECK_FALSE(scen.uses_custom_graphics);
		CHECK(scen.where_start == loc(3,3));
		CHECK(scen.which_town_start == 3);
	}
	SECTION("With boats") {
		REQUIRE(scen.boats.size() >= 1);
		CHECK(scen.boats[0].exists);
		CHECK(scen.boats[0].loc == loc(33,33));
		// TODO: This field is meaningless in legacy scenario boats but matters in legacy svaed game boats.
//		CHECK(scen.boats[0].loc_in_sec == loc(22,22));
Beispiel #9
0
/// Download preview & get timestamp if newer than cachefile's
/// last modified time, otherwise just get the timestamp
QDateTime RemoteGetPreviewIfModified(
    const ProgramInfo &pginfo, const QString &cachefile)
{
    QString loc("RemoteGetPreviewIfModified: ");
    QDateTime cacheLastModified;
    QFileInfo cachefileinfo(cachefile);
    if (cachefileinfo.exists())
        cacheLastModified = cachefileinfo.lastModified();

    QStringList strlist("QUERY_PIXMAP_GET_IF_MODIFIED");
    strlist << ((cacheLastModified.isValid()) ? // unix secs, UTC
                QString::number(cacheLastModified.toTime_t()) : QString("-1"));
    strlist << QString::number(200 * 1024); // max size of preview file
    pginfo.ToStringList(strlist);

    if (!gCoreContext->SendReceiveStringList(strlist) ||
        strlist.empty() || strlist[0] == "ERROR")
    {
        LOG(VB_GENERAL, LOG_ERR, loc + "Remote error" +
            ((strlist.size() >= 2) ? (":\n\t\t\t" + strlist[1]) : ""));

        return QDateTime();
    }

    if (strlist[0] == "WARNING")
    {
        LOG(VB_NETWORK, LOG_WARNING, loc + "Remote warning" +
                 ((strlist.size() >= 2) ? (":\n\t\t\t" + strlist[1]) : ""));

        return QDateTime();
    }

    QDateTime retdatetime;
    qlonglong timet = strlist[0].toLongLong();
    if (timet >= 0)
        retdatetime.setTime_t(timet);

    if (strlist.size() < 4)
    {
        return retdatetime;
    }

    size_t  length     = strlist[1].toULongLong();
    quint16 checksum16 = strlist[2].toUInt();
    QByteArray data = QByteArray::fromBase64(strlist[3].toAscii());
    if ((size_t) data.size() < length)
    { // (note data.size() may be up to 3 bytes longer after decoding
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Preview size check failed %1 < %2")
                .arg(data.size()).arg(length));
        return QDateTime();
    }
    data.resize(length);

    if (checksum16 != qChecksum(data.constData(), data.size()))
    {
        LOG(VB_GENERAL, LOG_ERR, loc + "Preview checksum failed");
        return QDateTime();
    }

    QString pdir(cachefile.section("/", 0, -2));
    QDir cfd(pdir);
    if (!cfd.exists() && !cfd.mkdir(pdir))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Unable to create remote cache directory '%1'")
                .arg(pdir));

        return QDateTime();
    }

    QFile file(cachefile);
    if (!file.open(QIODevice::WriteOnly|QIODevice::Truncate))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Unable to open cached preview file for writing '%1'")
                .arg(cachefile));

        return QDateTime();
    }

    off_t offset = 0;
    size_t remaining = length;
    uint failure_cnt = 0;
    while ((remaining > 0) && (failure_cnt < 5))
    {
        ssize_t written = file.write(data.data() + offset, remaining);
        if (written < 0)
        {
            failure_cnt++;
            usleep(50000);
            continue;
        }

        failure_cnt  = 0;
        offset      += written;
        remaining   -= written;
    }

    if (remaining)
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Failed to write cached preview file '%1'")
                .arg(cachefile));

        file.resize(0); // in case unlink fails..
        file.remove();  // closes fd
        return QDateTime();
    }

    file.close();

    return retdatetime;
}
Beispiel #10
0
/**
 * Add an item to the players inventory.
 *
 * If the new item can combine with an existing item in the inventory,
 * it will do so, using object_similar() and object_absorb(), else,
 * the item will be placed into the first available gear array index.
 *
 * This function can be used to "over-fill" the player's pack, but only
 * once, and such an action must trigger the "overflow" code immediately.
 * Note that when the pack is being "over-filled", the new item must be
 * placed into the "overflow" slot, and the "overflow" must take place
 * before the pack is reordered, but (optionally) after the pack is
 * combined.  This may be tricky.  See "dungeon.c" for info.
 *
 * Note that this code removes any location information from the object once
 * it is placed into the inventory, but takes no responsibility for removing
 * the object from any other pile it was in.
 */
void inven_carry(struct player *p, struct object *obj, bool absorb,
				 bool message)
{
	bool combining = false;

	/* Check for combining, if appropriate */
	if (absorb) {
		struct object *combine_item = NULL;

		struct object *gear_obj = p->gear;
		while (combine_item == false && gear_obj) {
			if (!object_is_equipped(p->body, gear_obj) &&
					object_similar(gear_obj, obj, OSTACK_PACK)) {
				combine_item = gear_obj;
			}

			gear_obj = gear_obj->next;
		}

		if (combine_item) {
			/* Increase the weight */
			p->upkeep->total_weight += (obj->number * obj->weight);

			/* Combine the items, and their known versions */
			object_absorb(combine_item->known, obj->known);
			obj->known = NULL;
			object_absorb(combine_item, obj);

			obj = combine_item;
			combining = true;
		}
	}

	/* We didn't manage the find an object to combine with */
	if (!combining) {
		/* Paranoia */
		assert(pack_slots_used(p) <= z_info->pack_size);

		gear_insert_end(obj);
		apply_autoinscription(obj);

		/* Remove cave object details */
		obj->held_m_idx = 0;
		obj->grid = loc(0, 0);
		obj->known->grid = loc(0, 0);

		/* Update the inventory */
		p->upkeep->total_weight += (obj->number * obj->weight);
		p->upkeep->notice |= (PN_COMBINE);

		/* Hobbits ID mushrooms on pickup, gnomes ID wands and staffs on pickup */
		if (!object_flavor_is_aware(obj)) {
			if (player_has(player, PF_KNOW_MUSHROOM) && tval_is_mushroom(obj)) {
				object_flavor_aware(obj);
				msg("Mushrooms for breakfast!");
			} else if (player_has(player, PF_KNOW_ZAPPER) && tval_is_zapper(obj))
				object_flavor_aware(obj);
		}
	}

	p->upkeep->update |= (PU_BONUS | PU_INVEN);
	p->upkeep->redraw |= (PR_INVEN);
	update_stuff(player);

	if (message) {
		char o_name[80];
		object_desc(o_name, sizeof(o_name), obj, ODESC_PREFIX | ODESC_FULL);
		msg("You have %s (%c).", o_name, gear_to_label(obj));
	}

	if (object_is_in_quiver(p, obj))
		sound(MSG_QUIVER);
}
Beispiel #11
0
bool gh_thing::met_biter (void)
{
    GH_FUNCTION()

    const size_t res = level->map.res;
    gh_point3d loc(at.x / res, at.y / res, at.z / res);

    for (int i = -2; i <= 2; i++) {
        for (int j = -2; j <= 2; j++) {
            vector <gh_thing*> **vp =
                level->map.real_isatp(at + gh_point3d(i*res, j*res, 0));

            if (vp == NULL) {
                //
                // Collision if we're off the map
                //
                continue;
            }

            vector <gh_thing*> *v = *vp;

            if (v == NULL) {
                continue;
            }

            vector<gh_thing*>::iterator things;

            for (things = v->begin(); things != v->end(); things++) {
                gh_thing *t = *things;

                //
                // Can't hit thyself!
                //
                if (t == this) {
                    continue;
                }

                //
                // To allow slime molds to move under heroes
                //
                if (t->is_hero) {
                    continue;
                }

                //
                // Silly...
                //
                if (is_part_of_my_body(t)) {
                    continue;
                }

                if (t->is_destroyable) {
                    if (gh_thing_gfx_can_hit(this, t)) {
                        return (true);
                    }
                }
            }
        }
    }

    return (false);
}
Beispiel #12
0
void Model::removeMaterial(const SPtr<Material> &material) {
   MaterialVector::iterator loc(std::find(materials.begin(), materials.end(), material));
   ASSERT(loc != materials.end(), "Material does not exist in vector");
   materials.erase(loc);
}
  if (env.isGotoing()) return;
  ENTER_STMT;
  // register with function_exists, invoke, etc.
  RequestEvalState::declareFunction(this);
}

Variant FunctionStatement::invoke(CArrRef params) const {
  DECLARE_THREAD_INFO_NOINIT
  if (m_closure) {
    if (m_ref) {
      return ref(invokeClosure(params));
    }
    return invokeClosure(params);
  }
  FuncScopeVariableEnvironment env(this);
  EvalFrameInjection fi(empty_string, m_name.c_str(), env, loc()->file);
  if (m_ref) {
    return ref(invokeImpl(env, params));
  }
  return invokeImpl(env, params);
}

void FunctionStatement::directBind(VariableEnvironment &env,
                                   const FunctionCallExpression *caller,
                                   FuncScopeVariableEnvironment &fenv,
                                   int start /* = 0 */) const {
  vector<ParameterPtr>::const_iterator piter = m_params.begin();
  const vector<ExpressionPtr> &args = caller->params();
  vector<ExpressionPtr>::const_iterator it = args.begin() + start;
  VariantStack &as = RequestEvalState::argStack();
  for (; it != args.end() && piter != m_params.end(); ++it, ++piter) {
Beispiel #14
0
//==== Generate Fuse Component ====//
void PropGeom::generate()
{
	int i, j;

	//==== Copy Current Section Data into SectVec ====//
	sectVec[currSectID].chord     = chord();
	sectVec[currSectID].twist     = twist();
	sectVec[currSectID].x_off     = loc();
	sectVec[currSectID].y_off     = offset();

	Xsec_surf surf;
	surf.set_num_pnts( numPnts.iget() );
	surf.set_num_xsecs( sectVec.size()+2 );

	//==== Load Up Airfoil ====//
	for ( int ip = 0 ; ip < surf.get_num_pnts() ; ip++ )
		surf.set_pnt(0, ip, sectVec[0].foil->get_end_cap(ip) );	

	int numxs = sectVec.size();
	for ( i = 0 ; i < numxs ; i++ )
	{
		for ( j = 0 ; j < surf.get_num_pnts() ; j++ )
		{
			surf.set_pnt( i+1, j, sectVec[i].foil->get_pnt(j) );
		}
	}
	for ( int ip = 0 ; ip < surf.get_num_pnts() ; ip++ )
		surf.set_pnt(numxs+1, ip, sectVec[numxs-1].foil->get_end_cap(ip) );	

	//==== Build Up One Blade ====//
	double rad = diameter()/2.0;
	for ( i = 0 ; i < surf.get_num_xsecs() ; i++ )
	{
		int sid = i;

		if ( i > 0 ) sid = i-1;

		if ( i > (int)sectVec.size()-1 ) sid = (int)sectVec.size()-1;

		Section* sPtr = &(sectVec[sid]);
		surf.scale_xsec_x(  i, sPtr->chord()*rad );
		surf.scale_xsec_z(  i, sPtr->chord()*rad );
		surf.offset_xsec_x( i, -0.5*(sPtr->chord()*rad) );
		surf.rotate_xsec_y( i, 90.0 );
		surf.rotate_xsec_y( i, -sPtr->twist() - pitch() );
		surf.offset_xsec_y( i, sPtr->x_off()*rad );
		surf.offset_xsec_z( i, -sPtr->y_off()*rad );
	}

	//==== Set Flags So Trailing Edge Remains Sharp ====//
	surf.set_pnt_tan_flag( 0, Bezier_curve::SHARP );
	surf.set_pnt_tan_flag( 1, Bezier_curve::SHARP );
    int num_pnts  = surf.get_num_pnts();
	surf.set_pnt_tan_flag( num_pnts-1, Bezier_curve::SHARP );

	if ( !smoothFlag )
	{
		for ( i = 0 ; i < surf.get_num_xsecs() ; i++ )
		{
			surf.set_xsec_tan_flag( i, Bezier_curve::SHARP );
		}
	}
	else	// Sharpen End Caps
	{
		surf.set_xsec_tan_flag( surf.get_num_xsecs()-2, Bezier_curve::SHARP );
	}


	bezier_surf besurf;
	surf.load_bezier_surface( &besurf );
	int umax = besurf.get_u_max();
	int wmax = besurf.get_w_max();

	Xsec_surf smooth_surf;
	smooth_surf.set_num_pnts( (surf.get_num_pnts()-1)*numW + 1 );
	smooth_surf.set_num_xsecs( (surf.get_num_xsecs()-1)*numU + 1 );

	for ( i = 0 ; i < smooth_surf.get_num_xsecs() ; i++ )
	{
		double fu = (double)i/(double)(smooth_surf.get_num_xsecs()-1);
		double u  = fu*(double)umax;
		for ( j = 0 ; j < smooth_surf.get_num_pnts() ; j++ )
		{
			double fw = (double)j/(double)(smooth_surf.get_num_pnts()-1);
			double w  = fw*(double)wmax;
			vec3d p = besurf.comp_pnt( u, w );
			smooth_surf.set_pnt( i, j, p );
		}
	}

	//==== Load Blades into bladeVec ====//
	for ( int nb = 0 ; nb < (int)bladeVec.size() ; nb++ )
	{
		bladeVec[nb].set_num_pnts( smooth_surf.get_num_pnts() );
		bladeVec[nb].set_num_xsecs(  smooth_surf.get_num_xsecs() );

		//==== Load Points ====//
		for ( i = 0 ; i < smooth_surf.get_num_xsecs() ; i++ )
			for ( j = 0 ; j < smooth_surf.get_num_pnts() ; j++ )
				bladeVec[nb].set_pnt( i, j, smooth_surf.get_pnt( i, j ) );

		double xang = 360.0*(double)nb/(double)(bladeVec.size());

		for ( i = 0 ; i < bladeVec[nb].get_num_xsecs() ; i++ )
		{
			bladeVec[nb].rotate_xsec_z( i, cone_angle() );
			bladeVec[nb].rotate_xsec_x( i, xang );
		}
		bladeVec[nb].load_refl_pnts_xsecs();
		bladeVec[nb].load_hidden_surf();
		bladeVec[nb].load_normals();
		bladeVec[nb].load_uw();

	}

	for ( int i = 0 ; i < (int)sectVec.size() ; i++ )
		sectVec[i].SetGeomPtr( this );

	update_bbox();


}
Beispiel #15
0
void IntlCalendarTest::TestJapaneseFormat() {
    Calendar *cal;
    UErrorCode status = U_ZERO_ERROR;
    cal = Calendar::createInstance("ja_JP_TRADITIONAL", status);
    CHECK(status, UnicodeString("Creating ja_JP_TRADITIONAL calendar"));
    
    Calendar *cal2 = cal->clone();
    delete cal;
    cal = NULL;
    
    // Test simple parse/format with adopt
    
    UDate aDate = 999932400000.0; 
    SimpleDateFormat *fmt = new SimpleDateFormat(UnicodeString("MMMM d, yy G"), Locale("en_US@calendar=japanese"), status);
    SimpleDateFormat *fmt2 = new SimpleDateFormat(UnicodeString("MMMM d, yyyy G"), Locale("en_US@calendar=gregorian"), status);
    CHECK(status, "creating date format instance");
    if(!fmt) { 
        errln("Coudln't create en_US instance");
    } else {
        UnicodeString str;
        fmt2->format(aDate, str);
        logln(UnicodeString() + "Test Date: " + str);
        str.remove();
        fmt->format(aDate, str);
        logln(UnicodeString() + "as Japanese Calendar: " + str);
        UnicodeString expected("September 8, 13 Heisei");
        if(str != expected) {
            errln("Expected " + expected + " but got " + str);
        }
        UDate otherDate = fmt->parse(expected, status);
        if(otherDate != aDate) { 
            UnicodeString str3;
            ParsePosition pp;
            fmt->parse(expected, *cal2, pp);
            fmt->format(otherDate, str3);
            errln("Parse incorrect of " + expected + " - wanted " + aDate + " but got " +  " = " +   otherDate + ", " + str3 + " = " + CalendarTest::calToStr(*cal2) );
            
        } else {
            logln("Parsed OK: " + expected);
        }
        delete fmt;
    }

    // Test parse with incomplete information
    fmt = new SimpleDateFormat(UnicodeString("G y"), Locale("en_US@calendar=japanese"), status);
    /* The test data below should points to 1868-09-08T00:00:00 in America/Los_Angeles.
     * The time calculated by original test code uses -7:00 UTC offset, because it assumes
     * DST is observed (because of a timezone bug, DST is observed for early 20th century
     * day to infinite past time).  The bug was fixed and DST is no longer used for time before
     * 1900 for any zones.  However, ICU timezone transition data is represented by 32-bit integer
     * (sec) and cannot represent transitions before 1901 defined in Olson tzdata.  For example,
     * based on Olson definition, offset -7:52:58 should be used for Nov 18, 1883 or older dates.
     * If ICU properly capture entire Olson zone definition, the start time of "Meiji 1" is
     * -3197117222000. -Yoshito
     */
    /* TODO: When ICU support the Olson LMT offset for America/Los_Angeles, we need to update
     * the reference data.
     */
    //aDate = -3197120400000.;
    aDate = -3197116800000.;
    CHECK(status, "creating date format instance");
    if(!fmt) { 
        errln("Coudln't create en_US instance");
    } else {
        UnicodeString str;
        fmt2->format(aDate, str);
        logln(UnicodeString() + "Test Date: " + str);
        str.remove();
        fmt->format(aDate, str);
        logln(UnicodeString() + "as Japanese Calendar: " + str);
        UnicodeString expected("Meiji 1");
        if(str != expected) {
            errln("Expected " + expected + " but got " + str);
        }
        UDate otherDate = fmt->parse(expected, status);
        if(otherDate != aDate) { 
            UnicodeString str3;
            ParsePosition pp;
            fmt->parse(expected, *cal2, pp);
            fmt->format(otherDate, str3);
            errln("Parse incorrect of " + expected + " - wanted " + aDate + " but got " +  " = " +
                otherDate + ", " + str3 + " = " + CalendarTest::calToStr(*cal2) );
        } else {
            logln("Parsed OK: " + expected);
        }
        delete fmt;
    }

    delete cal2;
    delete fmt2;
    CHECK(status, "Error occured");
    
    // Now, try in Japanese
    {
        UnicodeString expect = CharsToUnicodeString("\\u5e73\\u621013\\u5e749\\u67088\\u65e5\\u571f\\u66dc\\u65e5");
        UDate         expectDate = 999932400000.0; // Testing a recent date
        Locale        loc("ja_JP@calendar=japanese");
        
        status = U_ZERO_ERROR;
        simpleTest(loc, expect, expectDate, status);
    }
    {
        UnicodeString expect = CharsToUnicodeString("\\u5e73\\u621013\\u5e749\\u67088\\u65e5\\u571f\\u66dc\\u65e5");
        UDate         expectDate = 999932400000.0; // Testing a recent date
        Locale        loc("ja_JP_TRADITIONAL"); // legacy
        
        status = U_ZERO_ERROR;
        simpleTest(loc, expect, expectDate, status);
    }
    {
        UnicodeString expect = CharsToUnicodeString("\\u5b89\\u6c385\\u5e747\\u67084\\u65e5\\u6728\\u66dc\\u65e5");
        //UDate         expectDate = -6106035600000.0;
        UDate         expectDate = -6106032000000.0; // 1776-07-04T00:00:00Z-0800
        Locale        loc("ja_JP@calendar=japanese");
        
        status = U_ZERO_ERROR;
        simpleTest(loc, expect, expectDate, status);    
        
    }
    {   // Jitterbug 1869 - this is an ambiguous era. (Showa 64 = Jan 6 1989, but Showa could be 2 other eras) )
        UnicodeString expect = CharsToUnicodeString("\\u662d\\u548c64\\u5e741\\u67086\\u65e5\\u91d1\\u66dc\\u65e5");
        UDate         expectDate = 600076800000.0;
        Locale        loc("ja_JP@calendar=japanese");
        
        status = U_ZERO_ERROR;
        simpleTest(loc, expect, expectDate, status);    
        
    }
    {   // This Feb 29th falls on a leap year by gregorian year, but not by Japanese year.
        UnicodeString expect = CharsToUnicodeString("\\u5EB7\\u6B632\\u5e742\\u670829\\u65e5\\u65e5\\u66dc\\u65e5");
        // Add -1:00 to the following for historical TZ - aliu
        //UDate         expectDate =  -16214403600000.0;  // courtesy of date format round trip test
        UDate         expectDate =  -16214400000000.0;  // 1456-03-09T00:00:00Z-0800
        Locale        loc("ja_JP@calendar=japanese");
        
        status = U_ZERO_ERROR;
        simpleTest(loc, expect, expectDate, status);    
        
    }
}
Beispiel #16
0
    // teleport player to given game_tele.entry
    static bool HandleTeleNameCommand(ChatHandler* handler, const char* args)
    {
        char* nameStr;
        char* teleStr;
        handler->extractOptFirstArg((char*)args, &nameStr, &teleStr);
        if (!teleStr)
            return false;

        Player* target;
        ObjectGuid target_guid;
        std::string target_name;
        if (!handler->extractPlayerTarget(nameStr, &target, &target_guid, &target_name))
            return false;

        if (strcmp(teleStr, "$home") == 0)    // References target's homebind
        {
            if (target)
                target->TeleportTo(target->m_homebindMapId, target->m_homebindX, target->m_homebindY, target->m_homebindZ, target->GetOrientation());
            else
            {
                PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_HOMEBIND);
                stmt->setUInt32(0, target_guid.GetCounter());
                PreparedQueryResult resultDB = CharacterDatabase.Query(stmt);

                if (resultDB)
                {
                    Field* fieldsDB = resultDB->Fetch();
                    WorldLocation loc(fieldsDB[0].GetUInt16(), fieldsDB[2].GetFloat(), fieldsDB[3].GetFloat(), fieldsDB[4].GetFloat(), 0.0f);
                    uint32 zoneId = fieldsDB[1].GetUInt16();

                    SQLTransaction dummy;
                    Player::SavePositionInDB(loc, zoneId, target_guid, dummy);
                }
            }

            return true;
        }

        // id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r
        GameTele const* tele = handler->extractGameTeleFromLink(teleStr);
        if (!tele)
        {
            handler->SendSysMessage(LANG_COMMAND_TELE_NOTFOUND);
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (target)
        {
            // check online security
            if (handler->HasLowerSecurity(target, ObjectGuid::Empty))
                return false;

            std::string chrNameLink = handler->playerLink(target_name);

            if (target->IsBeingTeleported() == true)
            {
                handler->PSendSysMessage(LANG_IS_TELEPORTED, chrNameLink.c_str());
                handler->SetSentErrorMessage(true);
                return false;
            }

            handler->PSendSysMessage(LANG_TELEPORTING_TO, chrNameLink.c_str(), "", tele->name.c_str());
            if (handler->needReportToTarget(target))
                ChatHandler(target->GetSession()).PSendSysMessage(LANG_TELEPORTED_TO_BY, handler->GetNameLink().c_str());

            // stop flight if need
            if (target->IsInFlight())
            {
                target->GetMotionMaster()->MovementExpired();
                target->CleanupAfterTaxiFlight();
            }
            // save only in non-flight case
            else
                target->SaveRecallPosition();

            target->TeleportTo(tele->mapId, tele->position_x, tele->position_y, tele->position_z, tele->orientation);
        }
        else
        {
            // check offline security
            if (handler->HasLowerSecurity(NULL, target_guid))
                return false;

            std::string nameLink = handler->playerLink(target_name);

            handler->PSendSysMessage(LANG_TELEPORTING_TO, nameLink.c_str(), handler->GetTrinityString(LANG_OFFLINE), tele->name.c_str());

            SQLTransaction dummy;
            Player::SavePositionInDB(WorldLocation(tele->mapId, tele->position_x, tele->position_y, tele->position_z, tele->orientation),
                sMapMgr->GetZoneId(tele->mapId, tele->position_x, tele->position_y, tele->position_z), target_guid, dummy);
        }

        return true;
    }
Beispiel #17
0
void WorldManager::init()
{
	struct ModelLoadInfo
	{
		char* ModelPath;
		WCHAR* ShaderPath;
		WorldTransform transform;
	};
	ModelLoadInfo ModelPath[] =
	{
		{ "Resource/Model/CMC_MF_01.FBX",L"Resource/Shader/Common.hlsl",{ AS3DVECTOR3(2000.0f,0.0f,0.0f),AS3DVECTOR3(0.0f,0,1.0f),AS3DVECTOR3(0,1,0),AS3DVECTOR3(1.0f,1.0f,1.0f)}},//房子
		{ "Resource/Model/CMC_CM.FBX",L"Resource/Shader/Common.hlsl",{ AS3DVECTOR3(0.0f,0.0f,0.0f),AS3DVECTOR3(0.0f,0,1.0f),AS3DVECTOR3(0,1,0),AS3DVECTOR3(1.0f,1.0f,1.0f) }},//主要房子
		{ "Resource/Model/ChaSi.FBX",L"Resource/Shader/Common.hlsl",{ AS3DVECTOR3(-2000.0f,0.0f,0.0f),AS3DVECTOR3(0.0f,1,0.0f),AS3DVECTOR3(0,0,1),AS3DVECTOR3(1.0f,1.0f,1.0f) } },//茶肆
	};
	// models
	for (int i = 0; i < sizeof(ModelPath) / sizeof(ModelPath[0]); ++i)
	{
		Object* pObject = new Model(ModelPath[i].ModelPath, ModelPath[i].ShaderPath, ModelPath[i].transform);
		pObject->init();
		Objects.push_back(pObject);
	}
	
	//sky 
	{
		AS3DVECTOR3 scale(10.0f, 10.0f, 10.0f);
		AS3DVECTOR3 loc(0, 0.0f, 0);
		AS3DVECTOR3 dir(0.0f, 0.0f, 1.0f);
		AS3DVECTOR3 up(0.0f, 1.0f, 1.0f);
		Object* sky = new Sky(WorldTransform(loc, dir, up, scale));
		sky->init();
		Objects.push_back(sky);
	}
	//rain drop
	ModelLoadInfo RainDropModel[] =
	{
		//{ "Resource/Model/CMC_MF_01.FBX",L"Resource/Shader/Common.hlsl",{ XMFLOAT3(2000.0f,0.0f,0.0f),XMFLOAT3(0.0f,0,1.0f),XMFLOAT3(0,1,0),XMFLOAT3(1.0f,1.0f,1.0f)}},//房子
		//{ "Resource/Model/CMC_CM.FBX",L"Resource/Shader/Common.hlsl",{ XMFLOAT3(0.0f,0.0f,0.0f),XMFLOAT3(0.0f,0,1.0f),XMFLOAT3(0,1,0),XMFLOAT3(1.0f,1.0f,1.0f) }},//主要房子
		//{ "Resource/Model/ChaSi.FBX",L"Resource/Shader/Common.hlsl",{ XMFLOAT3(-2000.0f,0.0f,0.0f),XMFLOAT3(0.0f,1,0.0f),XMFLOAT3(0,0,1),XMFLOAT3(1.0f,1.0f,1.0f) } },//茶肆
		{ "Resource/Model/RainDrop0.FBX",L"Resource/Shader/RainDrop.hlsl",{ AS3DVECTOR3(0.0f,1000.0f,0.0f),AS3DVECTOR3(0.0f,1,0.0f),AS3DVECTOR3(0,0,1),AS3DVECTOR3(1.0f,1.0f,1.0f) } },//茶肆
	};
	for (int i = 0; i < sizeof(RainDropModel) / sizeof(RainDropModel[0]); ++i)
	{
		RainDrop* pObject = new RainDrop(RainDropModel[i].ModelPath, RainDropModel[i].ShaderPath, RainDropModel[i].transform);
		pObject->init();
		Objects.push_back(pObject);
		pRainDrop = pObject;
	}
	
	//sphere for test
	/*
	for( int row = 1; row < 9; ++row)
	{
		AS3DVECTOR3 scale(10.0f, 10.0f, 10.0f);
		float x =  1500 + row * 300;
		float z = 2000;
		float roughness = (row + 1) * 0.1;
		{
			AS3DVECTOR3 loc(x, 0.0f, z + 800);
			AS3DVECTOR3 dir(0.0f, 1.0f, 0.0f);
			AS3DVECTOR3 up(0.0f, 0.0f, 1.0f);
			Object* sphereForIBL = new SphereForTest(WorldTransform(loc,dir,up,scale), roughness, AS3DVECTOR3(0.972, 0.960, 0.915));//银子
			sphereForIBL->init();
			Objects.push_back(sphereForIBL);
		}
		{
			AS3DVECTOR3 loc(x, 0.0f, z + 600);
			AS3DVECTOR3 dir(0.0f, 0.0f, 1.0f);
			AS3DVECTOR3 up(0.0f, 1.0f, 0.0f);
			Object* sphereForIBL = new SphereForTest(WorldTransform(loc, dir, up, scale), roughness, AS3DVECTOR3(1.022, 0.782, 0.344)); //金子
			sphereForIBL->init();
			Objects.push_back(sphereForIBL);
		}
		{
			AS3DVECTOR3 loc(x, 0.0f, z + 400);
			AS3DVECTOR3 dir(0.0f, 0.0f, 1.0f);
			AS3DVECTOR3 up(0.0f, 1.0f, 0.0f);
			Object* sphereForIBL = new SphereForTest(WorldTransform(loc, dir, up, scale), roughness, AS3DVECTOR3(0.04, 0.04, 0.04));   //非金属
			sphereForIBL->init();
			Objects.push_back(sphereForIBL);
		}
		{
			AS3DVECTOR3 loc(x, 0.0f, z + 200);
			AS3DVECTOR3 dir(0.0f, 0.0f, 1.0f);
			AS3DVECTOR3 up(0.0f, 1.0f, 0.0f);
			Object* sphereForIBL = new SphereForTest(WorldTransform(loc, dir, up, scale), roughness, AS3DVECTOR3(0.562, 0.565, 0.578));  //铁
			sphereForIBL->init();
			Objects.push_back(sphereForIBL);
		}
	}
	*/
	//conerain
	{
		AS3DVECTOR3 scale(100.0f, 100.0f, 500.0f);
		float x = 2000;
		float z = 2000;
		{
			AS3DVECTOR3 loc(x, 0.0f, z + 800);
			AS3DVECTOR3 dir(0.0f, 1.0f, 0.0f);
			AS3DVECTOR3 up(0.0f, 0.0f, 1.0f);
			Object* conerain = new ConeRain(WorldTransform(loc, dir, up, scale), 0);
			conerain->init();
			pRain = static_cast<ConeRain*>(conerain);
			Objects.push_back(conerain);
		}
	}
	
	//init compute shader test module
	pComputeShaderTest = new ComputeShaderTestModule();
}
Beispiel #18
0
TRIGGER( targetobj )(obj user, obj usedon)
{
  if(usedon == NULL())
  {
    return(0x00);
  }
  if(isEquipped(usedon))
  {
    systemMessage(user, "Can't Dye clothing that is being worn.");
    return(0x00);
  }
  int Q66P = getObjType(usedon);
  int Q61R = getHue(this);
  loc Q66R = loc( getLocation(usedon) );
  switch(Q66P)
  {
  case 0x0DEF:
  case 0x0DF8:
  case 0x0DF9:
  case 0x0E1D:
  case 0x0E1E:
  case 0x0E1F:
  case 0x0E75:
  case 0x0E76:
  case 0x0F95:
  case 0x0F96:
  case 0x0F97:
  case 0x0F98:
  case 0x0F99:
  case 0x0F9A:
  case 0x0F9B:
  case 0x0F9C:
  case 0x0F9C:
  case 0x0FA0:
  case 0x0FA1:
  case 0x101F:
  case 0x13A4:
  case 0x0BD5:
  case 0x0BD6:
  case 0x0BD7:
  case 0x0BD8:
  case 0x0BD9:
  case 0x0BDA:
  case 0x0BDB:
  case 0x0BDC:
  case 0x0BDD:
  case 0x0BDE:
  case 0x1515:
  case 0x1516:
  case 0x1517:
  case 0x1518:
  case 0x152E:
  case 0x152F:
  case 0x1530:
  case 0x1531:
  case 0x1537:
  case 0x1538:
  case 0x1539:
  case 0x153A:
  case 0x153B:
  case 0x153C:
  case 0x153D:
  case 0x153E:
  case 0x153F:
  case 0x1540:
  case 0x1541:
  case 0x1542:
  case 0x1543:
  case 0x1544:
  case 0x170B:
  case 0x170C:
  case 0x170F:
  case 0x1710:
  case 0x1711:
  case 0x1712:
  case 0x1713:
  case 0x1714:
  case 0x1715:
  case 0x1716:
  case 0x1717:
  case 0x1718:
  case 0x1719:
  case 0x171A:
  case 0x171B:
  case 0x171C:
  case 0x175D:
  case 0x175E:
  case 0x175F:
  case 0x1760:
  case 0x1761:
  case 0x1762:
  case 0x1763:
  case 0x1764:
  case 0x1765:
  case 0x1766:
  case 0x1767:
  case 0x1768:
  case 0x1914:
  case 0x1915:
  case 0x1B74:
  case 0x1B75:
  case 0x1EFD:
  case 0x1EFE:
  case 0x1EFF:
  case 0x1F00:
  case 0x1F01:
  case 0x1F02:
  case 0x1F03:
  case 0x1F04:
  case 0x1F7B:
  case 0x1F7C:
  case 0x1F9F:
  case 0x1FA0:
  case 0x1FA1:
  case 0x1FA2:
  case 0x1F7B:
  case 0x1F7C:
  case 0x1FA1:
  case 0x1FA1:
  case 0x1FFD:
  case 0x1FFE:
    sfx(Q66R, 0x023E, 0x00);
    setHue(usedon, Q61R);
    break;
  }
  return(0x00);
}
Beispiel #19
0
bool Trace::get_location(const llvm::MDNode *m,
                         int *lineno,
                         std::string *fname,
                         std::string *dname){
  if(!m){
    return false;
  }
  llvm::DILocation loc(m);
  *lineno = loc.getLineNumber();
  *fname = loc.getFilename();
  *dname = loc.getDirectory();
#if defined(LLVM_MDNODE_OPERAND_IS_VALUE) /* Otherwise, disable fallback and hope that the C compiler produces well-formed metadata. */
  if(*fname == "" && *dname == ""){
    /* Failed to get file name and directory name.
     *
     * This may be caused by misformed metadata. Perform a brute-force
     * search through the metadata tree and try to find the names.
     */
    std::vector<const llvm::MDNode*> stack;
    std::set<const llvm::MDNode*> visited;
    stack.push_back(m);
    visited.insert(m);
#ifdef HAVE_LLVM_LLVMDEBUGVERSION
    llvm::APInt tag_file_type(32,llvm::LLVMDebugVersion | llvm::dwarf::DW_TAG_file_type);
#else
    llvm::APInt tag_file_type(32,llvm::dwarf::DW_TAG_file_type);
#endif
    while(stack.size()){
      const llvm::MDNode *n = stack.back();
      stack.pop_back();
      llvm::Value *tag = n->getOperand(0);
      if(tag->getType()->isIntegerTy(32)){
        const llvm::ConstantInt *tag_i =
          llvm::dyn_cast<llvm::ConstantInt>(tag);
        if(tag_i->getValue() == tag_file_type){
          if(n->getNumOperands() >= 3 &&
             (n->getOperand(1) && llvm::dyn_cast<llvm::MDString>(n->getOperand(1))) &&
             (n->getOperand(2) && llvm::dyn_cast<llvm::MDString>(n->getOperand(2)))){
            *fname = llvm::dyn_cast<llvm::MDString>(n->getOperand(1))->getString();
            *dname = llvm::dyn_cast<llvm::MDString>(n->getOperand(2))->getString();
          }else if(n->getNumOperands() >= 2 &&
                   n->getOperand(1) && llvm::dyn_cast<llvm::MDNode>(n->getOperand(1))){
            const llvm::MDNode *n2 = llvm::dyn_cast<llvm::MDNode>(n->getOperand(1));
            if(n2->getNumOperands() == 2 &&
               n2->getOperand(0) && llvm::dyn_cast<llvm::MDString>(n2->getOperand(0)) &&
               n2->getOperand(1) && llvm::dyn_cast<llvm::MDString>(n2->getOperand(1))){
              *fname = llvm::dyn_cast<llvm::MDString>(n2->getOperand(0))->getString();
              *dname = llvm::dyn_cast<llvm::MDString>(n2->getOperand(1))->getString();
            }
          }
          break;
        }else{
          for(unsigned i = 1; i < n->getNumOperands(); ++i){
            if(n->getOperand(i)){
              const llvm::MDNode *n2 = llvm::dyn_cast<llvm::MDNode>(n->getOperand(i));
              if(n2 && visited.count(n2) == 0){
                stack.push_back(n2);
              }
            }
          }
        }
      }
    }
  }
#endif
  return (lineno >= 0) && fname->size() && dname->size();
};
Beispiel #20
0
void SpawnMonitor::loadSpawnPoints()
{
  QString fileName;
  
  fileName = m_zoneName + ".sp";

  QFileInfo fileInfo = 
    m_dataLocMgr->findExistingFile("spawnpoints", fileName, false);

  if (!fileInfo.exists())
  {
    seqWarn("Can't find spawn point file %s", 
	   (const char*)fileInfo.absFilePath());
    return;
  }
  
  fileName = fileInfo.absFilePath();

  QFile spFile(fileName);
  
  if (!spFile.open(IO_ReadOnly))
  {
    seqWarn( "Can't open spawn point file %s", (const char*)fileName );
    return;
  }
  
  QTextStream input( &spFile );
  
  int16_t x, y, z;
  unsigned long diffTime;
  uint32_t count;
  QString name;

  while (!input.atEnd())
  {
    input >> x;
    input >> y;
    input >> z;
    input >> diffTime;
    input >> count;
    name = input.readLine();
    name = name.stripWhiteSpace();
    
    EQPoint	loc(x, y, z);
    SpawnPoint*	p = new SpawnPoint( 0, loc, name, diffTime, count );
    if (p)
    {
      QString key = p->key();
      
      if (!m_points.find(key))
      {
	m_points.insert(key, p);
	emit newSpawnPoint(p);
      }
      else
      {
	seqWarn("Warning: spawn point key already in use!");
	delete p;
      }
    }
  }

  seqInfo("Loaded spawn points: %s", (const char*)fileName);
  m_modified = false;
}
Beispiel #21
0
int main(int argc, char** argv)
{
  // initialize ROS
  ros::init(argc, argv, "find_grasps");
  ros::NodeHandle node("~");
  
  GraspLocalizer::Parameters params;
  
  // camera transforms (poses)
  Eigen::Matrix4d base_tf, sqrt_tf;
  base_tf <<  0, 0.445417, 0.895323, 0.215, 
              1, 0, 0, -0.015, 
              0, 0.895323, -0.445417, 0.23, 
              0, 0, 0, 1;
  sqrt_tf <<  0.9366, -0.0162, 0.3500, -0.2863, 
              0.0151, 0.9999, 0.0058, 0.0058, 
              -0.3501, -0.0002, 0.9367, 0.0554, 
              0, 0, 0, 1;
  params.cam_tf_left_ = base_tf * sqrt_tf.inverse();
  params.cam_tf_right_ = base_tf * sqrt_tf;

  // read ROS parameters
  std::string cloud_topic;
  std::string cloud_frame;
  std::string svm_file_name;
  std::vector<double> workspace;
  std::vector<double> camera_pose;
  int cloud_type;
  bool parallel;

  node.param("parallel", parallel, true);
  node.param("cloud_topic", cloud_topic, CLOUD_TOPIC);
  node.param("cloud_frame", cloud_frame, CLOUD_FRAME);
  node.param("cloud_type", cloud_type, CLOUD_TYPE);
  node.param("svm_file_name", svm_file_name, SVM_FILE_NAME);
  node.param("num_threads", params.num_threads_, NUM_THREADS);
  node.param("num_samples", params.num_samples_, NUM_SAMPLES); 
  node.param("num_clouds", params.num_clouds_, NUM_CLOUDS);

  if (parallel) {
      double finger_width, hand_outer_diameter, hand_depth;
      node.param("finger_width", finger_width, FINGER_WIDTH);
      node.param("hand_outer_diameter", hand_outer_diameter, HAND_OUTER_DIAMETER);
      node.param("hand_depth", hand_depth, HAND_DEPTH);
      params.finger_hand_ = new ParallelHand(finger_width, hand_outer_diameter, hand_depth);
  }
  //TODO else

  node.param("init_bite", params.init_bite_, INIT_BITE);
  node.param("hand_height", params.hand_height_, HAND_HEIGHT);
  node.param("min_inliers", params.min_inliers_, MIN_HANDLE_INLIERS);
  node.getParam("workspace", workspace);
  node.getParam("camera_pose", camera_pose);
  node.param("plotting", params.plotting_mode_, 0);
  node.param("marker_lifetime", params.marker_lifetime_, 0.0);
  
  Eigen::Matrix4d R;
  for (int i=0; i < R.rows(); i++)
    R.row(i) << camera_pose[i*R.cols()], camera_pose[i*R.cols() + 1], camera_pose[i*R.cols() + 2], camera_pose[i*R.cols() + 3];  
    
  Eigen::VectorXd ws(6);
  ws << workspace[0], workspace[1], workspace[2], workspace[3], workspace[4], workspace[5];
  params.workspace_ = ws;
  
  std::cout << "-- Parameters --\n";
  std::cout << " Input\n";
  std::cout << "  cloud_topic: " << cloud_topic << "\n";
  std::cout << "  cloud_frame: " << cloud_frame << "\n";
  std::cout << "  cloud_type: " << CLOUD_TYPES[cloud_type] << "\n";
  std::cout << " Hand Search\n";  
  std::cout << "  workspace: " << ws.transpose() << "\n";
  std::cout << "  num_samples: " << params.num_samples_ << "\n";
  std::cout << "  num_threads: " << params.num_threads_ << "\n";
  std::cout << "  num_clouds: " << params.num_clouds_ << "\n";  
  std::cout << "  camera pose:\n" << R << std::endl;
  std::cout << " Robot Hand Model\n";
  //TODO: Make FingerGrasp printable.
 // std::cout << "  finger_width: " << params.finger_width_ << "\n";
 // std::cout << "  hand_outer_diameter: " << params.hand_outer_diameter_ << "\n";
 // std::cout << "  hand_depth: " << params.finger_width_ << "\n";
 // std::cout << "  init_bite: " << params.finger_width_ << "\n";
 // std::cout << "  hand_height: " << params.finger_width_ << "\n";
  std::cout << " Antipodal Grasps Prediction\n";
  std::cout << "  svm_file_name: " << svm_file_name << "\n";
  std::cout << " Handle Search\n";
  std::cout << "  min_inliers: " << params.min_inliers_ << "\n";
  std::cout << " Visualization\n";
  std::cout << "  plot_mode: " << PLOT_MODES[params.plotting_mode_] << "\n";
  std::cout << "  marker_lifetime: " << params.marker_lifetime_ << "\n";
  
  GraspLocalizer loc(node, cloud_topic, cloud_frame, cloud_type, svm_file_name, params);
  loc.localizeGrasps();
  
	return 0;
}
/// \brief Creates a matcher that finds the locations of types referring to the
/// \c std::auto_ptr() type.
///
/// \code
///   std::auto_ptr<int> a;
///        ^~~~~~~~~~~~~
///
///   typedef std::auto_ptr<int> int_ptr_t;
///                ^~~~~~~~~~~~~
///
///   std::auto_ptr<int> fn(std::auto_ptr<int>);
///        ^~~~~~~~~~~~~         ^~~~~~~~~~~~~
///
///   <etc...>
/// \endcode
TypeLocMatcher makeAutoPtrTypeLocMatcher() {
  // Skip elaboratedType() as the named type will match soon thereafter.
  return typeLoc(loc(qualType(AutoPtrType, unless(elaboratedType()))))
      .bind(AutoPtrTokenId);
}
Beispiel #23
0
    // Note that, when parsing file names and arguments, paths are interpreted
    // to be relative to the applications working directory.
    void parser::parse_dag (void)
    {
      dag_ = boost::shared_ptr <dag> (new dag (scheduler_file_));

      std::cout << "parsing " << dag_file_ << std::endl;
      try
      {
        ticpp::Document doc (dag_file_);

        doc.LoadFile ();

        // get the top adag element
        ticpp::Element * adag = doc.FirstChildElement ("adag");

        // list nodes
        ticpp::Iterator <ticpp::Element> job ("job"); 


        // we parse jobs twice.  On the first run, we add all nodes.  On the
        // second run, we add all edges (connected nodes are known now).
        for ( job = job.begin (adag); job != job.end (); job++ )
        {
          node_description nd;

          std::string s_id   = job->GetAttribute ("id");
          std::string s_name = job->GetAttribute ("name");

          nd.set_attribute ("Executable", s_name);


          // get args
          ticpp::Element * args = job->FirstChildElement ("argument");

          if ( args )
          {
            // iterate over args, if we have them
            ticpp::Iterator <ticpp::Node> arg; 

            std::vector <std::string> s_args;

            for ( arg = arg.begin (args); arg != arg.end (); arg++ )
            {
              if ( arg->Type () == TiXmlNode::ELEMENT )
              {
                ticpp::Element * elem   = arg->ToElement ();
                std::string      s_file = elem->GetAttribute ("file");

                s_args.push_back (s_file);
              }
              else if ( arg->Type () == TiXmlNode::TEXT )
              {
                std::stringstream ss;
                ss << *arg;
                std::string tmp  = ss.str ();

                if ( tmp.size () )
                {
                  std::vector <std::string> s_tmp = split (tmp);

                  for ( unsigned int j = 0; j < s_tmp.size (); j++ )
                  {
                    if ( s_tmp [j] == "." )
                    {
                      s_args.push_back (s_tmp[j]);
                    }
                    else
                    {
                      s_args.push_back (s_tmp[j]);
                    }
                  }
                }
              }
            }
            
            nd.set_vector_attribute ("Arguments", s_args);
          }

          boost::shared_ptr <node> n = dag_->create_node (nd, s_id);

          dag_->add_node (s_id, n);
        }


        // second run: we have input and output files specified for each jobs.
        // Find pairs, and add as edges
        std::vector <std::pair <std::string, std::string> > inputs;
        std::vector <std::pair <std::string, std::string> > outputs;

        for ( job = job.begin (adag); job != job.end (); job++ )
        {
          std::string s_id   = job->GetAttribute ("id");
          std::string s_name = job->GetAttribute ("name");

          ticpp::Iterator <ticpp::Element> uses ("uses"); 

          for ( uses = uses.begin (job.Get ()); uses != uses.end (); uses++ )
          {
            std::string s_file     = uses->GetAttribute ("file");
            std::string s_link     = uses->GetAttribute ("link");
            std::string s_transfer = uses->GetAttribute ("transfer");

            if ( s_link == "input" )
            {
              inputs.push_back (std::pair <std::string, std::string> (s_file, s_id));
            }
            else if ( s_link == "output" )
            {
              outputs.push_back (std::pair <std::string, std::string> (s_file, s_id));
            }
            else
            {
              std::cerr << "cannot handle link type " << s_link << std::endl;
            }
            
          }
        }


        // iterate over inputs, and find outputs which produce them.  inputs not
        // produced by some outputting node are assumed to be staged in from
        // a data src (INPUT).  Also, data which are produced but not consumed
        // by another node are to be staged to an data sink (OUTPUT).  In both
        // cases, we simply add edges with empty src/tgt nodes, and leave it to
        // the scheduler to interprete that correctly.

        // first, iterate over inputs, and add edges for those inputs which are
        // produced by another node, and also for those which need to be staged
        // in.
        for ( unsigned int i = 0; i < inputs.size (); i++ )
        {
          std::string file   = inputs[i].first;
          std::string i_node = inputs[i].second;
          std::string o_node = "";

          // std::cout << " --- checking inputs: " << file << std::endl;

          // for each input file, find output node
          for ( unsigned int j = 0; j < outputs.size (); j++ )
          {
            if ( outputs[j].first == file )
            {
              o_node = outputs[j].second;

              // stop loop
              j = inputs.size ();
            }
          }

          if ( o_node == "" )
          {
            // std::cout << " --- needs to be staged to node " << i_node << std::endl;
            saga::url loc (file);
            loc.set_scheme ("any");
            boost::shared_ptr <edge> e = dag_->create_edge (loc);

            // std::cout << " e 1 " << file << " : " << "INPUT->" << o_node << std::endl;

            dag_->add_edge (e, "INPUT", i_node);
          }

          else if ( o_node != i_node )
          {
            saga::url loc (file);
            loc.set_scheme ("any");
            boost::shared_ptr <edge> e = dag_->create_edge (loc);

            // std::cout << " e 3: " << file << " : " << o_node << "->" << i_node << std::endl;

            dag_->add_edge (e, o_node, i_node);
          }
        }

        // inputs have been iterated above - now iterate over outputs, and look
        // for remaining ones which do not have a partner.
        for ( unsigned int k = 0; k < outputs.size (); k++ )
        {
          std::string file   = outputs[k].first;
          std::string i_node = "";
          std::string o_node = outputs[k].second;

          // for each output node, find the input node
          for ( unsigned int l = 0; l < inputs.size (); l++ )
          {
            if ( inputs[l].first == file )
            {
              i_node = inputs[l].second;

              // stop loop
              l = inputs.size ();
            }
          }

          if ( i_node == "" )
          {
            // will stage data out to data sink

            saga::url loc (file);
            loc.set_scheme ("any");
            boost::shared_ptr <edge> e  = dag_->create_edge (loc);

            // std::cout << " e 1 " << file << " : " << o_node << "-> OUTPUT " << std::endl;

            dag_->add_edge (e, o_node, "OUTPUT");
          }
        }
      }
      catch ( const ticpp::Exception & e )
      {
        std::cout << e.what () << std::endl;
      }
      std::cout << "parsing " << dag_file_ << " done" << std::endl;
    }
Beispiel #24
0
TEST(ProbDistributionsFrechet, chiSquareGoodnessFitTest_2) {
  boost::random::mt19937 rng;
  int N = 10000;
  int K = boost::math::round(2 * std::pow(N, 0.4));
  boost::math::chi_squared mydist(K-1);

  // compare rng to values generated in R
  stan::math::vector_d loc(K - 1);
  loc << 0.0955415954270533857029, 0.1041316533397634719327, 0.1103740935559852087700,
    0.1155522740053754326972, 0.1201122408786449852203, 0.1242675441002982356098,
    0.1281388937447018039339, 0.1318020457964521607863, 0.1353081473284461211382,
    0.1386936692085097289073, 0.1419857581568354232271, 0.1452053426999067309300,
    0.1483690435024691001153, 0.1514904048409720094259, 0.1545807200109403090060,
    0.1576496031786457641122, 0.1607053971093497513056, 0.1637554713779679482766,
    0.1668064455827929504217, 0.1698643600576038303895, 0.1729348091403954956746,
    0.1760230473253571181758, 0.1791340755387774430485, 0.1822727127227262711173,
    0.1854436565133893710655, 0.1886515358368690276070, 0.1919009575713397086627,
    0.1951965489490360139424, 0.1985429970347641626116, 0.2019450863797647710562,
    0.2054077357842012396816, 0.2089360349903569558094, 0.2125352820597541936287,
    0.2162110221529071896196, 0.2199690884253143186022, 0.2238156457748539107655,
    0.2277572382230414749227, 0.2318008407862954534107, 0.2359539167955838900870,
    0.2402244817572899704405, 0.2446211750202796908482, 0.2491533407314772130547,
    0.2538311198348010000458, 0.2586655552093837240335, 0.2636687124701073692279,
    0.2688538194897237554315, 0.2742354283777497792052, 0.2798296045075444049566,
    0.2856541482738663706442, 0.2917288566621027978698, 0.2980758335169671480180,
    0.3047198597496216798675, 0.3116888378074926801986, 0.3190143288159938972370,
    0.3267322062618903677489, 0.3348834574628689608744, 0.3435151741391668234193,
    0.3526817873222083399298, 0.3624466213226111843682, 0.3728838691486778267326,
    0.3840811316557718457787, 0.3961427211814618765118, 0.4091940177230903863403,
    0.4233872987100369411628, 0.4389096706055364283117, 0.4559940614596232899558,
    0.4749347769469325353242, 0.4961100434630218436460, 0.5200155800775090320087,
    0.5473162043798307507814, 0.5789281712257871026495, 0.6161565249522205078847,
    0.6609369681056525003271, 0.7162914824634227795030, 0.7872641783601075360366,
    0.8830792885403591085947, 1.0230050174489953018764, 1.2569469392970760157624,
    1.7832436936202971100585;


  int count = 0;
  int bin [K];
  double expect [K];
  for(int i = 0 ; i < K; i++) {
    bin[i] = 0;
    expect[i] = N / K;
  }

  while (count < N) {
    double a = stan::math::frechet_rng(2.0,0.2,rng);
    int i = 0;
    while (i < K-1 && a > loc[i]) 
      ++i;
    ++bin[i];
    count++;
   }

  double chi = 0;

  for(int j = 0; j < K; j++)
    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);

  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));
}
Beispiel #25
0
void StartMenu::UpdateAll(){
  //Update all the icons/text on all the pages
	
  // Update Text
  ui->retranslateUi(this);
	
  //Update Icons
  ui->tool_goto_apps->setIcon(LXDG::findIcon("system-run",""));
  ui->tool_goto_settings->setIcon(LXDG::findIcon("preferences-system",""));
  ui->tool_launch_fm->setIcon(LXDG::findIcon("user-home",""));
  ui->tool_launch_desksettings->setIcon(LXDG::findIcon("preferences-desktop",""));
  ui->tool_lock->setIcon(LXDG::findIcon("system-lock-screen",""));
  ui->tool_goto_logout->setIcon(LXDG::findIcon("system-log-out",""));
  ui->tool_back->setIcon(LXDG::findIcon("go-previous",""));
  ui->tool_launch_deskinfo->setIcon(LXDG::findIcon("system-help",""));
	
  ui->tool_launch_mixer->setIcon( LXDG::findIcon("preferences-desktop-sound","") );
  ui->label_bright_icon->setPixmap( LXDG::findIcon("preferences-system-power-management","").pixmap(ui->tool_goto_apps->iconSize()) );
  ui->label_locale_icon->setPixmap( LXDG::findIcon("preferences-desktop-locale","").pixmap(ui->tool_goto_apps->iconSize()) );
  ui->tool_set_nextwkspace->setIcon(LXDG::findIcon("go-next-view",""));
  ui->tool_set_prevwkspace->setIcon(LXDG::findIcon("go-previous-view",""));
  ui->tool_logout->setIcon(LXDG::findIcon("system-log-out",""));
  ui->tool_restart->setIcon(LXDG::findIcon("system-reboot",""));
  ui->tool_shutdown->setIcon(LXDG::findIcon("system-shutdown",""));
  ui->tool_suspend->setIcon(LXDG::findIcon("system-suspend",""));
  
  //Update Visibility of system/session/OS options
  // -- Control Panel
  QString tmp = LOS::ControlPanelShortcut();
  if(QFile::exists(tmp)){
    ui->tool_launch_controlpanel->setWhatsThis(tmp);
    //Now read the file to see which icon to use
    bool ok = false;
    XDGDesktop desk = LXDG::loadDesktopFile(tmp, ok);
    if(ok && LXDG::checkValidity(desk)){
       ui->tool_launch_controlpanel->setIcon(LXDG::findIcon(desk.icon,"preferences-other"));
    }else{ ui->tool_launch_controlpanel->setVisible(false); }
  }else{ ui->tool_launch_controlpanel->setVisible(false); }
  // -- App Store
  tmp = LOS::AppStoreShortcut();
  if(QFile::exists(tmp)){
    ui->tool_launch_store->setWhatsThis(tmp);
    //Now read the file to see which icon to use
    bool ok = false;
    XDGDesktop desk = LXDG::loadDesktopFile(tmp, ok);
    if(ok && LXDG::checkValidity(desk)){
       ui->tool_launch_store->setIcon(LXDG::findIcon(desk.icon,"utilities-file-archiver"));
    }else{ ui->tool_launch_store->setVisible(false); }
  }else{ ui->tool_launch_store->setVisible(false); }
  //Audio Controls
  ui->frame_audio->setVisible( LOS::audioVolume() >=0 );
  //Brightness controls
  ui->frame_bright->setVisible( LOS::ScreenBrightness() >=0 );
  //Shutdown/restart
  bool ok = LOS::userHasShutdownAccess();
  ui->frame_leave_system->setWhatsThis(ok ? "allowed": "");
  ui->frame_leave_system->setVisible(ok);
  //Battery Availability
  ok = LOS::hasBattery();
  ui->label_status_battery->setWhatsThis(ok ? "allowed": "");
  ui->label_status_battery->setVisible(ok);
  //Locale availability
  QStringList locales = LUtils::knownLocales();
  ui->stackedWidget->setCurrentWidget(ui->page_main); //need to ensure the settings page is not active
  ui->combo_locale->clear();
  QString curr = LUtils::currentLocale();
  //qDebug() << "Update Locales:" << locales;
  //qDebug() << "Current Locale:" << curr;
  for(int i=0; i<locales.length(); i++){
    QLocale loc( (locales[i]=="pt") ? "pt_PT" : locales[i] );
    ui->combo_locale->addItem(loc.nativeLanguageName() +" ("+locales[i]+")", locales[i]); //Make the display text prettier later
    if(locales[i] == curr || locales[i] == curr.section("_",0,0) ){
      //Current Locale
      ui->combo_locale->setCurrentIndex(ui->combo_locale->count()-1); //the last item in the list right now
    }
  }
  ui->frame_locale->setVisible(locales.length() > 1);
  //User Name in status bar
  ui->label_status->setText( QString::fromLocal8Bit(getlogin()) );
  //Lumina Utilities
  ui->tool_launch_desksettings->setVisible(LUtils::isValidBinary("lumina-config"));
  ui->tool_launch_deskinfo->setVisible(LUtils::isValidBinary("lumina-info"));

}
Beispiel #26
0
int main()
{
    std::cout << "- Backends: ";
    #ifdef BOOST_LOCALE_WITH_ICU
    std::cout << "icu:" << U_ICU_VERSION << " ";
    #endif
    #ifndef BOOST_LOCALE_NO_STD_BACKEND
    std::cout << "std ";
    #endif
    #ifndef BOOST_LOCALE_NO_POSIX_BACKEND
    std::cout << "posix ";
    #endif
    #ifndef BOOST_LOCALE_NO_WINAPI_BACKEND
    std::cout << "winapi";
    #endif
    std::cout << std::endl;
    #ifdef BOOST_LOCALE_WITH_ICONV
    std::cout << "- With iconv" << std::endl;
    #else
    std::cout << "- Without iconv" << std::endl;
    #endif
    std::cout << "- Environment " << std::endl;
    std::cout << "  LANG="<< env("LANG") << std::endl;
    std::cout << "  LC_ALL="<< env("LC_ALL") << std::endl;
    std::cout << "  LC_CTYPE="<< env("LC_CTYPE") << std::endl;
    std::cout << "  TZ="<< env("TZ") << std::endl;

    char const *clocale=setlocale(LC_ALL,"");
    if(!clocale)
        clocale= "undetected";
    std::cout <<"- C locale: " << clocale << std::endl;

    try {
        std::locale loc("");
        std::cout << "- C++ locale: " << loc.name() << std::endl;
    }
    catch(std::exception const &) {
        std::cout << "- C++ locale: is not supported" << std::endl;
    }

    char const *locales_to_check[] = {
        "en_US.UTF-8", "en_US.ISO8859-1", "English_United States.1252",
        "he_IL.UTF-8", "he_IL.ISO8859-8", "Hebrew_Israel.1255",
        "ru_RU.UTF-8", "Russian_Russia.1251",
        "tr_TR.UTF-8", "Turkish_Turkey.1254",
        "ja_JP.UTF-8", "ja_JP.SJIS", "Japanese_Japan.932",
        0
    };
    std::cout << "- Testing locales availability on the operation system:" << std::endl;
    check_locale(locales_to_check);

    std::cout << "- Testing timezone and time " << std::endl;
    {
        setlocale(LC_ALL,"C");
        time_t now = time(0);
        char buf[1024];
        strftime(buf,sizeof(buf),"%%c=%c; %%Z=%Z; %%z=%z",localtime(&now));
        std::cout << "  Local Time    :" << buf << std::endl;
        strftime(buf,sizeof(buf),"%%c=%c; %%Z=%Z; %%z=%z",gmtime(&now));
        std::cout << "  Universal Time:" << buf << std::endl;
    }
    std::cout << "- Boost.Locale's locale: ";
    try {
        boost::locale::generator gen;
        std::locale l = gen("");
        std::cout << std::use_facet<boost::locale::info>(l).name() << std::endl;
    }
    catch(std::exception const &) {
        std::cout << " undetected" << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;

}
Beispiel #27
0
static void HHVM_METHOD(IntlGregorianCalendar, __ctor_array,
                        const Array& args) {
  assert(args.size() == 6);

  int32_t numargs;
  for (numargs = 0; numargs < 6; ++numargs) {
    if (args[numargs].isNull()) {
      break;
    }
  }

  if (numargs > 6) {
    s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
                           "intlgregcal_create_instance: too many arguments");
    return;
  }

  icu::GregorianCalendar *gcal = nullptr;
  SCOPE_EXIT { if (gcal) { delete gcal; } };
  icu::TimeZone *tz = nullptr;
  SCOPE_EXIT { if (gcal && tz) { delete tz; } };

  UErrorCode error;
  if (numargs < 3) {
    tz = IntlTimeZone::ParseArg(args[0], "intlgregcal_create_instance",
                                         s_intl_error.get());
    String loc(localeOrDefault(args[1].toString()));
    error = U_ZERO_ERROR;
    gcal = new icu::GregorianCalendar(tz,
               icu::Locale::createFromName(loc.c_str()), error);
    if (U_FAILURE(error)) {
      s_intl_error->setError(error, "intlgregcal_create_instance: error "
               "creating ICU GregorianCalendar from time zone and locale");
      return;
    }
    goto success;
  }

  int32_t intarg[6];
  assert(numargs <= 6);
  for (int i = 0; i < numargs; ++i) {
    int64_t arg = args[i].toInt64();
    if ((arg < INT32_MIN) || (arg > INT32_MAX)) {
      s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
                             "intlgregcal_create_instance: at least one of "
                             "the arguments has an absolute value that is "
                             "too large");
      return;
    }
    intarg[i] = (int32_t)arg;
  }

  error = U_ZERO_ERROR;
  switch (numargs) {
    case 3: // year, month, day
      gcal = new icu::GregorianCalendar(intarg[0], intarg[1], intarg[2],
                                        error);
      break;
    case 4:
      s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
                             "intlgregcal_create_instance: no variant with "
                             "4 arguments (excluding trailing NULLs)");
      return;
    case 5: // ..., hour, minute
      gcal = new icu::GregorianCalendar(intarg[0], intarg[1], intarg[2],
                                        intarg[3], intarg[4],
                                        error);
      break;
    case 6: // ..., second
      gcal = new icu::GregorianCalendar(intarg[0], intarg[1], intarg[2],
                                        intarg[3], intarg[4], intarg[5],
                                        error);
      break;
    default:
      not_reached();
      return;
  }
  if (U_FAILURE(error)) {
    s_intl_error->setError(error, "intlgregcal_create_instance: error "
                                  "creating ICU GregorianCalendar from date");
    return;
  }

  tz = IntlTimeZone::ParseArg(uninit_null(), "intlgregcal_create_instance",
                                             s_intl_error.get());
  if (!tz) {
    // error already set
    return;
  }
  gcal->adoptTimeZone(tz);

success:
  Native::data<IntlCalendar>(this_)->setCalendar(gcal);
  gcal = nullptr; // prevent SCOPE_EXIT sweeps
}
Beispiel #28
0
void IntlCalendarTest::TestBuddhistFormat() {
    UErrorCode status = U_ZERO_ERROR;
    
    // Test simple parse/format with adopt
    
    // First, a contrived english test..
    UDate aDate = 999932400000.0; 
    SimpleDateFormat *fmt = new SimpleDateFormat(UnicodeString("MMMM d, yyyy G"), Locale("en_US@calendar=buddhist"), status);
    CHECK(status, "creating date format instance");
    SimpleDateFormat *fmt2 = new SimpleDateFormat(UnicodeString("MMMM d, yyyy G"), Locale("en_US@calendar=gregorian"), status);
    CHECK(status, "creating gregorian date format instance");
    if(!fmt) { 
        errln("Coudln't create en_US instance");
    } else {
        UnicodeString str;
        fmt2->format(aDate, str);
        logln(UnicodeString() + "Test Date: " + str);
        str.remove();
        fmt->format(aDate, str);
        logln(UnicodeString() + "as Buddhist Calendar: " + escape(str));
        UnicodeString expected("September 8, 2544 BE");
        if(str != expected) {
            errln("Expected " + escape(expected) + " but got " + escape(str));
        }
        UDate otherDate = fmt->parse(expected, status);
        if(otherDate != aDate) { 
            UnicodeString str3;
            fmt->format(otherDate, str3);
            errln("Parse incorrect of " + escape(expected) + " - wanted " + aDate + " but got " +  otherDate + ", " + escape(str3));
        } else {
            logln("Parsed OK: " + expected);
        }
        delete fmt;
    }
    delete fmt2;
    
    CHECK(status, "Error occured testing Buddhist Calendar in English ");
    
    status = U_ZERO_ERROR;
    // Now, try in Thai
    {
        UnicodeString expect = CharsToUnicodeString("\\u0E27\\u0E31\\u0E19\\u0E40\\u0E2A\\u0E32\\u0E23\\u0E4C\\u0E17\\u0E35\\u0E48"
            " 8 \\u0E01\\u0E31\\u0e19\\u0e22\\u0e32\\u0e22\\u0e19 \\u0e1e.\\u0e28. 2544");
        UDate         expectDate = 999932400000.0;
        Locale        loc("th_TH_TRADITIONAL"); // legacy
        
        simpleTest(loc, expect, expectDate, status);
    }
    status = U_ZERO_ERROR;
    {
        UnicodeString expect = CharsToUnicodeString("\\u0E27\\u0E31\\u0E19\\u0E40\\u0E2A\\u0E32\\u0E23\\u0E4C\\u0E17\\u0E35\\u0E48"
            " 8 \\u0E01\\u0E31\\u0e19\\u0e22\\u0e32\\u0e22\\u0e19 \\u0e1e.\\u0e28. 2544");
        UDate         expectDate = 999932400000.0;
        Locale        loc("th_TH@calendar=buddhist");
        
        simpleTest(loc, expect, expectDate, status);
    }
    status = U_ZERO_ERROR;
    {
        UnicodeString expect = CharsToUnicodeString("\\u0E27\\u0E31\\u0E19\\u0E40\\u0E2A\\u0E32\\u0E23\\u0E4C\\u0E17\\u0E35\\u0E48"
            " 8 \\u0E01\\u0E31\\u0e19\\u0e22\\u0e32\\u0e22\\u0e19 \\u0e04.\\u0e28. 2001");
        UDate         expectDate = 999932400000.0;
        Locale        loc("th_TH@calendar=gregorian");
        
        simpleTest(loc, expect, expectDate, status);
    }
    status = U_ZERO_ERROR;
    {
        UnicodeString expect = CharsToUnicodeString("\\u0E27\\u0E31\\u0E19\\u0E40\\u0E2A\\u0E32\\u0E23\\u0E4C\\u0E17\\u0E35\\u0E48"
            " 8 \\u0E01\\u0E31\\u0e19\\u0e22\\u0e32\\u0e22\\u0e19 \\u0e04.\\u0e28. 2001");
        UDate         expectDate = 999932400000.0;
        Locale        loc("th_TH_TRADITIONAL@calendar=gregorian");
        
        simpleTest(loc, expect, expectDate, status);
    }
}
wstring 
TransferRule::gen_apertium_transfer_rule(bool debug) {

  locale loc(setlocale(LC_ALL,""));	
 
  wstring rule=L"";
  bool include_otherwise=true;

  if (ats.size()==0) {
    cerr<<"Error in TransferRule::gen_apertium_transfer_rule: No alignment templates available\n";
    exit(EXIT_FAILURE);
  }

  //Sort the AT so as to apply always the most frequent AT that
  //satisfies the restrictions
  AlignmentTemplateGreaterThanByCount atcomparer;
  sort(ats.begin(), ats.end(), atcomparer);

  //debug
  //cerr<<"ats.size(): "<<ats.size()<<endl;

  rule+=L"<rule>\n";

  //The pattern to detect is the same for all AT within this transfer rule
  rule+=L"  <pattern>\n";
  wstring chunkName=L"";
  
  vector<wstring> generalpattern=StringUtils::split_wstring(source,L" ");
  
  //for(unsigned i=0; i<ats[0].source.size(); i++) {
	
  for(unsigned i=0; i<generalpattern.size(); i++) {
    wstring lemma=Utils::get_lemma(generalpattern[i]);
    wstring tags=Utils::tags2transferformat(Utils::get_tags(generalpattern[i]));
    wstring tagsnogen=tags;
    remove_generalised_tags(tagsnogen);   
    
    chunkName+=L"__";
    if(sm_generalise)
    {
		wstring tmpstr=Utils::get_first_tag(Utils::get_tags(generalpattern[i])).substr(1);
		rule+=L"    <pattern-item n=\"CAT__"+category_name(L"",tmpstr.substr(0,tmpstr.size()-1)+L".*")+L"\"/>\n";
		chunkName+=category_name(L"",tmpstr.substr(0,tmpstr.size()-1)+L".*");
	}
	else
	{
		rule+=L"    <pattern-item n=\"CAT__"+category_name(lemma,tagsnogen)+L"\"/>\n";
		chunkName+=category_name(lemma,tagsnogen);
	}
    
  }
  rule+=L"  </pattern>\n";

  rule+=L"  <action>\n";
  rule+=L"    <choose>\n";




  //There is a set of different actions depending on the TL side of
  //each AT. Consequently, there's one <when> statement per AT 
  for(unsigned i=0; i<ats.size(); i++) {
    rule+=L"      <when>";
    rule+=L"<!--"+ats[i].to_wstring()+L"-->\n";
    rule+=L"        <test>\n";

    int nconditions=0;
    wstring teststr=L"";
	
    
    //This AT can be applied if all restrictions are met
    for(unsigned j=0; j<ats[i].restrictions.size(); j++){
	
      if (ats[i].restrictions[j]!=L"__CLOSEWORD__") {
		  
	nconditions++;
	
	//teststr+=L"          <or>\n";
	if (empty_restrictions_match_everything)
	{
	    wstring source_tags_transfer_format=Utils::tags2transferformat(Utils::get_tags(ats[i].source[j]));
	    remove_generalised_tags(source_tags_transfer_format);
	    remove_final_asterisk(source_tags_transfer_format);
	    vector<wstring> nongenTags=StringUtils::split_wstring(source_tags_transfer_format,L".");
	    
	    teststr+=L"           <and>\n";	
	    teststr+=L"            <begins-with>\n";
	    teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\"tags\" />\n";
	    teststr+=L"              <lit-tag v=\""+escape_attr(StringUtils::split_wstring(Utils::tags2transferformat(ats[i].restrictions[j]),L".")[0])+L"\"/>\n";
	    teststr+=L"            </begins-with>\n";
	    
	    vector<wstring> resTags=StringUtils::split_wstring(Utils::tags2transferformat(ats[i].restrictions[j]),L".");
	    wstring partofspeech=resTags[0];
	    
	    for (unsigned k=1 ; k<resTags.size(); k++)
	    {
		wstring tag=resTags[k];
		if(tag[0]==L'['){
		  wstring attr=tag.substr(1);
		  teststr+=L"               <equal>\n";
		  teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\"learned_"+attr+L"\"/>\n";
		  teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"sl\" part=\"learned_"+attr+L"\"/>\n";
		  teststr+=L"               </equal>\n";
		}
		else if(tag[0]==L']'){
		  wstring attr=tag.substr(1);
		  teststr+=L"               <not><equal>\n";
		  teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\"learned_"+attr+L"\"/>\n";
		  teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"sl\" part=\"learned_"+attr+L"\"/>\n";
		  teststr+=L"               </equal></not>\n";
		}
		else{
		  wstring attr=get_attribute_for_tag(tag,partofspeech);
		  //teststr+=L"               <or>\n";
		  teststr+=L"               <equal>\n";
		  teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\""+attr+L"\"/>\n";
		  if(tag.size() >= 10 && tag.substr(0,10)==L"empty_tag_" )
			teststr+=L"                 <lit v=\"\"/>\n";
		  else
			teststr+=L"                 <lit-tag v=\""+escape_attr(tag)+L"\"/>\n";
			
		  teststr+=L"               </equal>\n";
		  //Not necessary anymore
		  //A restriction with the same value that the sl tag may also mean that the tag dissappears (e.g., genders in es-en)
		  //if(std::find(nongenTags.begin(), nongenTags.end(), tag) != nongenTags.end()) {
		    //teststr+=L"               <equal>\n";
		    //teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\""+attr+L"\"/>\n";
		    //teststr+=L"                 <lit v=\"\"/>\n";
		    //teststr+=L"               </equal>\n";
		  //}  
		  //teststr+=L"               </or>\n";
		}
	    }
	    
	    teststr+=L"           </and>\n";	
	}
	else
	{
	teststr+=L"            <equal>\n";
	teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\"tags\" queue=\"no\"/>\n";
	teststr+=L"              <lit-tag v=\""+escape_attr(Utils::tags2transferformat(ats[i].restrictions[j]))+L"\"/>\n";
	teststr+=L"            </equal>\n";
	}

 
	int targetWordPos=ats[i].get_open_target_word_pos(j,false);
	
	if(targetWordPos!=-1)
	{
	
	wstring target_transfer_format=Utils::tags2transferformat(Utils::get_tags(ats[i].target[targetWordPos]));
	
	bool isGeneralised=false;
	for(int myi=0; myi<target_transfer_format.size(); myi++)
    {
		if(target_transfer_format[myi] == L'*')
		{
			target_transfer_format=target_transfer_format.substr(0,myi-1);
			isGeneralised=true;
			break;
		}
	} 
	
	if(!isGeneralised){
		if(!no_double_check_restrictions)
		{
			teststr+=L"            <equal>\n";
			teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\"tags\" queue=\"yes\"/>\n";
			teststr+=L"              <lit-tag v=\""+escape_attr(target_transfer_format)+L"\"/>\n";
			teststr+=L"            </equal>\n";
		}
	}
	else{
				
		vector<wstring> tltags=StringUtils::split_wstring(target_transfer_format,L".");
		wstring partofspeech=tltags[0];
		tltags.erase(tltags.begin());
		
		vector<wstring> tlattrs;
		for(vector<wstring>::iterator it=tltags.begin(); it!=tltags.end(); ++it){
			wstring attribute=get_attribute_for_tag((*it),*(tltags.begin()));
			tlattrs.push_back(attribute);
		}
		
		if(!no_double_check_restrictions)
		{
		
			if(tltags.size() > 0)
				teststr+=L"            <and>\n";
			
			if(attributes.find(attribute_pos_group_name(partofspeech))==attributes.end())
			{
				pair<wstring,pair<set<wstring>, set<wstring> > > newelement;
				newelement.first=attribute_pos_group_name(partofspeech);
				pair<set<wstring>, wstring> newelementvalue;
				newelementvalue.first.insert(partofspeech);
				//newelementvalue.second=L"";
				attributes.insert(newelement);
			}
			
			teststr+=L"               <equal>\n";
			teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\""+attribute_pos_group_name(partofspeech)+L"\"/>\n";
			teststr+=L"                 <lit-tag v=\""+partofspeech+L"\"/>\n";
			teststr+=L"               </equal>\n";
			
			for(int vcounter=0; vcounter < tltags.size(); vcounter++){
				teststr+=L"               <equal>\n";
				teststr+=L"                 <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\""+tlattrs[vcounter]+L"\"/>\n";
				teststr+=L"                 <lit-tag v=\""+escape_attr(tltags[vcounter])+L"\"/>\n";
				teststr+=L"               </equal>\n";
			}
			if(tltags.size() > 0)
				teststr+=L"            </and>\n";
		}
		
	}
	
	}

	//teststr+=L"          </or>\n";
      }
      
      //If we are working with generalised ATs, check also SL side, as
      //ATs with different left side may be grouped in the same rule
      if(sm_generalise || provided_patterns || using_explicit_empty_tags)
      {
		  wstring source_tags_transfer_format=Utils::tags2transferformat(Utils::get_tags(ats[i].source[j]));
		  wstring source_lemma=Utils::get_lemma(ats[i].source[j]);
		  
		  if(source_lemma.size() > 0 && (sm_generalise || provided_patterns))
		  {
			nconditions++;
			teststr+=L"            <or>";
			
			teststr+=L"            <equal>\n";
			teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"sl\" part=\"lem\" />\n";
			teststr+=L"              <lit v=\""+StringUtils::substitute(source_lemma,L"_",L" ")+L"\"/>\n";
			teststr+=L"            </equal>\n";
			
			teststr+=L"            <equal>\n";
			teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"sl\" part=\"lem\" />\n";
			teststr+=L"              <lit v=\"";
			teststr+=toupper<wchar_t>(StringUtils::substitute(source_lemma,L"_",L" ")[0],loc);
			teststr+=StringUtils::substitute(source_lemma,L"_",L" ").substr(1)+L"\"/>\n";
			teststr+=L"            </equal>\n";
			
			teststr+=L"            </or>\n";
			
		  }
		  
		  vector<wstring> alltags=StringUtils::split_wstring(source_tags_transfer_format,L".");
		  remove_generalised_tags(source_tags_transfer_format);
		  remove_final_asterisk(source_tags_transfer_format);
		  vector<wstring> nongenTags=StringUtils::split_wstring(source_tags_transfer_format,L".");
		  
		  
		  for(int tagi=1; tagi<nongenTags.size(); tagi++)
		  {
			if( !(nongenTags[tagi].size()>=3 &&  nongenTags[tagi].substr(0,3)==L"RES") )
			{
			nconditions++;
			teststr+=L"            <equal>\n";
			teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"sl\" part=\""+get_attribute_for_tag(nongenTags[tagi],nongenTags[0])+L"\" />\n";
			if(nongenTags[tagi].size() >= 10 && nongenTags[tagi].substr(0,10)==L"empty_tag_" )
				teststr+=L"              <lit v=\"\"/>\n";
			else
				teststr+=L"              <lit-tag v=\""+escape_attr(nongenTags[tagi])+L"\"/>\n";
			teststr+=L"            </equal>\n";
			}
		  }
		  
		  //I think this chunk of code should be removed anyway but...
		  if (!empty_restrictions_match_everything)
		    for(int tagi=1; tagi<alltags.size(); tagi++)
		    {
			    wstring tag=alltags[tagi];
			    if(tag.size()>0 && tag[0]==L'*')
			    {
				  nconditions++;
			      teststr+=L"            <equal>\n";
				  teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"sl\" part=\"learned_"+tag.substr(1)+L"\" />\n";
				  teststr+=L"              <clip pos=\""+Utils::itoa(j+1)+L"\" side=\"tl\" part=\"learned_"+tag.substr(1)+L"\" />\n";
				  teststr+=L"            </equal>\n";
				  
			    }
		    }
	  }
      
    }
    
	

    if (nconditions==0) { //All words were close words. We introduce a
			  //condition that is always true
      teststr+=L"          <equal>\n";
      teststr+=L"            <lit v=\"TRUE\"/>\n";
      teststr+=L"            <lit v=\"TRUE\"/>\n";
      teststr+=L"          </equal>\n";
      //LO COMENTO PARA QUE MIS SCRIPTS DE DEPURACION FUNCIONEN BIEN
      //include_otherwise=false;
    }

    if (nconditions>1) // There are more than one restriction to test
      rule+=L"        <and>\n";

    rule+=teststr;

    if (nconditions>1)
      rule+=L"        </and>\n";

    rule+=L"        </test>\n";

    if (debug) {
      wstring s=StringUtils::substitute(ats[i].to_wstring(), L"><", L".");
      s=StringUtils::substitute(s,L"<",L"-");
      s=StringUtils::substitute(s,L">",L"");
      rule+=L"        <out>\n";
      rule+=L"          <lu><lit v=\"(rid:"+Utils::itoa(rule_id)+L" at:"+s+L")\"/></lu>\n";
      rule+=L"        </out>\n";
    }
    
    wstring letvarStrs=L"";
    rule+=L"       <out>\n";
    
    if (generate_chunks)
    {
       rule+=L"       <chunk name=\""+chunkName+L"\" case=\"caseFirstWord\">";
       rule+=L"       <tags>";
       rule+=L"             <tag><lit-tag v=\"LRN\"/></tag>";
       rule+=L"       </tags>";
    }
    
    
    int blank_pos=0;
    for(unsigned j=0; j<ats[i].target.size(); j++) {      
      if (ats[i].target[j][0]!='<') { //It's a lexicalized word, we copy it as is
    
    wstring target_tags=Utils::tags2transferformat(Utils::get_tags(ats[i].target[j]));
    wstring tagstoprint=Utils::tags2transferformat(Utils::get_tags(ats[i].target[j]));
	vector<wstring> attributeNames=extract_attribute_names(tagstoprint);
	vector<wstring> tagvector=StringUtils::split_wstring(tagstoprint,L".");
	//remove_generalised_tags(tagstoprint);
	//remove_final_asterisk(tagstoprint);
    
    int pos=-1;
    
    //Some tags come from bilingual dictionary. Get correct gender and number in case of GD/ND
    //if(attributeNames.size() > 0)
//	{
// 		pos=ats[i].get_source_word_pos(j);
// 		rule+=L"        <call-macro n=\"f_set_genre_num\">\n";
// 		rule+=L"          <with-param pos=\""+Utils::itoa(pos+1)+L"\"/>\n";
// 		rule+=L"        </call-macro>\n";
// 	}
    
// 	rule+=L"        <out>\n";
	rule+=L"          <lu>\n";
	rule+=L"            <lit v=\""+StringUtils::substitute(Utils::get_lemma_without_queue(ats[i].target[j]),L"_",L" ")+L"\"/>\n";
	//rule+=L"            <lit-tag v=\""+tagstoprint+L"\"/>\n";
	
	//Some tags come from bilingual dictionary.
	for(vector<wstring>::iterator it=tagvector.begin(); it!=tagvector.end(); ++it){
		if( (*it).substr(0,1)==L"*" )
			rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"sl\" part=\"learned_"+(*it).substr(1)+L"\"/>\n";
		else if ( (*it).substr(0,1)==L")" )
		{
			long locpos=Utils::wtol((*it).substr(1,4));
			rule+=L"            <clip pos=\""+Utils::itoa((int) (locpos+1))+L"\" side=\"tl\" part=\"learned_"+(*it).substr(4)+L"\"/>\n";
		}
		else if ( (*it).substr(0,1)==L"(" )
		{
			long locpos=Utils::wtol((*it).substr(1,4));
			rule+=L"            <clip pos=\""+Utils::itoa((int) (locpos+1))+L"\" side=\"sl\" part=\"learned_"+(*it).substr(4)+L"\"/>\n";
		}
		else
			rule+=L"            <lit-tag v=\""+escape_attr((*it))+L"\"/>\n";
		}
	//if(attributeNames.size() > 0)
	//{
	//	for(vector<wstring>::iterator it=attributeNames.begin(); it!=attributeNames.end(); ++it){
	//		rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"sl\" part=\""+(*it)+L"\"/>\n";
	//	}
	//}
	//rule+=L"            <lit-tag v=\""+target_tags+L"\"/>\n";
	rule+=L"            <lit v=\""+StringUtils::substitute(Utils::get_queue(ats[i].target[j]),L"_",L" ")+L"\"/>\n";
	rule+=L"          </lu>\n";
// 	rule+=L"        </out>\n";

	//Some tags come from bilingual dictionary. Copy gender/number to global variables
// 	if(attributeNames.size() > 0)
// 	{
// 		rule+=L"        <call-macro n=\"f_genre_num\">\n";
//         rule+=L"          <with-param pos=\""+Utils::itoa(pos+1)+L"\"/>\n";
//         rule+=L"        </call-macro>\n";
// 	}
	
	//Copy gender/number to global variables in case that they come directly from AT
	wstring genre=Utils::get_tag_value(tagstoprint,L"m|f");
	if(genre.length()>0)
	  letvarStrs+=L"        <let><var n=\"genre\"/><lit-tag v=\""+genre+L"\"/></let>\n";
	wstring number=Utils::get_tag_value(tagstoprint,L"sg|pl");
	if(number.length()>0)
	  letvarStrs+=L"        <let><var n=\"number\"/><lit-tag v=\""+number+L"\"/></let>\n";

      } else {

	wstring tagstoprint=Utils::tags2transferformat(Utils::get_tags(ats[i].target[j]));
	vector<wstring> attributeNames=extract_attribute_names(tagstoprint);
	vector<wstring> tagvector=StringUtils::split_wstring(tagstoprint,L".");
	
	//remove_generalised_tags(tagstoprint);
	//remove_final_asterisk(tagstoprint);
	int pos=ats[i].get_first_open_source_word_pos(j);
	
	//Some tags come from bilingual dictionary. Get correct gender and number in case of GD/ND
//     if(attributeNames.size() > 0)
// 	{
// 		int pos=ats[i].get_source_word_pos(j);
// 		rule+=L"        <call-macro n=\"f_set_genre_num\">\n";
// 		rule+=L"          <with-param pos=\""+Utils::itoa(pos+1)+L"\"/>\n";
// 		rule+=L"        </call-macro>\n";
// 	}
	
// 	rule+=L"        <out>\n";
	rule+=L"          <lu>\n";
	if(do_rbpe){
	rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"sl\" part=\"lemh\"/>\n";
	}
	else{
	rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"tl\" part=\"lemh\"/>\n";
	}
	
	
	for(vector<wstring>::iterator it=tagvector.begin(); it!=tagvector.end(); ++it){
		if( (*it).substr(0,1)==L"*" )
			rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"sl\" part=\"learned_"+(*it).substr(1)+L"\"/>\n";
		else if ( (*it).substr(0,1)==L")" )
		{
			long locpos=Utils::wtol((*it).substr(1,4));
			rule+=L"            <clip pos=\""+Utils::itoa((int) (locpos+1))+L"\" side=\"tl\" part=\"learned_"+(*it).substr(4)+L"\"/>\n";
		}
		else if ( (*it).substr(0,1)==L"(" )
		{
			long locpos=Utils::wtol((*it).substr(1,4));
			rule+=L"            <clip pos=\""+Utils::itoa((int) (locpos+1))+L"\" side=\"sl\" part=\"learned_"+(*it).substr(4)+L"\"/>\n";
		}
		else
			rule+=L"            <lit-tag v=\""+escape_attr((*it))+L"\"/>\n";
	}
	
	//rule+=L"            <lit-tag v=\""+tagstoprint+L"\"/>\n";
	
	//for(vector<wstring>::iterator it=attributeNames.begin(); it!=attributeNames.end(); ++it){
	//	rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"tl\" part=\""+(*it)+L"\"/>\n";
	//}
	
	if(do_rbpe){
	rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"sl\" part=\"lemq\"/>\n";
	}
	else{
	rule+=L"            <clip pos=\""+Utils::itoa(pos+1)+L"\" side=\"tl\" part=\"lemq\"/>\n";
	}
	rule+=L"          </lu>\n";
// 	rule+=L"        </out>\n";

        
        //Some tags come from bilingual dictionary. Copy gender/number to global variables
// 	if(attributeNames.size() > 0)
// 	{
//         rule+=L"        <call-macro n=\"f_genre_num\">\n";
//         rule+=L"          <with-param pos=\""+Utils::itoa(pos+1)+L"\"/>\n";
//         rule+=L"        </call-macro>\n";
//      }
        
	//Copy gender/number to global variables in case that they come directly from AT
	wstring genre=Utils::get_tag_value(tagstoprint,L"m|f");
	if(genre.length()>0)
	  letvarStrs+=L"        <let><var n=\"genre\"/><lit-tag v=\""+genre+L"\"/></let>\n";
	wstring number=Utils::get_tag_value(tagstoprint,L"sg|pl");
	if(number.length()>0)
	  letvarStrs+=L"        <let><var n=\"number\"/><lit-tag v=\""+number+L"\"/></let>\n";
        
      }

      if (blank_pos<(int)(ats[i].source.size()-1)) {
// 	rule+=L"        <out>\n";
	rule+=L"          <b pos=\""+Utils::itoa(blank_pos+1)+L"\"/>\n";
// 	rule+=L"        </out>\n";
	blank_pos++;
      } else if (j<(ats[i].target.size()-1)) {
	//TL output string has more words than the SL pattern detected
// 	rule+=L"        <out>\n";
	rule+=L"          <b/>\n";
// 	rule+=L"        </out>\n";
      }
    }

     if (generate_chunks)
     {
       rule+=L"      </chunk>\n";
     }
    rule+=L"      </out>\n";
    
     if (debug) {
      rule+=L"        <out>\n";
      rule+=L"          <lu><lit v=\"(END)\"/></lu>\n";
      rule+=L"        </out>\n";
    }
    
    //If there are remaining blanks we print them out if they have
    //format information inside. This is caused by a SL input string
    //longer than the TL output one
    for (unsigned j=ats[i].target.size(); j<ats[i].source.size(); j++) {
      rule+=L"        <call-macro n=\"f_bcond\">\n";
      rule+=L"          <with-param pos=\""+Utils::itoa(j)+L"\"/>\n";
      rule+=L"          <with-param pos=\""+Utils::itoa(j+1)+L"\"/>\n";
      rule+=L"        </call-macro>\n";
    }
    
    rule+=letvarStrs;
    rule+=L"      </when>\n";

    if(!include_otherwise) {
      //As the condition will always be met it has no sense to include
      //further ATs
      break;
    }
  }



  //Actions to perform when none of the ATs can be applied
  //word-for-word translation
  if(include_otherwise) {
    rule+=L"      <otherwise><!--Word-for-word translation-->\n";
     if (debug) {
      rule+=L"        <out>\n";
      rule+=L"          <lu><lit v=\"(rid:"+Utils::itoa(rule_id)+L" at:word-for-word)\"/></lu>\n";
      rule+=L"        </out>\n";
    }
    
	  if(use_discard_rule)
	  {
		rule+=L"        <reject-current-rule shifting=\"no\" />\n";
 rule+=L" <out><chunk name=\"any\" case=\"caseFirstWord\"><tags>             <tag><lit-tag v=\"LRN\"/></tag>       </tags> <lu>";
  if(do_rbpe){
	  rule+=L"<clip pos=\"1\" side=\"sl\" part=\"whole\"/>";
  }
  else{
   rule+=L"<clip pos=\"1\" side=\"tl\" part=\"whole\"/>";
  }
   rule+=L"</lu></chunk></out> </action><!--isolated word-->\n";

	  }
	  else
	  {

    for(unsigned i=0; i<ats[0].source.size(); i++) {
      rule+=L"        <call-macro n=\"f_genre_num\">\n";
      rule+=L"          <with-param pos=\""+Utils::itoa(i+1)+L"\"/>\n";
      rule+=L"        </call-macro>\n";

      rule+=L"        <call-macro n=\"f_set_genre_num\">\n";
      rule+=L"          <with-param pos=\""+Utils::itoa(i+1)+L"\"/>\n";
      rule+=L"        </call-macro>\n";

      rule+=L"        <out>\n";
      rule+=L"          <lu>\n";

      rule+=L"            <clip pos=\""+Utils::itoa(i+1)+L"\" side=\"tl\" part=\"whole\"/>\n";
      //rule+=L"            <clip pos=\""+Utils::itoa(i+1)+L"\" side=\"tl\" part=\"lemh\"/>\n";
      //rule+=L"            <clip pos=\""+Utils::itoa(i+1)+L"\" side=\"tl\" part=\"tags\"/>\n";
      //rule+=L"            <clip pos=\""+Utils::itoa(i+1)+L"\" side=\"tl\" part=\"lemq\"/>\n";

      rule+=L"          </lu>\n";
      if (i<(ats[0].source.size()-1))
	rule+=L"          <b pos=\""+Utils::itoa(i+1)+L"\"/>\n";
      rule+=L"        </out>\n";
    }
    if (debug) {
      rule+=L"        <out>\n";
      rule+=L"          <lu><lit v=\"(END)\"/></lu>\n";
      rule+=L"        </out>\n";
    }
  }

    rule+=L"      </otherwise>\n";
  }

  rule+=L"    </choose>\n";
  rule+=L"  </action>\n";
  rule+=L"</rule>\n";

  return rule;
}
Beispiel #30
0
int main() {
    //tokennizer
    Tokenizer tokenizer("../dataset/perloc/PerLoc.input", false);
    vector<Text_token> text_tokens = tokenizer.scan();
    //测试 extract_regex
    /*
     create view cap as
     extract regex /[A-Z][a-z]* /
     on D.text
     return group 0 as Cap
     from Document D;
     */
    View cap("cap");
    vector<int> groups;
    groups.push_back(0);
    vector<string> column_names;
    column_names.push_back("Cap");
    string text = tokenizer.text;
    cap.extract_regex("[A-Z][a-z]*", groups, column_names, text);
    cap.output("");
    //测试 extract_regex
    /*
     create view loc as
     extract regex /Washington|Georgia|Virginia/
     on D.text
     return group 0 as loc
     from Document D;
     */
    View loc("loc");
    groups.clear();
    groups.push_back(0);
    column_names.clear();
    column_names.push_back("loc");
    loc.extract_regex("Washington|Georgia|Virginia",
                      groups,
                      column_names,
                      text);
    loc.output("");
    //测试 select
    /*
     create view perloc as
      select c.Cap as col1
      from cap c;
     */
    View perloc("perloc");
    vector<string> column_names2;
    column_names2.push_back("col1");
    vector<Column> columns2;
    columns2.push_back(cap.columns[0]);
    perloc.select(columns2, column_names2);
	perloc.output("");
    //测试 extract_pattern
    /*
     create view pl as
     extract pattern (<c.cap>) /,/ (<l.loc>)
     return group 0 as Loc
     and group 1 as cap
     and group 2 as stt
     from cat c, loc l;
     */
    View pl("pl");
    vector<Atom> atoms;
    atoms.push_back(Atom(
                         COLUMN,
                         0,
                         0,
                         "",
                         cap.columns[0]
                    ));
    atoms.push_back(Atom(
                         REG,
                         0,
                         0,
                         ",",
                         Column()
                         ));
    atoms.push_back(Atom(
                         COLUMN,
                         0,
                         0,
                         "",
                         loc.columns[0]
                        ));
    vector<int> groups_;
    vector<string> names(1, "123");
    groups_.push_back(0);
    groups_.push_back(atoms.size());
    
    pl.extract_pattern(atoms,
                            groups_,
                            names,
                            text_tokens,
                            text
                            );
    pl.output("");
}