Exemple #1
0
int Molecule::get_new_frames() {
  int newframes = 0;

  // add a new frame if there are frames available in the I/O queue
  if (next_frame())
    newframes = 1; 

  // If an IMD simulation is in progress, store the forces in the current
  // timestep and send them to the simulation.  Otherwise, just toss them.
  if (app->imd_connected(id())) {
    // Add persistent forces to regular forces
    int ii;
    for (ii=0; ii<persistent_force_indices.num(); ii++) 
      force_indices.append(persistent_force_indices[ii]);
    for (ii=0; ii<persistent_force_vectors.num(); ii++) 
      force_vectors.append(persistent_force_vectors[ii]);

    // Clear old forces out of the timestep
    Timestep *ts = current();
    if (ts && ts->force) {
      memset(ts->force, 0, 3*nAtoms*sizeof(float));
    }

    // Check for atoms forced last time that didn't show up this time.
    // XXX order N^2 in number of applied forces; could be easily improved.
    // But N now is usually 1 or 2.
    ResizeArray<int> zero_force_indices;
    ResizeArray<float> zero_forces;
    for(ii=0; ii<last_force_indices.num(); ii++) {
      int j;
      int index_missing=1;
      for (j=0; j<force_indices.num(); j++) {
        if (force_indices[j]==last_force_indices[ii]) {
          index_missing=0;
          break;
        }
      }
      if (index_missing) {
        // this one didn't show up this time
        zero_force_indices.append(last_force_indices[ii]);
        zero_forces.append(0);
        zero_forces.append(0);
        zero_forces.append(0);
      }
    }

    if (zero_force_indices.num()) {
      // There some atoms forced last time that didn't show up this time.
      app->imd_sendforces(zero_force_indices.num(), &(zero_force_indices[0]),
                          &(zero_forces[0]));
    }

    // now clear the last forces so we don't send them again
    last_force_indices.clear();

    // Set/send forces if we got any
    if (force_indices.num()) {
      if (ts) {
        if (!ts->force) {
          ts->force = new float[3*nAtoms];
          memset(ts->force, 0, 3*nAtoms*sizeof(float));
        }
        for (int i=0; i<force_indices.num(); i++) {
          int ind = force_indices[i];
          ts->force[3*ind  ] += force_vectors[3*i  ];
          ts->force[3*ind+1] += force_vectors[3*i+1];
          ts->force[3*ind+2] += force_vectors[3*i+2];
        }
      }
      // XXX If we send multiple forces for the same atom, NAMD will keep only
      // the last force.  We therefore have to sum multiple contributions to the
      // same atom before sending.  Annoying.
      ResizeArray<float> summed_forces;
      int i;
      for (i=0; i<force_indices.num(); i++) {
        int ind = force_indices[i];
        summed_forces.append(ts->force[3*ind  ]);
        summed_forces.append(ts->force[3*ind+1]);
        summed_forces.append(ts->force[3*ind+2]);
      }
      app->imd_sendforces(force_indices.num(), &(force_indices[0]),
        &(summed_forces[0]));

      // save the force indices before clearing them
      for (i=0; i<force_indices.num(); i++) {
        last_force_indices.append(force_indices[i]);
      }

      // now clear the force indices
      force_indices.clear();
      force_vectors.clear();
    }
  }

  // Inform the top level class that background processing
  // is going on to prevent the CPU throttling code from activating
  if (newframes > 0)
    app->background_processing_set();

  return newframes;  
}
Exemple #2
0
 bool atParagraphSeparator() const
 {
     // Within a cue, paragraph boundaries are only denoted by Type B characters,
     // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
     return WTF::Unicode::category(current()) & WTF::Unicode::Separator_Paragraph;
 }
/**
 * Rearranges the atomic entities in this container in a way that connected
 * entities are stored in the right order and direction.
 * Non-recoursive. Only affects atomic entities in this container.
 *
 * @retval true all contours were closed
 * @retval false at least one contour is not closed
 */
bool RS_EntityContainer::optimizeContours() {

    RS_DEBUG->print("RS_EntityContainer::optimizeContours");

    RS_Vector current(false);
    RS_Vector start(false);
    RS_EntityContainer tmp;

    bool changed = false;
    bool closed = true;

    for (uint ci=0; ci<count(); ++ci) {
        RS_Entity* e1=entityAt(ci);

        if (e1!=NULL && e1->isEdge() && !e1->isContainer() &&
                !e1->isProcessed()) {

            RS_AtomicEntity* ce = (RS_AtomicEntity*)e1;

            // next contour start:
            ce->setProcessed(true);
            tmp.addEntity(ce->clone());
            current = ce->getEndpoint();
            start = ce->getStartpoint();

            // find all connected entities:
            bool done;
            do {
                done = true;
                for (uint ei=0; ei<count(); ++ei) {
                    RS_Entity* e2=entityAt(ei);

                    if (e2!=NULL && e2->isEdge() && !e2->isContainer() &&
                            !e2->isProcessed()) {

                        RS_AtomicEntity* e = (RS_AtomicEntity*)e2;

                        if (e->getStartpoint().distanceTo(current) <
                                1.0e-4) {

                            e->setProcessed(true);
                            tmp.addEntity(e->clone());
                            current = e->getEndpoint();

                            done=false;
                        } else if (e->getEndpoint().distanceTo(current) <
                                   1.0e-4) {

                            e->setProcessed(true);
                            RS_AtomicEntity* cl = (RS_AtomicEntity*)e->clone();
                            cl->reverse();
                            tmp.addEntity(cl);
                            current = cl->getEndpoint();

                            changed = true;
                            done=false;
                        }
                    }
                }
                if (!done) {
                    changed = true;
                }
            } while (!done);

            if (current.distanceTo(start)>1.0e-4) {
                closed = false;
            }
        }
    }

    // remove all atomic entities:
    bool done;
    do {
        done = true;
        for (RS_Entity* en=firstEntity(); en!=NULL; en=nextEntity()) {
            if (!en->isContainer()) {
                removeEntity(en);
                done = false;
                break;
            }
        }
    } while (!done);

    // add new sorted entities:
    for (RS_Entity* en=tmp.firstEntity(); en!=NULL; en=tmp.nextEntity()) {
        en->setProcessed(false);
        addEntity(en->clone());
    }

    RS_DEBUG->print("RS_EntityContainer::optimizeContours: OK");
    return closed;
}
Exemple #4
0
int SeqSummaryCommand::MPICreateSummary(int start, int num, vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long long>& MPIPos) {	
	try {
		
		int pid;
		MPI_Status status; 
		MPI_Comm_rank(MPI_COMM_WORLD, &pid); 

		for(int i=0;i<num;i++){
			
			if (m->control_pressed) { return 0; }
			
			//read next sequence
			int length = MPIPos[start+i+1] - MPIPos[start+i];
	
			char* buf4 = new char[length];
			MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
			
			string tempBuf = buf4;
			if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
			istringstream iss (tempBuf,istringstream::in);
			delete buf4;

			Sequence current(iss);  

			if (current.getName() != "") {
				
				int num = 1;
				if ((namefile != "") || (countfile != "")) {
					//make sure this sequence is in the namefile, else error 
					map<string, int>::iterator it = nameMap.find(current.getName());
					
					if (it == nameMap.end()) { cout << "[ERROR]: " << current.getName() << " is not in your name or count file, please correct." << endl; m->control_pressed = true; }
					else { num = it->second; }
				}
				
				//for each sequence this sequence represents
				for (int j = 0; j < num; j++) {
					startPosition.push_back(current.getStartPos());
					endPosition.push_back(current.getEndPos());
					seqLength.push_back(current.getNumBases());
					ambigBases.push_back(current.getAmbigBases());
					longHomoPolymer.push_back(current.getLongHomoPolymer());
				}
				
				string outputString = current.getName() + "\t" + toString(current.getStartPos()) + "\t" + toString(current.getEndPos()) + "\t";
				outputString += toString(current.getNumBases()) + "\t" + toString(current.getAmbigBases()) + "\t" + toString(current.getLongHomoPolymer()) + "\t" + toString(num) + "\n";
				
				//output to file
				length = outputString.length();
				char* buf3 = new char[length];
				memcpy(buf3, outputString.c_str(), length);
					
				MPI_File_write_shared(outMPI, buf3, length, MPI_CHAR, &status);
				delete buf3;
			}	
		}
		
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "SeqSummaryCommand", "MPICreateSummary");
		exit(1);
	}
}
Exemple #5
0
 void ReorderBuildStrategy::_handleMatchNoDedup( ResultDetails* resultDetails ) {
     DiskLoc loc = _cursor->currLoc();
     _scanAndOrder->add( current( false, resultDetails ),
                         _parsedQuery.showDiskLoc() ? &loc : 0 );
 }
void RelocIterator::print_current() {
  if (!has_current()) {
    tty->print_cr("(no relocs)");
    return;
  }
  tty->print("relocInfo@" INTPTR_FORMAT " [type=%d(%s) addr=" INTPTR_FORMAT,
	     _current, type(), reloc_type_string((relocInfo::relocType) type()), _addr);
  if (current()->format() != 0)
    tty->print(" format=%d", current()->format());
  if (datalen() == 1) {
    tty->print(" data=%d", data()[0]);
  } else if (datalen() > 0) {
    tty->print(" data={");
    for (int i = 0; i < datalen(); i++) {
      tty->print("%04x", data()[i] & 0xFFFF);
    }
    tty->print("}");
  }
  tty->print("]");
  switch (type()) {
  case relocInfo::oop_type:
    {
      oop_Relocation* r = oop_reloc();
      oop* oop_addr  = NULL;
      oop  raw_oop   = NULL;
      oop  oop_value = NULL;
      if (code() != NULL || r->oop_index() == 0) {
	oop_addr  = r->oop_addr();
	raw_oop   = *oop_addr;
	oop_value = r->oop_value();
      }
      tty->print_cr(" | [oop_addr=" INTPTR_FORMAT " *=" INTPTR_FORMAT " offset=%d]",
		    oop_addr, raw_oop, r->offset());
      // Do not print the oop by default--we want this routine to
      // work even during GC or other inconvenient times.
      if (WizardMode && oop_value != NULL) {
	tty->print("oop_value=" INTPTR_FORMAT ": ", oop_value);
	oop_value->print_value_on(tty);
      }
      break;
    }
  case relocInfo::external_word_type:
  case relocInfo::internal_word_type:
    {
      DataRelocation* r = (DataRelocation*) reloc();
      tty->print(" | [target=" INTPTR_FORMAT "]", r->value()); //value==target
      break;
    }
  case relocInfo::static_call_type:
  case relocInfo::runtime_call_type:
    {
      CallRelocation* r = (CallRelocation*) reloc();
      tty->print(" | [destination=" INTPTR_FORMAT "]", r->destination());
      break;
    }
  case relocInfo::virtual_call_type:
    {
      virtual_call_Relocation* r = (virtual_call_Relocation*) reloc();
      tty->print(" | [destination=" INTPTR_FORMAT " first_oop=" INTPTR_FORMAT " oop_limit=" INTPTR_FORMAT "]",
		 r->destination(), r->first_oop(), r->oop_limit());
      break;
    }
  case relocInfo::static_stub_type:
    {
      static_stub_Relocation* r = (static_stub_Relocation*) reloc();
      tty->print(" | [static_call=" INTPTR_FORMAT "]", r->static_call());
      break;
    }
  }
  tty->cr();
}
Exemple #7
0
int SeqSummaryCommand::driverCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename, string sumFile, linePair* filePos) {	
	try {
		
		ofstream outSummary;
		m->openOutputFile(sumFile, outSummary);
		
		//print header if you are process 0
		if (filePos->start == 0) {
			outSummary << "seqname\tstart\tend\tnbases\tambigs\tpolymer\tnumSeqs" << endl;	
		}
				
		ifstream in;
		m->openInputFile(filename, in);
				
		in.seekg(filePos->start);

		bool done = false;
		int count = 0;
        
        
		while (!done) {
				
			if (m->control_pressed) { in.close(); outSummary.close(); return 1; }
            
            if (m->debug) { m->mothurOut("[DEBUG]: count = " + toString(count) + "\n");  }
            
			Sequence current(in); m->gobble(in);
           
			if (current.getName() != "") {
				
                if (m->debug) { m->mothurOut("[DEBUG]: " + current.getName() + '\t' + toString(current.getNumBases()) + "\n");  }
                
				int num = 1;
				if ((namefile != "") || (countfile != "")) {
					//make sure this sequence is in the namefile, else error 
					map<string, int>::iterator it = nameMap.find(current.getName());
					
					if (it == nameMap.end()) { m->mothurOut("[ERROR]: '" + current.getName() + "' is not in your name or count file, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
					else { num = it->second; }
				}
				
				//for each sequence this sequence represents
				for (int i = 0; i < num; i++) {
					startPosition.push_back(current.getStartPos());
					endPosition.push_back(current.getEndPos());
					seqLength.push_back(current.getNumBases());
					ambigBases.push_back(current.getAmbigBases());
					longHomoPolymer.push_back(current.getLongHomoPolymer());
				}
				count++;
				outSummary << current.getName() << '\t';
				outSummary << current.getStartPos() << '\t' << current.getEndPos() << '\t';
				outSummary << current.getNumBases() << '\t' << current.getAmbigBases() << '\t';
				outSummary << current.getLongHomoPolymer() << '\t' << num << endl;
                
                if (m->debug) { m->mothurOut("[DEBUG]: " + current.getName() + '\t' + toString(current.getNumBases()) + "\n");  }
			}
			
			#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
				unsigned long long pos = in.tellg();
				if ((pos == -1) || (pos >= filePos->end)) { break; }
			#else
				if (in.eof()) { break; }
			#endif
		}
				
		in.close();
		
		return count;
	}
	catch(exception& e) {
		m->errorOut(e, "SeqSummaryCommand", "driverCreateSummary");
		exit(1);
	}
}
Exemple #8
0
void GlutWindow::refreshTimer(int _val) {
  current()->displayTimer(_val);
}
Exemple #9
0
void GlutWindow::runTimer(int _val) {
  current()->simTimer(_val);
}
Exemple #10
0
void GlutWindow::refresh() {
  current()->render();
}
Exemple #11
0
void GlutWindow::mouseMove(int _x, int _y) {
  current()->move(_x, _y);
}
Exemple #12
0
void GlutWindow::mouseDrag(int _x, int _y) {
  current()->drag(_x, _y);
}
Exemple #13
0
 QLayoutItem* next()
 {
     m_idx++;
     return current();
 }
Exemple #14
0
void
threadmain(int argc, char *argv[])
{
	int i, got, scr;
	Text *t;
	Rectangle r;
	Flayer *nwhich;

	getscreen(argc, argv);
	iconinit();
	initio();
	scratch = alloc(100*RUNESIZE);
	nscralloc = 100;
	r = screen->r;
	r.max.y = r.min.y+Dy(r)/5;
	flstart(screen->clipr);
	rinit(&cmd.rasp);
	flnew(&cmd.l[0], gettext, 1, &cmd);
	flinit(&cmd.l[0], r, font, cmdcols);
	cmd.nwin = 1;
	which = &cmd.l[0];
	cmd.tag = Untagged;
	outTs(Tversion, VERSION);
	startnewfile(Tstartcmdfile, &cmd);

	got = 0;
	for(;;got = waitforio()){
		if(hasunlocked && RESIZED())
			resize();
		if(got&(1<<RHost))
			rcv();
		if(got&(1<<RPlumb)){
			for(i=0; cmd.l[i].textfn==0; i++)
				;
			current(&cmd.l[i]);
			flsetselect(which, cmd.rasp.nrunes, cmd.rasp.nrunes);
			type(which, RPlumb);
		}
		if(got&(1<<RKeyboard))
			if(which)
				type(which, RKeyboard);
			else
				kbdblock();
		if(got&(1<<RMouse)){
			if(hostlock==2 || !ptinrect(mousep->xy, screen->r)){
				mouseunblock();
				continue;
			}
			nwhich = flwhich(mousep->xy);
			scr = which && ptinrect(mousep->xy, which->scroll);
			if(mousep->buttons)
				flushtyping(1);
			if(mousep->buttons&1){
				if(nwhich){
					if(nwhich!=which)
						current(nwhich);
					else if(scr)
						scroll(which, 1);
					else{
						t=(Text *)which->user1;
						if(flselect(which)){
							outTsl(Tdclick, t->tag, which->p0);
							t->lock++;
						}else if(t!=&cmd)
							outcmd();
					}
				}
			}else if((mousep->buttons&2) && which){
				if(scr)
					scroll(which, 2);
				else
					menu2hit();
			}else if((mousep->buttons&4)){
				if(scr)
					scroll(which, 3);
				else
					menu3hit();
			}
			mouseunblock();
		}
	}
}
bool CGUIDialogContextMenu::OnContextButton(const std::string &type, const CFileItemPtr& item, CONTEXT_BUTTON button)
{
  // Add Source doesn't require a valid share
  if (button == CONTEXT_BUTTON_ADD_SOURCE)
  {
    if (CProfilesManager::GetInstance().IsMasterProfile())
    {
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;
    }
    else if (!CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked())
      return false;

    return CGUIDialogMediaSource::ShowAndAddMediaSource(type);
  }

  // buttons that are available on both sources and autosourced items
  if (!item) return false;

  switch (button)
  {
  case CONTEXT_BUTTON_EJECT_DRIVE:
    return g_mediaManager.Eject(item->GetPath());

#ifdef HAS_DVD_DRIVE
  case CONTEXT_BUTTON_PLAY_DISC:
    return MEDIA_DETECT::CAutorun::PlayDisc(item->GetPath(), true, true); // restart

  case CONTEXT_BUTTON_RESUME_DISC:
    return MEDIA_DETECT::CAutorun::PlayDisc(item->GetPath(), true, false); // resume

  case CONTEXT_BUTTON_EJECT_DISC:
    g_mediaManager.ToggleTray(g_mediaManager.TranslateDevicePath(item->GetPath())[0]);
#endif
    return true;
  default:
    break;
  }

  // the rest of the operations require a valid share
  CMediaSource *share = GetShare(type, item.get());
  if (!share) return false;
  switch (button)
  {
  case CONTEXT_BUTTON_EDIT_SOURCE:
    if (CProfilesManager::GetInstance().IsMasterProfile())
    {
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;
    }
    else if (!g_passwordManager.IsProfileLockUnlocked())
      return false;

    return CGUIDialogMediaSource::ShowAndEditMediaSource(type, *share);

  case CONTEXT_BUTTON_REMOVE_SOURCE:
  {
    if (CProfilesManager::GetInstance().IsMasterProfile())
    {
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;
    }
    else
    {
      if (!CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsMasterLockUnlocked(false))
        return false;
      if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked())
        return false;
    }
    // prompt user if they want to really delete the source
    if (!CGUIDialogYesNo::ShowAndGetInput(CVariant{751}, CVariant{750}))
      return false;

    // check default before we delete, as deletion will kill the share object
    std::string defaultSource(GetDefaultShareNameByType(type));
    if (!defaultSource.empty())
    {
      if (share->strName == defaultSource)
        ClearDefault(type);
    }
    CMediaSourceSettings::GetInstance().DeleteSource(type, share->strName, share->strPath);
    return true;
  }
  case CONTEXT_BUTTON_SET_DEFAULT:
    if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked())
      return false;
    else if (!g_passwordManager.IsMasterLockUnlocked(true))
      return false;

    // make share default
    SetDefault(type, share->strName);
    return true;

  case CONTEXT_BUTTON_CLEAR_DEFAULT:
    if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked())
      return false;
    else if (!g_passwordManager.IsMasterLockUnlocked(true))
      return false;
    // remove share default
    ClearDefault(type);
    return true;

  case CONTEXT_BUTTON_SET_THUMB:
    {
      if (CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked())
        return false;
      else if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;

      // setup our thumb list
      CFileItemList items;

      // add the current thumb, if available
      if (!share->m_strThumbnailImage.empty())
      {
        CFileItemPtr current(new CFileItem("thumb://Current", false));
        current->SetArt("thumb", share->m_strThumbnailImage);
        current->SetLabel(g_localizeStrings.Get(20016));
        items.Add(current);
      }
      else if (item->HasArt("thumb"))
      { // already have a thumb that the share doesn't know about - must be a local one, so we mayaswell reuse it.
        CFileItemPtr current(new CFileItem("thumb://Current", false));
        current->SetArt("thumb", item->GetArt("thumb"));
        current->SetLabel(g_localizeStrings.Get(20016));
        items.Add(current);
      }
      // see if there's a local thumb for this item
      std::string folderThumb = item->GetFolderThumb();
      if (XFILE::CFile::Exists(folderThumb))
      {
        CFileItemPtr local(new CFileItem("thumb://Local", false));
        local->SetArt("thumb", folderThumb);
        local->SetLabel(g_localizeStrings.Get(20017));
        items.Add(local);
      }
      // and add a "no thumb" entry as well
      CFileItemPtr nothumb(new CFileItem("thumb://None", false));
      nothumb->SetIconImage(item->GetIconImage());
      nothumb->SetLabel(g_localizeStrings.Get(20018));
      items.Add(nothumb);

      std::string strThumb;
      VECSOURCES shares;
      g_mediaManager.GetLocalDrives(shares);
      if (!CGUIDialogFileBrowser::ShowAndGetImage(items, shares, g_localizeStrings.Get(1030), strThumb))
        return false;

      if (strThumb == "thumb://Current")
        return true;

      if (strThumb == "thumb://Local")
        strThumb = folderThumb;

      if (strThumb == "thumb://None")
        strThumb = "";

      if (!share->m_ignore)
      {
        CMediaSourceSettings::GetInstance().UpdateSource(type,share->strName,"thumbnail",strThumb);
        CMediaSourceSettings::GetInstance().Save();
      }
      else if (!strThumb.empty())
      { // this is some sort of an auto-share, so store in the texture database
        CTextureDatabase db;
        if (db.Open())
          db.SetTextureForPath(item->GetPath(), "thumb", strThumb);
      }

      CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES);
      g_windowManager.SendThreadMessage(msg);
      return true;
    }

  case CONTEXT_BUTTON_ADD_LOCK:
    {
      // prompt user for mastercode when changing lock settings) only for default user
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;

      std::string strNewPassword = "";
      if (!CGUIDialogLockSettings::ShowAndGetLock(share->m_iLockMode,strNewPassword))
        return false;
      // password entry and re-entry succeeded, write out the lock data
      share->m_iHasLock = 2;
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockcode", strNewPassword);
      strNewPassword = StringUtils::Format("%i", share->m_iLockMode);
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockmode", strNewPassword);
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0");
      CMediaSourceSettings::GetInstance().Save();

      CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES);
      g_windowManager.SendThreadMessage(msg);
      return true;
    }
  case CONTEXT_BUTTON_RESET_LOCK:
    {
      // prompt user for profile lock when changing lock settings
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;

      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0");
      CMediaSourceSettings::GetInstance().Save();
      CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES);
      g_windowManager.SendThreadMessage(msg);
      return true;
    }
  case CONTEXT_BUTTON_REMOVE_LOCK:
    {
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;

      if (!CGUIDialogYesNo::ShowAndGetInput(CVariant{12335}, CVariant{750}))
        return false;

      share->m_iHasLock = 0;
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockmode", "0");
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockcode", "0");
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0");
      CMediaSourceSettings::GetInstance().Save();
      CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES);
      g_windowManager.SendThreadMessage(msg);
      return true;
    }
  case CONTEXT_BUTTON_REACTIVATE_LOCK:
    {
      bool maxRetryExceeded = false;
      if (CSettings::GetInstance().GetInt(CSettings::SETTING_MASTERLOCK_MAXRETRIES) != 0)
        maxRetryExceeded = (share->m_iBadPwdCount >= CSettings::GetInstance().GetInt(CSettings::SETTING_MASTERLOCK_MAXRETRIES));
      if (!maxRetryExceeded)
      {
        // don't prompt user for mastercode when reactivating a lock
        g_passwordManager.LockSource(type, share->strName, true);
        return true;
      }
      return false;
    }
  case CONTEXT_BUTTON_CHANGE_LOCK:
    {
      if (!g_passwordManager.IsMasterLockUnlocked(true))
        return false;

      std::string strNewPW;
      std::string strNewLockMode;
      if (CGUIDialogLockSettings::ShowAndGetLock(share->m_iLockMode,strNewPW))
        strNewLockMode = StringUtils::Format("%i",share->m_iLockMode);
      else
        return false;
      // password ReSet and re-entry succeeded, write out the lock data
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockcode", strNewPW);
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "lockmode", strNewLockMode);
      CMediaSourceSettings::GetInstance().UpdateSource(type, share->strName, "badpwdcount", "0");
      CMediaSourceSettings::GetInstance().Save();
      CGUIMessage msg(GUI_MSG_NOTIFY_ALL,0,0,GUI_MSG_UPDATE_SOURCES);
      g_windowManager.SendThreadMessage(msg);
      return true;
    }
  default:
    break;
  }
  return false;
}
Exemple #16
0
Path& Path::makeAbsolute()
{
	return makeAbsolute(current());
}
Exemple #17
0
void GlutWindow::specKeyEvent(int _key, int _x, int _y) {
  current()->specKey(_key, _x, _y);
}
Exemple #18
0
void
NetworkPrefsView::MessageReceived (BMessage * msg)
{
	switch (msg->what)
	{
		case M_NETWORK_DEFAULTS:
			if (fActiveNetwork.HasString ("name"))
				vision_app->SetNetwork (fActiveNetwork.FindString ("name"), &fActiveNetwork);
			fActiveNetwork = vision_app->GetNetwork ("defaults");
			fNetworkMenu->MenuItem ()->SetLabel ("Defaults");
			SetupDefaults (fActiveNetwork);
			fDupeItem->SetEnabled (false);
			fRemoveItem->SetEnabled (false);
			break;

		case M_CHOOSE_NETWORK:
			{
				BMenuItem *item (NULL);
				msg->FindPointer ("source", reinterpret_cast < void **>(&item));
				SaveCurrentNetwork ();
				fActiveNetwork = vision_app->GetNetwork (item->Label ());
				fNetworkMenu->MenuItem ()->SetLabel (item->Label ());
				UpdatePersonalData (fActiveNetwork);
				UpdateNetworkData (fActiveNetwork);
				if (BMessenger (fServerPrefs).IsValid ())
					fServerPrefs->SetNetworkData (&fActiveNetwork);
				fDupeItem->SetEnabled (true);
				fRemoveItem->SetEnabled (true);
			}
			break;

		case M_ADD_NEW_NETWORK:
			{
				if (msg->HasString ("text"))
				{
					fNetPrompt = NULL;
					BString network (msg->FindString ("text"));
					network.RemoveAll (" ");
					BMenu *menu (fNetworkMenu->Menu ());
					for (int32 i = 0; i < menu->CountItems (); i++)
				{
						BMenuItem *item (menu->ItemAt (i));
						if (item && network == item->Label ())
						{
							dynamic_cast < BInvoker * >(item)->Invoke ();
							return;
						}
					}
					BMessage newNet (VIS_NETWORK_DATA);
					newNet.AddString ("name", network.String ());
					vision_app->SetNetwork (network.String (), &newNet);
					BMenuItem *item (new BMenuItem (network.String (), new BMessage (M_CHOOSE_NETWORK)));
					menu->AddItem (item, 0);
					item->SetTarget (this);
					dynamic_cast < BInvoker * >(item)->Invoke ();
			}
				else
				{
					BString promptText = B_TRANSLATE("Network Name");
					promptText += ": ";
					fNetPrompt = new PromptWindow (BPoint (Window ()->Frame ().left + Window ()->Frame ().Width () / 2, Window ()->Frame ().top + Window ()->Frame ().Height () / 2),
						promptText.String(), B_TRANSLATE("Add Network"), NULL, this, new BMessage (M_ADD_NEW_NETWORK), NULL, false);
					fNetPrompt->Show ();
				}
			}
			break;

		case M_REMOVE_CURRENT_NETWORK:
			{
				const char *name (fActiveNetwork.FindString ("name"));
				vision_app->RemoveNetwork (name);
				BMenu *menu (fNetworkMenu->Menu ());
				for (int32 i = 0; i < menu->CountItems (); i++)
				{
					BMenuItem *item (menu->ItemAt (i));
					if (!strcmp (item->Label (), name))
					{
						delete menu->RemoveItem (i);
						fActiveNetwork.MakeEmpty ();
						dynamic_cast < BInvoker * >(menu->ItemAt (0))->Invoke ();
						break;
					}
				}
			}
			break;

		case M_DUPE_CURRENT_NETWORK:
			{
				if (msg->HasString ("text"))
				{
					fDupePrompt = NULL;
					BString network (msg->FindString ("text"));
					network.RemoveAll (" ");
					BMenu *menu (fNetworkMenu->Menu ());
					for (int32 i = 0; i < menu->CountItems (); i++)
					{
						BMenuItem *item (menu->ItemAt (i));
						if (item && network == item->Label ())
						{
							dynamic_cast < BInvoker * >(item)->Invoke ();
							return;
						}
					}
					BMessage newNet = fActiveNetwork;
					newNet.ReplaceString ("name", network.String ());
					vision_app->SetNetwork (network.String (), &newNet);
					BMenuItem *item (new BMenuItem (network.String (), new BMessage (M_CHOOSE_NETWORK)));
					menu->AddItem (item, 0);
					item->SetTarget (this);
					dynamic_cast < BInvoker * >(item)->Invoke ();
				}
				else
				{
					BString promptText = B_TRANSLATE("Network Name");
					promptText += ": ";
					fDupePrompt = new PromptWindow (BPoint (Window ()->Frame ().left + Window ()->Frame ().Width () / 2, Window ()->Frame ().top + Window ()->Frame ().Height () / 2),
						promptText.String(), B_TRANSLATE("Duplicate Current Network"), NULL, this, new BMessage (M_DUPE_CURRENT_NETWORK), NULL, false);
					fDupePrompt->Show ();
				}
			}
			break;

		case M_SERVER_DATA_CHANGED:
			{
				UpdateNetworkData (fActiveNetwork);
			}
			break;

		case M_SERVER_DIALOG:
			{
				BMessenger msgr (fServerPrefs);
				if (msgr.IsValid ())
					fServerPrefs->Activate ();
				else
				{
					fServerPrefs = new NetPrefServerWindow (this);
					fServerPrefs->SetNetworkData (&fActiveNetwork);
					fServerPrefs->Show ();
				}
			}
			break;

		case M_NET_CHECK_LAG:
			{
				bool value = msg->FindInt32 ("be:value");
				if (fActiveNetwork.HasBool ("lagCheck"))
					fActiveNetwork.ReplaceBool ("lagCheck", value);
				else
					fActiveNetwork.AddBool ("lagCheck", value);
			}
			break;

		case M_CONNECT_ON_STARTUP:
			{
				bool value = msg->FindInt32 ("be:value");
				if (fActiveNetwork.HasBool ("connectOnStartup"))
					fActiveNetwork.ReplaceBool ("connectOnStartup", value);
				else
					fActiveNetwork.AddBool ("connectOnStartup", value);
			}
			break;

		case M_USE_NICK_DEFAULTS:
			{
				bool value = msg->FindInt32 ("be:value");
				if (fActiveNetwork.HasBool ("useDefaults"))
					fActiveNetwork.ReplaceBool ("useDefaults", value);
				else
					fActiveNetwork.AddBool ("useDefaults", value);
				UpdatePersonalData (fActiveNetwork);
			}
			break;

		case M_NETPREFS_TEXT_INVOKE:
			{
				if (fActiveNetwork.HasString("autoexec"))
					fActiveNetwork.ReplaceString("autoexec", fTextView->Text());
				else
					fActiveNetwork.AddString("autoexec", fTextView->Text());
			}
			break;

		case M_ADD_NICK:
			if (msg->HasString ("text"))
			{
				fNickPrompt = NULL;
				BString nick (msg->FindString ("text"));
				nick.RemoveAll (" ");
				for (int32 i = 0; i < fListView->CountItems (); i++)
				{
					BStringItem *item ((BStringItem *) fListView->ItemAt (i));
					if (item && nick == item->Text ())
						return;
				}
			fActiveNetwork.AddString ("nick", nick.String ());
			fListView->AddItem (new BStringItem (nick.String ()));
			}
			else
			{
				BString promptString = B_TRANSLATE("Nickname");
				promptString += ": ";
				fNickPrompt = new PromptWindow (BPoint (Window ()->Frame ().left + Window ()->Frame ().Width () / 2, Window ()->Frame ().top + Window ()->Frame ().Height () / 2),
					promptString.String(), B_TRANSLATE("Add Nickname"), NULL, this, new BMessage (M_ADD_NICK), NULL, false);
				fNickPrompt->Show ();
			}
			break;

		case M_REMOVE_NICK:
			{
				int32 current (fListView->CurrentSelection ());
				if (current >= 0)
			{
					delete fListView->RemoveItem (current);
					fActiveNetwork.RemoveData ("nick", current);
				}
			}
			break;

		case M_NICK_UP:
			{
				int32 current (fListView->CurrentSelection ());
				BString nick1, nick2;
				nick1 = fActiveNetwork.FindString ("nick", current);
				nick2 = fActiveNetwork.FindString ("nick", current - 1);
				fListView->SwapItems (current, current - 1);
				fActiveNetwork.ReplaceString ("nick", current - 1, nick1.String ());
				fActiveNetwork.ReplaceString ("nick", current, nick2.String ());
				current = fListView->CurrentSelection ();
				Window ()->DisableUpdates ();
				fListView->DeselectAll ();
				fListView->Select (current);
				Window ()->EnableUpdates ();
			}
			break;

		case M_NICK_DOWN:
			{
				int32 current (fListView->CurrentSelection ());
				BString nick1, nick2;
				nick1 = fActiveNetwork.FindString ("nick", current);
				nick2 = fActiveNetwork.FindString ("nick", current + 1);
				fListView->SwapItems (current, current + 1);
				fActiveNetwork.ReplaceString ("nick", current + 1, nick1.String ());
				fActiveNetwork.ReplaceString ("nick", current, nick2.String ());
				current = fListView->CurrentSelection ();
				Window ()->DisableUpdates ();
				fListView->DeselectAll ();
				fListView->Select (current);
				Window ()->EnableUpdates ();
			}
			break;

		case M_NICK_SELECTED:
			{
				int32 index (msg->FindInt32 ("index"));
				if (index >= 0 && !fNickDefaultsBox->Value ())
				{
					fNickUpButton->SetEnabled (index > 0);
					fNickDnButton->SetEnabled (index != (fListView->CountItems () - 1));
					fNickRemoveButton->SetEnabled (true);
				}
				else
				{
					fNickUpButton->SetEnabled (false);
					fNickDnButton->SetEnabled (false);
					fNickRemoveButton->SetEnabled (false);
				}
			}
			break;

		default:
			BView::MessageReceived (msg);
			break;
	}
}
 long long SeqSummaryCommand::driverCreateSummary(map<int, long long>& startPosition, map<int,  long long>& endPosition, map<int,  long long>& seqLength, map<int,  long long>& ambigBases, map<int,  long long>& longHomoPolymer, string filename, string sumFile, linePair* filePos) {
	try {
		
		ofstream outSummary;
		m->openOutputFile(sumFile, outSummary);
        
        ifstream in;
        m->openInputFile(filename, in);
        
        in.seekg(filePos->start);
		
		//print header if you are process 0
		if (filePos->start == 0) {
			outSummary << "seqname\tstart\tend\tnbases\tambigs\tpolymer\tnumSeqs" << endl;
            m->zapGremlins(in); m->gobble(in);
		}
				
		bool done = false;
		int count = 0;
        
        
		while (!done) {
				
			if (m->control_pressed) { in.close(); outSummary.close(); return 1; }
            
            if (m->debug) { m->mothurOut("[DEBUG]: count = " + toString(count) + "\n");  }
            
			Sequence current(in); m->gobble(in);
           
			if (current.getName() != "") {
				
                if (m->debug) { m->mothurOut("[DEBUG]: " + current.getName() + '\t' + toString(current.getNumBases()) + "\n");  }
                
				int num = 1;
				if ((namefile != "") || (countfile != "")) {
					//make sure this sequence is in the namefile, else error 
					map<string, int>::iterator it = nameMap.find(current.getName());
					
					if (it == nameMap.end()) { m->mothurOut("[ERROR]: '" + current.getName() + "' is not in your name or count file, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
					else { num = it->second; }
				}
				
				int thisStartPosition = current.getStartPos();
                map<int, long long>::iterator it = startPosition.find(thisStartPosition);
                if (it == startPosition.end()) { startPosition[thisStartPosition] = num; } //first finding of this start position, set count.
                else { it->second += num; } //add counts
                
                int thisEndPosition = current.getEndPos();
                it = endPosition.find(thisEndPosition);
                if (it == endPosition.end()) { endPosition[thisEndPosition] = num; } //first finding of this end position, set count.
                else { it->second += num; } //add counts
                
                int thisSeqLength = current.getNumBases();
                it = seqLength.find(thisSeqLength);
                if (it == seqLength.end()) { seqLength[thisSeqLength] = num; } //first finding of this length, set count.
                else { it->second += num; } //add counts
                
                int thisAmbig = current.getAmbigBases();
                it = ambigBases.find(thisAmbig);
                if (it == ambigBases.end()) { ambigBases[thisAmbig] = num; } //first finding of this ambig, set count.
                else { it->second += num; } //add counts
                
                int thisHomoP = current.getLongHomoPolymer();
                it = longHomoPolymer.find(thisHomoP);
                if (it == longHomoPolymer.end()) { longHomoPolymer[thisHomoP] = num; } //first finding of this homop, set count.
                else { it->second += num; } //add counts

				count++;
				outSummary << current.getName() << '\t';
				outSummary << thisStartPosition << '\t' << thisEndPosition << '\t';
				outSummary << thisSeqLength << '\t' << thisAmbig << '\t';
				outSummary << thisHomoP << '\t' << num << endl;
                
                if (m->debug) { m->mothurOut("[DEBUG]: " + current.getName() + '\t' + toString(num) + "\n");  }
			}
			
			#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
				unsigned long long pos = in.tellg();
				if ((pos == -1) || (pos >= filePos->end)) { break; }
			#else
				if (in.eof()) { break; }
			#endif
		}
				
		in.close();
		
		return count;
	}
	catch(exception& e) {
		m->errorOut(e, "SeqSummaryCommand", "driverCreateSummary");
		exit(1);
	}
}
Exemple #20
0
void ConfigParser::normalizeInput(
        Json::Value& json,
        const arbiter::Arbiter& arbiter)
{
    Json::Value& input(json["input"]);
    const bool verbose(json["verbose"].asBool());

    const std::string extension(
            input.isString() ?
                arbiter::Arbiter::getExtension(input.asString()) : "");

    const bool isInferencePath(extension == "entwine-inference");

    if (!isInferencePath)
    {
        // The input source is a path or array of paths.  First, we possibly
        // need to expand out directories into their containing files.
        FileInfoList fileInfo;

        auto insert([&fileInfo, &arbiter, verbose](std::string in)
        {
            Paths current(arbiter.resolve(in, verbose));
            for (const auto& c : current) fileInfo.emplace_back(c);
        });

        if (input.isArray())
        {
            for (const auto& entry : input)
            {
                if (entry.isString())
                {
                    insert(directorify(entry.asString()));
                }
                else
                {
                    fileInfo.emplace_back(entry);
                }
            }
        }
        else if (input.isString())
        {
            insert(directorify(input.asString()));
        }
        else return;

        // Now, we have an array of files (no directories).
        //
        // Reset our input with our resolved paths.  config.input.fileInfo will
        // be an array of strings, containing only paths with no associated
        // information.
        input = Json::Value();
        input.resize(fileInfo.size());
        for (std::size_t i(0); i < fileInfo.size(); ++i)
        {
            input[Json::ArrayIndex(i)] = fileInfo[i].toJson();
        }
    }
    else if (isInferencePath)
    {
        const std::string path(input.asString());
        const Json::Value inference(parse(arbiter.get(path)));

        input = inference["fileInfo"];

        if (!json.isMember("schema")) json["schema"] = inference["schema"];
        if (!json.isMember("bounds")) json["bounds"] = inference["bounds"];
        if (!json.isMember("numPointsHint"))
        {
            json["numPointsHint"] = inference["numPoints"];
        }

        if (inference.isMember("reprojection"))
        {
            json["reprojection"] = inference["reprojection"];
        }

        if (Delta::existsIn(inference))
        {
            if (!json.isMember("scale")) json["scale"] = inference["scale"];
            if (!json.isMember("offset")) json["offset"] = inference["offset"];
        }
    }
}
Exemple #21
0
	const bignum bignum::operator--(int)
	{	
		bignum current(*this);
		--(*this);
		return move(current);
	}
Exemple #22
0
 void push(const Transform& transform)
 {
     individual.push_back(transform);
     Transform result = multiply(transform, current());
     makeCurrent(result);
 }
Exemple #23
0
int main()
{
    cout << "Hello, World!\n" ;

    print_all(cout, "Hello", " World", '!', 0 ,'\n');

    ui_history h(1);

    current(h).emplace_back("Hello");
    current(h).emplace_back("World");
    current(h).emplace_back("1");
    current(h).emplace_back("2");
    current(h).emplace_back("3");
    current(h).emplace_back("4");
    current(h).emplace_back("5");
    current(h).emplace_back("6");
    current(h).emplace_back("7");
    current(h).emplace_back("8");
    current(h).emplace_back("9");
    current(h).emplace_back("10");
    current(h).emplace_back(my_class_t());

    current(h).operator[](1).test();
    current(h)[1].test();
    ui_object uio = current(h)[1];
    uio.test();
    auto &uior = current(h)[1];
    uior.test();
??    boost::uuids::uuid ot = uior.get_tag();
Exemple #24
0
bool MainWindow::showSaveAsDialog()
{
	if (!controller)
		return false;
	
	// Try current directory first
	QFileInfo current(currentPath());
	QString save_directory = current.canonicalPath();
	if (save_directory.isEmpty())
	{
		// revert to least recently used directory or home directory.
		QSettings settings;
		save_directory = settings.value(QString::fromLatin1("openFileDirectory"), QDir::homePath()).toString();
	}
	
	// Build the list of supported file filters based on the file format registry
	QString filters;
	for (auto format : FileFormats.formats())
	{
		if (format->supportsExport())
		{
			if (filters.isEmpty()) 
				filters = format->filter();
			else
				filters = filters + QLatin1String(";;") + format->filter();
		}
	}
	
	QString filter; // will be set to the selected filter by QFileDialog
	QString path = QFileDialog::getSaveFileName(this, tr("Save file"), save_directory, filters, &filter);
	
	// On Windows, when the user enters "sample", we get "sample.omap *.xmap".
	// (Fixed in upstream qtbase/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
	// Wednesday March 20 2013 in commit 426f2cc.)
	// This results in an error later, because "*" is not a valid character.
	// But it is reasonable to apply the workaround to all platforms, 
	// due to the special meaning of "*" in shell patterns.
	const int extensions_quirk = path.indexOf(QLatin1String(" *."));
	if (extensions_quirk >= 0)
	{
		path.truncate(extensions_quirk);
	}
	
	if (path.isEmpty())
		return false;
	
	const FileFormat *format = FileFormats.findFormatByFilter(filter);
	if (!format)
	{
		QMessageBox::information(this, tr("Error"), 
		  tr("File could not be saved:") + QLatin1Char('\n') +
		  tr("There was a problem in determining the file format.") + QLatin1Char('\n') + QLatin1Char('\n') +
		  tr("Please report this as a bug.") );
		return false;
	}
	
	// Ensure that the provided filename has a correct file extension.
	// Among other things, this will ensure that FileFormats.formatForFilename()
	// returns the same thing the user selected in the dialog.
// 	QString selected_extension = "." + format->primaryExtension();
	QStringList selected_extensions(format->fileExtensions());
	selected_extensions.replaceInStrings(QRegExp(QString::fromLatin1("^")), QString::fromLatin1("."));
	bool has_extension = false;
	for (auto selected_extension : qAsConst(selected_extensions))
	{
		if (path.endsWith(selected_extension, Qt::CaseInsensitive))
		{
			has_extension = true;
			break;
		}
	}
	if (!has_extension)
		path += QLatin1Char('.') + format->primaryExtension();
	// Ensure that the file name matches the format.
	Q_ASSERT(format->fileExtensions().contains(QFileInfo(path).suffix()));
	// Fails when using different formats for import and export:
	//	Q_ASSERT(FileFormats.findFormatForFilename(path) == format);
	
	return savePath(path);
}
int FormWindowCursor::position() const
{
    const int index = m_formWindow->widgets().indexOf(current());
    return index == -1 ? 0 : index;
}
Exemple #26
0
		void PeptideBuilder::insert_(Residue& resnew, Residue& resold)
		{
			PDBAtom* pcarbon     = getAtomByName_(resold, "C");
			PDBAtom* pcarbona    = getAtomByName_(resold, "CA");
			PDBAtom* pnitrogen   = getAtomByName_(resold, "N");
			PDBAtom* pnitrogen_n = getAtomByName_(resnew, "N");
			PDBAtom* pcarbona_n  = getAtomByName_(resnew, "CA");
			PDBAtom* pcarbon_n   = getAtomByName_(resnew, "C");

			Vector3 rot_axis;    // axis  for the torsion angle

			// set C-N-bond 
			pcarbon->createBond(*pnitrogen_n)->setOrder(Bond::ORDER__SINGLE);;


			//  --------------  move N into  0|0|0   
			TranslationProcessor translation(Vector3(BOND_LENGTH_N_CA, 0., 0.));
			resnew.apply(translation);

			// --------------- calculate the coordinates for N
			Vector3 CA_C_axis = (pcarbon->getPosition() - pcarbona->getPosition()).normalize();
			Vector3 N_CA_axis = (pcarbona->getPosition() - pnitrogen->getPosition()).normalize();
			Vector3 CA_N_axis = ((float)-1.) * N_CA_axis;
			Vector3 newpos = (CA_N_axis - (CA_C_axis * CA_N_axis) * CA_C_axis).normalize();
			Vector3 normaxis = (CA_C_axis % newpos).normalize();

			Matrix4x4 mat;
			mat.setRotation(Angle(-1. * 30.* Constants::PI/180.), normaxis);

			newpos = mat * newpos;               // rotation
			newpos = newpos *  BOND_LENGTH_N_C;  // scaling of the bond length
			newpos = newpos + pcarbon->getPosition();

			// positioning of the nitrogen
			translation.setTranslation(newpos);
			resnew.apply(translation);


			 //---------------set the angle in NN to 120 degrees
			Vector3 NN_C_axis   = pcarbon->getPosition() - pnitrogen_n->getPosition();
			Vector3 NN_NCA_axis = pcarbona_n->getPosition() - pnitrogen_n->getPosition();
			CA_C_axis = pcarbon->getPosition() - pcarbona->getPosition();

			// current angle for C
			Angle current(acos(NN_C_axis * NN_NCA_axis /
										 (NN_C_axis.getLength() * NN_NCA_axis.getLength() )));

			Matrix4x4 transmat;
			Vector3 rotaxis;

			if (current < (float)(Constants::PI - 1e-2))
			{
				current = Angle(120.*Constants::PI/180.) - current;
				rotaxis = (NN_C_axis%NN_NCA_axis).normalize();
			}
			else
			{
				if (current > (float)(Constants::PI+1e-2))
				{
				  // is this line really correct???
					current = Angle(-120. * 120. * Constants::PI / 180.) - current;
					rotaxis = (NN_C_axis % NN_NCA_axis).normalize();
				}
				else
				{
					current = Angle(-120. * Constants::PI / 180.) - current;
					rotaxis = (NN_C_axis%CA_C_axis).normalize();
				}
			}

			transmat.rotate(current, rotaxis);

			TransformationProcessor transformation(transmat);

			// translate to 0|0|0 (needed for the rotation)
			Vector3 toOrigin = pnitrogen_n->getPosition();
			translation.setTranslation(((float)(-1.))*toOrigin);
			resnew.apply(translation);
			// rotate in 0|0|0
			resnew.apply(transformation);
			// translate back to the correct position
			translation.setTranslation(toOrigin);
			resnew.apply(translation);

			//---------------- set torsion angle to 0
			Vector3 v_pca  = pcarbona->getPosition();
			Vector3 v_pc   = pcarbon->getPosition();
			Vector3 v_pn_n = pnitrogen_n->getPosition();
			Vector3 v_pca_n = pcarbona_n->getPosition();
			Vector3 v_pc_n  = pcarbon_n->getPosition();
			Vector3 v_pn   =pnitrogen->getPosition();
			current = getTorsionAngle( v_pca.x,   v_pca.y,   v_pca.z,
					 v_pc.x,    v_pc.y,    v_pc.z,
					 v_pn_n.x,  v_pn_n.y,  v_pn_n.z,
					 v_pca_n.x, v_pca_n.y, v_pca_n.z );


			rot_axis =  (pnitrogen_n->getPosition() - pcarbon->getPosition()).normalize();
			transmat.getZero();/// is this necessary???
			transmat.rotate(Angle(-1. * current), rot_axis);
			transformation.setTransformation(transmat);

			// translate to 0|0|0
			toOrigin = pnitrogen_n->getPosition();
			translation.setTranslation(((float)(-1.))*toOrigin);
					resnew.apply(translation);
			// set torsion angles
			 resnew.apply(transformation);

			// translate back
			translation.setTranslation(toOrigin);
			resnew.apply(translation);

			// ---------------------set the peptide bond angle omega  to 180 degrees
			v_pca  = pcarbona->getPosition();
			v_pc   = pcarbon->getPosition();
			v_pn_n = pnitrogen_n->getPosition();
			v_pca_n = pcarbona_n->getPosition();
			v_pc_n  = pcarbon_n->getPosition();
			current = getTorsionAngle( v_pca.x,   v_pca.y,   v_pca.z,
					 v_pc.x,    v_pc.y,    v_pc.z,
					 v_pn_n.x,  v_pn_n.y,  v_pn_n.z,
					 v_pca_n.x, v_pca_n.y, v_pca_n.z );

			transmat.getZero();
			transmat.rotate( Angle(Constants::PI , true),
					 (pnitrogen_n->getPosition() - pcarbon->getPosition()).normalize());
			transformation.setTransformation(transmat);
			// translate to 0|0|0 (needed for the rotation)
			toOrigin = pnitrogen_n->getPosition();
			translation.setTranslation(((float)(-1.))*toOrigin);
			resnew.apply(translation);
			//rotate in 0|0|0  about 180 degrees
			resnew.apply(transformation);
			//translate back
			translation.setTranslation(toOrigin);
			 resnew.apply(translation);

			//------------- angle psi
			v_pca  = pcarbona->getPosition();
			v_pc   = pcarbon->getPosition();
			v_pn_n = pnitrogen_n->getPosition();
			v_pca_n = pcarbona_n->getPosition();
			v_pc_n  = pcarbon_n->getPosition();
			current = getTorsionAngle( v_pc.x,    v_pc.y,    v_pc.z,
					 v_pn_n.x,  v_pn_n.y,  v_pn_n.z,
					 v_pca_n.x, v_pca_n.y, v_pca_n.z,
					 v_pc_n.x,  v_pc_n.y,  v_pc_n.z  );

			rot_axis = (pcarbona_n->getPosition()-pnitrogen_n->getPosition()).normalize();

			transmat.rotate(Angle(-1. * current), rot_axis);
			transformation.setTransformation(transmat);

			//translate to 0|0|0 (needed for the rotation)
			toOrigin = pcarbona_n->getPosition();
			translation.setTranslation(((float)(-1.))*toOrigin);
			 resnew.apply(translation);

			resnew.apply(transformation);
			// translate back to the correct position
			translation.setTranslation(toOrigin);
			resnew.apply(translation);

			return;
		}
Exemple #27
0
void DialogTwaLine::traceIt()
{
    line->deleteAll();
    QListIterator<POI*> i (list);
    while(i.hasNext())
    {
        POI * poi=i.next();
        list.removeOne(poi);
        if(poi->isPartOfTwa())
        {
            parent->slot_delPOI_list(poi);
            delete poi;
        }
    }
    this->myBoat=parent->getSelectedBoat();
    if(myBoat==NULL) return;
    if(!dataManager->isOk()) return;
    if(!myBoat->getPolarData()) return;
    time_t eta;
    if(this->startGrib->isChecked() || myBoat->get_boatType()!=BOAT_VLM)
        eta=dataManager->get_currentDate();
    else
        eta=((boatVLM*)myBoat)->getPrevVac()+myBoat->getVacLen();
    nbVac[0]=this->spinBox->value();
    nbVac[1]=this->spinBox_2->value();
    nbVac[2]=this->spinBox_3->value();
    nbVac[3]=this->spinBox_4->value();
    nbVac[4]=this->spinBox_5->value();
    twa[0]=this->doubleSpinBox->value();
    twa[1]=this->doubleSpinBox_2->value();
    twa[2]=this->doubleSpinBox_3->value();
    twa[3]=this->doubleSpinBox_4->value();
    twa[4]=this->doubleSpinBox_5->value();
    mode[0]=this->TWA1->isChecked();
    mode[1]=this->TWA2->isChecked();
    mode[2]=this->TWA3->isChecked();
    mode[3]=this->TWA4->isChecked();
    mode[4]=this->TWA5->isChecked();
    int vacLen=myBoat->getVacLen();
    vlmPoint current(start.x(),start.y());
    line->addVlmPoint(current);
    double wind_speed,wind_angle,cap;
    double lon=0,lat=0;
    time_t maxDate=dataManager->get_maxDate();
    bool crossing=false;
    //int i1,j1,i2,j2;
    GshhsReader *map=parent->get_gshhsReader();
    int mapQuality=map?map->getQuality():4;
    for (int page=0;page<5;page++)
    {
        if (nbVac[page]==0) continue;
        for(int i=1;i<=nbVac[page];i++)
        {
            double current_speed=-1;
            double current_angle=0;
            if(!dataManager->getInterpolatedWind(current.lon, current.lat,
                eta,&wind_speed,&wind_angle,INTERPOLATION_DEFAULT) || eta>maxDate)
                break;
            wind_angle=radToDeg(wind_angle);
            if(dataManager->getInterpolatedCurrent(current.lon, current.lat,
                eta,&current_speed,&current_angle,INTERPOLATION_DEFAULT))
            {
                current_angle=radToDeg(current_angle);
                QPointF p=Util::calculateSumVect(wind_angle,wind_speed,current_angle,current_speed);
                //qWarning()<<"cs="<<current_speed<<"cd="<<current_angle<<"tws="<<wind_speed<<"twd="<<wind_angle<<"Ltws="<<p.x()<<"Ltwd="<<p.y();
                wind_speed=p.x();
                wind_angle=p.y();
            }
            double TWA;
            if(mode[page])
            {
                cap=A360(wind_angle+twa[page]);
                TWA=twa[page];
            }
            else
            {
                cap=twa[page];
                TWA=A360(cap-wind_angle);
                if(qAbs(TWA)>180)
                {
                    if(TWA<0)
                        TWA=360+TWA;
                    else
                        TWA=TWA-360;
                }
            }
            double newSpeed=myBoat->getPolarData()->getSpeed(wind_speed,TWA);
            if(current_speed>0)
            {
                QPointF p=Util::calculateSumVect(cap,newSpeed,A360(current_angle+180.0),current_speed);
                newSpeed=p.x(); //in this case newSpeed is SOG
                cap=p.y(); //in this case cap is COG
            }
            double distanceParcourue=newSpeed*vacLen/3600.00;
            Util::getCoordFromDistanceAngle(current.lat, current.lon, distanceParcourue, cap,&lat,&lon);
            if(!crossing && map && mapQuality>=3)
            {
                double I1,J1,I2,J2;
                parent->getProj()->map2screenDouble(current.lon,current.lat,&I1,&J1);
                parent->getProj()->map2screenDouble(lon,lat,&I2,&J2);
                crossing=map->crossing(QLineF(I1,J1,I2,J2),QLineF(current.lon,current.lat,lon,lat));
            }
            current.lon=lon;
            current.lat=lat;
            line->addVlmPoint(current);
            eta=eta+vacLen;
        }
        if(crossing)
            pen.setColor(Qt::red);
        else
            pen.setColor(color);
        line->setLinePen(pen);
        QDateTime tm;
        tm.setTimeSpec(Qt::UTC);
        if(this->startVac->isChecked())
            tm.setTime_t(eta-vacLen);
        else
            tm.setTime_t(eta);
        //QString name;
        //name.sprintf("Twa %.1f",twa[page]);
        POI * arrival=parent->slot_addPOI(tr("ETA: ")+tm.toString("dd MMM-hh:mm"),0,lat,lon,-1,0,false,myBoat);
        arrival->setPartOfTwa(true);
        list.append(arrival);
    }
    line->slot_showMe();
    QApplication::processEvents();
}
	virtual void Execute(const DataObject &)
	{
		bool cardFound = false;

		wxInt32 players = numPlayers();
		wxInt32 curPlayer = current();

		bool thisPlayerCard = false;
		wxString thisPlayerName;

		// Go through each player, starting with the current player.  If
		// they get a progress card, run the card dialog.
		for(wxInt32 i = 0; i < players; ++i)
		{
			wxInt32 thisPlayer = (i + curPlayer) % players;

			if(TRUE == playerGameData<wxInt32>(shGainProgressCard, thisPlayer))
			{
                // This player is now in a blocking action.
                RULE.Execute(shRuleBeginBlockingAction, DataObject(thisPlayer));

				// They have some.
				cardFound = true;

				// Shut everything down.
				Controller::get().Transmit(shEventBuildUI, 
					DataObject(false, GetGame()));
				Controller::get().Transmit(shEventControlsUI, 
					DataObject(false));

				Controller::get().Transmit(shEventProgressCards, 
					DataObject(thisPlayer, GetGame()));

				thisPlayerName = playerGame(thisPlayer).player().Name();

				// See if this player is spending gold.
				DataObject input(thisPlayer), output;
				RULE.Decide(shLogicIsThisPlayer, input, output);
				if(true == output.read<bool>())
				{
					thisPlayerCard = true;
				}

				// Only do this one at a time.
				break;
			}
		}

		// If all cards have been selected, continue on.
		if(false == cardFound)
		{
			RULE.Execute(shRuleMarkerPostDiceRoll, DataObject());
		}
		// Otherwise, set the text.
		else
		{
			wxString str1;

			if(true == thisPlayerCard)
			{
				str1 = wxString::Format(stSelectAProgressCard.c_str(),
					thisPlayerName.c_str());
			}
			else
			{
				str1 = wxString::Format(stWaitingSelectAProgressCard.c_str(), 
					thisPlayerName.c_str());
			}

			Controller::get().Transmit(shEventMessageUI, DataObject(str1, 
				GetGame()));
		}
	}
template<typename OutputType, typename RangeType, typename IlwOutput, typename IlwRange> std::string
RangeIterator<OutputType, RangeType, IlwOutput, IlwRange>::__str__(){
    return "RangeIterator at value: " + std::to_string(current()) + " of Range: " + _rng->__str__();
}
Exemple #30
-2
void GlutWindow::mouseClick(int _button, int _state, int _x, int _y) {
  current()->click(_button, _state, _x, _y);
}