void ScreenshotManager::updateHistory(const QString &fileName, const QString &url, const QString &deleteHash)
{
    if (!mSettings->value("/options/history", true).toBool() || url.isEmpty()) {
        return;
    }

    if (!mHistoryInitialized) {
        initHistory();
    }

    QSqlQuery query;
    query.prepare("SELECT fileName FROM history WHERE URL IS NOT EMPTY AND fileName = ?");
    query.addBindValue(fileName);
    query.exec();

    if (query.record().count() > 0) {
        QSqlQuery updateQuery;
        updateQuery.prepare("UPDATE history SET URL = ?, deleteURL = ?, time = ? WHERE fileName = ?");
        updateQuery.addBindValue(url);
        updateQuery.addBindValue("https://imgur.com/delete/" + deleteHash);
        updateQuery.addBindValue(QDateTime::currentMSecsSinceEpoch());
        updateQuery.addBindValue(fileName);

        updateQuery.exec();
    } else {
        saveHistory(fileName, url, deleteHash);
    }
}
Example #2
0
int main(int argc, char **argv)
{
    if( argc != 2 || strcmp(argv[1], "-DoIt") != 0 ){
	fprintf(stderr,
		"警告!  initbbs只用在「第一次安裝」的時候.\n"
		"若您的站台已經上線,  initbbs將會破壞掉原有資料!\n\n"
		"將把 BBS 安裝在 " BBSHOME "\n\n"
		"確定要執行, 請使用 initbbs -DoIt\n");
	return 1;
    }

    if(chdir(BBSHOME)) {
	perror(BBSHOME);
	exit(1);
    }
    
    initDir();
    initHome();
    initBoardsDIR();
    initManDIR();
    initPasswds();
    initBoards();
    initMan();
    initSymLink();
    initHistory();
    
    return 0;
}
/* Adds a command to the history list, deleting the first if the 
* size of the list is too large */
void addCommandToHistory(char* command_line)
{
    history_item* theItem = (history_item*)malloc(sizeof(history_item));
    
    if(history_list == NULL)
    {
        initHistory();
    }
    if(length(history_list) == 0)
    {
        theItem->command_number = 1;
    }
    else
    {
        theItem->command_number = 
            1 + ((history_item*)(history_list->tail->data))->command_number;
    }
    
    theItem->command_line = command_line;

    addLast(history_list, theItem);
    if(length(history_list) > HISTORY_LENGTH)
    {
        free(((history_item*)(history_list->head->data))->command_line);
        free(history_list->head->data);
        removeFirst(history_list);
    }
}
Example #4
0
void ScreenshotManager::clearHistory()
{
  QSqlQuery clearQuery("DROP TABLE history");
  clearQuery.exec();

  initHistory();
}
Example #5
0
void vcvs::initTR (void) {
  nr_double_t t = getPropertyDouble ("T");
  initDC ();
  deleteHistory ();
  if (t > 0.0) {
    setHistory (true);
    initHistory (t);
    setC (VSRC_1, NODE_1, 0.0); setC (VSRC_1, NODE_4, 0.0);
  }
}
Example #6
0
// Initialize transient analysis.
void digital::initTR (void) {
  nr_double_t t = getPropertyDouble ("t");
  initDC ();
  deleteHistory ();
  if (t > 0.0) {
    delay = true;
    setHistory (true);
    initHistory (t);
    setC (VSRC_1, NODE_OUT, 1);
  }
}
Example #7
0
void vccs::initTR (void) {
  nr_double_t t = getPropertyDouble ("T");
  initDC ();
  deleteHistory ();
  if (t > 0.0) {
    setISource (true);
    setHistory (true);
    initHistory (t);
    clearY ();
  }
}
bool OcaOctaveController::startThread()
{
  fprintf( stderr, "OcaOctaveController::startThread, thread = %p\n",
                                             QThread::currentThread() );
  m_host = new OcaOctaveHost();
  m_host->moveToThread( this );
  OcaOctaveHost::initialize();
  initHistory();

  start();
  return true;
}
/* Returns the command_line of the last item in the history list */
char* getLastCommandFromHistory()
{
    if(history_list == NULL)
    {
        initHistory();
    }
    if(length(history_list) == 0)
    {
        return NULL;
    }
    return ((history_item*)(history_list->tail->data))->command_line;
}
Example #10
0
void cccs::initTR (void) {
  nr_double_t t = getPropertyDouble ("T");
  initDC ();
  deleteHistory ();
  if (t > 0.0) {
    setISource (true);
    setHistory (true);
    initHistory (t);
    setB (NODE_1, VSRC_1, +1.0); setB (NODE_2, VSRC_1, +0.0);
    setB (NODE_3, VSRC_1, -0.0); setB (NODE_4, VSRC_1, -1.0);
  }
}
void ScreenshotManager::clearHistory()
{
    if (!mHistoryInitialized) {
        initHistory();
    }

    QSqlQuery deleteQuery("DELETE FROM history");
    deleteQuery.exec();

    QSqlQuery vacQuery("VACUUM");
    vacQuery.exec();
}
void ScreenshotManager::removeHistory(const QString &fileName, qint64 time)
{
    if (!mHistoryInitialized) {
        initHistory();
    }

    QSqlQuery removeQuery;
    removeQuery.prepare("DELETE FROM history WHERE fileName = ? AND time = ?");
    removeQuery.addBindValue(fileName);
    removeQuery.addBindValue(time);

    removeQuery.exec();
}
Example #13
0
void addHistory(char* operation)
{
    if (!history.array)
    {
        initHistory(operation);
    }
    else
    {
        history.bytes += strlen(operation)+1;
        history.array = (char **) realloc(history.array, history.bytes);
    }
    
    history.array[history.used++] = operation;
}
/* Prints the whole history list to stdout */
void printHistoryList()
{
    node* cursor;
    if(history_list == NULL)
    {
        initHistory();
    }
    cursor = history_list->head;
    while(cursor != NULL)
    {
        printf("%d %s\n", ((history_item*)(cursor->data))->command_number,
               ((history_item*)(cursor->data))->command_line);
        cursor = cursor->next;
    }
}
Example #15
0
ScreenshotManager::ScreenshotManager(QObject *parent = 0) : QObject(parent)
{
  if (QFile::exists(qApp->applicationDirPath() + QDir::separator() + "config.ini")) {
    mSettings     = new QSettings(qApp->applicationDirPath() + QDir::separator() + "config.ini", QSettings::IniFormat);
    mPortableMode = true;
    mHistoryPath  = qApp->applicationDirPath() + QDir::separator();
  }
  else {
    mSettings     = new QSettings();
    mPortableMode = false;
    mHistoryPath  = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QDir::separator();
  }

  initHistory();

  connect(Uploader::instance(), SIGNAL(done(QString, QString, QString)), this, SLOT(uploadDone(QString, QString, QString)));
}
Example #16
0
// accept a time step into the solution history
void e_trsolver::acceptstep_sync()
{
    statIterations += iterations;
    if (--convError < 0) convHelper = 0;

    // Now advance in time or not...
    if (running > 1)
    {
        adjustDelta_sync (current);
//        deltaOld = delta;
//        stepDelta = deltaOld;
//        nextStates ();
//        rejected = 0;
        adjustOrder ();
    }
    else
    {
        fillStates ();
        nextStates ();
        rejected = 0;
    }

    saveCurrent = current;
    current += delta;
    running++;
    converged++;

    // Tell integrators to be running.
    setMode (MODE_NONE);

    // Initialize or update history.
    if (running > 1)
    {
        // update the solution history with the new results
        updateHistory (current);
    }
    else
    {
        // we have just solved the first transient state
        initHistory (current);
    }

    // store the current time
    lastsynctime = current;
}
Example #17
0
void tline::initTR (void) {
  nr_double_t l = getPropertyDouble ("L");
  nr_double_t z = getPropertyDouble ("Z");
  deleteHistory ();
  if (l > 0.0) {
    setVoltageSources (2);
    allocMatrixMNA ();
    setHistory (true);
    initHistory (l / C0);
    setB (NODE_1, VSRC_1, +1); setB (NODE_2, VSRC_2, +1);
    setC (VSRC_1, NODE_1, +1); setC (VSRC_2, NODE_2, +1);
    setD (VSRC_1, VSRC_1, -z); setD (VSRC_2, VSRC_2, -z); 
  } else {
    setVoltageSources (1);
    allocMatrixMNA ();
    voltageSource (VSRC_1, NODE_1, NODE_2);
  }
}
/* prints to stderr if the number is not in the list */
void executeCommandFromHistory(int command_number)
{
    history_item* theItem;
    int lastNumber;

    if(history_list == NULL)
    {
        initHistory();
    }
    if(length(history_list) == 0)
    {
        return;
    }
    
    lastNumber = ((history_item*)(history_list->tail->data))->command_number - 1;
    if(command_number > lastNumber 
        || command_number < (lastNumber - HISTORY_LENGTH)
        || command_number <= 0)
    {
        fprintf(stderr, "%d: Event not found.\n", command_number);
        free(((history_item*)(history_list->tail->data))->command_line);
        free(history_list->tail->data);
        removeLast(history_list);
    }
    else
    {
        char* copy;
        theItem = find(history_list, historyNumberEquals, 
                       &command_number)->data;
        copy = newstr(theItem->command_line);
        printf("%s\n", copy);
        free(((history_item*)(history_list->tail->data))->command_line);
        ((history_item*)(history_list->tail->data))->command_line 
            = newstr(copy);
        runPipeline(crack_pipeline(copy));
    }
    
}
void ScreenshotManager::saveHistory(const QString &fileName, const QString &url, const QString &deleteHash)
{
    if (!mSettings->value("/options/history", true).toBool()) {
        return;
    }

    if (!mHistoryInitialized) {
        initHistory();
    }

    QString deleteUrl;

    if (!deleteHash.isEmpty()) {
        deleteUrl = "https://imgur.com/delete/" + deleteHash;
    }

    QSqlQuery query;
    query.prepare("INSERT INTO history (fileName, URL, deleteURL, time) VALUES(?, ?, ?, ?)");
    query.addBindValue(fileName);
    query.addBindValue(url);
    query.addBindValue(deleteUrl);
    query.addBindValue(QDateTime::currentMSecsSinceEpoch());
    query.exec();
}
Example #20
0
// asynchronous step solver
int e_trsolver::stepsolve_async(nr_double_t steptime)
{
    // Start to sweep through time.
    int error = 0;
    convError = 0;

    time = steptime;
    // update the interpolation time of any externally controlled
    // components which require it.
    updateExternalInterpTime(time);
    // make the stored histories for all ircuits that have
    // requested them at least as long as the next major time
    // step so we can reject the step later if needed and
    // restore all the histories to their previous state
    updateHistoryAges (time - lastasynctime);

    //delta = (steptime - time) / 10;
    //if (progress) logprogressbar (i, swp->getSize (), 40);
#if DEBUG && 0
    messagefcn (LOG_STATUS, "NOTIFY: %s: solving netlist for t = %e\n",
              getName (), (double) time);
#endif

    do
    {
#if STEPDEBUG
        if (delta == deltaMin)
        {
            messagefcn (LOG_ERROR,
                      "WARNING: %s: minimum delta h = %.3e at t = %.3e\n",
                      getName (), (double) delta, (double) current);
        }
#endif
        // update the integration coefficients
        updateCoefficients (delta);

        // Run predictor to get a start value for the solution vector for
        // the successive iterative corrector process
        error += predictor ();

        // restart Newton iteration
        if (rejected)
        {
            restart ();      // restart non-linear devices
            rejected = 0;
        }

        // Run corrector process with appropriate exception handling.
        // The corrector iterates through the solutions of the integration
        // process until a certain error tolerance has been reached.
        try_running () // #defined as:    do {
        {
            error += corrector ();
        }
        catch_exception () // #defined as:   } while (0); if (estack.top ()) switch (estack.top()->getCode ())
        {
        case EXCEPTION_NO_CONVERGENCE:
            pop_exception ();

            // Reduce step-size (by half) if failed to converge.
            if (current > 0) current -= delta;
            delta /= 2;
            if (delta <= deltaMin)
            {
                delta = deltaMin;
                adjustOrder (1);
            }
            if (current > 0) current += delta;

            // Update statistics.
            statRejected++;
            statConvergence++;
            rejected++;
            converged = 0;
            error = 0;

            // Start using damped Newton-Raphson.
            convHelper = CONV_SteepestDescent;
            convError = 2;
#if DEBUG
            messagefcn (LOG_ERROR, "WARNING: delta rejected at t = %.3e, h = %.3e "
                      "(no convergence)\n", (double) saveCurrent, (double) delta);
#endif
            break;
        default:
            // Otherwise return.
            estack.print ();
            error++;
            break;
        }
        if (error) return -1;
        if (rejected) continue;

        // check whether Jacobian matrix is still non-singular
        if (!A->isFinite ())
        {
            messagefcn (LOG_ERROR, "ERROR: %s: Jacobian singular at t = %.3e, "
                      "aborting %s analysis\n", getName (), (double) current,
			getDescription ().c_str());
            return -1;
        }

        // Update statistics and no more damped Newton-Raphson.
        statIterations += iterations;
        if (--convError < 0) convHelper = 0;

        // Now advance in time or not...
        if (running > 1)
        {
            adjustDelta (time);
            adjustOrder ();
        }
        else
        {
            fillStates ();
            nextStates ();
            rejected = 0;
        }

        saveCurrent = current;
        current += delta;
        running++;
        converged++;

        // Tell integrators to be running.
        setMode (MODE_NONE);

        // Initialize or update history.
        if (running > 1)
        {
            updateHistory (saveCurrent);
        }
        else
        {
            initHistory (saveCurrent);
        }
    }
    while (saveCurrent < time); // Hit a requested time point?

    return 0;
}
Example #21
0
void MainWindow::init()
{
	// Log
	connect(this, SIGNAL(logUpdated(QString)), this, SLOT(updateLog(QString)));

	enableCtrls(false);

	for (int i = DOCK_SNAP; i <= DOCK_PCB; i ++)
		initSnap(i);

	for (int i = DOCK_HISTORY; i <= DOCK_COMMAND; i ++)
		initHistory(i);

	ipsUI->init();

	// must call optUtils->init() after win, before show()
	optUtils->init();

#ifdef Q_OS_WIN
	//fixme: win font hack
	if (language.startsWith("zh_") || language.startsWith("ja_"))
	{
		QFont font;
		font.setFamily("MS Gothic");
		font.setFixedPitch(true);
		tbCommand->setFont(font);
//		tbCommand->setLineWrapMode(QTextEdit::NoWrap);
	}

	//rearrange docks
	addDockWidget(static_cast<Qt::DockWidgetArea>(Qt::LeftDockWidgetArea), m1UI);
	tabifyDockWidget(dwFolderList, m1UI);
#endif /* Q_OS_WIN */
	tabifyDockWidget(dwHistory, dwGUILog);

	//hide non popular docks by default
	dwGUILog->hide();

	for (int i = DOCK_SNAP; i < DOCK_LAST; i ++)
	{
		if (i != DOCK_SNAP
		 && i != DOCK_TITLE
		 && i != DOCK_HISTORY
		 && i != DOCK_MAMEINFO)
			dockCtrls[i]->hide();
	}

	dwFolderList->raise();
	dockCtrls[DOCK_SNAP]->raise();
	dockCtrls[DOCK_HISTORY]->raise();

	/* test ini readable/writable */
	// mkdir for individual game settings
	QDir().mkpath(CFG_PREFIX);

	QString warnings = "";
	QFile iniFile(CFG_PREFIX + "mamepgui" INI_EXT);
	if (!iniFile.open(QIODevice::ReadWrite | QFile::Text))
		warnings.append(QFileInfo(iniFile).absoluteFilePath());
	iniFile.close();

	if (warnings.size() > 0)
	{
		poplog("Current user has no sufficient privilege to read/write:\n" + warnings + "\n\ncouldn't save GUI settings.");
		//quit the program
		close();
		return;
	}

	loadGuiSettings();
	
	if (!validateMameBinary())
	{
			//quit the program
			close();
			return;
	}

	QIcon mamepIcon(":/res/mamep_256.png");
	qApp->setWindowIcon(mamepIcon);
	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setIcon(mamepIcon);

	// must init app style before background
	if (gui_style.isEmpty())
		gui_style = pGuiSettings->value("gui_style").toString();

	QStringList styles = QStyleFactory::keys();
	QActionGroup *styleActions = new QActionGroup(this);
	foreach (QString style, styles)
	{
		QAction* act = menuGUIStyle->addAction(style);
		act->setCheckable(true);
		if (gui_style == style)
			act->setChecked(true);
		styleActions->addAction(act);
		connect(act, SIGNAL(triggered()), this, SLOT(setGuiStyle()));
	}
Example #22
0
int main(int argc, char ** argv) 
{
  int do_usage = 0;
  unsigned int seed = 0;  // seed for random setup of the game
  char * filename = NULL; // to load game from a file

  chdir( "/home/games/blue" );


  printf("\n     BLUE. Version 1.0.2\n"
    "     Copyright (c) 2002\n"
    "Blue comes with ABSOLUTELY NO WARRANTY.\n"
    "This software is free and you are welcome to redistribute it\n"
    "under certain conditions; for more details see the file \n"
    "COPYRIGHT included in the distribution.\n\n");

  initGUI(0);

  while (1) {
     int c;
#ifdef USE_LONG_OPTIONS
     int option_index = 0;
     static struct option long_options[] =
     {
       {"seed", 1, 0, 's'},
       {"file", 1, 0, 'f'},
       {0, 0, 0, 0}
     };

     if ( (c = getopt_long (argc, argv, "s:f:",
                        long_options, &option_index)) == -1)
#else
     if ( (c = getopt (argc, argv, "s:f:") ) == -1 )
#endif
     break;
     switch (c) {
       case 's': // seed
         seed = atoi(optarg);
         break;
       case 'f': // file
         filename = optarg;
         break;
       default:
         do_usage = 1;
     }
   }
   if (do_usage) {
     printf("Usage: blue [-f file] [-s seed]\n");
  }
/*init Game*/
  initHistory( & theHistory );
  resetStrategy();
  play_mode = STRATEGY;

  if (filename) {
    // printf("load game from %s\n", filename);
    // TODO : load game from file
    if ( ( seed = load_game( filename )) < 0) {
      seed = time( NULL );         // else use the default seed(=time)
      setgame(seed);
      saveBoard();
    }
  } else {
    if (! seed) {
      seed = time( NULL );         // else use the default seed(=time)
    }
    setgame(seed);
    saveBoard();
  }

  setgui(seed);
  PlayGame(seed);                // play the game( core of the game)
  return (0);
}
Example #23
0
int main(int argc, char * argv[], char **envp)
{
    //The following two functions catch and process the interrupt and stop signals
    //AKA signals sent by the Ctrl-C and Ctrl-Z commands
    if (signal(SIGINT,signal_catcher)==SIG_ERR)
    {
        perror("Sigset cannot set SIGINT");
        exit(SIGINT);
    }
    if (signal(SIGTSTP, signal_catcher)==SIG_ERR)
    {
        perror("Sigset can not set SIGTSTP");
        exit(SIGTSTP);
    }
    
    //Declaring and initializing variables to be used later
    initHistory();
    initAlias();
    int this_input = 0;
    
    char * input = (char *) malloc(sizeof(char)*64);
    strcpy (input, "noexit");
    char *shellname = (char *) malloc(sizeof(char)*32);
    strcpy (shellname, "myshell");
    
    setShellName(shellname);
    
    printf ("[%s]%% ", shellname);
    input = getLine(input, 100);
    
    //Making sure the program does not crash if the input simply the return key
    while (strcmp(input,"\0") == 0)
    {
        printf ("[%s]%% ", shellname);
        input = getLine(input, 100);
    }
    
    setHistory(input);
    breakLine (input);
    this_input = whichInput();
    
    char ** argrv = getargrv();
    int argrc = getargrc();
    
    int loop = 1;
    
    while (loop != 0)
    {
        //Loop and process commands until the exist command is entered
        if(this_input==4) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                //printf("Before forking PID:%d\n", getpid());
                int pid = fork();
                if(pid==0)
                {
                    //sleep(2); //putting a delay in to emphasize background process
                    //printf("\nchild PID: %d\n", getpid());
                    decrargrc();
                    list();
                    //printf("\nIn the child process - ended.\n\n");
                    return 0;
                } else
                {
                    //printf("PPID:%d\n", getpid());
                    //printf("In the parent process.\n");
                    printf("%s process running in background", argrv[0]);
                }
            } else
                list();
            
        } else if(this_input==3) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    pwd();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                pwd();
        } else if(this_input==6) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    prompt();
                    shellname = getShellName();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
            {
                prompt();
                shellname = getShellName();
            }
        } else if(this_input==2) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    dirChange();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                dirChange();
        } else if(this_input==5) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    mypid();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                mypid();
        } else if(this_input==1) {
            if (getargrc() == 1)
            {
                loop = 0;
                free (input);
                free (shellname);
                
                input = NULL;
                shellname = NULL;
                
                freeDynamicMem();
                return 0;
            } else {
                printf("%s: Arguments not valid.", argrv[0]);
            }
        } else if(this_input==7) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    printHistory();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                printHistory();
        } else if(this_input==8) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    printf("\n***I've put a 3 second delay in to emphasize this background process\n");
                    sleep(3); //putting a delay in to emphasize background proces
                    decrargrc();
                    printEnv(envp);
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                printEnv(envp);
        }else if(this_input==9) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    alias();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                alias();
        }else if(this_input==10) {
            if(strcmp(argrv[argrc-1], "&")==0)
            {
                int pid = fork();
                if(pid==0)
                {
                    decrargrc();
                    murder();
                    return 0;
                } else
                    printf("%s process running in background", argrv[0]);
            } else
                murder();
        }else {
            nocmd(input);
        }
        printf ("\n[%s]%% ", shellname);
        input = getLine(input, 100);
        while (strcmp(input,"\0") == 0)
        {
            printf ("[%s]%% ", shellname);
            input = getLine(input, 100);
        }
        setHistory(input);
        breakLine (input);
        this_input = whichInput();
        argrv = getargrv();
        argrc = getargrc();
    }
    return 0;
}
int main(int argc, char *argv[]){
  char *line;
  pipeline pl;
  int run;
  
  //flags
  int redo = 0;
  int skip = 0;
  int isResume = 0;
  
  char *promptstr;
  char* buffer;
  numExits = 0;
  jobIndex = 0;
  histIndex = 0;
  back = 0;
  script = 0;
  
  FILE* in;
  /* check for the right number of arguments */
  //if ( argc > 2 ) {
  //  printusage(argv[0]);
  //  exit(-1);
  //}
  if (argc >= 2)
  {
  	DIR* dirp;
	struct dirent *dp;
	int isFound = 0;
	if ((dirp = opendir(".")) == NULL) 
        {
        	perror("couldn't open path");
                return 0;
        }
        
        //put files into array and sort their names
        while ((dp = readdir(dirp)) != NULL)
	{
		if (strcmp(dp->d_name, argv[1]) == 0)
		{
			isFound = 1;
		}
	}
	if (isFound == 0)
	{
		printf("%s: Command not found\n", argv[1]);
	}
	else
	{
		in = fopen(argv[1], "r");
		buffer = (char*)malloc(sizeof(in));
		script = 1;
	}
  }
  //struct termios saved_term_mode; 
  struct sigaction action;
  action.sa_handler = killHandle;     /* set tick to be the handler function */
  sigemptyset(&action.sa_mask); /* clear out masked functions */
  action.sa_flags   = 0;        /* no special handling */
  
  struct sigaction action2;
  action2.sa_handler = susHandle;     /* set tick to be the handler function */
  sigemptyset(&action2.sa_mask); /* clear out masked functions */
  action2.sa_flags   = 0;        /* no special handling */

    /*
     * Use the sigaction function to associate the signal action with SIGALRM.
     */
    if (sigaction(SIGINT, &action, NULL) < 0 ) {
        fprintf(stderr, "SIGINT\n");
        exit(-1);
    }
    
    if(sigaction(SIGTSTP, &action2, NULL) < 0) {
    	fprintf(stderr, "SIGTSTP\n");
        exit(-1);
    }
    //saved_term_mode = set_raw_term_mode();
	initHistory();
	initJobs();
	//strcpy(jobs[1], "hey");
  /* set prompt */
  promptstr = PROMPT;

  run = TRUE;
  if (script == 0)
  	prompt(promptstr);
  while ( run ) 
  {
    /// if reexecute was not called
    if (redo == 0)
    {
    	if (script == 0)
    	{
	    if ( NULL == (line = readLongString(stdin)) ) 
	    {
	      if ( feof(stdin) )
	        run = FALSE;
	    } 
	}
	else
	{
		fgets(line, sizeof(in), in);
		if (line[0] == '%')
		{
			line++;
			isResume = 1;
		}
	}
	
    }
    else
    {
    	//printf("histInd: %d\n", histIndex);
    	///if reexecute was called,
    	///find the correct place in the history
    	///list to extract the reexecuted command
    	int temp = histIndex;
    	temp--;
    	int ind = 0;
    	while (ind != reNumber)
    	{
    		temp--;
    		ind++;
    	}
    	line = history[temp];
    	printf("%s\n", line);
    }
    if (line == NULL)
    {
	    if (feof(stdin))
        run = FALSE;
    }
    else 
    {
    	if (line[0] == '%')
	{
		line++;
		isResume = 1;
	}
      /* We got a line, send it off to the pipeline cracker and
       * launch it
       */
       //if (redo == 0)
       //{
       	  pl = crack_pipeline(line);     	  
       //}
	redo = 0;
      /*
       * Show that it worked.  This is where you're going to do
       * something radically different: rather than printing the
       * pipeline, you're going to execute it.
       */
       
      if ( pl != NULL && strlen(pl->cline) > 0) 
      {
      	/*
      	if (pl->cline[0] == '%')
        {
        	int i;
        	isResume = 1;
        	pl->stage[0].argv[0][0] = ' ';
        	for (i = 0; i < strlen(pl->cline)-1; i++)
        	{
        		pl->stage[0].argv[0][i] = pl->stage[0].argv[0][i+1];
        	}
        	pl->stage[0].argv[0][strlen(pl->cline)-1] = '\0';
        }
        
        */
        //print_pipeline(stdout,pl); /* print it. */
        addHistory(pl->cline);
        
        ///add to the history what was typed into the command line
        if (strcmp(pl->stage[0].argv[0], "history") == 0)
        {
        	///print the history if possible
        	if (pl->stage[0].argc > 1)
        	{
        		printf("Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		printHistory();
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "jobs") == 0)
        {
        	///print the suspended jobs if possible
        	if (pl->stage[0].argc > 1)
        	{
        		printf("Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		printJobs();
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "exit") == 0)
        {
        	///exit vssh if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits++;
        	if (skip == 0)
        		exitCmd();
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "bg") == 0)
        {
        	///background the most recently suspended job if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		bg(jobs[jobIndex-1]);
        	skip  = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "fg") == 0)
        {
        	///foreground the most recently backgrounded job if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		fg(jobs[jobIndex-1]);
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "cd") == 0)
        {
        	///change the directory of vssh if possible
        	if (pl->stage[0].argc > 2)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        		cd(pl->stage[0].argv[1]);
        	skip = 0;
        }
        else if (isResume == 1)
        {
        	///foreground the specified job if possible
        	if (pl->stage[0].argc > 1)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        	{
        		//pl->stage[0].argv[0]++;
        		int i; 
        		int killFlag = 0;
        		for (i = 0; i < strlen(pl->stage[0].argv[0]); i++)
        		{
        			if (!isdigit(pl->stage[0].argv[0][i]))
        			{
        				///if the supplied job number is not a number
        				///then print error
        				killFlag = 1;
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[0]);	
        			}
        		}
        		if (killFlag == 0)
        		{
        			if (atoi(pl->stage[0].argv[0]) <= 0 || atoi(pl->stage[0].argv[0]) > jobIndex)
        				///if the supplied job number is not a valid job index
        				///then print error
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[0]);
        			else
        				resume(jobs[atoi(pl->stage[0].argv[0])-1]->id, atoi(pl->stage[0].argv[0])-1);
        		}
        	}
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "!") == 0)
        {
        	///reexecute the specified history command if possible
        	if (pl->stage[0].argc > 2 || strlen(pl->stage[0].argv[1]) > 3)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	///if the number supplied is not a valid history index
        	///then print error
        	if (pl->stage[0].argv[1][0] == '0' && skip == 0)
        	{
        		fprintf(stderr, "%s: Event not found\n", pl->stage[0].argv[1]);
        		skip = 1;
        	}
        	if (strlen(history[atoi(pl->stage[0].argv[1])]) <= 0 && skip == 0)
		{
			fprintf(stderr, "%s: Event not found\n", pl->stage[0].argv[1]);
			skip = 1;
		}
        	int i;
        	for (i = 0; i < strlen(pl->stage[0].argv[1]); i++)
        	{
			if (!isdigit(pl->stage[0].argv[1][i]) && skip == 0)
			{
				///if the number supplied is not a number
        			///then print error
				fprintf(stderr, "%s: Event not found\n", pl->stage[0].argv[1]);
				skip = 1;
			}
		}
        	numExits = 0;
        	if (skip == 0)
        	{
        		redo = 1;
        		reNumber = atoi(pl->stage[0].argv[1]);
        		//printf("renum: %d\n", reNumber);
        		//pl = crack_pipeline(history[atoi(pl->stage[0].argv[1])]);
			//printf("%s\n", pl->cline);
			//lineno++;
        		//continue;
        	}
        	skip = 0;
        }
        else if (strcmp(pl->stage[0].argv[0], "kill") == 0)
        {
        	///kill the specified job if possible
        	if (pl->stage[0].argc > 2)
        	{
        		fprintf(stderr, "Junk after built-in command\n");
        		skip = 1;
        	}
        	numExits = 0;
        	if (skip == 0)
        	{
        		int i; 
        		int killFlag = 0;
        		for (i = 0; i < strlen(pl->stage[0].argv[1]); i++)
        		{
        			///if the supplied job number is not a number
        			///then print error
        			if (!isdigit(pl->stage[0].argv[1][i]))
        			{
        				killFlag = 1;
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[1]);	
        			}
        		}
        		if (killFlag == 0)
        		{
        			if (atoi(pl->stage[0].argv[1]) <= 0 || atoi(pl->stage[0].argv[1]) > jobIndex)
        				///if the supplied job number is not a valid job index
        				///then print error
        				fprintf(stderr, "%s: No such job.\n", pl->stage[0].argv[1]);
        			else
        				killProcess(atoi(pl->stage[0].argv[1])-1, jobs[atoi(pl->stage[0].argv[1])-1]->id);
        		}
        	}
        	skip = 0;
        }
        else
        {
        	///pipe/redirect as necessary
        	numExits = 0;
        	//int i;
        	//for (i = 0; i < pl->length; i++)
        	//{
        		
	        	//else
	        	//{
	        		//handle backgrounding "&"
	        			//find the &
		        		int j;
		        		int andFound = 0;
		        		int pipeFound = 0;
		        		for (j = 1; j < strlen(pl->cline); j++)
		        		{
		        			if (pl->cline[j] == '|')
		        			{
		        				//fprintf(stderr, "Pipelines cannot be backgrounded\n");
		        				pipeFound = 1;
		        			}
		        			else if (pl->cline[j] == '&')
		        			{
		        				//error if & is not the last arg, exec nothing
		        				if (pipeFound == 1)
		        				{
		        					fprintf(stderr, "Pipelines cannot be backgrounded\n");	
		        				}
		        				else if (j != strlen(pl->cline) - 1)
		        				{
		        					andFound = 1;
		        					fprintf(stderr, "Junk after '&'.\n");
		        				}
		        				else if (pl->cline[j-1] == ' ')
		        				{
		        					andFound = 1;
		        					pl->cline[j] = '\0';
		        					//backExec(pl->stage[0].argv[0], pl->stage[0].argv, pl->cline);
		        					back = 1;
		        				}
		        			}
		        		}
		        if (pl->length >= 2)
	        	{
	        		///pipe if the pipline has 2 or more stages
	        		pipeCmd(pl);
	        	}
	        	else if (pl->stage[0].outname != NULL && pl->stage[0].inname != NULL)
	        	{
	        		redirectBoth(pl->stage[0].argv, pl->stage[0].inname, pl->stage[0].outname);
	        	}
	        	else if (pl->stage[0].outname != NULL)
	        	{
	        		///otherwise redirect output if there is an outfile
	        		redirectOutput(pl->stage[0].argv, pl->stage[0].outname, pl->cline);	
	        	}
	        	else if (pl->stage[0].inname != NULL)
	        	{
	        		///otherwise redirect input if there is an infile
	        		redirectInput(pl->stage[0].argv, pl->stage[0].inname, pl->cline);	
	        	}
		        else if (andFound == 0)
		        {
			        //execute if not a built-in command
			        execute(pl->stage[0].argv[0], pl->stage[0].argv, pl->cline);
			}
			back = 0;
	        	//}
	        	
	        //}
        }
      }
      free_pipeline(pl);   
      fflush(stdout);       /* also frees line */

      lineno++;  /* readLongString trims newlines, so increment it manually */
    }
    if (run )
    {     
    	if (script == 0)            /* assuming we still want to run */
      		prompt(promptstr);
    }
  }
  return 0;
}
Example #25
0
int main(int argc, char * argv[])
{
	//variables
	static unsigned long commHistSize = 10;
	static const char USAGE_MESS[] = "Usage: mysh [-v] [-h pos_num]";

	if(argc > 1) //parse options if any given
	{
		if(strcmp("-v", argv[1]) == 0) //if verbose option given
			verboseMode = 1;
		else if(strcmp("-h", argv[1]) == 0) //if history option given
		{
			if(argc > 2) //convert to long and update if number given
			{
				long temp = strtol(argv[2], NULL, 10);
				if(temp > 0) //if positive num, update command history
					commHistSize = temp;
				else
				{
					fprintf(stderr, "%s\n", USAGE_MESS);
					return EXIT_INVALID_ARG;
				}
			}
			else //no number given
			{
				fprintf(stderr, "%s\n", USAGE_MESS);
				return EXIT_INVALID_ARG;
			}
		}
		else //if unrecognized argument
		{
			fprintf(stderr, "%s\n", USAGE_MESS);
			return EXIT_INVALID_ARG;
		}
	}

	//initialize all necessary variables
	static unsigned long curCommand = 1; //current command index
	char *prevCommands[commHistSize]; //command history array
	initHistory(prevCommands, commHistSize); //initialize prevCommands array

	//variables needed for getting input
	char *inputBuf = NULL;
	size_t lineLen = 0;
	int progRet = EXIT_SUCCESS;
	int ret = -1;

	printf("mysh[%lu]> ", curCommand); //print prompt
	//get line, process while we have actually read bytes
	while((ret = getline(&inputBuf, &lineLen, stdin)) > 0)
	{
		if(ret == 1) //if only a new line given, prompt and start again
		{
			printf("mysh[%lu]> ", curCommand);
			continue;
		}

		//handle if ! was given, get given command history index
		if(inputBuf[0] == '!')
		{
			//get the num after the !
			unsigned long tempNum = 0;
			ret = sscanf(inputBuf, "!%lu", &tempNum);
			char *tempBuf = NULL;

			if(ret > 0) //if no number found there was an error. keep it NULL
				tempBuf = getCommand(prevCommands, commHistSize, curCommand,
									 tempNum);

			if(!tempBuf) //if null, there was an error
			{
				fprintf(stderr, "Invalid command index number given.\n");
				printf("mysh[%lu]> ", curCommand);
				continue;
			}
			else //if not null, realloc and copy string to inputBuf
			{
				char *temp = (char*)realloc(inputBuf, strlen(tempBuf) + 1);
				if(temp)
				{
					inputBuf = temp;
					strcpy(inputBuf, tempBuf);
				}
			}
		}
		else //remove trailing newline if no ! given
			inputBuf[ret - 1] = '\0';

		if(verboseMode)
			printf("\tCommand: %s\n\n", inputBuf);

		if(!strncmp(inputBuf, "quit", 4))
			break;

		//add command to command history
		ret = addCommand(prevCommands, commHistSize, inputBuf, curCommand);
		if(ret) //if nonzero, something failed
		{
			perror("mysh");
			ret = 1;
			progRet = EXIT_FAILURE;
			break;
		}

		//tokenize input and get it in args
		char **args = NULL;
		int argSize = split(inputBuf, &args);

		//we don't need inputBuf any more so free it
		free(inputBuf);
		inputBuf = NULL;

		if(argSize < 0) //if error found parsing args.
		{
			perror("mysh");
			ret = 1;
			progRet = EXIT_FAILURE;
			break;
		}

		//process commands and do what they ask
		if(!strcmp(args[0], "history")) //if they gave history command
			printHistory(prevCommands, commHistSize, curCommand);
		else if(!strcmp(args[0], "verbose")) //turn verbose on/off
		{
			if(argSize > 2)
				verbose(args[1]);
			else
				verbose("");
		}
		else if(!strcmp(args[0], "help")) //print help for mysh
			help(USAGE_MESS);
		else if(!strcmp(args[0], "echo")) //echo their given args
			echo(args, argSize - 1, 1);
		else //external command, fork dat
		{
			int runRet = 0;
			//fork/exec command, if -2, child failed so end gracefully
			if((runRet = run(args)) == -2)
			{
				destroyArgs(args, argSize);
				ret = 1;
				progRet = runRet;
				break;
			}
			if(runRet || verboseMode)
				printf("Command status: %d\n", runRet);
		}

		//free some memory and print prompt before starting again
		destroyArgs(args, argSize);
		printf("mysh[%lu]> ", ++curCommand);
	}

	//memory management
	destroyHistory(prevCommands, commHistSize);
	free(inputBuf);

	//if CTRL-D pressed/EOF, print newline for formatting
	if(ret < 1)
		putchar('\n');

	return progRet;
}
Example #26
0
int main (int argc, const char * argv[])
{
    char *line;
    pipeline pl;
    char *promptstr;

    initHistory();
    initJobs();

    /* check for the right number of arguments */
    if(argc >= 2)
    {
        FILE* theFile = fopen(argv[1], "r");
        if(theFile == NULL)
        {
            if(errno == ENOENT)
            {
                fprintf(stderr, "%s: Command not found.\n", argv[1]);
            }
            else
            {
                perror("fopen");
            }
            exit(-1);
        }
        if(dup2(fileno(theFile), STDIN_FILENO) == -1)
        {
            perror("dup2");
            exit(-1);
        }
        fclose(theFile);
    }

    /* set prompt */
    promptstr = PROMPT;

    prompt(promptstr);
    while ( TRUE )
    {
        if ( NULL == (line = readLongString(stdin)))
        {
            if ( feof(stdin) )
            {
                /* end of the input file, we're done */
                exit(0);
            }
        }
        else if(line[0] == '\0')
        {
            /* do nothing */
        }
        else
        {
            /* line is added to history list, and freed from there */
            /* copyLine is sent to pipeline, and freed from there */
            /* jobs need their own copy of the command_line */
            char* copyLine = newstr(line);
            /* We got a line, send it off to the pipeline cracker and
            * launch it
            */
            pl = crack_pipeline(copyLine);
            if(pl != NULL)
            {
                addCommandToHistory(line);
                runPipeline(pl);
            }
            free_pipeline(pl);

            lineno++;  /* readLongString trims newlines, so increment it manually */
        }
        fflush(stdout);
        //tcsetpgrp(STDIN_FILENO, getpgid(0));
        prompt(promptstr);
    }

    return 0;

}
Example #27
0
void initFIR(filter * f) 
{
  f->len = FILTER_LENGTH;
  initWeights(f);
  initHistory(f);
}