bool test_file_directory_find (Test *test)
{
	char *path;
	Directory *directory;
	Directory *found_directory;
	File *found_file;

	TITLE ();
	CATCH (!(path = directory_current_path ()));
	CATCH (!string_append (&path, "/stage/find"));
        /*
                d stage/find
                f f1
                d stage/find/d1
         */
	CATCH (!(directory = directory_open (path)));
	string_destroy (path);
	CATCH (!directory_read (directory));
	CATCH (!directory->directories);
	CATCH (!directory->files);
	CATCH (directory->directories->count != 1);
	CATCH (directory->files->count != 1);
	CATCH (!(found_directory = directory_find_directory (directory, "d1")));
	CATCH (!string_equals (found_directory->name, "d1"));
	CATCH (directory_find_directory (directory, "d2"));
	CATCH (!(found_file = directory_find_file (directory, "f1")));
	CATCH (!string_equals (found_file->name, "f1"));
	CATCH (directory_find_file (directory, "f2"));
	directory_close (directory);
	PASS ();
}
Exemple #2
0
void join_path(Value* left, Value* right)
{
    const char* leftStr = as_cstring(left);
    const char* rightStr = as_cstring(right);
    int left_len = (int) strlen(leftStr);
    int right_len = (int) strlen(leftStr);

    if (string_equals(left, "") || string_equals(left, ".")) {
        copy(right, left);
        return;
    }

    if (string_equals(right, ""))
        return;

    int seperatorCount = 0;
    if (left_len > 0 && is_path_seperator(leftStr[left_len-1]))
        seperatorCount++;

    if (right_len > 0 && is_path_seperator(rightStr[0]))
        seperatorCount++;

    if (seperatorCount == 2)
        string_resize(left, left_len - 1);
    else if (seperatorCount == 0)
        string_append(left, "/");

    string_append(left, right);
}
Exemple #3
0
int main(int argc, char **argv) {
    char *arg;

    char *address = NULL;
    char *language = NULL;

    bool use_json = false;

    string_array *languages = NULL;

    for (int i = 1; i < argc; i++) {
        arg = argv[i];
        if (string_equals(arg, "-h") || string_equals(arg, "--help")) {
            printf(LIBPOSTAL_USAGE);
            exit(EXIT_SUCCESS);
        } else if (string_equals(arg, "--json")) {
            use_json = true;
        } else if (address == NULL) {
            address = arg;
        } else if (!string_starts_with(arg, "-")) {
            if (languages == NULL) {
                languages = string_array_new();
            }
            string_array_push(languages, arg);
        }
    }

    if (address == NULL && (!use_json || isatty(fileno(stdin)))) {
        log_error(LIBPOSTAL_USAGE);
        exit(EXIT_FAILURE);
    }

    if (!libpostal_setup() || (languages == NULL && !libpostal_setup_language_classifier())) {
        exit(EXIT_FAILURE);
    }

    normalize_options_t options = get_libpostal_default_options();

    if (languages != NULL) {
        options.languages = languages->a;
        options.num_languages = languages->n;
    }

    if (address == NULL) {
        char *line;
        while ((line = file_getline(stdin)) != NULL) {
            print_output(line, options, use_json);
            free(line);
        }
    } else {
        print_output(address, options, use_json);
    }

    if (languages != NULL) {
        string_array_destroy(languages);
    }

    libpostal_teardown();
    libpostal_teardown_language_classifier();
}
Exemple #4
0
void get_path_relative_to_source(caBlock* relativeTo, Value* relPath, Value* result)
{
    if (relativeTo == NULL) {
        copy(relPath, result);
        return;
    }

    // Don't modify absolute paths
    if (is_absolute_path(relPath)) {
        copy(relPath, result);
        return;
    }

    Value scriptLocation;
    get_source_file_location(relativeTo, &scriptLocation);

    if (string_equals(&scriptLocation, "") || string_equals(&scriptLocation, ".")) {
        set_value(result, relPath);
        return;
    }

    set_value(result, &scriptLocation);

    if (!string_equals(relPath,"")) {
        string_append(result, "/");
        string_append(result, relPath);
    }

}
Exemple #5
0
void test_equality_with_symbol()
{
    Value val;
    set_symbol(&val, s_Append);
    test_assert(string_equals(&val, ":Append"));
    test_assert(!string_equals(&val, "Append"));
    test_assert(!string_equals(&val, "Appen"));
}
void leerArchivoDeConfiguracion(int argc, char *argv[]) {

	char* logMsg = NULL;

	if (argc < 2) {
		logMsg =
				string_from_format(
						"Debe especificar la ruta al archivo de configuracion, al invocar al programa, por ejemplo: ./Memoria /home/utnso/tp-2015-2c-tpso/Memoria/config_memoria.cfg\n");
		puts(logMsg);
		my_log_error(logMsg);
		exit(-1);
	}

	char* nombreArchivoConfig = nombreArchivoConfig = strdup(argv[1]);
	uint8_t result = checkearRutaArchivoConfig(nombreArchivoConfig);
	if (result == -1) {
		logMsg = string_from_format("Archivo de configuracion no encontrado. Parametro especificado: %s\n", nombreArchivoConfig);
		puts(logMsg);
		my_log_error(logMsg);
		exit(-1);
	} else {
		t_config* archivoConfig;
		archivoConfig = config_create(nombreArchivoConfig);
		//warning asignacion diferentes tipos
		configuracion = iniciarArchivoConfig();
		configuracion->puertoEscucha = config_get_int_value(archivoConfig, "PUERTO_ESCUCHA");
		configuracion->puertoSwap = config_get_int_value(archivoConfig, "PUERTO_SWAP");
		configuracion->ipSwap = strdup(config_get_string_value(archivoConfig, "IP_SWAP"));

		char* nombreMemoria = config_get_string_value(archivoConfig, "NOMBRE_MEMORIA");
		configuracion->nombreMemoria = strdup(nombreMemoria != NULL ? nombreMemoria : "NOMBRE_MEMORIA");

		configuracion->maximosMarcosPorProceso = config_get_int_value(archivoConfig, "MAXIMO_MARCOS_POR_PROCESO");
		configuracion->cantidadMarcos = config_get_int_value(archivoConfig, "CANTIDAD_MARCOS");
		configuracion->tamanioMarcos = config_get_int_value(archivoConfig, "TAMANIO_MARCO");
		configuracion->entradasTlb = config_get_int_value(archivoConfig, "ENTRADAS_TLB");
		if (string_equals(config_get_string_value(archivoConfig, "TLB_HABILITADA"),"SI")){
			configuracion->tlbHabilitada=1;
		}
		else if (string_equals(config_get_string_value(archivoConfig, "TLB_HABILITADA"),"NO")){
			configuracion->tlbHabilitada=0;
		}
		configuracion->retardoMemoria = config_get_int_value(archivoConfig, "RETARDO_MEMORIA");
		configuracion->algoritmo_reemplazo = strdup(config_get_string_value(archivoConfig, "ALGORITMO_REEMPLAZO"));
		my_log_info("[INFO]: Archivo de configuracion leido correctamente\n");

		logMsg = string_from_format("Archivo de configuracion leido correctamente\n");
		puts(logMsg);

		//config_destroy(archivoConfig);

	}

}
Exemple #7
0
static void     test_int_to_malloced_string_base(void)
{
  char          *s;

  s = int_to_malloced_string_base(0xdeadbeef, 16);
  ASSERT(s != NULL);
  ASSERT(string_equals("deadbeef", s));
  free(s);
  s = int_to_malloced_string_base(0xff, 2);
  ASSERT(s != NULL);
  ASSERT(string_equals("1111" "1111", s));
  free(s);
}
Exemple #8
0
static void     test_int_to_string_base(void)
{
  char          buffer[100];

  ASSERT(int_to_string_base(0, buffer, 2, 10) == 0);
  ASSERT(string_equals(buffer, "0"));
  ASSERT(int_to_string_base(0, buffer, 1, 10) == -1);
  ASSERT(int_to_string_base(123, buffer, 3, 10) == -1);
  ASSERT(int_to_string_base(123, buffer, 4, 10) == 0);
  ASSERT(string_equals(buffer, "123"));
  ASSERT(int_to_string_base(0xdeadbeef, buffer, 8, 16) == -1);
  ASSERT(int_to_string_base(0xdeadbeef, buffer, 9, 16) == 0);
  ASSERT(string_equals(buffer, "deadbeef"));
}
t_list* files_getEntriesOfDirectory(char* path) {
	t_list* list = list_create();

	DIR* dir;
	struct dirent* ent;
	if ((dir = opendir(path)) != NULL) {
		while((ent = readdir(dir)) != NULL) {
			char* name = ent->d_name;
			if (!string_equals(name, ".") && !string_equals(name, ".."))
				list_add(list, string_duplicate(name));
		}
		closedir(dir);
	}

	return list;
}
bool test_websocket_connect_error (Test *test)
{
        NetWebsocket *websocket;
        NetClientConnection connection;
        NetClient *client;

        TITLE ();
        CATCH (!(websocket = net_websocket_create (&on_add, 
                                                   &on_close, 
                                                   &on_request)));
        websocket->test.ConnectError = true;
        // Connect with client.
        CATCH (!(client = net_client_create (&client_on_connect,
                                             &client_on_connect_error,
                                             &client_on_error,
                                             NULL)));
        connection.ip = "127.0.0.1";
        connection.port = 8888;
        net_client_connect (client, &connection);
        CATCH (!thread_signal_wait (&client_ready));
        net_client_destroy (client);
        net_websocket_destroy (websocket);
        CATCH (error_at (0).error != ErrorFunctionCall);
        CATCH (!string_equals (error_at (0).function, "server_on_connect"));
        PASS ();
}
bool compile_project_execute_with_directory_name (CompileProject *project, 
                                                  const char *directory_name, 
                                                  bool bootstrap)
{
	Compile *compile = NULL;
	ListNode *node;

	if (!project) {
		compile_debug_invalid_arguments ();
		return false;
	}
	if (!directory_name) {
		compile_debug_invalid_arguments ();
		return false;
	}
	for (node = list_last (project->sorted); !compile && node; node = list_previous (node)) {
		if (string_equals (((Compile *)node->data)->directory->name, directory_name)) {
			compile = node->data;
		}
	}
	if (!compile) {
		compile_debug_invalid_value ();
		return false;
	}
	if (!included_libraries_are_up_to_date (project, compile)) {
		return false;
	}
	if (!compile_execute (compile, bootstrap)) {
		return false;
	}
	return true;
}
bool test_encode_base64 (Test *test)
{
        char *base64;
        char bytes[1024 * 16];
        size_t i;

        TITLE ();
        CATCH (encode_base64 (NULL, 0));
        CATCH (error_at (0).error != ErrorInvalidArgument);
        CATCH (error_at (0).code != 1);
        CATCH (encode_base64 ("", 0));
        CATCH (error_at (0).error != ErrorInvalidArgument);
        CATCH (error_at (0).code != 2);
        memory_commit_limit (0);
        CATCH (encode_base64 ("abc", 3));
        CATCH (error_at (0).error != ErrorFunctionCall);
        memory_commit_limit (ULLONG_MAX);

        for (i = 0; i < 1000; i++) {
                CATCH (!(base64 = encode_base64 ("any carnal pleasure.", 20)));
                CATCH (!string_equals (base64, "YW55IGNhcm5hbCBwbGVhc3VyZS4="));
                string_destroy (base64);
        }

        CATCH (!random_open ());
        for (i = 0; i < 1000; i++) {
                CATCH (!random_bytes ((unsigned char *)&bytes, 1024 * 16));
                CATCH (!(base64 = encode_base64 (bytes, 1024 * 16)));
                CATCH (string_length (base64) < 21848);
                string_destroy (base64);
        }
        random_close ();
        PASS ();
}
result test_string_equals_EmptyStrings() {
	int passed = 0;
	char* description = "string_equals(char*, char*) : 2EmptyString CASE";

	passed = is_true(string_equals("", ""));

	return (result){passed, description};
}
result test_string_equals_StringWithSameString() {
	int passed = 0;
	char* description = "string_equals(char*, char*) : StringWithSameString CASE";

	passed = is_true(string_equals("abc", "abc"));

	return (result){passed, description};
}
bool test_file_directory_open_current_2 (Test *test)
{
	char *path;
	Directory *directory;

	TITLE ();
	path = directory_current_path ();
	CATCH (!(directory = directory_open_current ()));
	CATCH (!string_equals (directory->path, path));
	CATCH (!string_equals (directory->name, "app.test.lib.core"));
	CATCH (directory->directories);
	CATCH (directory->files);
	CATCH (directory->modified == 0);
	directory_close (directory);
	string_destroy (path);
	PASS ();
}
result test_string_equals_StringWithOtherString() {
	int passed = 0;
	char* description = "string_equals(char*, char*) : StringWithOtherString CASE";

	passed = is_false(string_equals("abc", "efg"));

	return (result){passed, description};
}
result test_string_equals_NULL() {
	int passed = 0;
	char* description = "string_equals(char*, char*) : NULL CASE";

	passed = is_false(string_equals(0, 0));

	return (result){passed, description};
}
Exemple #18
0
bool TokenStream::nextEqualsString(const char* str, int lookahead)
{
    if ((this->_position + lookahead) >= tokens.size())
        return false;

    Value next;
    getNextStr(&next, lookahead);
    return string_equals(&next, str);
}
Exemple #19
0
Term* loop_find_done_call(Block* block)
{
    for (int i=0; i < block->length(); i++) {
        Term* term = block->get(i);
        Value* methodName = term->getProp(s_method_name);
        if (methodName && string_equals(methodName, "done"))
            return term;
    }
    return NULL;
}
bool test_file_name_from_path (Test *test)
{
	char *name;

	TITLE ();
	CATCH (!(name = file_name_from_path ("/")));
	CATCH (!string_equals (name, "/"));
	string_destroy (name);
	CATCH (!(name = file_name_from_path ("/a")));
	CATCH (!string_equals (name, "a"));
	string_destroy (name);
	CATCH (!(name = file_name_from_path ("/a/bb")));
	CATCH (!string_equals (name, "bb"));
	string_destroy (name);
	CATCH (!(name = file_name_from_path ("/a/bb/ccc.dddd")));
	CATCH (!string_equals (name, "ccc.dddd"));
	string_destroy (name);
	PASS ();
}
Exemple #21
0
/* @builtin-bind { 'd', builtin_defun }, */
int builtin_defun(interpreter* interp) {
  string name, body;
  byte n1;
  long_command* curr;

  if (!stack_pop_strings(interp, 2, &body, &name)) UNDERFLOW;

  /* If name is one character, it is a short name; if it is more than one
   * character, it is a long name. An empty string is an error.
   */
  if (!name->len) {
    print_error("Empty command name");
    goto error;
  }

  if (name->len == 1) {
    n1 = string_data(name)[0];
    /* Both pointers are in the same spot, so check either */
    if (interp->commands[n1].cmd.native) {
      print_error_s("Short command already exists", name);
      goto error;
    } else {
      /* OK */
      interp->commands[n1].is_native = 0;
      interp->commands[n1].cmd.user = body;
      free(name);
    }
  } else {
    /* Long command name.
     * First, check to see if it already exists.
     */
    for (curr = interp->long_commands; curr; curr = curr->next) {
      if (string_equals(name, curr->name)) {
        print_error_s("Long command already exists", name);
        goto error;
      }
    }

    /* OK, add it */
    curr = tmalloc(sizeof(long_command));
    curr->name = name;
    curr->cmd.is_native = 0;
    curr->cmd.cmd.user = body;
    curr->next = interp->long_commands;
    interp->long_commands = curr;
  }

  return 1;

  error:
  /* Restore the stack and return failure */
  stack_push(interp, name);
  stack_push(interp, body);
  return 0;
}
double test_accuracy(char *filename) {
    language_classifier_data_set_t *data_set = language_classifier_data_set_init(filename);
    if (data_set == NULL) {
        log_error("Error creating data set\n");
        exit(EXIT_FAILURE);
    }

    language_classifier_minibatch_t *minibatch;

    uint32_t correct = 0;
    uint32_t total = 0;

    language_classifier_t *classifier = get_language_classifier();
    trie_t *label_ids = trie_new_from_cstring_array(classifier->labels);

    while (language_classifier_data_set_next(data_set)) {
        char *address = char_array_get_string(data_set->address);
        char *language = char_array_get_string(data_set->language);
        
        uint32_t label_id;
        if (!trie_get_data(label_ids, language, &label_id)) {
            continue;
        }

        language_classifier_response_t *response = classify_languages(address);
        if (response == NULL || response->num_languages == 0) {
            printf("%s\tNULL\t%s\n", language, address);
            continue;
        }

        char *top_lang = response->languages[0];

        if (string_equals(top_lang, language)) {
            correct++;
        } else {
            printf("%s\t%s\t%s\n", language, top_lang, address);
        }

        total++;

        language_classifier_response_destroy(response);

    }

    log_info("total=%zu\n", total);

    trie_destroy(label_ids);

    return (double) correct / total;


}
Exemple #23
0
Term* loop_find_iterator_advance(Block* block)
{
    Term* iterator = loop_find_iterator(block);
    for (int i=0; i < block->length(); i++) {
        Term* term = block->get(i);
        if (term->input(0) != iterator)
            continue;
        Value* methodName = term->getProp(s_method_name);
        if (methodName && string_equals(methodName, "advance"))
            return term;
    }
    return NULL;
}
Exemple #24
0
bool hayQueEjecutarTests(int argc, char *argv[]) {

    int i;
    for (i = 0; i < argc; ++i) {
        if (string_equals(argv[i], "test")) {
            //printf("Hay que ejecutar tests\n");
            return true;
        }
    }

    //printf("No hay que ejecutar tests\n");
    return false;
}
result test_string_copy_String() {
	int passed = 0;
	char* description = "string_copy(char*) : String CASE";

	char* str = "abc";
	char* cpy = string_copy(str);

	passed = is_true(string_equals(str, cpy));

	free(cpy);

	return (result){passed, description};
}
Exemple #26
0
Term* find_from_unique_name(Block* block, Value* name)
{
    // O(n) search; this should be made more efficient.

    for (int i=0; i < block->length(); i++) {
        Term* term = block->get(i);
        if (term == NULL)
            continue;
        if (string_equals(unique_name(term), name)) {
            return term;
        }
    }
    return NULL;
}
bool test_file_reader_create (Test *test)
{
        FileReader *reader;
        char *path;

        TITLE ();
        CATCH (!(path = directory_current_path ()));
        CATCH (!string_append (&path, "/stage/file_reader/file"));
        CATCH (!(reader = file_reader_create (path)));
        CATCH (reader->size != 5);
        CATCH (!string_equals ((const char *)reader->map, "test\n"));
        file_reader_destroy (reader);
        string_destroy (path);
        PASS ();
}
Exemple #28
0
int email_remove_email_from_recipients(struct email* email, char* addr)
{
  int i;
  int output = 0;
  for (i = 0; i < MAX_RECIPIENTS; i++) {
    if (email->to[i] && string_equals(email->to[i], addr)) {
      SAFEFREE(email->to[i]);
      int j;
      for (j = i; j < MAX_RECIPIENTS; j++)
        email->to[j] = email->to[j+1];
      output = 1;
    }
  }
  return output;
}
Exemple #29
0
void     assert_token_equals(const char *expected, const t_token *token)
{
  char          *string;
  int           r;

  string = token_to_string(token);
  r = string_equals(expected, string);
  ASSERT(r);
  if (!r)
    {
      print_string("Expected ");
      print_string(expected);
      print_string(", got ");
      print_string(string);
      print_string("\n");
    }
  free(string);
}
Exemple #30
0
CIRCA_EXPORT caWorld* circa_initialize()
{
    bootstrap_kernel();

    caWorld* world = global_world();

    Block* builtins = global_builtins_block();
    //dump(builtins);

    // Make sure there are no static errors in builtins. This shouldn't happen.
    #if 0
    if (has_static_errors(builtins)) {
        std::cout << "Static errors found in kernel:" << std::endl;
        dump(builtins);
        Value msg;
        print_static_errors_formatted(builtins, &msg);
        dump(&msg);
    }
    #endif

    // Load library paths from CIRCA_LIB_PATH
    const char* libPathEnv = getenv("CIRCA_LIB_PATH");
    if (libPathEnv != NULL) {
        Value libPathStr;
        set_string(&libPathStr, libPathEnv);

        Value libPaths;
        string_split(&libPathStr, ';', &libPaths);

        for (int i=0; i < list_length(&libPaths); i++) {
            Value* path = list_get(&libPaths, i);
            if (string_equals(path, ""))
                continue;
            module_add_search_path(world, as_cstring(path));
        }
    }

    log_msg(0, "finished circa_initialize");

    world->bootstrapStatus = s_Done;

    return world;
}