Ejemplo n.º 1
0
static int
check_values(Heap *h,int idx,int depth)
{
    HeapElement *he_l = NULL;
    HeapElement *he_r = NULL;
    HeapElement *he_p = NULL;
    HeapInternCmp cmp_func;

    if (idx < 0 || idx >= HSIZE(h))
	return 0;

    if (h->hpMode == HEAP_MINIMIZE)
	cmp_func = heap_larger;
    else 
	cmp_func = heap_smaller;

    he_p = HARRAY(h,idx);

    if (HLEFT(idx) >= HSIZE(h))	/* No left child */
    	return 0;

    if (HRIGHT(idx) < HSIZE(h))	/* Has right child */
	he_r = HARRAY(h,HRIGHT(idx));
	
    he_l = HARRAY(h,HLEFT(idx));

    if ( cmp_func(h,he_p,he_l))
    {
	printf("*** Heap violates parent-lchild property.\n");
	printf("*** Left child (%d) is %s than parent (%d)\n",
		HLEFT(idx),
		h->hpMode == HEAP_MINIMIZE ? "smaller" : "larger",
		idx);
	printf("*** Depth %d\n",depth);
	printf("%.8f - %.8f = %.8f\n",Key2Double(he_l),Key2Double(he_p),
		Key2Double(he_l) - Key2Double(he_p));

	return -1;
    }

    if (he_r &&  cmp_func(h,he_p,he_r))
    {
	printf("*** Heap violates parent-rchild property.\n");
	printf("*** Right child (%d) is %s than parent (%d)\n",
		HRIGHT(idx),h->hpMode == HEAP_MINIMIZE ? "smaller" : "larger",
		idx);
	printf("*** Depth %d\n",depth);
	printf("%.8f - %.8f = %.8f\n",Key2Double(he_r),Key2Double(he_p),
		Key2Double(he_r) - Key2Double(he_p));

	return -1;
    }

    if (check_values(h,HLEFT(idx),depth+1))
	return -1;

    if (he_r)
	return check_values(h,HRIGHT(idx),depth+1);
    return 0;
}
Ejemplo n.º 2
0
void ShortcutDialog::on_validate()
{
	int ok = check_values() ;

	if (ok==1) {
		chosen_path = path_entry.get_text() ;
		chosen_display = display_entry.get_text() ;
		response(Gtk::RESPONSE_OK) ;
	}
	else if (ok<0) {
		Glib::ustring txt ;
		if (ok==-1)
			txt = _("Please enter a shortcut name ") ;
		else if (ok==-2)
			txt = _("Please choose a target") ;
		else if (ok==-3)
			txt = _("This target is already used by a shortcut") ;
		else if (ok==-4)
			txt = _("This target does not exist") ;
		else if (ok==-5)
			txt = _("This name is too long or contains invalid symbol, please choose another") ;
		else if (ok==-6)
			txt = _("Please change directory permissions (enable read and execute) or change directory") ;
		Explorer_dialog::msg_dialog_warning(txt, this, true) ;
	}
}
Ejemplo n.º 3
0
/**
 * facq_net_send:
 * @skt: A connected #GSocket object.
 * @buf: A pointer to the memory area that contains the data that you want to
 * send.
 * @size: The size of the memory area pointed by @buf, in bytes.
 * @retry: The number of retries or 0 for infinite retries.
 * @err: A #GError, it will be set in case of error if not %NULL.
 *
 * Tries to send the number of bytes, @size, in the memory area pointed by @buf,
 * using at most @retry retries.
 *
 * returns: The number of bytes sent if successful, -1 in case of error,
 * -2 in case of timeout, -3 if wrong parameters are passed to the function.
 */
gssize facq_net_send(GSocket *skt,gchar *buf,gsize size,guint retry,GError **err)
{
    guint retries = 0;
    GError *local_err = NULL;
    gsize to_send = 0, remaining = 0;
    gssize ret = 0, total = 0;

    if(!check_values(skt,buf,size)) {
        if(err != NULL)
            g_set_error_literal(err,G_IO_ERROR,
                                G_IO_ERROR_FAILED,"Can't send any data");
        return -3;
    }

    if(retry == 0)
        retry = G_MAXUINT;

    to_send = 0;
    remaining = size;

    /* Try to send all the data in one call, retrying at most retry times */
    for(retries = 0; retries < retry; retries++) {
        ret = g_socket_send(skt,&buf[to_send],remaining,NULL,&local_err);
        if(ret <= 0) {
            if(local_err) {
                facq_log_write_v(FACQ_LOG_MSG_TYPE_ERROR,
                                 "%s",local_err->message);
                if(err != NULL)
                    g_propagate_error(err,local_err);
                return -1;
            }
            else {
                if(err != NULL)
                    g_set_error_literal(err,G_IO_ERROR,
                                        G_IO_ERROR_FAILED,"Error sending data");
                return -1;
            }
        }
        else {
            total += ret;
            remaining = size - total;
            to_send += ret;
            if(total == size)
                break;
#if ENABLE_DEBUG
            facq_log_write_v(FACQ_LOG_MSG_TYPE_DEBUG,"%s",
                             "Retrying to send all the data");
#endif
        }
    }

    if(total != size) {
        if(err != NULL)
            g_set_error_literal(err,G_IO_ERROR,
                                G_IO_ERROR_TIMED_OUT,"Operation timed out");
        return -2;
    }

    return total;
}
Ejemplo n.º 4
0
int insert_signals( T&                  signal,   
                    char *              signal_name, 
                    char *              wu_name,
                    sqlint8_t           sah_result_id,
                    std::ifstream&      result_file, 
                    receiver_config&    receiver_cfg,   
                    int                 appid,
                    int                 max_signals_allowed,
                    list<long>&         qpixlist) {

    int signal_count=0, signal_inserted_count=0, retval=0, qpix;
    sqlint8_t signal_id=0;

    result_file.clear();
    result_file.seekg(0);
    while (!result_file.eof()) {
        result_file >> signal;
        if (!result_file.eof()) {
            signal_count++;
            if (max_signals_allowed == 0 || signal_count <= max_signals_allowed) {
                if (!(signal.rfi_found = check_values(signal, sah_result_id, wu_name))) {
                    // preprocess only if we have good values
                    retval = pre_process(signal, receiver_cfg);  
                    qpixlist.push_back(npix2qpix((long long)signal.q_pix));
                }
                signal.result_id = sah_result_id;
                if (appid == 2) signal.reserved = 1;        // temporary for enhanced rollout
                signal_id = signal.insert();
                if (signal_id) {
                    log_messages.printf(SCHED_MSG_LOG::MSG_DEBUG,
                        "[%s] Inserted %s %"INT8_FMT" for sah result %"INT8_FMT"\n",
                        wu_name, signal_name, INT8_PRINT_CAST(signal_id), INT8_PRINT_CAST(sah_result_id)
                    );
                    signal_inserted_count++;
                } else {
                    log_messages.printf(SCHED_MSG_LOG::MSG_CRITICAL,
                                "[%s] Could not insert %s for sah result %"INT8_FMT". SQLCODE is %d. q_pix is %"INT8_FMT"  ra is %lf  decl is %lf .\n",
                                wu_name, signal_name, sah_result_id, sql_last_error_code(), signal.q_pix, signal.ra, signal.decl
                    );
#if 0
                    log_messages.printf(SCHED_MSG_LOG::MSG_CRITICAL,
                                "[%s] Could not insert %s for sah result %ld. SQLCODE is %d.  SQLMSG is %s  q_pix is %"INT8_FMT".\n",
                                wu_name, signal_name, sah_result_id, sql_last_error_code(), sql_error_message(), signal.q_pix
                    );
#endif
                    return -1;
                }  
            }   
        }   
    } 

    log_messages.printf(SCHED_MSG_LOG::MSG_NORMAL,
        "[%s] Inserted %d out of %d %s(s) for sah result %"INT8_FMT" \n",
        wu_name, signal_inserted_count, signal_count, signal_name, INT8_PRINT_CAST(sah_result_id)
    );

}
Ejemplo n.º 5
0
static void test_slice_hash_table() {
  const test_entry test_entries[] = {
      {"key_0", "value_0"},   {"key_1", "value_1"},   {"key_2", "value_2"},
      {"key_3", "value_3"},   {"key_4", "value_4"},   {"key_5", "value_5"},
      {"key_6", "value_6"},   {"key_7", "value_7"},   {"key_8", "value_8"},
      {"key_9", "value_9"},   {"key_10", "value_10"}, {"key_11", "value_11"},
      {"key_12", "value_12"}, {"key_13", "value_13"}, {"key_14", "value_14"},
      {"key_15", "value_15"}, {"key_16", "value_16"}, {"key_17", "value_17"},
      {"key_18", "value_18"}, {"key_19", "value_19"}, {"key_20", "value_20"},
      {"key_21", "value_21"}, {"key_22", "value_22"}, {"key_23", "value_23"},
      {"key_24", "value_24"}, {"key_25", "value_25"}, {"key_26", "value_26"},
      {"key_27", "value_27"}, {"key_28", "value_28"}, {"key_29", "value_29"},
      {"key_30", "value_30"}, {"key_31", "value_31"}, {"key_32", "value_32"},
      {"key_33", "value_33"}, {"key_34", "value_34"}, {"key_35", "value_35"},
      {"key_36", "value_36"}, {"key_37", "value_37"}, {"key_38", "value_38"},
      {"key_39", "value_39"}, {"key_40", "value_40"}, {"key_41", "value_41"},
      {"key_42", "value_42"}, {"key_43", "value_43"}, {"key_44", "value_44"},
      {"key_45", "value_45"}, {"key_46", "value_46"}, {"key_47", "value_47"},
      {"key_48", "value_48"}, {"key_49", "value_49"}, {"key_50", "value_50"},
      {"key_51", "value_51"}, {"key_52", "value_52"}, {"key_53", "value_53"},
      {"key_54", "value_54"}, {"key_55", "value_55"}, {"key_56", "value_56"},
      {"key_57", "value_57"}, {"key_58", "value_58"}, {"key_59", "value_59"},
      {"key_60", "value_60"}, {"key_61", "value_61"}, {"key_62", "value_62"},
      {"key_63", "value_63"}, {"key_64", "value_64"}, {"key_65", "value_65"},
      {"key_66", "value_66"}, {"key_67", "value_67"}, {"key_68", "value_68"},
      {"key_69", "value_69"}, {"key_70", "value_70"}, {"key_71", "value_71"},
      {"key_72", "value_72"}, {"key_73", "value_73"}, {"key_74", "value_74"},
      {"key_75", "value_75"}, {"key_76", "value_76"}, {"key_77", "value_77"},
      {"key_78", "value_78"}, {"key_79", "value_79"}, {"key_80", "value_80"},
      {"key_81", "value_81"}, {"key_82", "value_82"}, {"key_83", "value_83"},
      {"key_84", "value_84"}, {"key_85", "value_85"}, {"key_86", "value_86"},
      {"key_87", "value_87"}, {"key_88", "value_88"}, {"key_89", "value_89"},
      {"key_90", "value_90"}, {"key_91", "value_91"}, {"key_92", "value_92"},
      {"key_93", "value_93"}, {"key_94", "value_94"}, {"key_95", "value_95"},
      {"key_96", "value_96"}, {"key_97", "value_97"}, {"key_98", "value_98"},
      {"key_99", "value_99"},
  };
  const size_t num_entries = GPR_ARRAY_SIZE(test_entries);
  // Construct table.
  grpc_slice_hash_table_entry* entries =
      gpr_zalloc(sizeof(*entries) * num_entries);
  populate_entries(test_entries, num_entries, entries);
  grpc_slice_hash_table* table =
      grpc_slice_hash_table_create(num_entries, entries, destroy_string);
  gpr_free(entries);
  // Check contents of table.
  check_values(test_entries, num_entries, table);
  check_non_existent_value("XX", table);
  // Clean up.
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_slice_hash_table_unref(&exec_ctx, table);
  grpc_exec_ctx_finish(&exec_ctx);
}
Ejemplo n.º 6
0
bool PrismaticModel::guessParameters() {
	if(model.track.pose.size() < 2)
		return false;

	size_t i,j;
	do{
		i = rand() % getSamples();
		j = rand() % getSamples();
	} while (i==j);

	tf::Transform pose1 = poseToTransform(model.track.pose[i]);
	tf::Transform pose2 = poseToTransform(model.track.pose[j]);

	rigid_position = pose1.getOrigin();
	rigid_orientation = pose1.getRotation();
	prismatic_dir =  pose2.getOrigin() - pose1.getOrigin();
	prismatic_dir.normalize();

	if(!check_values(rigid_position)) return false;
	if(!check_values(rigid_orientation)) return false;
	if(!check_values(prismatic_dir)) return false;

	return true;
}
Ejemplo n.º 7
0
/* This function assigns values to the face cards and others based on user input

	card_name: the name of the card truncated to 2 characters
	val: the value of the card to be set in this function
*/	
void assign_values(char card_name[], int *val)
{
	switch(card_name[0]) {
	case 'K':
	case 'Q':
	case 'J':
		*val = 10;
		break;
	case 'A':
		*val = 11;
		break;
	default:
		*val = atoi(card_name);
		if ((*val < 2) || (*val > 10)) {
			puts("I don't understand that value!");
		}
	}
	check_values(&value, &count);
	
}
Ejemplo n.º 8
0
int main( int argc, const char *argv[])
{
     int h1,h2,m1,m2, difh=0, difm=0 ;
     printf("digite as horas do horario de inicio(valor entre 0-23)\n");
    scanf ( "%d", &h1 ); 
    printf ( "digite os minutos do horario de inicio (valor entre 0-59)\n" );
    scanf ( "%d", &m1 );
    printf ( "digite as horas do horario de termino (valor entre 0-23)\n");
    scanf ( "%d", &h2 );
    printf ( "digite os minutos do horario de termino (valor entre 0-59)\n" );
    scanf ( "%d", &m2 );
    if(check_values(h1,h2,m1,m2))
    {
        difm = dif_min(m1,m2);
        difh = dif_hour(h1,h2,m1,m2);
	printf("A duração do jogo é de %d horas e %d minutos.\n",difh,difm);
    }
    else
    {
        printf ( "Dados Inválidos \n" );
    }
    return 0;
}
Ejemplo n.º 9
0
static GList * cover_jamendo_parse (cb_object *capo)
{
    // A nice parser with zero memory overhead..

    GList * result_list = NULL;
    gchar * line = capo->cache->data;

    while (continue_search (g_list_length (result_list),capo->s) )
    {
        char * line_end;

        if ( (line_end = strchr (line,'\n') ) != NULL)
        {
            *line_end = 0;

            char * line_split[3] = {0,0,0};
            do_line_split (line_split,line);

            if (check_values (capo->s,line_split[2],line_split[1]) )
            {
                char * url =  g_strdup_printf (RESULT_URL,line_split[0],get_cover_size (capo->s) );
                GlyrMemCache * result = DL_init();
                result->data = url;
                result->size = strlen (url);
                result_list = g_list_prepend (result_list,result);
            }

            line = ++line_end;
        }
        else
        {
            break;
        }
    }
    return result_list;
}
Ejemplo n.º 10
0
    void runTest(int prec1, int prec2, int loc1, int loc2, int matrix,
            int extended, double time_average)
    {
        int num_baselines, status = 0, type;
        oskar_Mem *vis1, *vis2;
        oskar_Timer *timer1, *timer2;
        double time1, time2, frequency = 100e6;

        // Create the timers.
        timer1 = oskar_timer_create(loc1 == OSKAR_GPU ?
                OSKAR_TIMER_CUDA : OSKAR_TIMER_NATIVE);
        timer2 = oskar_timer_create(loc2 == OSKAR_GPU ?
                OSKAR_TIMER_CUDA : OSKAR_TIMER_NATIVE);

        // Run first part.
        createTestData(prec1, loc1, matrix);
        num_baselines = oskar_telescope_num_baselines(tel);
        type = prec1 | OSKAR_COMPLEX;
        if (matrix) type |= OSKAR_MATRIX;
        vis1 = oskar_mem_create(type, loc1, num_baselines, &status);
        oskar_mem_clear_contents(vis1, &status);
        ASSERT_EQ(0, status) << oskar_get_error_string(status);
        oskar_sky_set_use_extended(sky, extended);
        oskar_telescope_set_channel_bandwidth(tel, bandwidth);
        oskar_telescope_set_time_average(tel, time_average);
        oskar_timer_start(timer1);
        oskar_cross_correlate(vis1, oskar_sky_num_sources(sky), jones, sky,
                tel, u_, v_, w_, 1.0, frequency, &status);
        time1 = oskar_timer_elapsed(timer1);
        destroyTestData();
        ASSERT_EQ(0, status) << oskar_get_error_string(status);

        // Run second part.
        createTestData(prec2, loc2, matrix);
        num_baselines = oskar_telescope_num_baselines(tel);
        type = prec2 | OSKAR_COMPLEX;
        if (matrix) type |= OSKAR_MATRIX;
        vis2 = oskar_mem_create(type, loc2, num_baselines, &status);
        oskar_mem_clear_contents(vis2, &status);
        ASSERT_EQ(0, status) << oskar_get_error_string(status);
        oskar_sky_set_use_extended(sky, extended);
        oskar_telescope_set_channel_bandwidth(tel, bandwidth);
        oskar_telescope_set_time_average(tel, time_average);
        oskar_timer_start(timer2);
        oskar_cross_correlate(vis2, oskar_sky_num_sources(sky), jones, sky,
                tel, u_, v_, w_, 1.0, frequency, &status);
        time2 = oskar_timer_elapsed(timer2);
        destroyTestData();
        ASSERT_EQ(0, status) << oskar_get_error_string(status);

        // Destroy the timers.
        oskar_timer_free(timer1);
        oskar_timer_free(timer2);

        // Compare results.
        check_values(vis1, vis2);

        // Free memory.
        oskar_mem_free(vis1, &status);
        oskar_mem_free(vis2, &status);
        ASSERT_EQ(0, status) << oskar_get_error_string(status);

        // Record properties for test.
        RecordProperty("SourceType", extended ? "Gaussian" : "Point");
        RecordProperty("JonesType", matrix ? "Matrix" : "Scalar");
        RecordProperty("TimeSmearing", time_average == 0.0 ? "off" : "on");
        RecordProperty("Prec1", prec1 == OSKAR_SINGLE ? "Single" : "Double");
        RecordProperty("Loc1", loc1 == OSKAR_CPU ? "CPU" : "GPU");
        RecordProperty("Time1_ms", int(time1 * 1000));
        RecordProperty("Prec2", prec2 == OSKAR_SINGLE ? "Single" : "Double");
        RecordProperty("Loc2", loc2 == OSKAR_CPU ? "CPU" : "GPU");
        RecordProperty("Time2_ms", int(time2 * 1000));

#ifdef ALLOW_PRINTING
        // Print times.
        printf("  > %s. %s sources. Time smearing %s.\n",
                matrix ? "Matrix" : "Scalar",
                extended ? "Gaussian" : "Point",
                time_average == 0.0 ? "off" : "on");
        printf("    %s precision %s: %.2f ms, %s precision %s: %.2f ms\n",
                prec1 == OSKAR_SINGLE ? "Single" : "Double",
                loc1 == OSKAR_CPU ? "CPU" : "GPU",
                time1 * 1000.0,
                prec2 == OSKAR_SINGLE ? "Single" : "Double",
                loc2 == OSKAR_CPU ? "CPU" : "GPU",
                time2 * 1000.0);
#endif
    }
Ejemplo n.º 11
0
int main(void)
{

/* ######################### Variables #########################  */

    /* Variables for modbus */
    modbus_t *ctx;
    int pollingInterval;
    uint16_t valueArray[2];
    float floatValue;
    int no_register;
    uint8_t desiredBit;
    GenDataType_t dataType;
    MoBuRegType_t registerType;

    /* Variables for mosquitto */
    struct mosquitto *mosq;
    char topic[BUFFER_SIZE];
    char text[50];

    /* Variables for time */
    struct timespec last_read_time;
    struct timespec now;


/* ######################### Initialize variables #########################  */

    sprintf(topic, "/test");

    /* Read values from configfile */
    if(getStringFromFile_n(CONFIG_FILE_PATH, "mosquitto_topic", topic, BUFFER_SIZE) == -1) {
        log_entry(APP_NAME, "Error reading topic");
        printf("Error reading topic..\n");
        
        /* wait for new config */
        wait_for_new_config();
        
        return EXIT_FAILURE;
    }

    pollingInterval = getIntFromFile(CONFIG_FILE_PATH, "modbus_polling_Interval");
    no_register = getIntFromFile(CONFIG_FILE_PATH, "modbus_register");
    dataType = getIntFromFile(CONFIG_FILE_PATH, "modbus_data_type");
    registerType = getIntFromFile(CONFIG_FILE_PATH, "modbus_register_type");
    desiredBit = getIntFromFile(CONFIG_FILE_PATH, "modbus_desired_bit");

    /* Check values of variables */
    if(check_values(no_register, pollingInterval) == ERROR) {
        log_entry(APP_NAME, "Error: Invalid values");
        
        /* wait for new config */
        wait_for_new_config();
        
        return EXIT_FAILURE;
    }


/* ######################### Initialize communication #########################  */

    /* Initialize Mosquitto */
    printf(SPLIT_LINE);
    mosq = mosquitto_initialize(CONFIG_FILE_PATH);
    if(mosq == NULL) {
        log_entry(APP_NAME, "Error: Could not initialize mqtt connection");

        /* wait for new config */
        wait_for_new_config();

        return EXIT_FAILURE;
    }

    /* Initialize Modbus */
    printf(SPLIT_LINE);
    ctx = modbus_init(CONFIG_FILE_PATH);
    if(ctx == NULL) {
        log_entry(APP_NAME, "Error: Could not initialize modbus connection");

        /* wait for new config */
        wait_for_new_config();

        return EXIT_FAILURE;
    }

    /* Initialize time */
    clock_gettime(CLOCK_MONOTONIC, &last_read_time);


/* ######################### Start application #########################  */

    printf(SPLIT_LINE);
    log_entry(APP_NAME, "Start reading values..");
    printf("\nStart reading values..\n\n");

    /* Endless Loop */
    while(1)
    {
        clock_gettime(CLOCK_MONOTONIC, &now);

        /* Check if polling time is over (multiply with 1000 to calculate seconds) */
        if(diff(&last_read_time, &now) >= pollingInterval * 1000) {

            /* Read values from modbus */
            if(read_modbus(ctx, 0, no_register, dataType, registerType, desiredBit, valueArray) == ERROR) {
                /* Set last read time */
                clock_gettime(CLOCK_MONOTONIC, &last_read_time);
                continue;
            }

            switch(dataType)
            {
                case bitCoil:
                case sint16:
                case sint32:
                case uint16:
                case uint32:
                    floatValue = modbus_get_float(valueArray);
                    sprintf(text, "%.0f", floatValue);
                    break;
                case float32:
                    floatValue = modbus_get_float(valueArray);
                    sprintf(text, "%.2f", floatValue);
                    break;
            }

            /* Message for user */
            printf("Value: %s\n", text);

            /* Publish value */
            if(mosquitto_pub(mosq, topic, strlen(text), text) == SUCCESS) {
                log_entry(APP_NAME, "Published value successfully");
                printf("Published value successfully.\n\n");
            } else {
                log_entry(APP_NAME, "Error: Value could not be published.");
                printf("Error: Value could not be published.\n");
            }

            /* Set last read time */
            clock_gettime(CLOCK_MONOTONIC, &last_read_time);
        }

        /* taking care of processor and slow down the loop */
        usleep(500);
    }

    /* We should never get here */
    mosquitto_quit(mosq);
    modbus_quit(ctx);

    log_entry(APP_NAME, "Quit application");

    return EXIT_SUCCESS;
}
Ejemplo n.º 12
0
void crf1dc_debug_context(FILE *fp)
{
    int y1, y2, y3;
    floatval_t norm = 0;
    const int L = 3;
    const int T = 3;
    crf1d_context_t *ctx = crf1dc_new(CTXF_MARGINALS, L, T);
    floatval_t *trans = NULL, *state = NULL;
    floatval_t scores[3][3][3];
    int labels[3];

    /* Initialize the state scores. */
    state = EXP_STATE_SCORE(ctx, 0);
    state[0] = .4;    state[1] = .5;    state[2] = .1;
    state = EXP_STATE_SCORE(ctx, 1);
    state[0] = .4;    state[1] = .1;    state[2] = .5;
    state = EXP_STATE_SCORE(ctx, 2);
    state[0] = .4;    state[1] = .1;    state[2] = .5;

    /* Initialize the transition scores. */
    trans = EXP_TRANS_SCORE(ctx, 0);
    trans[0] = .3;    trans[1] = .1;    trans[2] = .4;
    trans = EXP_TRANS_SCORE(ctx, 1);
    trans[0] = .6;    trans[1] = .2;    trans[2] = .1;
    trans = EXP_TRANS_SCORE(ctx, 2);
    trans[0] = .5;    trans[1] = .2;    trans[2] = .1;

    ctx->num_items = ctx->cap_items;
    crf1dc_alpha_score(ctx);
    crf1dc_beta_score(ctx);

    /* Compute the score of every label sequence. */
    for (y1 = 0;y1 < L;++y1) {
        floatval_t s1 = EXP_STATE_SCORE(ctx, 0)[y1];
        for (y2 = 0;y2 < L;++y2) {
            floatval_t s2 = s1;
            s2 *= EXP_TRANS_SCORE(ctx, y1)[y2];
            s2 *= EXP_STATE_SCORE(ctx, 1)[y2];
            for (y3 = 0;y3 < L;++y3) {
                floatval_t s3 = s2;
                s3 *= EXP_TRANS_SCORE(ctx, y2)[y3];
                s3 *= EXP_STATE_SCORE(ctx, 2)[y3];
                scores[y1][y2][y3] = s3;
            }
        }
    }

    /* Compute the partition factor. */
    norm = 0.;
    for (y1 = 0;y1 < L;++y1) {
        for (y2 = 0;y2 < L;++y2) {
            for (y3 = 0;y3 < L;++y3) {
                norm += scores[y1][y2][y3];
            }
        }
    }

    /* Check the partition factor. */
    fprintf(fp, "Check for the partition factor... ");
    check_values(fp, exp(ctx->log_norm), norm);

    /* Compute the sequence probabilities. */
    for (y1 = 0;y1 < L;++y1) {
        for (y2 = 0;y2 < L;++y2) {
            for (y3 = 0;y3 < L;++y3) {
                floatval_t logp;
                
                labels[0] = y1;
                labels[1] = y2;
                labels[2] = y3;
                logp = crf1dc_score(ctx, labels) - crf1dc_lognorm(ctx);

                fprintf(fp, "Check for the sequence %d-%d-%d... ", y1, y2, y3);
                check_values(fp, exp(logp), scores[y1][y2][y3] / norm);
            }
        }
    }

    /* Compute the marginal probability at t=0 */
    for (y1 = 0;y1 < L;++y1) {
        floatval_t a, b, c, s = 0.;
        for (y2 = 0;y2 < L;++y2) {
            for (y3 = 0;y3 < L;++y3) {
                s += scores[y1][y2][y3];
            }
        }

        a = ALPHA_SCORE(ctx, 0)[y1];
        b = BETA_SCORE(ctx, 0)[y1];
        c = 1. / ctx->scale_factor[0];
        
        fprintf(fp, "Check for the marginal probability (0,%d)... ", y1);
        check_values(fp, a * b * c, s / norm);
    }

    /* Compute the marginal probability at t=1 */
    for (y2 = 0;y2 < L;++y2) {
        floatval_t a, b, c, s = 0.;
        for (y1 = 0;y1 < L;++y1) {
            for (y3 = 0;y3 < L;++y3) {
                s += scores[y1][y2][y3];
            }
        }

        a = ALPHA_SCORE(ctx, 1)[y2];
        b = BETA_SCORE(ctx, 1)[y2];
        c = 1. / ctx->scale_factor[1];
        
        fprintf(fp, "Check for the marginal probability (1,%d)... ", y2);
        check_values(fp, a * b * c, s / norm);
    }

    /* Compute the marginal probability at t=2 */
    for (y3 = 0;y3 < L;++y3) {
        floatval_t a, b, c, s = 0.;
        for (y1 = 0;y1 < L;++y1) {
            for (y2 = 0;y2 < L;++y2) {
                s += scores[y1][y2][y3];
            }
        }

        a = ALPHA_SCORE(ctx, 2)[y3];
        b = BETA_SCORE(ctx, 2)[y3];
        c = 1. / ctx->scale_factor[2];
        
        fprintf(fp, "Check for the marginal probability (2,%d)... ", y3);
        check_values(fp, a * b * c, s / norm);
    }

    /* Compute the marginal probabilities of transitions. */
    for (y1 = 0;y1 < L;++y1) {
        for (y2 = 0;y2 < L;++y2) {
            floatval_t a, b, s, t, p = 0.;
            for (y3 = 0;y3 < L;++y3) {
                p += scores[y1][y2][y3];
            }

            a = ALPHA_SCORE(ctx, 0)[y1];
            b = BETA_SCORE(ctx, 1)[y2];
            s = EXP_STATE_SCORE(ctx, 1)[y2];
            t = EXP_TRANS_SCORE(ctx, y1)[y2];

            fprintf(fp, "Check for the marginal probability (0,%d)-(1,%d)... ", y1, y2);
            check_values(fp, a * t * s * b, p / norm);
        }
    }

    for (y2 = 0;y2 < L;++y2) {
        for (y3 = 0;y3 < L;++y3) {
            floatval_t a, b, s, t, p = 0.;
            for (y1 = 0;y1 < L;++y1) {
                p += scores[y1][y2][y3];
            }

            a = ALPHA_SCORE(ctx, 1)[y2];
            b = BETA_SCORE(ctx, 2)[y3];
            s = EXP_STATE_SCORE(ctx, 2)[y3];
            t = EXP_TRANS_SCORE(ctx, y2)[y3];

            fprintf(fp, "Check for the marginal probability (1,%d)-(2,%d)... ", y2, y3);
            check_values(fp, a * t * s * b, p / norm);
        }
    }
}
Ejemplo n.º 13
0
/*
 * check_results --
 *	Check all the tables and verify the results.
 */
static int
check_results(TEST_OPTS *opts, uint64_t *foundp)
{
	WT_CURSOR *maincur, *maincur2, *v0cur, *v1cur, *v2cur;
	WT_SESSION *session;
	uint64_t count, idxcount, nrecords;
	uint32_t rndint;
	int key, key_got, ret, v0, v1, v2;
	char *big, *bigref;

	testutil_check(create_big_string(&bigref));
	nrecords = opts->nrecords;
	testutil_check(wiredtiger_open(opts->home, NULL,
	    "create,log=(enabled)", &opts->conn));
	testutil_check(
	    opts->conn->open_session(opts->conn, NULL, NULL, &session));

	testutil_check(session->open_cursor(session, "table:subtest", NULL,
	    NULL, &maincur));
	testutil_check(session->open_cursor(session, "table:subtest2", NULL,
	    NULL, &maincur2));
	testutil_check(session->open_cursor(session, "index:subtest:v0", NULL,
	    NULL, &v0cur));
	testutil_check(session->open_cursor(session, "index:subtest:v1", NULL,
	    NULL, &v1cur));
	testutil_check(session->open_cursor(session, "index:subtest:v2", NULL,
	    NULL, &v2cur));

	count = 0;
	while ((ret = maincur->next(maincur)) == 0) {
		testutil_check(maincur2->next(maincur2));
		testutil_check(maincur2->get_key(maincur2, &key_got));
		testutil_check(maincur2->get_value(maincur2, &rndint));

		generate_key(count, &key);
		generate_value(rndint, count, bigref, &v0, &v1, &v2, &big);
		testutil_assert(key == key_got);

		/* Check the key/values in main table. */
		testutil_check(maincur->get_key(maincur, &key_got));
		testutil_assert(key == key_got);
		check_values(maincur, v0, v1, v2, big);

		/* Check the values in the indices. */
		v0cur->set_key(v0cur, v0);
		testutil_check(v0cur->search(v0cur));
		check_values(v0cur, v0, v1, v2, big);
		v1cur->set_key(v1cur, v1);
		testutil_check(v1cur->search(v1cur));
		check_values(v1cur, v0, v1, v2, big);
		v2cur->set_key(v2cur, v2);
		testutil_check(v2cur->search(v2cur));
		check_values(v2cur, v0, v1, v2, big);

		count++;
		if (count % VERBOSE_PRINT == 0 && opts->verbose)
			printf("checked %" PRIu64 "/%" PRIu64 "\n", count,
			    nrecords);
	}
	if (count % VERBOSE_PRINT != 0 && opts->verbose)
		printf("checked %" PRIu64 "/%" PRIu64 "\n", count, nrecords);

	/*
	 * Always expect at least one entry, as populate does a
	 * checkpoint after the first insert.
	 */
	testutil_assert(count > 0);
	testutil_assert(ret == WT_NOTFOUND);
	testutil_assert(maincur2->next(maincur2) == WT_NOTFOUND);
	cursor_count_items(v0cur, &idxcount);
	testutil_assert(count == idxcount);
	cursor_count_items(v1cur, &idxcount);
	testutil_assert(count == idxcount);
	cursor_count_items(v2cur, &idxcount);
	testutil_assert(count == idxcount);

	testutil_check(opts->conn->close(opts->conn, NULL));
	opts->conn = NULL;

	free(bigref);
	*foundp = count;
	return (0);
}
Ejemplo n.º 14
0
int main(int argc, char **argv)
{
   PAPI_event_info_t info;
   int i, j, retval;
   int iters = NUM_FLOPS;
   double x = 1.1, y;
   long long t1, t2;
   long long values[MAXEVENTS], refvalues[MAXEVENTS];
   int sleep_time = SLEEPTIME;
   double valsqsum[MAXEVENTS];
   double valsum[MAXEVENTS];
   int nevents = MAXEVENTS;
   int eventset = PAPI_NULL;
   int events[MAXEVENTS];

   events[0] = PAPI_FP_INS;
   events[1] = PAPI_TOT_INS;
   events[2] = PAPI_INT_INS;
   events[3] = PAPI_TOT_CYC;
   events[4] = PAPI_STL_CCY;
   events[5] = PAPI_BR_INS;
   events[6] = PAPI_SR_INS;
   events[7] = PAPI_LD_INS;
   events[8] = PAPI_TOT_IIS;
   events[9] = PAPI_FAD_INS;
   events[10] = PAPI_BR_TKN;
   events[11] = PAPI_BR_MSP;
   events[12] = PAPI_L1_ICA;
   events[13] = PAPI_L1_DCA;

   for (i = 0; i < MAXEVENTS; i++) {
      values[i] = 0;
      valsqsum[i] = 0;
      valsum[i] = 0;
   }

   if (argc > 1) {
      if (!strcmp(argv[1], "TESTS_QUIET"))
         tests_quiet(argc, argv);
      else {
         sleep_time = atoi(argv[1]);
         if (sleep_time <= 0)
            sleep_time = SLEEPTIME;
      }
   }

   if (!TESTS_QUIET) {
      printf("\nAccuracy check of multiplexing routines.\n");
      printf("Comparing a multiplex measurement with separate measurements.\n\n");
   }

   if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT)
      test_fail(__FILE__, __LINE__, "PAPI_library_init", retval);

   decide_which_events(events, &nevents);

   init_multiplex();

   /* Find a reasonable number of iterations (each 
    * event active 20 times) during the measurement
    */
   t2 = 10000 * 20 * nevents;   /* Target: 10000 usec/multiplex, 20 repeats */
   if (t2 > 30e6)
      test_skip(__FILE__, __LINE__, "This test takes too much time", retval);

   y = dummy3(x, iters);
   /* Measure one run */
   t1 = PAPI_get_real_usec();
   y = dummy3(x, iters);
   t1 = PAPI_get_real_usec() - t1;

   if (t1 < 1000000)                 /* Scale up execution time to match t2 */
     {
       iters = iters * (1000000/t1);
       printf("Modified iteration count to %d\n\n",iters);
     }

   /* Now loop through the items one at a time */

   ref_measurements(iters, &eventset, events, nevents, refvalues); 

   /* Now check multiplexed */

   if ((retval = PAPI_create_eventset(&eventset)))
      test_fail(__FILE__, __LINE__, "PAPI_create_eventset", retval);


   /* In Component PAPI, EventSets must be assigned a component index
      before you can fiddle with their internals.
      0 is always the cpu component */
   retval = PAPI_assign_eventset_component(eventset, 0);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_assign_eventset_component", retval);

   if ((retval = PAPI_set_multiplex(eventset)))
     test_fail(__FILE__, __LINE__, "PAPI_set_multiplex", retval);

   if ((retval = PAPI_add_events(eventset, events, nevents)))
     test_fail(__FILE__, __LINE__, "PAPI_add_events", retval);

   printf("\nPAPI multiplexed measurements:\n");
   x = 1.0;
   t1 = PAPI_get_real_usec();
   if ((retval = PAPI_start(eventset)))
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);
   y = dummy3(x, iters);
   if ((retval = PAPI_stop(eventset, values)))
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);
   t2 = PAPI_get_real_usec();

   for (j = 0; j < nevents; j++) {
      PAPI_get_event_info(events[j], &info);
      if (!TESTS_QUIET) {
         printf("%20s = ", info.short_descr);
         printf(LLDFMT, values[j]);
         printf("\n");
      }
   }

   check_values(eventset, events, nevents, values, refvalues);

   if ((retval = PAPI_remove_events(eventset, events, nevents)))
      test_fail(__FILE__, __LINE__, "PAPI_remove_events", retval);
   if ((retval = PAPI_cleanup_eventset(eventset)))
     test_fail(__FILE__, __LINE__, "PAPI_cleanup_eventset", retval);
   if ((retval = PAPI_destroy_eventset(&eventset)))
      test_fail(__FILE__, __LINE__, "PAPI_destroy_eventset", retval);
   eventset = PAPI_NULL;

   /* Now loop through the items one at a time */

   ref_measurements(iters, &eventset, events, nevents, refvalues);

   check_values(eventset, events, nevents, values, refvalues);

   test_pass(__FILE__, NULL, 0);

   return 0;
}
Ejemplo n.º 15
0
/**
 * facq_net_receive:
 * @skt: A connected #GSocket object.
 * @buf: A pointer to a free memory area.
 * @size: The size of the memory area pointed by @buf.
 * @retry: The number of times to retry receiving data until @buf is full, or 0.
 * if 0 the function will use an automatic number of retries, and won't return
 * until size bytes are read.
 * @err: A #GError, it will be set in case of error if not %NULL.
 *
 * Receives @size bytes, in the memory area pointed by @buf, from the connect
 * socket @skt, using at most @retry retries.
 *
 * Returns: The number of bytes received if successful, 0 if disconnected, -1 in case of error,
 * -2 in case of timeout, -3 if wrong parameters are passed to the function.
 */
gssize facq_net_receive(GSocket *skt,gchar *buf,gsize size,guint retry,GError **err)
{
    guint retries = 0;
    gsize to_read = 0, remaining = 0;
    gssize ret = 0, total = 0;
    GError *local_err = NULL;

    if(!check_values(skt,buf,size)) {
        if(err != NULL)
            g_set_error_literal(err,G_IO_ERROR,
                                G_IO_ERROR_FAILED,"Can't receive any data");
        return -3;
    }

    if(retry == 0)
        retry = G_MAXUINT;

    to_read = 0;
    remaining = size;

    for(retries = 0; retries < retry && total < size; retries++) {
#if ENABLE_DEBUG
        facq_log_write_v(FACQ_LOG_MSG_TYPE_DEBUG,"Receiving data retry=%u",retries);
#endif
        ret = g_socket_receive(skt,&buf[to_read],remaining,NULL,&local_err);
#if ENABLE_DEBUG
        facq_log_write_v(FACQ_LOG_MSG_TYPE_DEBUG,
                         "g_socket_receive ret=%"G_GSSIZE_FORMAT,
                         ret);
#endif
        switch(ret) {
        case 0:
            facq_log_write_v(FACQ_LOG_MSG_TYPE_INFO,
                             "Disconnected");
            return 0;
            break;
        case -1:
            if(local_err) {
                facq_log_write_v(FACQ_LOG_MSG_TYPE_ERROR,
                                 "%s",local_err->message);
                if(err != NULL)
                    g_propagate_error(err,local_err);
                return -1;
            }
            else {
                if(err != NULL)
                    g_set_error_literal(err,G_IO_ERROR,
                                        G_IO_ERROR_FAILED,"Error receiving data");
                facq_log_write_v(FACQ_LOG_MSG_TYPE_ERROR,
                                 "Unknown error receiving data");
                return -1;
            }
            break;
        default:
            total += ret;
            to_read += ret;
            remaining = size - total;
            if(total == size)
                break;
        }
    }

    if(total != size) {
        if(err != NULL)
            g_set_error_literal(err,G_IO_ERROR,
                                G_IO_ERROR_TIMED_OUT,"Operation timed out");
        return -2;
    }

    return total;
}
Ejemplo n.º 16
0
int
heapCheck(HEAP h)
{
    return check_values((Heap*)h,0,0);
}
Ejemplo n.º 17
0
    void runTest(int prec1, int prec2, int loc1, int loc2, int matrix)
    {
        int status = 0, type;
        oskar_Mem *beam1, *beam2;
        oskar_Timer *timer1, *timer2;
        double time1, time2;

        // Create the timers.
        timer1 = oskar_timer_create(loc1 == OSKAR_GPU ?
                OSKAR_TIMER_CUDA : OSKAR_TIMER_NATIVE);
        timer2 = oskar_timer_create(loc2 == OSKAR_GPU ?
                OSKAR_TIMER_CUDA : OSKAR_TIMER_NATIVE);

        // Run first part.
        type = prec1 | OSKAR_COMPLEX;
        if (matrix) type |= OSKAR_MATRIX;
        beam1 = oskar_mem_create(type, loc1, num_sources, &status);
        oskar_mem_clear_contents(beam1, &status);
        ASSERT_EQ(0, status) << oskar_get_error_string(status);
        createTestData(prec1, loc1, matrix);
        oskar_timer_start(timer1);
        oskar_evaluate_cross_power(num_sources, num_stations,
                jones, 0, beam1, &status);
        time1 = oskar_timer_elapsed(timer1);
        destroyTestData();
        ASSERT_EQ(0, status) << oskar_get_error_string(status);

        // Run second part.
        type = prec2 | OSKAR_COMPLEX;
        if (matrix) type |= OSKAR_MATRIX;
        beam2 = oskar_mem_create(type, loc2, num_sources, &status);
        oskar_mem_clear_contents(beam2, &status);
        ASSERT_EQ(0, status) << oskar_get_error_string(status);
        createTestData(prec2, loc2, matrix);
        oskar_timer_start(timer2);
        oskar_evaluate_cross_power(num_sources, num_stations,
                jones, 0, beam2, &status);
        time2 = oskar_timer_elapsed(timer2);
        destroyTestData();
        ASSERT_EQ(0, status) << oskar_get_error_string(status);

        // Destroy the timers.
        oskar_timer_free(timer1);
        oskar_timer_free(timer2);

        // Compare results.
        check_values(beam1, beam2);

        // Free memory.
        oskar_mem_free(beam1, &status);
        oskar_mem_free(beam2, &status);
        ASSERT_EQ(0, status) << oskar_get_error_string(status);

        // Record properties for test.
        RecordProperty("JonesType", matrix ? "Matrix" : "Scalar");
        RecordProperty("Prec1", prec1 == OSKAR_SINGLE ? "Single" : "Double");
        RecordProperty("Loc1", loc1 == OSKAR_CPU ? "CPU" : "GPU");
        RecordProperty("Time1_ms", int(time1 * 1000));
        RecordProperty("Prec2", prec2 == OSKAR_SINGLE ? "Single" : "Double");
        RecordProperty("Loc2", loc2 == OSKAR_CPU ? "CPU" : "GPU");
        RecordProperty("Time2_ms", int(time2 * 1000));

#ifdef ALLOW_PRINTING
        // Print times.
        printf("  > %s.\n", matrix ? "Matrix" : "Scalar");
        printf("    %s precision %s: %.2f ms, %s precision %s: %.2f ms\n",
                prec1 == OSKAR_SINGLE ? "Single" : "Double",
                loc1 == OSKAR_CPU ? "CPU" : "GPU",
                time1 * 1000.0,
                prec2 == OSKAR_SINGLE ? "Single" : "Double",
                loc2 == OSKAR_CPU ? "CPU" : "GPU",
                time2 * 1000.0);
#endif
    }