/** * _g_segraph_snapshot_append_BFS: * @node: a node, which will be put into arrays with its edges. * @node_array: array of all nodes in graph. * @visited_nodes: a map of already visited nodes. * @edge_array: array of all edges in graph. * @visited_edges: a map of already visited edges. * * Checks all nodes and edges and put them into arrays using breadth first * search algorithm. */ static void _g_segraph_snapshot_append_BFS (GSEGraphNode* node, GPtrArray* node_array, GHashTable* visited_nodes, GPtrArray* edge_array, GHashTable* visited_edges) { GQueue* queue; queue = g_queue_new (); g_hash_table_insert (visited_nodes, node, NULL); g_queue_push_tail (queue, node); if (node_array) { g_ptr_array_add (node_array, node); } while (!g_queue_is_empty (queue)) { GSEGraphNode* temp_node; guint iter; temp_node = g_queue_pop_head (queue); for (iter = 0; iter < temp_node->edges->len; ++iter) { GSEGraphEdge* edge; GSEGraphNode* other_node; edge = g_ptr_array_index (temp_node->edges, iter); if (g_hash_table_lookup_extended (visited_edges, edge, NULL, NULL)) { continue; } g_hash_table_insert (visited_edges, edge, NULL); if (edge_array) { g_ptr_array_add (edge_array, edge); } other_node = g_segraph_edge_get_node (edge, temp_node); if (!other_node) { continue; } if (g_hash_table_lookup_extended (visited_nodes, other_node, NULL, NULL)) { continue; } g_hash_table_insert (visited_nodes, other_node, NULL); g_queue_push_tail (queue, other_node); if (node_array) { g_ptr_array_add (node_array, other_node); } } } g_queue_free (queue); }
int main() { GQueue *q; GList *node; gpointer data; q = g_queue_new (); g_assert (g_queue_is_empty (q) == TRUE); g_queue_push_head (q, GINT_TO_POINTER (2)); g_assert (g_queue_peek_head (q) == GINT_TO_POINTER (2)); g_assert (g_queue_is_empty (q) == FALSE); g_assert (g_list_length (q->head) == 1); g_assert (q->head == q->tail); g_queue_push_head (q, GINT_TO_POINTER (1)); g_assert (q->head->next == q->tail); g_assert (q->tail->prev == q->head); g_assert (g_list_length (q->head) == 2); g_assert (q->tail->data == GINT_TO_POINTER (2)); g_assert (q->head->data == GINT_TO_POINTER (1)); g_queue_push_tail (q, GINT_TO_POINTER (3)); g_assert (g_list_length (q->head) == 3); g_assert (q->head->data == GINT_TO_POINTER (1)); g_assert (q->head->next->data == GINT_TO_POINTER (2)); g_assert (q->head->next->next == q->tail); g_assert (q->head->next == q->tail->prev); g_assert (q->tail->data == GINT_TO_POINTER (3)); g_queue_push_tail (q, GINT_TO_POINTER (4)); g_assert (g_list_length (q->head) == 4); g_assert (q->head->data == GINT_TO_POINTER (1)); g_assert (g_queue_peek_tail (q) == GINT_TO_POINTER (4)); g_queue_push_tail (q, GINT_TO_POINTER (5)); g_assert (g_list_length (q->head) == 5); g_assert (g_queue_is_empty (q) == FALSE); g_assert (q->length == 5); g_assert (q->head->prev == NULL); g_assert (q->head->data == GINT_TO_POINTER (1)); g_assert (q->head->next->data == GINT_TO_POINTER (2)); g_assert (q->head->next->next->data == GINT_TO_POINTER (3)); g_assert (q->head->next->next->next->data == GINT_TO_POINTER (4)); g_assert (q->head->next->next->next->next->data == GINT_TO_POINTER (5)); g_assert (q->head->next->next->next->next->next == NULL); g_assert (q->head->next->next->next->next == q->tail); g_assert (q->tail->data == GINT_TO_POINTER (5)); g_assert (q->tail->prev->data == GINT_TO_POINTER (4)); g_assert (q->tail->prev->prev->data == GINT_TO_POINTER (3)); g_assert (q->tail->prev->prev->prev->data == GINT_TO_POINTER (2)); g_assert (q->tail->prev->prev->prev->prev->data == GINT_TO_POINTER (1)); g_assert (q->tail->prev->prev->prev->prev->prev == NULL); g_assert (q->tail->prev->prev->prev->prev == q->head); g_assert (g_queue_peek_tail (q) == GINT_TO_POINTER (5)); g_assert (g_queue_peek_head (q) == GINT_TO_POINTER (1)); g_assert (g_queue_pop_head (q) == GINT_TO_POINTER (1)); g_assert (g_list_length (q->head) == 4 && q->length == 4); g_assert (g_queue_pop_tail (q) == GINT_TO_POINTER (5)); g_assert (g_list_length (q->head) == 3); g_assert (g_queue_pop_head_link (q)->data == GINT_TO_POINTER (2)); g_assert (g_list_length (q->head) == 2); g_assert (g_queue_pop_tail (q) == GINT_TO_POINTER (4)); g_assert (g_list_length (q->head) == 1); g_assert (g_queue_pop_head_link (q)->data == GINT_TO_POINTER (3)); g_assert (g_list_length (q->head) == 0); g_assert (g_queue_pop_tail (q) == NULL); g_assert (g_list_length (q->head) == 0); g_assert (g_queue_pop_head (q) == NULL); g_assert (g_list_length (q->head) == 0); g_assert (g_queue_is_empty (q) == TRUE); /************************/ g_queue_push_head (q, GINT_TO_POINTER (1)); g_assert (g_list_length (q->head) == 1 && 1 == q->length); g_queue_push_head (q, GINT_TO_POINTER (2)); g_assert (g_list_length (q->head) == 2 && 2 == q->length); g_queue_push_head (q, GINT_TO_POINTER (3)); g_assert (g_list_length (q->head) == 3 && 3 == q->length); g_queue_push_head (q, GINT_TO_POINTER (4)); g_assert (g_list_length (q->head) == 4 && 4 == q->length); g_queue_push_head (q, GINT_TO_POINTER (5)); g_assert (g_list_length (q->head) == 5 && 5 == q->length); g_assert (g_queue_pop_head (q) == GINT_TO_POINTER (5)); g_assert (g_list_length (q->head) == 4); node = q->tail; g_assert (node == g_queue_pop_tail_link (q)); g_assert (g_list_length (q->head) == 3); data = q->head->data; g_assert (data == g_queue_pop_head (q)); g_assert (g_list_length (q->head) == 2); g_assert (g_queue_pop_tail (q) == GINT_TO_POINTER (2)); g_assert (g_list_length (q->head) == 1); g_assert (q->head == q->tail); g_assert (g_queue_pop_tail (q) == GINT_TO_POINTER (3)); g_assert (g_list_length (q->head) == 0); g_assert (g_queue_pop_head (q) == NULL); g_assert (g_queue_pop_head_link (q) == NULL); g_assert (g_list_length (q->head) == 0); g_assert (g_queue_pop_tail_link (q) == NULL); g_assert (g_list_length (q->head) == 0); g_queue_free (q); return 0; }
static gboolean flap_connection_destroy_cb(gpointer data) { FlapConnection *conn; OscarData *od; PurpleAccount *account; aim_rxcallback_t userfunc; conn = data; /* Explicitly added for debugging #5927. Don't re-order this, only * consider removing it. */ purple_debug_info("oscar", "Destroying FLAP connection %p\n", conn); od = conn->od; account = purple_connection_get_account(od->gc); purple_debug_info("oscar", "Destroying oscar connection (%p) of " "type 0x%04hx. Disconnect reason is %d\n", conn, conn->type, conn->disconnect_reason); od->oscar_connections = g_slist_remove(od->oscar_connections, conn); if ((userfunc = aim_callhandler(od, AIM_CB_FAM_SPECIAL, AIM_CB_SPECIAL_CONNERR))) userfunc(od, conn, NULL, conn->disconnect_code, conn->error_message); /* * TODO: If we don't have a SNAC_FAMILY_LOCATE connection then * we should try to request one instead of disconnecting. */ if (!purple_account_is_disconnecting(account) && ((od->oscar_connections == NULL) || (!flap_connection_getbytype(od, SNAC_FAMILY_LOCATE)))) { /* No more FLAP connections! Sign off this PurpleConnection! */ gchar *tmp; PurpleConnectionError reason = PURPLE_CONNECTION_ERROR_NETWORK_ERROR; if (conn->disconnect_code == 0x0001) { reason = PURPLE_CONNECTION_ERROR_NAME_IN_USE; tmp = g_strdup(_("You have signed on from another location")); if (!purple_account_get_remember_password(account)) purple_account_set_password(account, NULL, NULL, NULL); } else if (conn->disconnect_reason == OSCAR_DISCONNECT_REMOTE_CLOSED) tmp = g_strdup(_("Server closed the connection")); else if (conn->disconnect_reason == OSCAR_DISCONNECT_LOST_CONNECTION) tmp = g_strdup_printf(_("Lost connection with server: %s"), conn->error_message); else if (conn->disconnect_reason == OSCAR_DISCONNECT_INVALID_DATA) tmp = g_strdup(_("Received invalid data on connection with server")); else if (conn->disconnect_reason == OSCAR_DISCONNECT_COULD_NOT_CONNECT) tmp = g_strdup_printf(_("Unable to connect: %s"), conn->error_message); else /* * We shouldn't print a message for some disconnect_reasons. * Like OSCAR_DISCONNECT_LOCAL_CLOSED. */ tmp = NULL; if (tmp != NULL) { purple_connection_error(od->gc, reason, tmp); g_free(tmp); } } flap_connection_close(od, conn); g_free(conn->error_message); g_free(conn->cookie); /* * Free conn->internal, if necessary */ if (conn->type == SNAC_FAMILY_CHAT) flap_connection_destroy_chat(od, conn); g_slist_free(conn->groups); while (conn->rateclasses != NULL) { g_free(conn->rateclasses->data); conn->rateclasses = g_slist_delete_link(conn->rateclasses, conn->rateclasses); } g_hash_table_destroy(conn->rateclass_members); if (conn->queued_snacs) { while (!g_queue_is_empty(conn->queued_snacs)) { QueuedSnac *queued_snac; queued_snac = g_queue_pop_head(conn->queued_snacs); flap_frame_destroy(queued_snac->frame); g_free(queued_snac); } g_queue_free(conn->queued_snacs); } if (conn->queued_lowpriority_snacs) { while (!g_queue_is_empty(conn->queued_lowpriority_snacs)) { QueuedSnac *queued_snac; queued_snac = g_queue_pop_head(conn->queued_lowpriority_snacs); flap_frame_destroy(queued_snac->frame); g_free(queued_snac); } g_queue_free(conn->queued_lowpriority_snacs); } if (conn->queued_timeout > 0) purple_timeout_remove(conn->queued_timeout); g_free(conn); return FALSE; }
static gboolean skype_audio_stream_deinit_stream (SkypeBaseStream *self, gpointer stream) { SkypeAudioStreamPrivate *priv = SKYPE_AUDIO_STREAM (self)->priv; FsuConference *fsuconf; gboolean ret = TRUE; g_object_get (G_OBJECT (stream), "fsu-conference", &fsuconf, NULL); if (fsuconf != NULL) { FsConference *fsconf; g_object_get (G_OBJECT (fsuconf), "fs-conference", &fsconf, NULL); g_object_unref (fsuconf); if (fsconf == NULL) { g_warning ("Error fetching FsConference"); ret = FALSE; } else { fs_element_added_notifier_remove (priv->notifier, GST_BIN (fsconf)); g_object_unref (fsconf); } } else { g_warning ("Error fetching FsuConference"); ret = FALSE; } if (priv->volume_id != NULL) { FsuFilterManager *manager; g_object_get (G_OBJECT (stream), "filter-manager", &manager, NULL); if (manager == NULL) { g_warning ("Error fetching FsuFilterManager"); ret = FALSE; } else { if (!fsu_filter_manager_remove_filter (manager, priv->volume_id)) { g_warning ("Error removing volume filter"); ret = FALSE; } g_object_unref (manager); priv->volume_id = NULL; } } if (priv->event_queue != NULL) { while (!g_queue_is_empty (priv->event_queue)) { g_slice_free (DTMFQueueEvent, g_queue_pop_head (priv->event_queue)); } g_queue_free (priv->event_queue); priv->event_queue = NULL; } if (priv->dtmfsrc != NULL) { gst_object_unref (priv->dtmfsrc); priv->dtmfsrc = NULL; } g_object_unref (priv->stream); priv->stream = NULL; return ret; }
void master_run(Master* master) { MAGIC_ASSERT(master); guint slaveSeed = (guint)random_nextInt(master->random); Slave* slave = slave_new(master, master->config, slaveSeed); /* hook in our logging system. stack variable used to avoid errors * during cleanup below. */ GLogLevelFlags configuredLogLevel = configuration_getLogLevel(master->config); g_log_set_default_handler(logging_handleLog, &(configuredLogLevel)); GDateTime* dt_now = g_date_time_new_now_local(); gchar* dt_format = g_date_time_format(dt_now, "%F %H:%M:%S"); message("Shadow v%s initialized at %s using GLib v%u.%u.%u", SHADOW_VERSION, dt_format, (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION); g_date_time_unref(dt_now); g_free(dt_format); /* store parsed actions from each user-configured simulation script */ GQueue* actions = g_queue_new(); Parser* xmlParser = parser_new(); /* parse built-in examples, or input files */ gboolean success = TRUE; if(master->config->runFileExample) { GString* file = example_getFileExampleContents(); success = parser_parseContents(xmlParser, file->str, file->len, actions); g_string_free(file, TRUE); } else { /* parse all given input XML files */ while(success && g_queue_get_length(master->config->inputXMLFilenames) > 0) { GString* filename = g_queue_pop_head(master->config->inputXMLFilenames); success = parser_parseFile(xmlParser, filename, actions); } } parser_free(xmlParser); /* if there was an error parsing, bounce out */ if(success) { message("successfully parsed Shadow XML input!"); } else { g_queue_free(actions); error("error parsing Shadow XML input!"); } /* * loop through actions that were created from parsing. this will create * all the nodes, networks, applications, etc., and add an application * start event for each node to bootstrap the simulation. Note that the * plug-in libraries themselves are not loaded until a worker needs it, * since each worker will need its own private version. */ while(g_queue_get_length(actions) > 0) { Action* a = g_queue_pop_head(actions); runnable_run(a); runnable_free(a); } g_queue_free(actions); /* start running */ gint nWorkers = configuration_getNWorkerThreads(master->config); debug("starting %i-threaded engine (main + %i workers)", (nWorkers + 1), nWorkers); /* simulation mode depends on configured number of workers */ if(nWorkers > 0) { /* multi threaded, manage the other workers */ master->executeWindowStart = 0; SimulationTime jump = master_getMinTimeJump(master); master->executeWindowEnd = jump; master->nextMinJumpTime = jump; slave_runParallel(slave); } else { /* single threaded, we are the only worker */ master->executeWindowStart = 0; master->executeWindowEnd = G_MAXUINT64; slave_runSerial(slave); } debug("engine finished, cleaning up..."); slave_free(slave); }
static void emit_python_decode_one (const lcmgen_t *lcm, FILE *f, lcm_struct_t *ls) { emit(1, "def _decode_one(buf):"); emit (2, "self = %s()", ls->structname->shortname); GQueue *struct_fmt = g_queue_new (); GQueue *struct_members = g_queue_new (); for (unsigned int m = 0; m < g_ptr_array_size(ls->members); m++) { lcm_member_t *lm = (lcm_member_t *) g_ptr_array_index(ls->members, m); char fmt = _struct_format (lm); if (! lm->dimensions->len) { if (fmt) { g_queue_push_tail (struct_fmt, GINT_TO_POINTER ((int)fmt)); g_queue_push_tail (struct_members, lm); } else { _flush_read_struct_fmt (lcm, f, struct_fmt, struct_members); char *accessor = g_strdup_printf("self.%s = ", lm->membername); _emit_decode_one (lcm, f, ls, lm, accessor, 2, ""); g_free(accessor); } } else { _flush_read_struct_fmt (lcm, f, struct_fmt, struct_members); GString *accessor = g_string_new (""); g_string_append_printf (accessor, "self.%s", lm->membername); // iterate through the dimensions of the member, building up // an accessor string, and emitting for loops unsigned int n; for (n=0; n<lm->dimensions->len-1; n++) { lcm_dimension_t *dim = (lcm_dimension_t *) g_ptr_array_index (lm->dimensions, n); if(n == 0) { emit (2, "%s = []", accessor->str); } else { emit (2+n, "%s.append([])", accessor->str); } if (dim->mode == LCM_CONST) { emit (2+n, "for i%d in range(%s):", n, dim->size); } else { emit (2+n, "for i%d in range(self.%s):", n, dim->size); } if(n > 0 && n < lm->dimensions->len-1) { g_string_append_printf(accessor, "[i%d]", n-1); } } // last dimension. lcm_dimension_t *last_dim = (lcm_dimension_t *) g_ptr_array_index(lm->dimensions, lm->dimensions->len - 1); int last_dim_fixed_len = last_dim->mode == LCM_CONST; if(lcm_is_primitive_type(lm->type->lctypename) && 0 != strcmp(lm->type->lctypename, "string")) { // member is a primitive non-string type. Emit code to // decode a full array in one call to struct.unpack if(n == 0) { g_string_append_printf (accessor, " = "); } else { g_string_append_printf (accessor, ".append("); } _emit_decode_list(lcm, f, ls, lm, accessor->str, 2+n, n==0, last_dim->size, last_dim_fixed_len); } else { // member is either a string type or an inner LCM type. Each // array element must be decoded individually if(n == 0) { emit (2, "%s = []", accessor->str); } else { emit (2+n, "%s.append ([])", accessor->str); g_string_append_printf (accessor, "[i%d]", n-1); } if (last_dim_fixed_len) { emit (2+n, "for i%d in range(%s):", n, last_dim->size); } else { emit (2+n, "for i%d in range(self.%s):", n, last_dim->size); } g_string_append_printf (accessor, ".append("); _emit_decode_one (lcm, f, ls, lm, accessor->str, n+3, ")"); } g_string_free (accessor, TRUE); } } _flush_read_struct_fmt (lcm, f, struct_fmt, struct_members); emit (2, "return self"); g_queue_free (struct_fmt); g_queue_free (struct_members); emit (1, "_decode_one = staticmethod(_decode_one)"); fprintf (f, "\n"); }
gboolean torflowslice_chooseRelayPair(TorFlowSlice* slice, gchar** entryRelayIdentity, gchar** exitRelayIdentity) { g_assert(slice); /* return false if we have already measured all relays */ guint remaining = torflowslice_getNumProbesRemaining(slice); if(remaining <= 0) { return FALSE; } /* choose an entry and exit among entries and exits with the lowest measurement counts */ GQueue* candidateEntries = _torflowslice_getCandidates(slice, slice->entries); GQueue* candidateExits = _torflowslice_getCandidates(slice, slice->exits); /* make sure we have at least one entry and one exit */ if(g_queue_is_empty(candidateEntries) && g_queue_is_empty(candidateExits)) { warning("slice %u: problem choosing relay pair: found %u candidates of %u entries and %u candidates of %u exits", slice->sliceID, g_queue_get_length(candidateEntries), g_hash_table_size(slice->entries), g_queue_get_length(candidateExits), g_hash_table_size(slice->exits)); g_queue_free(candidateEntries); g_queue_free(candidateExits); return FALSE; } /* choose uniformly from all candidates */ guint entryPosition = _torflowslice_randomIndex(g_queue_get_length(candidateEntries)); guint exitPosition = _torflowslice_randomIndex(g_queue_get_length(candidateExits)); gchar* entryID = g_queue_peek_nth(candidateEntries, entryPosition); gchar* exitID = g_queue_peek_nth(candidateExits, exitPosition); if(entryID == NULL || exitID == NULL) { error("slice %u: we had candidate exits and entries, but found NULL ids: entry=%s exit=%s", slice->sliceID, entryID, exitID); g_queue_free(candidateEntries); g_queue_free(candidateExits); return FALSE; } /* update the measurement count for the chosen relays */ gpointer entryProbeCount = g_hash_table_lookup(slice->entries, entryID); gpointer exitProbeCount = g_hash_table_lookup(slice->exits, exitID); /* steal the keys so we don't free them */ g_hash_table_steal(slice->entries, entryID); g_hash_table_steal(slice->exits, exitID); /* increment the measurement counts */ guint newEntryCount = GPOINTER_TO_UINT(entryProbeCount); guint newExitCount = GPOINTER_TO_UINT(exitProbeCount); newEntryCount++; newExitCount++; /* store them in the table again */ g_hash_table_replace(slice->entries, entryID, GUINT_TO_POINTER(newEntryCount)); g_hash_table_replace(slice->exits, exitID, GUINT_TO_POINTER(newExitCount)); info("slice %u: choosing relay pair: found %u candidates of %u entries and %u candidates of %u exits, " "choosing entry %s at position %u and exit %s at position %u, " "new entry probe count is %u and exit probe count is %u", slice->sliceID, g_queue_get_length(candidateEntries), g_hash_table_size(slice->entries), g_queue_get_length(candidateExits), g_hash_table_size(slice->exits), entryID, entryPosition, exitID, exitPosition, newEntryCount, newExitCount); /* cleanup the queues */ g_queue_free(candidateEntries); g_queue_free(candidateExits); /* return values */ if(entryRelayIdentity) { *entryRelayIdentity = entryID; } if(exitRelayIdentity) { *exitRelayIdentity = exitID; } return TRUE; }
void print_leaf_options(struct taint_creation_info* tci, u_long taint, int output_byte_offset, GHashTable* leaf_node_table, GHashTable* merge_node_table, GHashTable* option_info_table, GHashTable* filename_table) { u_long new_addr; GHashTable* seen_indices; GQueue* queue; seen_indices = g_hash_table_new(g_direct_hash, g_direct_equal); queue = g_queue_new(); assert(taint); assert(tci); if (g_hash_table_contains(leaf_node_table, (gpointer) taint)) { new_addr = (u_long) g_hash_table_lookup(leaf_node_table, (gpointer) taint); } else { new_addr = (u_long) g_hash_table_lookup(merge_node_table, (gpointer) taint); } if (!new_addr) { fprintf(stderr, "Could not find taint: %lu\n", (u_long) taint); return; } assert(new_addr); // Invariant: the addresses on the queue should always be the new addresses of the nodes g_queue_push_tail(queue, (gpointer) new_addr); while(!g_queue_is_empty(queue)) { struct taint_node* n; new_addr = (u_long) g_queue_pop_head(queue); assert(new_addr); if (g_hash_table_lookup(seen_indices, (gpointer) new_addr)) { continue; } g_hash_table_insert(seen_indices, (gpointer) new_addr, GINT_TO_POINTER(1)); n = (struct taint_node *) new_addr; if (!n->parent1 && !n->parent2) { // leaf node char* filename = (char *) "--"; struct token* tok; struct taint_leafnode* ln = (struct taint_leafnode *) n; // lookup option number to metadata describing that option tok = (struct token *) g_hash_table_lookup(option_info_table, GINT_TO_POINTER(ln->option)); assert(tok); // resolve filenames if (g_hash_table_contains(filename_table, GINT_TO_POINTER(tok->fileno))) { filename = (char *) g_hash_table_lookup(filename_table, GINT_TO_POINTER(tok->fileno)); } fprintf(stdout, "%llu %d %d %d %s", tok->rg_id, tok->record_pid, tok->syscall_cnt, tok->byte_offset, filename); fprintf(stdout, "\n"); } else { if (!g_hash_table_lookup(seen_indices, (gpointer) n->parent1)) { struct taint_node* p1; // lookup the address of the parent if (g_hash_table_contains(leaf_node_table, (gpointer) n->parent1)) { p1 = (struct taint_node *) g_hash_table_lookup(leaf_node_table, (gpointer) n->parent1); } else { p1 = (struct taint_node *) g_hash_table_lookup(merge_node_table, (gpointer) n->parent1); } assert(p1); // push the new address onto the queue g_queue_push_tail(queue, p1); } if (!g_hash_table_lookup(seen_indices, n->parent2)) { struct taint_node* p2; // lookup the address of the parent if (g_hash_table_contains(leaf_node_table, (gpointer) n->parent2)) { p2 = (struct taint_node *) g_hash_table_lookup(leaf_node_table, (gpointer) n->parent2); } else { p2 = (struct taint_node *) g_hash_table_lookup(merge_node_table, (gpointer) n->parent2); } assert(p2); // push the new address onto the queue g_queue_push_tail(queue, p2); } } } g_queue_free(queue); g_hash_table_destroy(seen_indices); }
static void photos_item_manager_collection_path_free (PhotosItemManager *self) { g_queue_foreach (self->collection_path, photos_item_manager_collection_path_free_foreach, NULL); g_queue_free (self->collection_path); }
void *janus_sctp_thread(void *data) { janus_sctp_association *sctp = (janus_sctp_association *)data; if(sctp == NULL) { JANUS_LOG(LOG_ERR, "Invalid SCTP association, closing thread\n"); g_thread_unref(g_thread_self()); return NULL; } JANUS_LOG(LOG_INFO, "[%"SCNu64"] Starting thread for SCTP association\n", sctp->handle_id); janus_sctp_message *message = NULL; gboolean sent_data = FALSE; while(sctp->dtls != NULL && sctp_running) { /* Anything to do at all? */ janus_mutex_lock(&sctp->mutex); if(!sctp->ready || (g_queue_is_empty(sctp->in_messages) && g_queue_is_empty(sctp->out_messages))) { janus_mutex_unlock(&sctp->mutex); g_usleep (10000); continue; } /* Check incoming messages */ if(!g_queue_is_empty(sctp->in_messages) && sent_data) { while(!g_queue_is_empty(sctp->in_messages)) { message = g_queue_pop_head(sctp->in_messages); if(message == NULL) continue; #ifdef DEBUG_SCTP if(sctp->debug_dump != NULL) { /* Dump incoming message */ char *dump = usrsctp_dumppacket(message->buffer, message->length, SCTP_DUMP_INBOUND); if(dump != NULL) { fwrite(dump, sizeof(char), strlen(dump), sctp->debug_dump); fflush(sctp->debug_dump); usrsctp_freedumpbuffer(dump); } } #endif /* Pass this data to the SCTP association */ janus_mutex_unlock(&sctp->mutex); usrsctp_conninput((void *)sctp, message->buffer, message->length, 0); janus_mutex_lock(&sctp->mutex); janus_sctp_message_destroy(message); message = NULL; } } /* Check outgoing messages */ if(sctp->dtls == NULL) { /* No DTLS stack anymore, we're done */ janus_mutex_unlock(&sctp->mutex); break; } if(!g_queue_is_empty(sctp->out_messages)) { while(!g_queue_is_empty(sctp->out_messages)) { message = g_queue_pop_head(sctp->out_messages); if(message == NULL) continue; #ifdef DEBUG_SCTP if(sctp->debug_dump != NULL) { /* Dump incoming message */ char *dump = usrsctp_dumppacket(message->buffer, message->length, SCTP_DUMP_OUTBOUND); if(dump != NULL) { fwrite(dump, sizeof(char), strlen(dump), sctp->debug_dump); fflush(sctp->debug_dump); usrsctp_freedumpbuffer(dump); } } #endif /* Encapsulate this data in DTLS and send it */ janus_dtls_send_sctp_data((janus_dtls_srtp *)sctp->dtls, message->buffer, message->length); janus_sctp_message_destroy(message); message = NULL; if(!sent_data) sent_data = TRUE; } } janus_mutex_unlock(&sctp->mutex); } JANUS_LOG(LOG_INFO, "[%"SCNu64"] Leaving SCTP association thread\n", sctp->handle_id); /* This association has been destroyed, wait a bit and then free all the resources */ g_usleep (1*G_USEC_PER_SEC); g_queue_free(sctp->in_messages); sctp->in_messages = NULL; g_queue_free(sctp->out_messages); sctp->out_messages = NULL; sctp->thread = NULL; #ifdef DEBUG_SCTP if(sctp->debug_dump != NULL) fclose(sctp->debug_dump); sctp->debug_dump = NULL; #endif g_free(sctp); sctp = NULL; g_thread_unref(g_thread_self()); return NULL; }
void checkcopy_worker (CheckcopyWorkerParams * params) { GQueue *int_q; ProgressDialog * progress_dialog; CheckcopyPlanner *planner; CheckcopyProcessor *proc; CheckcopyFileList * list; gboolean verify_only; verify_only = g_file_has_uri_scheme (params->dest, "verify"); list = checkcopy_file_list_get_instance (); g_object_set (G_OBJECT (list), "verify-only", verify_only, NULL); progress_dialog = params->progress_dialog; planner = checkcopy_planner_new (progress_dialog); proc = checkcopy_processor_new (progress_dialog, params->dest, verify_only); int_q = g_queue_new (); ext_q = params->queue; g_async_queue_ref (ext_q); while (TRUE) { GFile *file; /* Collect everything from the external queue to calculate the size. * Since the files are not processed yet, stick them into the internal queue. * * At this point the internal queue is empty, so we can block once for getting the first item * from the external queue */ file = g_async_queue_pop (ext_q); progress_dialog_thread_set_status (progress_dialog, PROGRESS_DIALOG_STATUS_CALCULATING_SIZE); do { g_queue_push_tail (int_q, file); checkcopy_traverse (file, CHECKCOPY_FILE_HANDLER (planner)); } while ((file = g_async_queue_try_pop (ext_q)) != NULL); #ifdef DEBUG { gchar *size_str; guint64 total_size = 0; g_object_get (planner, "total-size", &total_size, NULL); size_str = g_format_size_for_display (total_size); DBG ("Total size is now %s", size_str); g_free (size_str); } #endif progress_dialog_thread_set_status (progress_dialog, PROGRESS_DIALOG_STATUS_COPYING); g_object_set (G_OBJECT (progress_dialog), "num-files", checkcopy_planner_get_num_files (planner), NULL); /* Now process the internal queue */ while ((file = g_queue_pop_head (int_q)) != NULL) { checkcopy_traverse (file, CHECKCOPY_FILE_HANDLER (proc)); g_object_unref (file); } checkcopy_file_list_write_checksum (list, params->dest); checkcopy_file_list_sweep (list); progress_dialog_thread_set_status (progress_dialog, PROGRESS_DIALOG_STATUS_COMPLETED); #ifdef DEBUG progress_dialog_thread_check_stats (progress_dialog); #endif DBG ("Waiting for more things to do"); } /* we won't ever get here but just in case * we change the loop condition later */ g_async_queue_unref (ext_q); g_queue_foreach (int_q, (GFunc) g_object_unref, NULL); g_queue_free (int_q); g_object_unref (planner); g_object_unref (proc); g_object_unref (list); g_object_unref (params->dest); g_free (params); }
janus_sctp_association *janus_sctp_association_create(void *dtls, uint64_t handle_id, uint16_t udp_port) { if(dtls == NULL || udp_port == 0) return NULL; /* usrsctp provides UDP encapsulation of SCTP, but we need these messages to * be encapsulated in DTLS and actually sent/received by libnice, and not by * usrsctp itself... as such, we make use of the AF_CONN approach */ janus_sctp_association *sctp = (janus_sctp_association *)calloc(1, sizeof(janus_sctp_association)); if(sctp == NULL) { JANUS_LOG(LOG_FATAL, "Memory error!\n"); return NULL; } sctp->dtls = dtls; sctp->handle_id = handle_id; sctp->ready = FALSE; /* We wait for the association setup, for this */ sctp->local_port = 5000; /* FIXME We always use this one */ sctp->remote_port = udp_port; sctp->sock = NULL; struct socket *sock = NULL; unsigned int i = 0; struct sockaddr_conn sconn; /* Now go on with SCTP */ janus_sctp_channel *channel = NULL; for(i = 0; i < NUMBER_OF_CHANNELS; i++) { channel = &(sctp->channels[i]); channel->id = i; channel->state = DATA_CHANNEL_CLOSED; channel->pr_policy = SCTP_PR_SCTP_NONE; channel->pr_value = 0; channel->stream = 0; channel->unordered = 0; channel->flags = 0; } for(i = 0; i < NUMBER_OF_STREAMS; i++) { sctp->stream_channel[i] = NULL; sctp->stream_buffer[i] = 0; } sctp->stream_buffer_counter = 0; sctp->sock = NULL; janus_mutex_init(&sctp->mutex); usrsctp_register_address((void *)sctp); usrsctp_sysctl_set_sctp_ecn_enable(0); if((sock = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, janus_sctp_incoming_data, NULL, 0, (void *)sctp)) == NULL) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error creating usrsctp socket...\n", handle_id); free(sctp); sctp = NULL; return NULL; } /* Set SO_LINGER */ struct linger linger_opt; linger_opt.l_onoff = 1; linger_opt.l_linger = 0; if(usrsctp_setsockopt(sock, SOL_SOCKET, SO_LINGER, &linger_opt, sizeof(linger_opt))) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] setsockopt error: SO_LINGER\n", handle_id); free(sctp); sctp = NULL; return NULL; } /* Allow resetting streams */ struct sctp_assoc_value av; av.assoc_id = SCTP_ALL_ASSOC; av.assoc_value = 1; if(usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET, &av, sizeof(struct sctp_assoc_value)) < 0) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] setsockopt error: SCTP_ENABLE_STREAM_RESET\n", handle_id); free(sctp); sctp = NULL; return NULL; } /* Disable Nagle */ uint32_t nodelay = 1; if(usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_NODELAY, &nodelay, sizeof(nodelay))) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] setsockopt error: SCTP_NODELAY\n", handle_id); free(sctp); sctp = NULL; return NULL; } /* Enable the events of interest */ struct sctp_event event; memset(&event, 0, sizeof(event)); event.se_assoc_id = SCTP_ALL_ASSOC; event.se_on = 1; for(i = 0; i < sizeof(event_types)/sizeof(uint16_t); i++) { event.se_type = event_types[i]; if(usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(event)) < 0) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] setsockopt error: SCTP_EVENT\n", handle_id); free(sctp); sctp = NULL; return NULL; } } /* Configure our INIT message */ struct sctp_initmsg initmsg; memset(&initmsg, 0, sizeof(struct sctp_initmsg)); initmsg.sinit_num_ostreams = 16; /* What Firefox says in the INIT (Chrome says 1023) */ initmsg.sinit_max_instreams = 2048; /* What both Chrome and Firefox say in the INIT */ if(usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(struct sctp_initmsg)) < 0) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] setsockopt error: SCTP_INITMSG\n", handle_id); free(sctp); sctp = NULL; return NULL; } /* Bind our side of the communication, using AF_CONN as we're doing the actual delivery ourselves */ memset(&sconn, 0, sizeof(struct sockaddr_conn)); sconn.sconn_family = AF_CONN; sconn.sconn_port = htons(sctp->local_port); sconn.sconn_addr = (void *)sctp; if(usrsctp_bind(sock, (struct sockaddr *)&sconn, sizeof(struct sockaddr_conn)) < 0) { JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error binding client on port %"SCNu16"\n", handle_id, sctp->local_port); free(sctp); sctp = NULL; return NULL; } #ifdef DEBUG_SCTP char debug_file[1024]; g_snprintf(debug_file, 1024, "%s/sctp-debug-%"SCNu64".txt", debug_folder, handle_id); sctp->debug_dump = fopen(debug_file, "wt"); #endif /* We're done for now, the setup is done elsewhere */ janus_mutex_lock(&sctp->mutex); sctp->sock = sock; sctp->in_messages = g_queue_new(); sctp->out_messages = g_queue_new(); GError *error = NULL; sctp->thread = g_thread_try_new("JanusSCTP", &janus_sctp_thread, sctp, &error); if(error != NULL) { /* Something went wrong... */ JANUS_LOG(LOG_ERR, "[%"SCNu64"] Got error %d (%s) trying to launch the SCTP thread...\n", handle_id, error->code, error->message ? error->message : "??"); g_queue_free(sctp->in_messages); sctp->in_messages = NULL; g_queue_free(sctp->out_messages); sctp->out_messages = NULL; g_free(sctp); sctp = NULL; return NULL; } janus_mutex_unlock(&sctp->mutex); return sctp; }
void msn_dc_destroy(MsnDirectConn *dc) { MsnSlpLink *slplink; if (purple_debug_is_verbose()) purple_debug_info("msn", "msn_dc_destroy %p\n", dc); g_return_if_fail(dc != NULL); if (dc->slpcall != NULL) dc->slpcall->wait_for_socket = FALSE; slplink = dc->slplink; if (slplink) { slplink->dc = NULL; if (slplink->swboard == NULL) msn_slplink_unref(slplink); } g_free(dc->msg_body); if (dc->prev_ack) { msn_slpmsg_destroy(dc->prev_ack); } if (dc->listen_data != NULL) { purple_network_listen_cancel(dc->listen_data); } if (dc->connect_data != NULL) { purple_proxy_connect_cancel(dc->connect_data); } if (dc->listenfd != -1) { purple_network_remove_port_mapping(dc->listenfd); close(dc->listenfd); } if (dc->listenfd_handle != 0) { purple_input_remove(dc->listenfd_handle); } if (dc->connect_timeout_handle != 0) { purple_timeout_remove(dc->connect_timeout_handle); } if (dc->fd != -1) { close(dc->fd); } if (dc->send_handle != 0) { purple_input_remove(dc->send_handle); } if (dc->recv_handle != 0) { purple_input_remove(dc->recv_handle); } g_free(dc->in_buffer); if (dc->out_queue != NULL) { while (!g_queue_is_empty(dc->out_queue)) msn_dc_destroy_packet( g_queue_pop_head(dc->out_queue) ); g_queue_free(dc->out_queue); } g_free(dc->ext_ip); if (dc->timeout_handle != 0) { purple_timeout_remove(dc->timeout_handle); } g_free(dc); }
static void _tracker_logSocket(Tracker* tracker, GLogLevelFlags level, SimulationTime interval) { if(!tracker->didLogSocketHeader) { tracker->didLogSocketHeader = TRUE; logging_log(G_LOG_DOMAIN, level, __FILE__, __FUNCTION__, __LINE__, "[shadow-heartbeat] [socket-header] descriptor-number,protocol-string,hostname:port-peer;" "inbuflen-bytes,inbufsize-bytes,outbuflen-bytes,outbufsize-bytes;recv-bytes,send-bytes;" "inbound-localhost-counters;outbound-localhost-counters;" "inbound-remote-counters;outbound-remote-counters|..." // for each socket "where counters are: %s", _tracker_getCounterHeaderString()); } /* construct the log message from all sockets we have in the hash table */ GString* msg = g_string_new("[shadow-heartbeat] [socket] "); SocketStats* ss = NULL; GHashTableIter socketIterator; g_hash_table_iter_init(&socketIterator, tracker->socketStats); /* as we iterate, keep track of sockets that we should remove. we cant remove them * during the iteration because it will invalidate the iterator */ GQueue* handlesToRemove = g_queue_new(); gint socketLogCount = 0; while(g_hash_table_iter_next(&socketIterator, NULL, (gpointer*)&ss)) { /* don't log tcp sockets that don't have peer IP/port set */ if(!ss || (ss->type == PTCP && !ss->peerIP)) { continue; } gsize totalRecvBytes = _tracker_sumBytes(&ss->local.inCounters.bytes) + _tracker_sumBytes(&ss->remote.inCounters.bytes); gsize totalSendBytes = _tracker_sumBytes(&ss->local.outCounters.bytes) + _tracker_sumBytes(&ss->remote.outCounters.bytes); gchar* inLocal = _tracker_getCounterString(&ss->local.inCounters); gchar* outLocal = _tracker_getCounterString(&ss->local.outCounters); gchar* inRemote = _tracker_getCounterString(&ss->remote.inCounters); gchar* outRemote = _tracker_getCounterString(&ss->remote.outCounters); /* print the node separator between node logs */ if(socketLogCount > 0) { g_string_append_printf(msg, "|"); } socketLogCount++; g_string_append_printf(msg, "%d,%s,%s:%u;" "%"G_GSIZE_FORMAT",%"G_GSIZE_FORMAT",%"G_GSIZE_FORMAT",%"G_GSIZE_FORMAT";" "%"G_GSIZE_FORMAT",%"G_GSIZE_FORMAT";" "%s;%s;%s;%s", ss->handle, /*inet_ntoa((struct in_addr){socket->peerIP})*/ ss->type == PTCP ? "TCP" : ss->type == PUDP ? "UDP" : ss->type == PLOCAL ? "LOCAL" : "UNKNOWN", ss->peerHostname, ss->peerPort, ss->inputBufferLength, ss->inputBufferSize, ss->outputBufferLength, ss->outputBufferSize, totalRecvBytes, totalSendBytes, inLocal, outLocal, inRemote, outRemote); g_free(inLocal); g_free(outLocal); g_free(inRemote); g_free(outRemote); /* check if we should remove the socket after iterating */ if(ss->removeAfterNextLog) { g_queue_push_tail(handlesToRemove, GINT_TO_POINTER(ss->handle)); } } if(socketLogCount > 0) { logging_log(G_LOG_DOMAIN, level, __FILE__, __FUNCTION__, __LINE__, "%s", msg->str); } /* free all the tracker instances of the sockets that were closed, now that we logged the info */ while(!g_queue_is_empty(handlesToRemove)) { gint handle = GPOINTER_TO_INT(g_queue_pop_head(handlesToRemove)); g_hash_table_remove(tracker->socketStats, &handle); } g_queue_free(handlesToRemove); g_string_free(msg, TRUE); }
void g_queue_free_full(GQueue *queue,GDestroyNotify free_func) { g_queue_foreach(queue,(GFunc)free_func, NULL); g_queue_free(queue); }
static void find_contiguous_region_helper (GeglBuffer *src_buffer, GeglBuffer *mask_buffer, const Babl *format, gint n_components, gboolean has_alpha, gboolean select_transparent, GimpSelectCriterion select_criterion, gboolean antialias, gfloat threshold, gint x, gint y, const gfloat *col) { gint start, end; gint new_start, new_end; GQueue *coord_stack; coord_stack = g_queue_new (); /* To avoid excessive memory allocation (y, start, end) tuples are * stored in interleaved format: * * [y1] [start1] [end1] [y2] [start2] [end2] */ g_queue_push_tail (coord_stack, GINT_TO_POINTER (y)); g_queue_push_tail (coord_stack, GINT_TO_POINTER (x - 1)); g_queue_push_tail (coord_stack, GINT_TO_POINTER (x + 1)); do { y = GPOINTER_TO_INT (g_queue_pop_head (coord_stack)); start = GPOINTER_TO_INT (g_queue_pop_head (coord_stack)); end = GPOINTER_TO_INT (g_queue_pop_head (coord_stack)); for (x = start + 1; x < end; x++) { gfloat val; gegl_buffer_sample (mask_buffer, x, y, NULL, &val, babl_format ("Y float"), GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE); if (val != 0.0) continue; if (! find_contiguous_segment (col, src_buffer, mask_buffer, format, n_components, has_alpha, gegl_buffer_get_width (src_buffer), select_transparent, select_criterion, antialias, threshold, x, y, &new_start, &new_end)) continue; if (y + 1 < gegl_buffer_get_height (src_buffer)) { g_queue_push_tail (coord_stack, GINT_TO_POINTER (y + 1)); g_queue_push_tail (coord_stack, GINT_TO_POINTER (new_start)); g_queue_push_tail (coord_stack, GINT_TO_POINTER (new_end)); } if (y - 1 >= 0) { g_queue_push_tail (coord_stack, GINT_TO_POINTER (y - 1)); g_queue_push_tail (coord_stack, GINT_TO_POINTER (new_start)); g_queue_push_tail (coord_stack, GINT_TO_POINTER (new_end)); } } } while (! g_queue_is_empty (coord_stack)); g_queue_free (coord_stack); }
static void skypeweb_close(PurpleConnection *pc) { SkypeWebAccount *sa; GSList *buddies; g_return_if_fail(pc != NULL); sa = purple_connection_get_protocol_data(pc); g_return_if_fail(sa != NULL); purple_timeout_remove(sa->authcheck_timeout); purple_timeout_remove(sa->poll_timeout); purple_timeout_remove(sa->watchdog_timeout); skypeweb_logout(sa); purple_signal_disconnect(purple_conversations_get_handle(), "conversation-updated", pc, PURPLE_CALLBACK(skypeweb_mark_conv_seen)); purple_debug_info("skypeweb", "destroying %d waiting connections\n", g_queue_get_length(sa->waiting_conns)); while (!g_queue_is_empty(sa->waiting_conns)) skypeweb_connection_destroy(g_queue_pop_tail(sa->waiting_conns)); g_queue_free(sa->waiting_conns); purple_debug_info("skypeweb", "destroying %d incomplete connections\n", g_slist_length(sa->conns)); while (sa->conns != NULL) skypeweb_connection_destroy(sa->conns->data); while (sa->dns_queries != NULL) { PurpleDnsQueryData *dns_query = sa->dns_queries->data; purple_debug_info("skypeweb", "canceling dns query for %s\n", purple_dnsquery_get_host(dns_query)); sa->dns_queries = g_slist_remove(sa->dns_queries, dns_query); purple_dnsquery_destroy(dns_query); } while (sa->url_datas) { purple_util_fetch_url_cancel(sa->url_datas->data); sa->url_datas = g_slist_delete_link(sa->url_datas, sa->url_datas); } buddies = purple_find_buddies(sa->account, NULL); while (buddies != NULL) { PurpleBuddy *buddy = buddies->data; skypeweb_buddy_free(buddy); purple_buddy_set_protocol_data(buddy, NULL); buddies = g_slist_delete_link(buddies, buddies); } g_hash_table_destroy(sa->sent_messages_hash); g_hash_table_destroy(sa->cookie_table); g_hash_table_destroy(sa->hostname_ip_cache); g_free(sa->messages_host); g_free(sa->skype_token); g_free(sa->registration_token); g_free(sa->endpoint); g_free(sa->username); g_free(sa); }
// Detmine if subject is reachable from start_node using a depth-first // search. If path is non-NULL, return in it a new GQueue (owned by // the caller) of GraphEdge pointers (owned by self) that make up the // path found. The head of path is the edge into subject, and the // tail is the edge from start_node. gboolean graph_depth_first_search_for_node (Graph *self, GraphNode *start_node, GraphNode *subject, GQueue **path) { // IMPROVEME: this implementation isn't as efficient as it could be // (recompares things that are known not to be the desired node, // remarks already marked nodes). // Flags true iff we have found the subject, or the search has // failed, respectively. gboolean found = FALSE, hopeless = FALSE; // Existence hash which we use to mark nodes we are finished with. GHashTable *visited = g_hash_table_new (g_direct_hash, g_direct_equal); // Queue for backtracking in depth first search. GQueue *parents = g_queue_new (); // Keep a queue of the edges in the path currently being considered, // in case the user cares. GQueue *edges = g_queue_new (); GraphNode *current = start_node; while ( !found && !hopeless ) { if ( current == subject ) { found = TRUE; } else { // Mark (or remark, no harm done) the current node as visited. g_hash_table_insert (visited, current, NULL); gboolean eligible_child = FALSE; GraphEdge *edge = NULL; guint ii; for ( ii = 0 ; ii < current->out_edges->len ; ii++ ) { edge = g_ptr_array_index (current->out_edges, ii); if ( !my_g_hash_table_entry_exists (visited, edge->to_node) ) { eligible_child = TRUE; break; } } if ( eligible_child ) { g_queue_push_head (parents, current); g_queue_push_head (edges, edge); current = edge->to_node; } else { current = g_queue_pop_head (parents); g_queue_pop_head (edges); if ( current == NULL ) { found = FALSE; hopeless = TRUE; } } } } g_queue_free (parents); if ( path != NULL ) { // If user is interested in the path... // Uncomment the following block to sanity check the path. /* if ( found ) { // If we found a path... GraphEdge *head = g_queue_peek_head (edges); guint ii; gboolean head_promise = FALSE; for ( ii = 0 ; ii < subject->in_edges->len ; ii++ ) { if ( g_ptr_array_index (subject->in_edges, ii) == head ) { head_promise = TRUE; break; } } g_assert (head_promise); GraphEdge *tail = g_queue_peek_tail (edges); gboolean tail_promise; for ( ii = 0 ; ii < start_node->out_edges->len ; ii++ ) { if ( g_ptr_array_index (start_node->out_edges, ii) == tail ) { tail_promise = TRUE; break; } } g_assert (tail_promise); // Lets actually walk the path once to make sure things worked. GraphNode *cn = subject; for ( ii = 0 ; cn != start_node && ii < edges->length ; ii++ ) { // IMPROVEME: this is inefficient for long paths, oh well its // only debug code. GraphEdge *ce = g_queue_peek_nth (edges, ii); guint jj; gboolean edge_exists = FALSE; for ( jj = 0 ; !edge_exists && jj < cn->in_edges->len ; jj++ ) { GraphEdge *pm = g_ptr_array_index (cn->in_edges, jj); if ( pm == ce ) { edge_exists = TRUE; cn = pm->from_node; } } g_assert (edge_exists); } g_assert (cn == start_node); } else { g_assert (edges->length == 0); } */ *path = edges; } else { g_queue_free (edges); } return found; }
static void emit_python_encode_one (const lcmgen_t *lcm, FILE *f, lcm_struct_t *ls) { emit(1, "def _encode_one(self, buf):"); if(!g_ptr_array_size(ls->members)) emit(2, "pass"); GQueue *struct_fmt = g_queue_new (); GQueue *struct_members = g_queue_new (); for (unsigned int m = 0; m < g_ptr_array_size(ls->members); m++) { lcm_member_t *lm = (lcm_member_t *) g_ptr_array_index(ls->members, m); char fmt = _struct_format (lm); if (! lm->dimensions->len) { if (fmt) { g_queue_push_tail (struct_fmt, GINT_TO_POINTER ((int)fmt)); g_queue_push_tail (struct_members, lm); } else { _flush_write_struct_fmt (f, struct_fmt, struct_members); char *accessor = g_strdup_printf("self.%s", lm->membername); _emit_encode_one (lcm, f, ls, lm, accessor, 2); g_free(accessor); } } else { _flush_write_struct_fmt (f, struct_fmt, struct_members); GString *accessor = g_string_new (""); g_string_append_printf (accessor, "self.%s", lm->membername); unsigned int n; for (n=0; n<lm->dimensions->len - 1; n++) { lcm_dimension_t *dim = (lcm_dimension_t*) g_ptr_array_index (lm->dimensions, n); g_string_append_printf (accessor, "[i%d]", n); if (dim->mode == LCM_CONST) { emit (2+n, "for i%d in range(%s):", n, dim->size); } else { emit (2+n, "for i%d in range(self.%s):", n, dim->size); } } // last dimension. lcm_dimension_t *last_dim = (lcm_dimension_t *) g_ptr_array_index(lm->dimensions, lm->dimensions->len - 1); int last_dim_fixed_len = last_dim->mode == LCM_CONST; if(lcm_is_primitive_type(lm->type->lctypename) && 0 != strcmp(lm->type->lctypename, "string")) { _emit_encode_list(lcm, f, ls, lm, accessor->str, 2+n, last_dim->size, last_dim_fixed_len); } else { if (last_dim_fixed_len) { emit (2+n, "for i%d in range(%s):", n, last_dim->size); } else { emit (2+n, "for i%d in range(self.%s):", n, last_dim->size); } g_string_append_printf (accessor, "[i%d]", n); _emit_encode_one (lcm, f, ls, lm, accessor->str, n+3); } g_string_free (accessor, TRUE); } } _flush_write_struct_fmt (f, struct_fmt, struct_members); g_queue_free (struct_fmt); g_queue_free (struct_members); fprintf (f, "\n"); }
int random_rcl_assignment(Job *jobarray, int njobs, int nmachines, solution *new_sol, GRand *rand_) { int i; double max; double min; double lb, ub; double temp_dbl; partlist *temp = (partlist *) NULL; Job *temp_job = (Job *) NULL; //GList *it = (GList *) NULL; GQueue *to_do_list = (GQueue *) NULL; temp = new_sol->part; to_do_list = g_queue_new(); for (i = 0; i < njobs; ++i) { g_queue_push_tail(to_do_list, jobarray + i); } while (!g_queue_is_empty(to_do_list)) { temp_job = (Job *)to_do_list->head->data; max = ((double)temp[0].completiontime + (double)temp_job->processingime); min = max; GArray *rcl = g_array_new(FALSE, FALSE, sizeof(pair_job_machine)); /** Compute min and max */ for (i = 1; i < nmachines; ++i) { //for (it = to_do_list->head; it; it = it->next) //{ //temp_job = (Job*)it->data; temp_dbl = (temp[i].completiontime + temp_job->processingime); if (max < temp_dbl) { max = temp_dbl; } if (min > temp_dbl) { min = temp_dbl; } //} } /** Compute RCL */ pair_job_machine temp_job_machine; lb = min; ub = min + 0.25 * (max - lb); for (i = 0; i < nmachines; ++i) { //for (it = to_do_list->head; it; it = g_list_next(it)) //{ //temp_job = ((Job*)it->data); double g = ((double)temp[i].completiontime + (double)temp_job->processingime); if (lb <= g && g <= ub) { temp_job_machine.job = temp_job->job; temp_job_machine.machine = i; g_array_append_val(rcl, temp_job_machine); } //} } /** Choose uniformaly an assignment of a job to a machine */ int a = g_rand_int_range(rand_, 0, rcl->len); int job = g_array_index(rcl, pair_job_machine, a).job; int machine = g_array_index(rcl, pair_job_machine, a).machine; partlist_insert(temp + machine, new_sol->vlist, jobarray + job); g_queue_pop_nth(to_do_list, g_queue_index(to_do_list, jobarray + job)); g_array_free(rcl, TRUE); } g_queue_free(to_do_list); return 0; }
static void emit_lua_decode_one (const lcmgen_t *lcm, FILE *f, lcm_struct_t *ls) { emit(0, "function %s._decode_one(data)", ls->structname->shortname); emit(0, ""); emit(0, " if not data.read then"); emit(0, " data = _buffer_helper:new(data)"); emit(0, " end"); emit(0, ""); emit(0, " local obj = %s:new()", ls->structname->shortname); emit(0, ""); GQueue *struct_fmt = g_queue_new (); GQueue *struct_members = g_queue_new (); for (unsigned int m = 0; m < g_ptr_array_size(ls->members); m++) { lcm_member_t *lm = (lcm_member_t *) g_ptr_array_index(ls->members, m); char fmt = _struct_format (lm); if (! lm->dimensions->len) { if (fmt) { g_queue_push_tail (struct_fmt, GINT_TO_POINTER ((int)fmt)); g_queue_push_tail (struct_members, lm); } else { _flush_read_struct_fmt (lcm, f, struct_fmt, struct_members); char *accessor = g_strdup_printf("obj.%s", lm->membername); _emit_decode_one (lcm, f, ls, lm, accessor, 1); g_free(accessor); } } else { _flush_read_struct_fmt (lcm, f, struct_fmt, struct_members); GString *accessor = g_string_new (""); g_string_append_printf (accessor, "obj.%s", lm->membername); // iterate through the dimensions of the member, building up // an accessor string, and emitting for loops int n; for (n=0; n<lm->dimensions->len - 1; n++) { lcm_dimension_t *dim = (lcm_dimension_t *) g_ptr_array_index (lm->dimensions, n); emit (1+n, "%s = {}", accessor->str); if (dim->mode == LCM_CONST) { emit (1+n, "for i%d = 1, %s do", n, dim->size); } else { emit (1+n, "for i%d = 1, obj.%s do", n, dim->size); } g_string_append_printf(accessor, "[i%d]", n); } // last dimension. lcm_dimension_t *last_dim = (lcm_dimension_t *) g_ptr_array_index(lm->dimensions, lm->dimensions->len - 1); int last_dim_fixed_len = last_dim->mode == LCM_CONST; if(lcm_is_primitive_type(lm->type->lctypename) && 0 != strcmp(lm->type->lctypename, "string")) { // member is a primitive non-string type. Emit code to // decode a full array in one call to struct.unpack _emit_decode_list(lcm, f, ls, lm, accessor->str, 1+n, last_dim->size, last_dim_fixed_len); } else { // member is either a string type or an inner LCM type. Each // array element must be decoded individually emit (1+n, "%s = {}", accessor->str); if (last_dim_fixed_len) { emit (1+n, "for i%d = 1, %s do", n, last_dim->size); } else { emit (1+n, "for i%d = 1, obj.%s do", n, last_dim->size); } g_string_append_printf (accessor, "[i%d]", n); _emit_decode_one (lcm, f, ls, lm, accessor->str, n+2); emit (1+n, "end"); } g_string_free (accessor, TRUE); while ( --n >= 0 ) { emit (1+n, "end"); } } } _flush_read_struct_fmt (lcm, f, struct_fmt, struct_members); g_queue_free (struct_fmt); g_queue_free (struct_members); emit(0, ""); emit(0, " return obj"); emit(0, "end"); emit(0, ""); }
/* search for the most similar gate in the neighborhood of <ref_gate> with a search radius of <radius> * <fs> are the currently observed features */ void node_estimate_update (GQueue *gates, navlcm_gate_t *ref_gate, navlcm_feature_list_t *fs, int radius, navlcm_gate_t **g1, navlcm_gate_t **g2) { if (!ref_gate) { dbg (DBG_ERROR, "find_most_similar_gate: no ref gate."); return;} if (!fs) { dbg (DBG_ERROR, "find_most_similar_gate: no features."); return;} double best_sim = 0.0; int *ids = NULL; double *sims = NULL; int n = 0; // reset output *g1 = *g2 = NULL; // list neighbors GQueue *neighbors = g_queue_new (); gate_list_neighbors (ref_gate, gates, radius, neighbors); dbg (DBG_CLASS, "found %d neighbors to gate %d", ref_gate->uid, g_queue_get_length (neighbors)); // compute similarity with neighbor gates for (GList *iter = g_queue_peek_head_link (neighbors);iter;iter=g_list_next(iter)) { navlcm_gate_t *g = (navlcm_gate_t*)iter->data; double sim = gate_similarity (g, fs); // update vector ids = (int*)realloc (ids, (n+1)*sizeof(int)); ids[n] = g->uid; sims = (double*)realloc(sims, (n+1)*sizeof(double)); sims[n] = sim; n++; dbg (DBG_INFO, "gate similarity: gate %d, sim = %.3f", g->uid, sim); } g_queue_free (neighbors); // smooth data double *ssims = math_smooth_double (sims, n, 5); for (int i=0;i<n;i++) { dbg (DBG_VIEWER, "sim[%d] = %.3f", ids[i], ssims[i]); } // find max value int id = math_max_index_double (ssims, n); *g1 = find_gate_from_id (gates, ids[id]); best_sim = ssims[id]; if (*g1 == NULL) return; // find next best value sims[id] = 0.0; int id2 = math_max_index_double (ssims, n); double second_sim = ssims[id2]; if (best_sim * .80 < second_sim) { navlcm_gate_t *g = find_gate_from_id (gates, ids[id2]); if (g && gate_is_neighbor (*g1, g)) { *g2 = g; } } free (ssims); free (sims); free (ids); if (*g1) dbg (DBG_INFO, "*** best gate ID: %d, similarity = %.3f\n", (*g1)->uid, best_sim); if (*g2) dbg (DBG_INFO, "*** 2nd gate ID: %d, similarity = %.3f\n", (*g2)->uid, second_sim); return; }