Exemplo n.º 1
0
// Test put and get functions
int test_hmap_2() {
    hmap_handle* hmap;
    hmap = hmap_create();

    int* data1;
    int* data2;
    int* data3;

    data1 = new(int);
    *data1 = 0;
    hmap_put(hmap, (long) (*data1), data1);

    data2 = new(int);
    *data2 = 1;
    hmap_put(hmap, (long) (*data2), data2);

    data3 = new(int);
    *data3 = 2;
    hmap_put(hmap, (long) (*data3), data3);

    if (hmap_get(hmap, (long) (*data1)) != data1
            || hmap_get(hmap, (long) (*data2)) != data2
            || hmap_get(hmap, (long) (*data3)) != data3) {
        kfree(data1);
        kfree(data2);
        kfree(data3);
        hmap_free(hmap);
        return TEST_FAIL;
    }

    return TEST_OK;
}
Exemplo n.º 2
0
void main()
{
	hashmap *hMap;
	hMap = hmap_creat(int_hash_fn, int_eq_fn, int_del_fn);

	if(!hmap_put(hMap, (void*)"test", (void*)"value"))
		return;
	printf( "%s\n", (char*)hmap_get(hMap, (void*)"test") );
	free_hmap(hMap);
	hMap = NULL;
}
Exemplo n.º 3
0
 /* param: char*, filename
 * param: Agg_Data
 * func:  Do a DFS starting at char*
 *        flag vlaues:
 *          0: not discovered on current search
 *          1: discovered (but not done)( to find cycles)
 *          2: finished (so that cross edges can still use finished nodes
 * ret:
 *    0: no bad edge (good)
 *    1: has bad edge (bad)
 */
int has_bad_edge( char* filename, HMAP_PTR hmap, Fdata* files, int numFData){
  //printf("filename:%s:\n", filename);
  if( hmap_contains( hmap, filename) ){
    Fdata Curfile = hmap_get( hmap, filename);
    Curfile->flag = 1;
    int i;
    for( i=0; i<Curfile->numDepends; ++i){ //for every dependency
     // printf("CHECKING DEPEND:%s:\n", Curfile->dependsOn[i]);
      Fdata depends = (Fdata)hmap_get( hmap, (Curfile->dependsOn)[i] );
      if(depends->flag == 1) return 1; //back edge
      if( has_bad_edge( (Curfile->dependsOn)[i], hmap, files, numFData) ) return 1;
    }
    Curfile->flag = 2;
    return 0;
  }
  else{ //file never existed
    fprintf(stderr, "ERROR, file doesn't exist\n");
    return 1;
  }
}
Exemplo n.º 4
0
static int bldg_add(fixed x, fixed z, mesh_s *mesh)
{
    int idx = bldg_count++;
    bldg_s *bldg = &bldg_list[idx];
    memset(bldg, 0, sizeof(bldg_s));
    bldg->pos[0] = x;
    bldg->pos[1] = hmap_get(x, z);
    bldg->pos[2] = z;
    bldg->mesh = mesh;

    return idx;
}
Exemplo n.º 5
0
/* Create a new user info structure, representing a user on the hub.
 */
DCUserInfo *
user_info_new(const char *nick)
{
    DCUserInfo *info;
    char *ucname;

    info = (DCUserInfo*) xmalloc(sizeof(DCUserInfo));
    info->nick = xstrdup(nick);
    info->description = NULL;
    info->speed = NULL;
    info->level = 0;
    info->email = NULL;
    info->share_size = 0;
    info->active_state = DC_ACTIVE_UNKNOWN;
    info->download_queue = ptrv_new();
    info->slot_granted = false;
    info->refcount = 1;
    info->is_operator = false;
    info->info_quered = false;
    info->conn_count = 0;

    /* XXX Find existing connections to this user... */
    ucname = xasprintf("%s|%s", nick, _("UL"));
    info->conn[info->conn_count] = (DCUserConn*) hmap_get(user_conns, ucname);
    if (info->conn[info->conn_count] != NULL)
        info->conn_count++;
    free(ucname);
    ucname = xasprintf("%s|%s", nick, _("DL"));
    info->conn[info->conn_count] = (DCUserConn*) hmap_get(user_conns, ucname);
    if (info->conn[info->conn_count] != NULL)
        info->conn_count++;
    free(ucname);
    ucname = xasprintf("%s|", nick);
    info->conn[info->conn_count] = (DCUserConn*) hmap_get(user_conns, ucname);
    if (info->conn[info->conn_count] != NULL)
        info->conn_count++;
    free(ucname);

    return info;
}
Exemplo n.º 6
0
int main() {
	hashmap* h = mk_hmap(str_hash_fn, str_eq_fn, str_del_fn);
	
	char* s = (char*) malloc(8);
	char* k = (char*) malloc(8); 
	
	sprintf(s, "hello"); 
	sprintf(k, "world"); 
	
	hmap_add(h, s, k); // map "hello" to "world"
	hmap_add(h, k, s); // map "world" to "hello"
	
	char* x = (char*) hmap_get(h, k);
	printf("%s ", x);
	
	x = (char*) hmap_get(h, s);
	printf("%s!\n", x);
	
	free_hmap(h);
	
	return 0;
}
Exemplo n.º 7
0
Arquivo: state.c Projeto: dongh11/ymd
struct variable *vm_mem(struct ymd_mach *vm, void *o, const char *field) {
	struct variable k, *v = NULL;
	switch (gcx(o)->type) {
	case T_HMAP:
		setv_kstr(&k, kstr_fetch(vm, field, -1));
		v = hmap_get(o, &k);
		break;
	case T_SKLS:
		setv_kstr(&k, kstr_fetch(vm, field, -1));
		v = skls_get(vm, o, &k);
		break;
	default:
		assert(!"No reached.");
		break;
	}
	return v;
}
Exemplo n.º 8
0
Arquivo: state.c Projeto: dongh11/ymd
struct variable *vm_get(struct ymd_mach *vm, struct variable *var,
                        const struct variable *key) {
	struct ymd_context *l = ioslate(vm);
	if (is_nil(key))
		ymd_panic(l, "No any key will be `nil`");
	switch (ymd_type(var)) {
	case T_SKLS:
		return skls_get(vm, skls_x(var), key);
	case T_HMAP:
		return hmap_get(hmap_x(var), key);
	case T_DYAY:
		return vm_at(vm, dyay_x(var), int_of(l, key));
	case T_MAND:
		if (!mand_x(var)->proto)
			ymd_panic(l, "Management memory has no metatable yet");
		return mand_get(vm, mand_x(var), key);
	default:
		ymd_panic(l, "Variable can not be index");
		break;
	}
	assert(!"No reached.");
	return NULL;
}
Exemplo n.º 9
0
static bool
validate_nick(DCUserConn *uc, const char *nick)
{
    DCUserInfo *ui;

    ui = (DCUserInfo*) hmap_remove(pending_userinfo, nick);
    if (ui != NULL) {
        if (ui->conn_count < DC_USER_MAX_CONN) {
            uc->info = ui;
            uc->info->refcount++;
            uc->info->conn[uc->info->conn_count++] = uc;
            hmap_remove(pending_userinfo, ui->nick);
            user_info_free(ui);
            update_user_connection_name(uc, "%s|", uc->info->nick);
            return true;
        }
        warn(_("No more connections to user %s allowed.\n"), quotearg(nick));
        user_info_free(ui);
        return false;
    }

    ui = (DCUserInfo*) hmap_get(hub_users, nick);
    if (ui != NULL) {
        if (ui->conn_count < DC_USER_MAX_CONN) {
            uc->info = ui;
            uc->info->refcount++;
            uc->info->conn[uc->info->conn_count++] = uc;
            update_user_connection_name(uc, "%s|", uc->info->nick);
            return true;
        }
        warn(_("No more connections to user %s allowed.\n"), quotearg(nick));
        return false;
    }

    return false;
}
Exemplo n.º 10
0
static void
hub_handle_command(char *buf, uint32_t len)
{
    char *hub_my_nick; /* XXX */

    hub_my_nick = main_to_hub_string(my_nick);

    if (len >= 6 && strncmp(buf, "$Lock ", 6) == 0) {
        char *key;

        if (!check_state(buf, (DCUserState) DC_HUB_LOCK))
            goto hub_handle_command_cleanup;

        key = (char*) memmem(buf+6, len-6, " Pk=", 4);
        if (key == NULL) {
            warn(_("Invalid $Lock message: Missing Pk value\n"));
            key = buf+len;
        }
        key = decode_lock(buf+6, key-buf-6, DC_CLIENT_BASE_KEY);
        if (strleftcmp("EXTENDEDPROTOCOL", buf+6) == 0) {
            if (!hub_putf("$Supports TTHSearch NoGetINFO NoHello|")) {
                free(key);
                goto hub_handle_command_cleanup;
            }
        }
        if (!hub_putf("$Key %s|", key)) {
            free(key);
            goto hub_handle_command_cleanup;
        }
        free(key);
        if (!hub_putf("$ValidateNick %s|", hub_my_nick))
            goto hub_handle_command_cleanup;
        hub_state = DC_HUB_HELLO;
    }
    else if (len >= 10 && strncmp(buf, "$Supports ", 10) == 0) {
        char *p0, *p1;

        hub_extensions = 0;
        for (p0 = buf+10; (p1 = strchr(p0, ' ')) != NULL; p0 = p1+1) {
            *p1 = '\0';
            parse_hub_extension(p0);
        }
        if (*p0 != '\0')
            parse_hub_extension(p0);
    }
    else if (strcmp(buf, "$GetPass") == 0) {
        if (my_password == NULL) {
            screen_putf(_("Hub requires password.\n"));
            hub_disconnect();
            goto hub_handle_command_cleanup;
        }
        screen_putf(_("Sending password to hub.\n"));
        if (!hub_putf("$MyPass %s|", my_password))
            goto hub_handle_command_cleanup;
    }
    else if (strcmp(buf, "$BadPass") == 0) {
        warn(_("Password not accepted.\n"));
        hub_disconnect();
    }
    else if (strcmp(buf, "$LogedIn") == 0) {
        screen_putf(_("You have received operator status.\n"));
    }
    else if (len >= 9 && strncmp(buf, "$HubName ", 9) == 0) {
        free(hub_name);
        hub_name = hub_to_main_string(buf + 9);
        screen_putf(_("Hub name is %s.\n"), quotearg(hub_name));
    }
    else if (strcmp(buf, "$GetNetInfo") == 0) {
        hub_putf("$NetInfo %d$1$%c|", my_ul_slots, is_active ? 'A' : 'P');
    }
    else if (strcmp(buf, "$ValidateDenide") == 0) {
        if (!check_state(buf, (DCUserState) DC_HUB_HELLO))
            goto hub_handle_command_cleanup;
        /* DC++ disconnects immediately if this is received.
         * But shouldn't we give the client a chance to change the nick?
         * Also what happens if we receive this when correctly logged in?
         */
        warn(_("Hub did not accept nick. Nick may be in use.\n"));
        hub_disconnect();
    }
    else if (len >= 7 && strncmp(buf, "$Hello ", 7) == 0) {
        DCUserInfo *ui;
        char *conv_nick;

        conv_nick = hub_to_main_string(buf + 7);

        if (hub_state == DC_HUB_HELLO) {
            if (strcmp(buf+7, hub_my_nick) == 0) {
                screen_putf(_("Nick accepted. You are now logged in.\n"));
            } else {
                /* This probably won't happen, but better safe... */
                free(my_nick);
                my_nick = xstrdup(conv_nick);
                free(hub_my_nick);
                hub_my_nick = xstrdup(buf + 7);
                screen_putf(_("Nick accepted but modified to %s. You are now logged in.\n"), quotearg(my_nick));
            }

            ui = user_info_new(conv_nick);
            ui->info_quered = true; /* Hub is sending this automaticly */
            hmap_put(hub_users, ui->nick, ui);

            free (conv_nick);

            if (!hub_putf("$Version 1,0091|"))
                goto hub_handle_command_cleanup;
            if (!hub_putf("$GetNickList|"))
                goto hub_handle_command_cleanup;
            if (!send_my_info())
                goto hub_handle_command_cleanup;

            hub_state = DC_HUB_LOGGED_IN;
        } else {
            flag_putf(DC_DF_JOIN_PART, _("User %s logged in.\n"), quotearg(conv_nick));
            ui = user_info_new(conv_nick);
            hmap_put(hub_users, ui->nick, ui);
            free (conv_nick);
            if ((hub_extensions & HUB_EXT_NOGETINFO) == 0) {
                if (!hub_putf("$GetINFO %s %s|", buf+7, hub_my_nick))
                    goto hub_handle_command_cleanup;
                ui->info_quered = true;
            }
        }
    }
    else if (len >= 8 && strncmp(buf, "$MyINFO ", 8) == 0) {
        DCUserInfo *ui;
        char *token;
        uint32_t len;
        char* conv_buf;
        char *work_buf;

        buf += 8;
        work_buf = conv_buf = hub_to_main_string(buf);
        token = strsep(&work_buf, " ");
        if (strcmp(token, "$ALL") != 0) {
            warn(_("Invalid $MyINFO message: Missing $ALL parameter, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }

        token = strsep(&work_buf, " ");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing nick parameter, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        ui = (DCUserInfo*) hmap_get(hub_users, token);
        if (ui == NULL) {
            /*
             * if the full buf has not been converted from hub to local charset,
             * we should try to convert nick only
             */
            /*
            char *conv_nick = hub_to_main_string(token);
            if ((ui = hmap_get(hub_users, conv_nick)) == NULL) {
            */
            ui = user_info_new(token);
            ui->info_quered = true;
            hmap_put(hub_users, ui->nick, ui);
            /*
            }
            free(conv_nick);
            */
        }

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing description parameter, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        free(ui->description);
        ui->description = xstrdup(token);

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing description separator, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing connection speed, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        len = strlen(token);
        free(ui->speed);
        if (len == 0) {
            ui->speed = xstrdup("");
            ui->level = 0; /* XXX: or 1? acceptable level? */
        } else {
            ui->speed = xstrndup(token, len-1);
            ui->level = token[len-1];
        }

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing e-mail address, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        free(ui->email);
        ui->email = xstrdup(token);

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing share size, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        if (!parse_uint64(token, &ui->share_size)) {
            warn(_("Invalid $MyINFO message: Invalid share size, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }

        if (ui->active_state == DC_ACTIVE_RECEIVED_PASSIVE
                || ui->active_state == DC_ACTIVE_KNOWN_ACTIVE)
            ui->active_state = DC_ACTIVE_UNKNOWN;

        /* XXX: Now that user's active_state may have changed, try queue again? */
        free(conv_buf);
    }
    else if (strcmp(buf, "$HubIsFull") == 0) {
        warn(_("Hub is full.\n"));
        /* DC++ does not disconnect immediately. So I guess we won't either. */
        /* Maybe we should be expecting an "hub follow" message? */
        /* hub_disconnect(); */
    }
    else if (len >= 3 && (buf[0] == '<' || strncmp(buf, " * ", 3) == 0)) {
        char *head;
        char *tail;
        char *msg;
        bool first = true;
        /*
        int scrwidth;
        size_t firstlen;
        size_t otherlen;

        screen_get_size(NULL, &scrwidth);
        firstlen = scrwidth - strlen(_("Public:"));
        otherlen = scrwidth - strlen(_(" | "));
        */

        msg = prepare_chat_string_for_display(buf);

        for (head = msg; (tail = strchr(head, '\n')) != NULL; head = tail+1) {
            /*PtrV *wrapped;*/

            if (tail[-1] == '\r') /* end > buf here, buf[0] == '<' or ' ' */
                tail[-1] = '\0';
            else
                tail[0] = '\0';

            /*wrapped = wordwrap(quotearg(buf), first ? firstlen : otherlen, otherlen);
            for (c = 0; c < wrapped->cur; c++)
            flag_putf(DC_DF_PUBLIC_CHAT, first ? _("Public: %s\n") : _(" | %s\n"), );
            ptrv_foreach(wrapped, free);
            ptrv_free(wrapped);*/
            flag_putf(DC_DF_PUBLIC_CHAT, first ? _("Public: %s\n") : _(" | %s\n"), quotearg(head));
            first = false;
        }
        flag_putf(DC_DF_PUBLIC_CHAT, first ? _("Public: %s\n") : _(" | %s\n"), quotearg(head));
        free(msg);
    }
    else if (len >= 5 && strncmp(buf, "$To: ", 5) == 0) {
        char *msg;
        char *tail;
        char *frm;
        char *head;
        bool first = true;

        msg = strchr(buf+5, '$');
        if (msg == NULL) {
            warn(_("Invalid $To message: Missing text separator, ignoring\n"));
            goto hub_handle_command_cleanup;
        }
        *msg = '\0';
        msg++;

        /* FIXME: WTF is this? Remove multiple "From: "? Why!? */
        frm = buf+5;
        while ((tail = strstr(msg, "From: ")) != NULL && tail < msg)
            frm = tail+6;

        msg = prepare_chat_string_for_display(msg);
        frm = prepare_chat_string_for_display(frm);
        for (head = msg; (tail = strchr(head, '\n')) != NULL; head = tail+1) {
            if (tail[-1] == '\r') /* tail > buf here because head[0] == '<' or ' ' */
                tail[-1] = '\0';
            else
                tail[0] = '\0';
            if (first) {
                screen_putf(_("Private: [%s] %s\n"), quotearg_n(0, frm), quotearg_n(1, head));
                first = false;
            } else {
                screen_putf(_(" | %s\n"), quotearg(head));
            }
        }
        if (first) {
            screen_putf(_("Private: [%s] %s\n"), quotearg_n(0, frm), quotearg_n(1, head));
        } else {
            screen_putf(_(" | %s\n"), quotearg(head));
        }
        free(msg);
        free(frm);
    }
    else if (len >= 13 && strncmp(buf, "$ConnectToMe ", 13) == 0) {
        struct sockaddr_in addr;

        buf += 13;
        if (strsep(&buf, " ") == NULL) {
            warn(_("Invalid $ConnectToMe message: Missing or invalid nick\n"));
            goto hub_handle_command_cleanup;
        }
        if (!parse_ip_and_port(buf, &addr, 0)) {
            warn(_("Invalid $ConnectToMe message: Invalid address specification.\n"));
            goto hub_handle_command_cleanup;
        }

        flag_putf(DC_DF_CONNECTIONS, _("Connecting to user on %s\n"), sockaddr_in_str(&addr));
        user_connection_new(&addr, -1);
    }
    else if (len >= 16 && strncmp(buf, "$RevConnectToMe ", 16) == 0) {
        char *nick;
        char *local_nick;
        DCUserInfo *ui;

        nick = strtok(buf+16, " ");
        if (nick == NULL) {
            warn(_("Invalid $RevConnectToMe message: Missing nick parameter\n"));
            goto hub_handle_command_cleanup;
        }
        if (strcmp(nick, hub_my_nick) == 0) {
            warn(_("Invalid $RevConnectToMe message: Remote nick is our nick\n"));
            goto hub_handle_command_cleanup;
        }
        local_nick = hub_to_main_string(nick);
        ui = (DCUserInfo*) hmap_get(hub_users, local_nick);
        if (ui == NULL) {
            warn(_("Invalid $RevConnectToMe message: Unknown user %s, ignoring\n"), quotearg(local_nick));
            free(local_nick);
            goto hub_handle_command_cleanup;
        }
        free(local_nick);

        if (ui->conn_count >= DC_USER_MAX_CONN) {
            warn(_("No more connections to user %s allowed.\n"), quotearg(ui->nick));
            goto hub_handle_command_cleanup;
        }

        if (!is_active) {
            if (ui->active_state == DC_ACTIVE_SENT_PASSIVE) {
                warn(_("User %s is also passive. Cannot establish connection.\n"), quotearg(ui->nick));
                /* We could set this to DC_ACTIVE_UNKNOWN too. This would mean
                 * we would keep sending RevConnectToMe next time the download
                 * queue is modified or some timer expired and told us to retry
                 * download. The remote would then send back RevConnectToMe
                 * and this would happen again. This way we would try again -
                 * maybe remote has become active since last time we checked?
                 * But no - DC++ only replies with RevConnectToMe to our first
                 * RevConnectToMe. After that it ignores them all.
                 */
                ui->active_state = DC_ACTIVE_RECEIVED_PASSIVE;
                if (hmap_remove(pending_userinfo, ui->nick) != NULL)
                    ui->refcount--;
                goto hub_handle_command_cleanup;
            }
            if (ui->active_state != DC_ACTIVE_RECEIVED_PASSIVE) {
                /* Inform remote that we are also passive. */
                if (!hub_putf("$RevConnectToMe %s %s|", hub_my_nick, nick))
                    goto hub_handle_command_cleanup;
            }
        }
        ui->active_state = DC_ACTIVE_RECEIVED_PASSIVE;

        if (!hub_connect_user(ui))
            goto hub_handle_command_cleanup;
    }
    else if ( (len >= 10 && strncmp(buf, "$NickList ", 10) == 0)
              || (len >= 8 && strncmp(buf, "$OpList ", 8) == 0) ) {
        char *nick;
        char *end;
        int oplist;
        char *conv_nick;

        if ( strncmp(buf, "$NickList ", 10) == 0) {
            nick = buf + 10;
            oplist = 0;
        } else {
            nick = buf + 8;
            oplist = 1;
        }

        for (; (end = strstr(nick, "$$")) != NULL; nick = end+2) {
            DCUserInfo *ui;
            *end = '\0';

            conv_nick = hub_to_main_string(nick);

            ui = (DCUserInfo*) hmap_get(hub_users, conv_nick);
            if (ui == NULL) {
                ui = user_info_new(conv_nick);
                hmap_put(hub_users, ui->nick, ui);
            }

            free(conv_nick);

            if (!ui->info_quered && (hub_extensions & HUB_EXT_NOGETINFO) == 0) {
                if (!hub_putf("$GetINFO %s %s|", nick, hub_my_nick))  {
                    goto hub_handle_command_cleanup;
                }
                ui->info_quered = true;
            }

            if (oplist)
                ui->is_operator = true;
        }
    }
    else if (len >= 6 && strncmp(buf, "$Quit ", 6) == 0) {
        DCUserInfo *ui;
        char *conv_nick = hub_to_main_string(buf+6);

        // I don't want these messages.
        //flag_putf(DC_DF_JOIN_PART, "User %s quits.\n", quotearg(conv_nick));
        ui = (DCUserInfo*) hmap_remove(hub_users, conv_nick);
        if (ui == NULL) {
            /* Some hubs print quit messages for users that never joined,
             * so print this as debug only.
             */
            flag_putf(DC_DF_DEBUG, _("Invalid $Quit message: Unknown user %s.\n"), quotearg(conv_nick));
        } else
            user_info_free(ui);
        free(conv_nick);
    }
    else if (len >= 8 && strncmp(buf, "$Search ", 8) == 0) {
        char *source;
        int parse_result = 0;
        DCSearchSelection sel;
        sel.patterns = NULL;

        buf += 8;
        source = strsep(&buf, " ");
        if (source == NULL) {
            warn(_("Invalid $Search message: Missing source specification.\n"));
            goto hub_handle_command_cleanup;
        }
        /* charset handling is in parse_search_selection */
        parse_result = parse_search_selection(buf, &sel);
        if (parse_result != 1) {
            if (sel.patterns != NULL) {
                int i = 0;
                for (i = 0; i < sel.patterncount; i++) {
                    search_string_free(sel.patterns+i);
                }
                free(sel.patterns);
            }
            if (parse_result == 0)
                warn(_("Invalid $Search message: %s: Invalid search specification.\n"), buf);
            goto hub_handle_command_cleanup;
        }
        if (strncmp(source, "Hub:", 4) == 0) {
            DCUserInfo *ui;
            char *conv_nick = hub_to_main_string(source+4);
            ui = (DCUserInfo*) hmap_get(hub_users, conv_nick);

            if (ui == NULL) {
                warn(_("Invalid $Search message: Unknown user %s.\n"), quotearg(conv_nick));
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                free(conv_nick);
                goto hub_handle_command_cleanup;
            }
            free(conv_nick);

            if (strcmp(ui->nick, my_nick) == 0) {
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                goto hub_handle_command_cleanup;
            }
            perform_inbound_search(&sel, ui, NULL);
            if (sel.patterns != NULL) {
                int i = 0;
                for (i = 0; i < sel.patterncount; i++) {
                    search_string_free(sel.patterns+i);
                }
                free(sel.patterns);
            }
        } else {
            struct sockaddr_in addr;
            if (!parse_ip_and_port(source, &addr, DC_CLIENT_UDP_PORT)) {
                warn(_("Invalid $Search message: Invalid address specification.\n"));
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                goto hub_handle_command_cleanup;
            }
            if (local_addr.sin_addr.s_addr == addr.sin_addr.s_addr && listen_port == ntohs(addr.sin_port)) {
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                goto hub_handle_command_cleanup;
            }
            perform_inbound_search(&sel, NULL, &addr);
            if (sel.patterns != NULL) {
                int i = 0;
                for (i = 0; i < sel.patterncount; i++) {
                    search_string_free(sel.patterns+i);
                }
                free(sel.patterns);
            }
        }
    } else if (len >= 4 && strncmp(buf, "$SR ", 4) == 0) {
        handle_search_result(buf, len);
    } else if (len == 0) {
        /* Ignore empty commands. */
    }
hub_handle_command_cleanup:
    free(hub_my_nick);
}
Exemplo n.º 11
0
Arquivo: state.c Projeto: dongh11/ymd
struct variable *vm_getg(struct ymd_mach *vm, const char *field) {
	struct variable k, *v;
	setv_kstr(&k, kstr_fetch(vm, field, -1));
	v = hmap_get(vm->global, &k);
	return v;
}
Exemplo n.º 12
0
/* MaxWalkSAT */
void mw_sat(samp_table_t *table, int32_t num_trials, double rvar_probability,
		int32_t max_flips, uint32_t timeout) {
	rule_inst_table_t *rule_inst_table = &table->rule_inst_table;
	atom_table_t *atom_table = &table->atom_table;
	int32_t i, j;
	time_t fintime;

	if (timeout != 0) {
		fintime = time(NULL) + timeout;
	}

	double best_cost = DBL_MAX;
	for (i = 0; i < num_trials; i++) {
		init_random_assignment(table);
		//scan_rule_instances(table);
		for (j = 0; j < rule_inst_table->num_rule_insts; j++) {
			if (rule_inst_table->rule_insts[j]->weight == DBL_MAX) 
				rule_inst_table->assignment[j] = v_up_true;
			else
				rule_inst_table->assignment[j] = v_true;
		}
		init_live_clauses(table);
		scan_live_clauses(table);

		if (get_verbosity_level() >= 3) {
			printf("\n[mw_sat] Trial %d: \n", i);
			print_live_clauses(table);
		}

		for (j = 0; j < max_flips; j++) {

			if (timeout != 0 && time(NULL) >= fintime) {
				printf("Timeout after %"PRIu32" samples\n", i);
				break;
			}

			if (rule_inst_table->unsat_clauses.length == 0 
					&& rule_inst_table->unsat_soft_rules.nelems == 0) {
				return;
			}
			int32_t c = genrand_uint(rule_inst_table->unsat_clauses.length
					+ rule_inst_table->unsat_soft_rules.nelems);

			if (c < rule_inst_table->unsat_clauses.length) { /* picked a hard clause */
				samp_clause_t *clause = choose_random_clause(&rule_inst_table->unsat_clauses);
				int32_t litidx = choose_clause_var(table, clause, rvar_probability);
				
				if (litidx == clause->num_lits) {
					if (get_verbosity_level() >= 3) {
						printf("[flip_rule_to_unsat] Rule %d: ", clause->rule_index);
						print_rule_instance(rule_inst_table->rule_insts[clause->rule_index], table);
						printf("\n");
					}
					/* picked the rule auxiliary variable, i.e., rinst T -> F */
					hmap_get(&rule_inst_table->unsat_soft_rules, clause->rule_index);
					rule_inst_table->assignment[clause->rule_index] = v_false;
					rule_inst_t *rinst = rule_inst_table->rule_insts[clause->rule_index];
					rule_inst_table->unsat_weight += rinst->weight;
                                        /* Is this really going to do the right thing?? */
					rule_inst_table->sat_weight   -= rinst->weight;
					/* move unsat_clauses to live_clause_list and rescan */
					clause_list_concat(&rule_inst_table->unsat_clauses, 
							&rule_inst_table->live_clauses);
					scan_live_clauses(table);
				} else { 
					flip_unfixed_variable(table, var_of(clause->disjunct[litidx]));
				}
			} else {
				/* picked a soft rule auxiliary variable, i.e., rinst F -> T */
				int32_t rule_index = hmap_remove_random(&rule_inst_table->unsat_soft_rules);
				rule_inst_table->assignment[rule_index] = v_true;
				rule_inst_t *rinst = rule_inst_table->rule_insts[rule_index];
				rule_inst_table->unsat_weight -= rinst->weight;
				rule_inst_table->sat_weight   += rinst->weight;
				if (get_verbosity_level() >= 3) {
					printf("[flip_rule_to_sat] Rule %d: ", rule_index);
					print_rule_instance(rinst, table);
					printf("\n");
				}
				/* move watch[~r] to live_clause_list and rescan */
				clause_list_concat(&rule_inst_table->rule_watched[rule_index],
						&rule_inst_table->live_clauses);
				scan_live_clauses(table);
			}

			if (get_verbosity_level() >= 1) {
				printf("[mw_sat] Flip %d: # unsat hard = %d, # unsat soft = %d, " 
						"weight of unsat soft = %f; weight of sat soft = %f\n", j,
						rule_inst_table->unsat_clauses.length,
						rule_inst_table->unsat_soft_rules.nelems,
                                                rule_inst_table->unsat_weight,
                                                rule_inst_table->sat_weight
                                       );
			}
			if (get_verbosity_level() >= 3) {
				print_live_clauses(table);
			}

			if (best_cost > rule_inst_table->unsat_weight) {
				best_cost = rule_inst_table->unsat_weight;
				copy_assignment_array(atom_table);
			}
		}
	}
	restore_assignment_array(atom_table);
}