Ejemplo n.º 1
0
void T1WrenchMainWindow::on_configurePushButton_clicked()
{
    // 实在是不想写异步调用的了。
    if (prompt_user("将检查 adb,继续?") == "yes") {
        QDir::home().mkpath(".android");
        QString adbConfig = QDir::homePath() + QDir::separator() + ".android" + QDir::separator() + "adb_usb.ini";
        QFile adbConfigFile(adbConfig);
        adbConfigFile.open(QIODevice::WriteOnly);
        QTextStream out(&adbConfigFile);
        out << "0x29a9\n";
        out.flush();
        adbConfigFile.close();
        getExecutionOutput("adb kill-server");
        QString uname = getExecutionOutput("adb shell uname");
        if (!uname.contains("Linux")) {
            prompt_user("手机状态错误:uname应该是Linux,无法完成配置:\n\n" + uname);
        }
    }

    if (prompt_user("将会安装操作手机剪贴板的SetClip.apk,继续?") == "yes") {
        QString apk = QCoreApplication::applicationDirPath() + QDir::separator() + "SetClip.apk";
        QString res = getExecutionOutput("adb install -r " + apk);
        if (!res.contains("Success")) {
            prompt_user("SetClip.apk安装失败:\n\n" + res);
        } else {
            prompt_user("SetClip.apk安装成功:\n\n" + res);
        }
    }

    if (prompt_user("将获取手机屏幕尺寸,继续?") != "yes") {
        return;
    }
    QString screenPng = QDir::tempPath() + QDir::separator() + "screencap.png";
    QFile(screenPng).remove();
    getExecutionOutput("adb shell screencap /sdcard/screen.png");
    getExecutionOutput("adb pull /sdcard/screen.png " + screenPng);
    if (!QFile(screenPng).exists()) {
        prompt_user("无法获取手机截图及其屏幕尺寸, 无法完成配置");
        return;
    }

    QPixmap screenPixmap(screenPng);
    int w = screenPixmap.width();
    int h = screenPixmap.height();

    prompt_user(QString().sprintf("width is %d, height is %d", w, h));
    if (w != 1080 || h != 1920) {
        QString newEmacsWeixinSh = QCoreApplication::applicationDirPath() + QDir::separator() + QString().sprintf("emacs-weixin-%dx%d.sh", w, h);
        if (QFile(newEmacsWeixinSh).exists()) {
            emacsWeixinSh = newEmacsWeixinSh;
        } else {
            prompt_user("你的手机尺寸未进行过适配,需要自行修改" + emacsWeixinSh + ",将里面的各个座标按比例缩放,并将新的文件保存在" + newEmacsWeixinSh + "\n\n" + "详情请点击启动时右边的超级链接(我写的关于T1小扳手的博客)查看帮助");
        }
    }
}
Ejemplo n.º 2
0
// handle ADD command
int do_add(jokedb_struct *jokedb) {
    char joke_str[MAX_JOKE_STRING_LEN] = { 0 };

    int ret;

    // send ADDJOKE msg
    send(ADDJOKE, cgc_strlen(ADDJOKE));

    // send ADDPROMPT
    // get JOKE_STR from user
    prompt_user(ADDPROMPT, joke_str, MAX_JOKE_STRING_LEN);

    // append JOKE_STR to jokedb
    ret = insert_joke(jokedb, joke_str);
    if (ret == -1) {
        // jokedb is full
        send(JOKEDBFULL, cgc_strlen(JOKEDBFULL));
    } else if (ret <= -2) {
        // joke too long
        send(BADJOKEERROR, cgc_strlen(BADJOKEERROR));
    } else if (ret >= 0) {

        // joke is good
        // send JOKESTORED msg and joke_id to user
        int joke_id = ret;

        // the joke_id is up to 32bits, plus extra padding for \n and \0.
        int return_buf_len = cgc_strlen(JOKESTORED) + 40;
        char return_buf[return_buf_len];
        snprintf(return_buf, return_buf_len, JOKESTORED, joke_id);
        send(return_buf, cgc_strlen(return_buf));
    }

    return 0;
}
Ejemplo n.º 3
0
QString getActionScript(const QString& scenario)
{
    QFile emacsWeixinFile(emacsWeixinSh);
    if (!emacsWeixinFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        prompt_user("Cannot open " + emacsWeixinSh);
        return "";
    }

    QTextStream in(&emacsWeixinFile);
    in.setCodec("UTF-8");
    QString res;
    while (!in.atEnd()) {
        QString line = in.readLine();
        if (line.contains(scenario)) {
            while (!in.atEnd()) {
                QString add = in.readLine();
                if (add.contains(QRegExp("^\\s*;;\\s*$"))) {
                    goto end;
                }
                res += add + "\n";
            }
        }
    }
end:
    return res;
}
Ejemplo n.º 4
0
void fillFromAdbTaps(QList<QStringList>& cmds, QString& shellScript)
{
    foreach (const QString &sh, shellScript.split("\n")) {
        QString shCopy = sh;
        shCopy.replace(QRegExp("^\\s+"), "");
        shCopy.replace(QRegExp("#.*"), "");
        shCopy.replace(QRegExp("\\s+$"), "");
        if (!shCopy.isEmpty()) {
            if (shCopy.contains(QRegExp("^adb-tap "))) {
                shCopy.replace(QRegExp("^adb-tap "), "adb shell input tap ");
                cmds << QStringList(shCopy);
            } else if (shCopy.contains(QRegExp("^adb-tap-2 "))) {
                shCopy.replace(QRegExp("^adb-tap-2 "), "adb shell input tap ");
                cmds << QStringList(shCopy);
                cmds << QStringList(shCopy);
            } else if (shCopy.contains(QRegExp("^adb-long-press "))) {
                shCopy.replace(QRegExp("^adb-long-press "), "");
                shCopy = "adb shell input touchscreen swipe " + shCopy + " " + shCopy + " 550";
                cmds << QStringList(shCopy);
            } else if (shCopy.contains(QRegExp("^adb-swipe "))) {
                shCopy.replace(QRegExp("^adb-swipe "), "");
                QStringList args = shCopy.split(QRegExp("\\s+"));
                if (args.length() != 5) {
                    prompt_user("Error: usage: adb-swipe x1 y1 x2 y2 micro-seconds");
                }
                shCopy = "adb shell input touchscreen swipe " + shCopy;
                cmds << QStringList(shCopy);
            } else if (shCopy.contains(QRegExp("^adb-key "))) {
                shCopy.replace(QRegExp("^adb-key "), "");
                shCopy = "adb shell input keyevent " + shCopy;
                cmds << QStringList(shCopy);
            } else if (shCopy.contains(QRegExp("^sleep "))) {
#ifdef Q_OS_WIN32
                shCopy = "adb shell " + shCopy;
#endif
                cmds << QStringList(shCopy);
            } else {
                prompt_user("Unknown shell script: " + shCopy );
            }
        }
    }
}
Ejemplo n.º 5
0
static char * test_prompt() {
    char * prompt = "Enter 1: ";
    char * entered = prompt_user(prompt);
    char * expected = "1";
    if (entered == NULL) {
        mu_assert("error, prompt was null", 0);
    }
    else {
        mu_assert("error, prompt not equal to '1'", strcmp(entered,expected) == 0);
    }
    return 0;
}
Ejemplo n.º 6
0
QString T1WrenchMainWindow::get_text()
{
    QString text = ui->phoneTextEdit->toPlainText();
    while (text.endsWith("\r") || text.endsWith("\n") || text.endsWith("\t") ||
            text.endsWith(" ")) {
        text = text.left(text.length() -1);
    }
    if (text.isEmpty()) {
        prompt_user("输入手机中的文字必须不能为空", QMessageBox::Ok);
    }
    return text;
}
Ejemplo n.º 7
0
/*
** COMMAND: scrub*
** %fossil scrub ?OPTIONS? ?REPOSITORY?
**
** The command removes sensitive information (such as passwords) from a
** repository so that the repository can be sent to an untrusted reader.
**
** By default, only passwords are removed.  However, if the --verily option
** is added, then private branches, concealed email addresses, IP
** addresses of correspondents, and similar privacy-sensitive fields
** are also purged.  If the --private option is used, then only private
** branches are removed and all other information is left intact.
**
** This command permanently deletes the scrubbed information. THE EFFECTS
** OF THIS COMMAND ARE IRREVERSIBLE. USE WITH CAUTION!
**
** The user is prompted to confirm the scrub unless the --force option
** is used.
**
** Options:
**   --force     do not prompt for confirmation
**   --private   only private branches are removed from the repository
**   --verily    scrub real thoroughly (see above)
*/
void scrub_cmd(void){
  int bVerily = find_option("verily",0,0)!=0;
  int bForce = find_option("force", "f", 0)!=0;
  int privateOnly = find_option("private",0,0)!=0;
  int bNeedRebuild = 0;
  db_find_and_open_repository(OPEN_ANY_SCHEMA, 2);
  db_close(1);
  db_open_repository(g.zRepositoryName);
  if( !bForce ){
    Blob ans;
    char cReply;
    blob_zero(&ans);
    prompt_user(
         "Scrubbing the repository will permanently delete information.\n"
         "Changes cannot be undone.  Continue (y/N)? ", &ans);
    cReply = blob_str(&ans)[0];
    if( cReply!='y' && cReply!='Y' ){
      fossil_exit(1);
    }
  }
  db_begin_transaction();
  if( privateOnly || bVerily ){
    bNeedRebuild = db_exists("SELECT 1 FROM private");
    delete_private_content();
  }
  if( !privateOnly ){
    db_multi_exec(
      "UPDATE user SET pw='';"
      "DELETE FROM config WHERE name GLOB 'last-sync-*';"
      "DELETE FROM config WHERE name GLOB 'peer-*';"
      "DELETE FROM config WHERE name GLOB 'login-group-*';"
      "DELETE FROM config WHERE name GLOB 'skin:*';"
      "DELETE FROM config WHERE name GLOB 'subrepo:*';"
    );
    if( bVerily ){
      db_multi_exec(
        "DELETE FROM concealed;"
        "UPDATE rcvfrom SET ipaddr='unknown';"
        "DROP TABLE IF EXISTS accesslog;"
        "UPDATE user SET photo=NULL, info='';"
      );
    }
  }
  if( !bNeedRebuild ){
    db_end_transaction(0);
    db_multi_exec("VACUUM;");
  }else{
    rebuild_db(0, 1, 0);
    db_end_transaction(0);
  }
}
Ejemplo n.º 8
0
MultipleChoiceAnswer::Ptr TextDisplay::handle_multiple_choice_interaction(MultipleChoicePrompt::Ptr prompt) {
  while (true) {
    cout << "> ";
    string line = prompt_user();
    if (line.size() != 1) {
      cout << "Please choose a character." << endl;
    } else {
      char choice = toupper(line[0]);
      if ('A' <= choice && choice < 'A' + prompt->num_choices()) {
        return boost::make_shared<MultipleChoiceAnswer>(Util::kDefaultObject, choice - 'A');
      } else {
        cout << "Please choose one of the possible answers." << endl;
      }
    }
  }
}
Ejemplo n.º 9
0
int main(void) {
  char input[MAX_INPUT_LENGTH]; // Input string buffer
  bool terminate = false; // Termination flag
  process_options_t process_opts;

  do {
    prompt_user(input);

    if (strcmp(trim(input), "exit") == 0) { // Look for exit
      terminate = true;
    } else if (parse_input(input, &process_opts) == true) { // Parse input
      create_child_process(exec_program, &process_opts);
      wait(NULL); // Wait for child process
    }
  } while (terminate != true);

  printf("Bye!\n");
  return EXIT_SUCCESS;
}
Ejemplo n.º 10
0
int do_show(jokedb_struct *jokedb) {

    // define buffer to store user provided 
    int joke_id_buf_sz = 11;
    char joke_id_buf[joke_id_buf_sz];
    uint32_t joke_id;
    char joke_str[MAX_JOKE_STRING_LEN] = { 0 };
    int id_type;
    
    // send SHOWWHICHID msg
    send(SHOWWHICHID, cgc_strlen(SHOWWHICHID));

provide_joke_id:
    // send LISTPROMPT and handle user input
    cgc_memset(joke_id_buf, '\0', joke_id_buf_sz);
    prompt_user(SHOWPROMPT, joke_id_buf, joke_id_buf_sz);

    // is joke_id_buf a number?

    id_type = is_numeric(joke_id_buf);
    // numeric and >= 0
    if (id_type == 0) {
        joke_id = str2uint32(joke_id_buf);
        if (joke_id == 1337) {
            send(EASTEREGG, cgc_strlen(EASTEREGG));           
        } else if (joke_id < joke_count(jokedb)) {
            send_joke(&jokedb->jokes[joke_id]);
        } else {
            send(BADIDERROR, cgc_strlen(BADIDERROR));
            goto provide_joke_id;
        }
    // not numeric
    } else if (id_type == -1 && streq(joke_id_buf, "RANDOM") == 0) {
        send_random_joke(jokedb);
    // either numeric < 0, or not numeric that is not "RANDOM"
    } else {
        send(BADIDERROR, cgc_strlen(BADIDERROR));
        goto provide_joke_id;
    }
    
    return 0;
}
Ejemplo n.º 11
0
int main() 
{
  // Allocate memory for a new list
  llist *list = (llist *)malloc(sizeof(llist));
  if (list == NULL) {
    printf("Unable to allocate memory\n");
    exit(1);
  }
  init_list(list);

  int option = 0;
  bool quit = false;

  // Display menu and prompt user for action
  while (!quit) {
    option = prompt_user();
    switch (option) {
      case 1:
	printf("\n\tNumber of elements in list: %d\n", list->length);
	print(list);
	break;
      case 2: test_insert(list);
	break;
      case 3: test_delete(list);
	break;
      case 4: test_search(list);
	break;
      case 5: print_backwards(list);
	break;
      case 6: printf("Bye.\n");
	quit = true;
	break;
    }
  }
  // call function to free memory for entire list
  delete_list(list);

  return 0;
}
int main(int argc, char *argv[]) {

	// Program Vars
	char user_input[20];
	
	// Display the purpose of the program
	program_purpose();
	printf("%s", user_input);
	
	// Prompt the user, convert the input and store the converted input in a variable
	prompt_user(user_input);
	
	// Run conversion of string input into an integer representing bytes
	int total_bytes = convert_input_to_bytes(user_input);
	
	// Calculate the time it would take to transfer a given ammount of bytes (in seconds)
	int seconds = time_of_transfer(total_bytes);
	
	// Output the results in a Human-Readable form
	format_time_output(seconds);
	
	
}
Ejemplo n.º 13
0
void run_program() {
	
	// Used for logging the pass of each loop
	int i = 0;
	
	while(1) {
	
	// Prompt User for resistor factor
	prompt_user();
	
	// Break on sentinal
	if(current_denominator == 0 || current_numerator == 0) {
		printf("Breaking Run Program Loop\n");
		printf("current_denominator: %d\n", current_denominator);
		printf("current_numerator: %d\n", current_numerator);
		
		break;
	}
	
	// Calculate resistor_denominator
	combine_resistor_factor(current_numerator, current_denominator);
	
	// Increment Loop Counter
	i++;
	
	// Testing
	printf("\n");
	printf("Input Pass %d\n", i);
	printf("common_n: %d\n", common_numerator);
	printf("common_d: %d\n", common_denominator);
	printf("current_denominator: %d\n", current_denominator);
	printf("current_numerator: %d\n", current_numerator);
	printf("\n");
	
	}
	
}
Ejemplo n.º 14
0
int main(void) {
    size_t cmd_buf_sz = 20;
    char buf[cmd_buf_sz];
    jokedb_struct jokedb;

    // load with default jokes (array of joke_struct's)
    load_default_jokes(&jokedb);

    // send INITMSG
    send(INITMSG, cgc_strlen(INITMSG));
    
    // send MENU
    do_menu();
    
    while (1) {
        // send ROOTPROMPT
        cgc_memset(buf, '\0', cmd_buf_sz);
        prompt_user(ROOTPROMPT, buf, cmd_buf_sz);

        // receive user input and check for COMMAND
        if (streq(buf, "LIST") == 0) {
            do_list(&jokedb);
        } else if (streq(buf, "ADD") == 0) {
            do_add(&jokedb);
        } else if (streq(buf, "COUNT") == 0) {
            do_count(&jokedb);
        } else if (streq(buf, "SHOW") == 0) {
            do_show(&jokedb);
        } else if (streq(buf, "HELP") == 0) {
            do_help();
        } else if (streq(buf, "QUIT") == 0) {
            do_quit();
        } else {
            do_menu();
        }
    }
}
Ejemplo n.º 15
0
FreeResponseAnswer::Ptr TextDisplay::handle_free_response_interaction(FreeResponsePrompt::Ptr prompt) {
  cout << "> ";
  return boost::make_shared<FreeResponseAnswer>(Util::kDefaultObject, prompt_user());
}
Ejemplo n.º 16
0
/*
** Write all files from vid to the disk.  Or if vid==0 and id!=0
** write just the specific file where VFILE.ID=id.
*/
void vfile_to_disk(
  int vid,               /* vid to write to disk */
  int id,                /* Write this one file, if not zero */
  int verbose,           /* Output progress information */
  int promptFlag         /* Prompt user to confirm overwrites */
){
  Stmt q;
  Blob content;
  int nRepos = strlen(g.zLocalRoot);

  if( vid>0 && id==0 ){
    db_prepare(&q, "SELECT id, %Q || pathname, mrid, isexe, islink"
                   "  FROM vfile"
                   " WHERE vid=%d AND mrid>0",
                   g.zLocalRoot, vid);
  }else{
    assert( vid==0 && id>0 );
    db_prepare(&q, "SELECT id, %Q || pathname, mrid, isexe, islink"
                   "  FROM vfile"
                   " WHERE id=%d AND mrid>0",
                   g.zLocalRoot, id);
  }
  while( db_step(&q)==SQLITE_ROW ){
    int id, rid, isExe, isLink;
    const char *zName;

    id = db_column_int(&q, 0);
    zName = db_column_text(&q, 1);
    rid = db_column_int(&q, 2);
    isExe = db_column_int(&q, 3);
    isLink = db_column_int(&q, 4);
    content_get(rid, &content);
    if( file_is_the_same(&content, zName) ){
      blob_reset(&content);
      if( file_wd_setexe(zName, isExe) ){
        db_multi_exec("UPDATE vfile SET mtime=%lld WHERE id=%d",
                      file_wd_mtime(zName), id);
      }
      continue;
    }
    if( promptFlag && file_wd_size(zName)>=0 ){
      Blob ans;
      char *zMsg;
      char cReply;
      zMsg = mprintf("overwrite %s (a=always/y/N)? ", zName);
      prompt_user(zMsg, &ans);
      free(zMsg);
      cReply = blob_str(&ans)[0];
      blob_reset(&ans);
      if( cReply=='a' || cReply=='A' ){
        promptFlag = 0;
        cReply = 'y';
      }
      if( cReply=='n' || cReply=='N' ){
        blob_reset(&content);
        continue;
      }
    }
    if( verbose ) vcs_print("%s\n", &zName[nRepos]);
    if( file_wd_isdir(zName) == 1 ){
      /*TODO(dchest): remove directories? */
      vcs_fatal("%s is directory, cannot overwrite\n", zName);
    }    
    if( file_wd_size(zName)>=0 && (isLink || file_wd_islink(zName)) ){
      file_delete(zName);
    }
    if( isLink ){
      symlink_create(blob_str(&content), zName);
    }else{
      blob_write_to_file(&content, zName);
    }
    file_wd_setexe(zName, isExe);
    blob_reset(&content);
    db_multi_exec("UPDATE vfile SET mtime=%lld WHERE id=%d",
                  file_wd_mtime(zName), id);
  }
  db_finalize(&q);
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
  int debug = 1;
  int ch;
  char *file_path = NULL;

  static struct option long_options[] = {
                { "test", no_argument, 0, 't' },
                { "input", no_argument, 0, 'i' },
                { "debug", no_argument, 0, 'd' },
                { "help",  no_argument, 0, 'h' },
                { "version", no_argument, 0, 'v' },
    { 0 },
    { 0 }
  };
  while (1) {
    int option_index = 0;
    ch = getopt_long(argc, argv, "hvdtD:i:",
        long_options, &option_index);
    if (ch == -1) break;
    switch (ch) {
    case 'h':
      usage();
      exit(0);
      break;
    case 'v':
      fprintf(stdout, "%s\n", PACKAGE_VERSION);
      exit(0);
      break;
    case 'd':
      debug++;
      break;
    case 'D':
      log_accept(optarg);
      break;
    case 'i':
      file_path = optarg;
      break;
    case 't':
      log_init(2, __progname);
      test();
      exit(0);
      break;
    default:
      fprintf(stderr, "unknown option `%c'\n", ch);
      usage();
      exit(1);
    }
  }

  // Setup program
  log_init(debug, __progname);
  log_info("main", "hello world!");
  description();

  // Create abstract types variables
  seq_ptr seq = NULL;
  stack_ptr stack = NULL;

  // Initialize and solve exercise
  if(file_path == NULL) {
    seq_prepare(&seq, TMP_SEQUENCE);
    prompt_user(&seq);
    seq_init(&seq);
  } else {
    seq_prepare(&seq, file_path);
  }
  stack_create(&stack);
  solve_exercise(&seq, &stack);
  printf("[OUTPUT] The result for the algorithm is the following:\n");
  stack_output(&stack);

  // Clean up and return success
  if(file_path == NULL) remove(TMP_SEQUENCE);
  return EXIT_SUCCESS;
}
Ejemplo n.º 18
0
/*
** COMMAND:  user
**
** Usage: %fossil user SUBCOMMAND ...  ?-R|--repository FILE?
**
** Run various subcommands on users of the open repository or of
** the repository identified by the -R or --repository option.
**
**    %fossil user capabilities USERNAME ?STRING?
**
**        Query or set the capabilities for user USERNAME
**
**    %fossil user default ?USERNAME?
**
**        Query or set the default user.  The default user is the
**        user for command-line interaction.
**
**    %fossil user list
**
**        List all users known to the repository
**
**    %fossil user new ?USERNAME? ?CONTACT-INFO? ?PASSWORD?
**
**        Create a new user in the repository.  Users can never be
**        deleted.  They can be denied all access but they must continue
**        to exist in the database.
**
**    %fossil user password USERNAME ?PASSWORD?
**
**        Change the web access password for a user.
*/
void user_cmd(void){
  int n;
  db_find_and_open_repository(1);
  if( g.argc<3 ){
    usage("capabilities|default|list|new|password ...");
  }
  n = strlen(g.argv[2]);
  if( n>=2 && strncmp(g.argv[2],"new",n)==0 ){
    Blob passwd, login, contact;
    char *zPw;

    if( g.argc>=4 ){
      blob_init(&login, g.argv[3], -1);
    }else{
      prompt_user("login: "******"SELECT 1 FROM user WHERE login=%B", &login) ){
      fossil_fatal("user %b already exists", &login);
    }
    if( g.argc>=5 ){
      blob_init(&contact, g.argv[4], -1);
    }else{
      prompt_user("contact-info: ", &contact);
    }
    if( g.argc>=6 ){
      blob_init(&passwd, g.argv[5], -1);
    }else{
      prompt_for_password("password: "******"INSERT INTO user(login,pw,cap,info)"
      "VALUES(%B,%Q,'v',%B)",
      &login, zPw, &contact
    );
    free(zPw);
  }else if( n>=2 && strncmp(g.argv[2],"default",n)==0 ){
    user_select();
    if( g.argc==3 ){
      printf("%s\n", g.zLogin);
    }else{
      if( !db_exists("SELECT 1 FROM user WHERE login=%Q", g.argv[3]) ){
        fossil_fatal("no such user: %s", g.argv[3]);
      }
      if( g.localOpen ){
        db_lset("default-user", g.argv[3]);
      }else{
        db_set("default-user", g.argv[3], 0);
      }
    }
  }else if( n>=2 && strncmp(g.argv[2],"list",n)==0 ){
    Stmt q;
    db_prepare(&q, "SELECT login, info FROM user ORDER BY login");
    while( db_step(&q)==SQLITE_ROW ){
      printf("%-12s %s\n", db_column_text(&q, 0), db_column_text(&q, 1));
    }
    db_finalize(&q);
  }else if( n>=2 && strncmp(g.argv[2],"password",2)==0 ){
    char *zPrompt;
    int uid;
    Blob pw;
    if( g.argc!=4 && g.argc!=5 ) usage("password USERNAME ?NEW-PASSWORD?");
    uid = db_int(0, "SELECT uid FROM user WHERE login=%Q", g.argv[3]);
    if( uid==0 ){
      fossil_fatal("no such user: %s", g.argv[3]);
    }
    if( g.argc==5 ){
      blob_init(&pw, g.argv[4], -1);
    }else{
      zPrompt = mprintf("new passwd for %s: ", g.argv[3]);
      prompt_for_password(zPrompt, &pw, 1);
    }
    if( blob_size(&pw)==0 ){
      printf("password unchanged\n");
    }else{
      char *zSecret = sha1_shared_secret(blob_str(&pw), g.argv[3]);
      db_multi_exec("UPDATE user SET pw=%Q WHERE uid=%d", zSecret, uid);
      free(zSecret);
    }
  }else if( n>=2 && strncmp(g.argv[2],"capabilities",2)==0 ){
    int uid;
    if( g.argc!=4 && g.argc!=5 ){
      usage("user capabilities USERNAME ?PERMISSIONS?");
    }
    uid = db_int(0, "SELECT uid FROM user WHERE login=%Q", g.argv[3]);
    if( uid==0 ){
      fossil_fatal("no such user: %s", g.argv[3]);
    }
    if( g.argc==5 ){
      db_multi_exec(
        "UPDATE user SET cap=%Q WHERE uid=%d", g.argv[4],
        uid
      );
    }
    printf("%s\n", db_text(0, "SELECT cap FROM user WHERE uid=%d", uid));
  }else{
    fossil_panic("user subcommand should be one of: "
                 "capabilities default list new password");
  }
}
Ejemplo n.º 19
0
int main ()
{
  char cmd[LINE_SIZE], buf[LINE_SIZE + 1];
  char *fifo_file;
  int count, flags, fd = -1;
  
  if ((fifo_file = getenv(FIFONAME_ENV)) == 0)
    fatal("missing %s environment variable", FIFONAME_ENV); 
  
  for (;;) {
    prompt_user ("Command (? for help)", cmd, sizeof (cmd));
    if (strlen (cmd) != 1) {
      printf (" > One letter only\n");
      continue;
    }
    switch (cmd [0]) {
      case '?':
        printf(" > c  create fifo\n");
	printf(" > i  open fifo to read\n");
	printf(" > j  open fifo to read  (O_NDELAY)\n");
	printf(" > o  open fifo to write\n");
	printf(" > p  open fifo to write (O_NDELAY)\n");
	printf(" > w  write to fifo\n");
	printf(" > r  read from fifo\n");
	printf(" > s  on/off flag O_NDELAY (default off)\n");
	printf(" > e  close fifo\n");
	printf(" > d  delete fifo\n");
	printf(" > q  quit\n");
	
	break;
    case 'c':
      if (mknod(fifo_file, S_IFIFO | 0666, 0) != 0)
	perror("Can't create fifo");
      else 
	printf(">OK create fifo %s\n", fifo_file);
      break;
    
    case 'o':
      if (fd != -1)
        close(fd);
      fd = my_open(fifo_file, O_WRONLY,
		 "Can't open fifo to write", ">OK open to write\n");
      break;

    case 'p':
      if(fd != -1)
        close(fd);
      fd = my_open(fifo_file, O_WRONLY | O_NDELAY,
		 "Can't open fifo to write", ">OK open to write\n");
      break;
    
    case 'i':
      if (fd != -1) 
        close(fd);
      fd = my_open(fifo_file, O_RDONLY,
		 "Can't open fifo to read", ">OK open to read\n");
      break;
    
    case 'j':
      if (fd != -1)
        close(fd);
      fd = my_open(fifo_file, O_RDONLY | O_NDELAY,
		 "Can't open fifo to read", ">OK open to read\n");
      break;
    
    case 'w':
      count = prompt_user ("Message", buf, sizeof (buf));
      
      if (write(fd, buf, count) != count)
	perror("Can't write to fifo");
      else 
	printf(">OK write\n");
      break;
    
    case 'r':
      switch (count = read(fd, buf, sizeof(buf) - 1)) {
        case -1:
	  perror("Can't read from fifo");
	  break;
        case 0:
	  printf(">end of file\n");
	  break;
        default:
	  buf[count] = 0;
	  printf(">Read %d bytes : %s\n", count, buf);
      }
      break;
    
    case 's':
      if ((flags = fcntl(fd, F_GETFL)) == -1)
	perror("Can't get flags");
      else
	if (flags & O_NDELAY){
	  if (fcntl(fd, F_SETFL, flags & ~O_NDELAY) == -1)
	    perror("Can't set flags");
	  printf(">OFF O_NDELAY\n");
	} else {
	  if (fcntl(fd, F_SETFL, flags | O_NDELAY) == -1)
	    perror("Can't set flags");
	  printf(">ON O_NDELAY\n");
	}
      break;
    
    case 'e':
      if (close(fd) != 0)
	perror("Can't close fifo");
      else 
	printf(">OK close fifo\n");
      break;
    
    case 'd': 
      if (unlink(fifo_file) != 0)
	perror("Can't delete fifo");
      else 
	printf(">OK delete fifo\n");
      break;   
    
    case 'q':
      fprintf (stderr, " > Exiting...\n");
      return 0;
    default:
      fprintf (stderr, " > Unknown command - use ? for help\n");
    }
  }
}
Ejemplo n.º 20
0
/*
**  fossil branch new    BRANCH-NAME ?ORIGIN-CHECK-IN? ?-bgcolor COLOR?
**  argv0  argv1  argv2  argv3       argv4
*/
void branch_new(void){
  int rootid;            /* RID of the root check-in - what we branch off of */
  int brid;              /* RID of the branch check-in */
  int noSign;            /* True if the branch is unsigned */
  int i;                 /* Loop counter */
  char *zUuid;           /* Artifact ID of origin */
  Stmt q;                /* Generic query */
  const char *zBranch;   /* Name of the new branch */
  char *zDate;           /* Date that branch was created */
  char *zComment;        /* Check-in comment for the new branch */
  const char *zColor;    /* Color of the new branch */
  Blob branch;           /* manifest for the new branch */
  Manifest *pParent;     /* Parsed parent manifest */
  Blob mcksum;           /* Self-checksum on the manifest */
  const char *zDateOvrd; /* Override date string */
  const char *zUserOvrd; /* Override user name */
  int isPrivate = 0;     /* True if the branch should be private */
 
  noSign = find_option("nosign","",0)!=0;
  zColor = find_option("bgcolor","c",1);
  isPrivate = find_option("private",0,0)!=0;
  zDateOvrd = find_option("date-override",0,1);
  zUserOvrd = find_option("user-override",0,1);
  verify_all_options();
  if( g.argc<5 ){
    usage("new BRANCH-NAME CHECK-IN ?-bgcolor COLOR?");
  }
  db_find_and_open_repository(0, 0);  
  noSign = db_get_int("omitsign", 0)|noSign;
  
  /* fossil branch new name */
  zBranch = g.argv[3];
  if( zBranch==0 || zBranch[0]==0 ){
    fossil_panic("branch name cannot be empty");
  }
  if( db_exists(
        "SELECT 1 FROM tagxref"
        " WHERE tagtype>0"
        "   AND tagid=(SELECT tagid FROM tag WHERE tagname='sym-%s')",
        zBranch)!=0 ){
    fossil_fatal("branch \"%s\" already exists", zBranch);
  }

  user_select();
  db_begin_transaction();
  rootid = name_to_typed_rid(g.argv[4], "ci");
  if( rootid==0 ){
    fossil_fatal("unable to locate check-in off of which to branch");
  }

  pParent = manifest_get(rootid, CFTYPE_MANIFEST);
  if( pParent==0 ){
    fossil_fatal("%s is not a valid check-in", g.argv[4]);
  }

  /* Create a manifest for the new branch */
  blob_zero(&branch);
  if( pParent->zBaseline ){
    blob_appendf(&branch, "B %s\n", pParent->zBaseline);
  }
  zComment = mprintf("Create new branch named \"%h\"", zBranch);
  blob_appendf(&branch, "C %F\n", zComment);
  zDate = date_in_standard_format(zDateOvrd ? zDateOvrd : "now");
  blob_appendf(&branch, "D %s\n", zDate);

  /* Copy all of the content from the parent into the branch */
  for(i=0; i<pParent->nFile; ++i){
    blob_appendf(&branch, "F %F", pParent->aFile[i].zName);
    if( pParent->aFile[i].zUuid ){
      blob_appendf(&branch, " %s", pParent->aFile[i].zUuid);
      if( pParent->aFile[i].zPerm && pParent->aFile[i].zPerm[0] ){
        blob_appendf(&branch, " %s", pParent->aFile[i].zPerm);
      }
    }
    blob_append(&branch, "\n", 1);
  }
  zUuid = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", rootid);
  blob_appendf(&branch, "P %s\n", zUuid);
  if( pParent->zRepoCksum ){
    blob_appendf(&branch, "R %s\n", pParent->zRepoCksum);
  }
  manifest_destroy(pParent);

  /* Add the symbolic branch name and the "branch" tag to identify
  ** this as a new branch */
  if( content_is_private(rootid) ) isPrivate = 1;
  if( isPrivate && zColor==0 ) zColor = "#fec084";
  if( zColor!=0 ){
    blob_appendf(&branch, "T *bgcolor * %F\n", zColor);
  }
  blob_appendf(&branch, "T *branch * %F\n", zBranch);
  blob_appendf(&branch, "T *sym-%F *\n", zBranch);
  if( isPrivate ){
    blob_appendf(&branch, "T +private *\n");
    noSign = 1;
  }

  /* Cancel all other symbolic tags */
  db_prepare(&q,
      "SELECT tagname FROM tagxref, tag"
      " WHERE tagxref.rid=%d AND tagxref.tagid=tag.tagid"
      "   AND tagtype>0 AND tagname GLOB 'sym-*'"
      " ORDER BY tagname",
      rootid);
  while( db_step(&q)==SQLITE_ROW ){
    const char *zTag = db_column_text(&q, 0);
    blob_appendf(&branch, "T -%F *\n", zTag);
  }
  db_finalize(&q);
  
  blob_appendf(&branch, "U %F\n", zUserOvrd ? zUserOvrd : g.zLogin);
  md5sum_blob(&branch, &mcksum);
  blob_appendf(&branch, "Z %b\n", &mcksum);
  if( !noSign && clearsign(&branch, &branch) ){
    Blob ans;
    blob_zero(&ans);
    prompt_user("unable to sign manifest.  continue (y/N)? ", &ans);
    if( blob_str(&ans)[0]!='y' ){
      db_end_transaction(1);
      fossil_exit(1);
    }
  }

  brid = content_put_ex(&branch, 0, 0, 0, isPrivate);
  if( brid==0 ){
    fossil_panic("trouble committing manifest: %s", g.zErrMsg);
  }
  db_multi_exec("INSERT OR IGNORE INTO unsent VALUES(%d)", brid);
  if( manifest_crosslink(brid, &branch)==0 ){
    fossil_panic("unable to install new manifest");
  }
  assert( blob_is_reset(&branch) );
  content_deltify(rootid, brid, 0);
  zUuid = db_text(0, "SELECT uuid FROM blob WHERE rid=%d", brid);
  fossil_print("New branch: %s\n", zUuid);
  if( g.argc==3 ){
    fossil_print(
      "\n"
      "Note: the local check-out has not been updated to the new\n"
      "      branch.  To begin working on the new branch, do this:\n"
      "\n"
      "      %s update %s\n",
      fossil_nameofexe(), zBranch
    );
  }


  /* Commit */
  db_end_transaction(0);
  
  /* Do an autosync push, if requested */
  if( !isPrivate ) autosync(AUTOSYNC_PUSH);
}
Ejemplo n.º 21
0
Archivo: main.c Proyecto: kerichsen/asf
/** \brief Compass / magnetometer calibration application
 *
 * This application illustrates the use of the sensor_calibrate() function
 * for compass/magnetometer calibration.  It prompts the user (via serial
 * output) to manipulate the sensor board and press a button to continue.
 *
 * The calibration process is used to correct for fixed magnetic forces
 * present on the board where the compass is mounted.  If uncorrected, these
 * fixed forces will prevent accurate measurement of the actual external
 * magnetic forces (e.g. magnetic North).
 *
 * The calibration sequence requires three steps.  During each step, the
 * board is placed in a specific orientation, and the user presses the button
 * on the board to trigger a compass sensor reading.
 *
 * The three orientations are:
 *   -#  Board lying flat (on a table, for example).
 *   -#  Board rotated 180 degrees (end-for-end), still lying flat.
 *   -#  Board flipped (inverted) so that the opposite side is facing up.
 *
 * After Step 3 is completed, the calibration values for the sensor are
 * calculated and are written to non-volatile (flash) memory on the
 * microcontroller.  These values will continue to be used for future
 * compass heading readings.
 */
int main(void)
{
	sensor_t compass_dev;           /* Compass/magnetometer device */
	sensor_data_t compass_data;     /* Compass data */

	/* Initialize hardware & sensor interfaces */
	sensor_platform_init();

	LED_On(ALL_LEDS);              

	/* Wait for user to press button to start */
	prompt_user("Press button to start");
	
	/* Attach descriptor and initialize the compass device */
	sensor_attach(&compass_dev, SENSOR_TYPE_COMPASS, 0, 0);

	/* Set sensor data output formats (for display after calibration
	 * is complete)
	 */
	compass_data.scaled = true;

	/* Perform calibration sequence */

	/* Step 1 */
	prompt_user("Lay board flat & press button");
	(void)sensor_calibrate(&compass_dev, MANUAL_CALIBRATE, 1, NULL);

	/* Step 2 */
	prompt_user("Rotate 180 degrees & press button");
	(void)sensor_calibrate(&compass_dev, MANUAL_CALIBRATE, 2, NULL);

	/* Step 3 */
	prompt_user("Flip board & press button");
	if (sensor_calibrate(&compass_dev, MANUAL_CALIBRATE, 3, NULL) == false) {
		if (compass_dev.err == SENSOR_ERR_IO) {
			printf("Calibration failure: write error\n\r");
		} else {
			printf("Unknown error while calibrating device\n\r");
		}

		while (true) {
			/* Error occurred, loop forever */
		}
	}

	/* Once the calibration is complete, the magnetic heading is
	 * continuously
	 * calculated and displayed.
	 */

	while (true) {
		static uint8_t led_num = 0;

		/* Change LED display */
		LED_Toggle(led_array[led_num++]);
		if (led_num >= NUM_BLINK_LEDS) {
			led_num = 0;
		}

		/* Sample compass and display heading values */
		sensor_get_heading(&compass_dev, &compass_data);

		printf("Direction = %d, Inclination = %d, Strength = %d uT\r\n",
				(int)compass_data.heading.direction,
				(int)compass_data.heading.inclination,
				(int)compass_data.heading.strength);

		delay_ms(100);
	}

	return 0;
}
Ejemplo n.º 22
0
Archivo: main.c Proyecto: marekr/asf
/** \brief Proximity sensor threshold calibration application
 *
 * This application illustrates the use of the sensor_calibrate() function
 * to set the proximity detection thresholds in a 3-channel proximity sensor.
 * This threshold is the level at which the sensor will report that an object
 * is near the device.
 *
 * The calibration sequence requires three steps, one for each channel.  During
 * each step, an object is placed at the desired distance in front of the
 * sensor, and the user presses the button on the board to trigger a proximity
 * reading.
 *
 * After Step 3 is completed, the threshold values for the sensor are
 * calculated and are written to non-volatile (flash) memory on the
 * microcontroller.  These values will continue to be used for future
 * proximity readings, unless they are overwritten by an application
 * calling the sensor_set_threshold function for the proximity sensor
 * channel(s).
 */
int main(void)
{
	sensor_t prox_dev;           /* Proximity sensor device */
	sensor_data_t prox_data;     /* Proximity data */
	int led_num = 0;

	/* Initialize the board (Xplained UC3 or XMEGA & Xplained Sensor boards)
	 * I/O pin mappings and any other configurable resources selected in
	 * the build configuration.
	 */
	sensor_platform_init();

	LED_On(ALL_LEDS);

	/* Wait for user to press button to start */
	prompt_user("Press button to start");
	
	/* Attach descriptor and initialize the proximity sensor */
	sensor_attach(&prox_dev, SENSOR_TYPE_PROXIMITY, 0, 0);

#if (SET_PROX_CURRENT == true)
	/* Manually set LED current value for each channel */
	/* Otherwise, sensor will use default values */
	sensor_set_channel(&prox_dev, SENSOR_CHANNEL_ALL);
	sensor_set_current(&prox_dev, PROX_CURRENT_mA);
#endif

	/* Set sensor data output formats (for display after calibration
	 * complete) */
	prox_data.scaled = true;
	
	/* Perform calibration sequence */

	/* Step 1 */
	printf("Setting channel 1: ");
	prompt_user("Place object at desired distance and press button");
	(void)sensor_calibrate(&prox_dev, MANUAL_CALIBRATE, 1, NULL);

	/* Step 2 */
	printf("Setting channel 2: ");
	prompt_user("Place object at desired distance and press button");
	(void)sensor_calibrate(&prox_dev, MANUAL_CALIBRATE, 2, NULL);

	/* Step 3 */
	printf("Setting channel 3: ");
	prompt_user("Place object at desired distance and press button");
	if (sensor_calibrate(&prox_dev, MANUAL_CALIBRATE, 3, NULL) != true) {
		if (prox_dev.err == SENSOR_ERR_IO) {
			printf("Calibration failure: write error\n\r");
		} else {
			printf("Unknown error while calibrating device\n\r");
		}

		while (true) {
			/* Error occurred, loop forever */
		}
	}

	int16_t value;

	/* Display threshold values */
	sensor_set_channel(&prox_dev, 1);
	sensor_get_threshold(&prox_dev, SENSOR_THRESHOLD_NEAR_PROXIMITY,
			&value);
	printf("Channel 1 threshold = %d\r\n", value);

	sensor_set_channel(&prox_dev, 2);
	sensor_get_threshold(&prox_dev, SENSOR_THRESHOLD_NEAR_PROXIMITY,
			&value);
	printf("Channel 2 threshold = %d\r\n", value);

	sensor_set_channel(&prox_dev, 3);
	sensor_get_threshold(&prox_dev, SENSOR_THRESHOLD_NEAR_PROXIMITY,
			&value);
	printf("Channel 3 threshold = %d\r\n", value);

	/* Once the calibration is complete, the proximity status is
	 * continuously captured and displayed.
	 */

	while (true) {
		/* Change LED display */
		LED_Toggle(led_array [led_num++]);
		if (led_num >= NUM_BLINK_LEDS) {
			led_num = 0;
		}

		/* Sample proximity and display results for each channel */
		sensor_get_proximity(&prox_dev, &prox_data);

		printf("prox  = 1:%s 2:%s 3:%s\r\n",
				prox_labels[prox_data.proximity.value[0]],
				prox_labels[prox_data.proximity.value[1]],
				prox_labels[prox_data.proximity.value[2]]);

		delay_ms(500);
	}

	return 0;
}
Ejemplo n.º 23
0
void f( ) {
   vector<int> v;
   // The following could result in v being initialized out of
   // sequence
   intialize(v) = prompt_user( ), prompt_user( );
}
Ejemplo n.º 24
0
int main() {
    prompt_user();
    
    return EXIT_SUCCESS; 
}