コード例 #1
0
ファイル: orbment.c プロジェクト: Cloudef/orbment
int
main(int argc, char *argv[])
{
   (void)argc, (void)argv;

   signals_setup_debug();

   // XXX: Potentially dangerous under suid
   handle_arguments(argc, argv);
   log_open();

   if (!wlc_init())
      return EXIT_FAILURE;

   signals_setup();

   if (!setup_plugins())
      return EXIT_FAILURE;

   plog(0, PLOG_INFO, "-- Orbment started --");

   wlc_run();

   plog(0, PLOG_INFO, "-- Orbment is gone, bye bye! --");
   log_close();
   return EXIT_SUCCESS;
}
コード例 #2
0
ファイル: main.c プロジェクト: bernied/bcfun
int
main(int argc, char** argv)
{
  int result;
  struct stat sb;
  char* file_name;

  // Handle arguments
  file_name = handle_arguments(argc, argv, &args);

  if (stat(file_name, &sb) == -1)
  {
    fprintf(stderr, "File %s does not exist.\n", file_name);
    exit(EXIT_FAILURE);
  }
  off_t size = sb.st_size;

  // Open file for processing
  FILE* file = fopen(file_name, "r");
  if (file == NULL) 
  {
    fprintf(stderr, "An error occured while opening file \"%s\".", file_name);
    exit(EXIT_FAILURE);
  }

  if (args.b) {
    result = sha_256_bc_json(file_name, file, size);
  }
  else {
    result = sha_256_file(file_name, file, size);
  }

  fclose(file);
  exit(result);
}
コード例 #3
0
ファイル: env.c プロジェクト: jseltzer/gentils
int main(int argc, char const * const *argv)
{
    if (argc > 1)
        handle_arguments(argv);
    
    print_env();
    return 0;
}
コード例 #4
0
ファイル: main.c プロジェクト: carsonk/cs202-labs
/*
* Method: main
* Purpose: Handles primary functionality.
* Parameters:
* int argc: The count of arguments.
* char *argv[]: The array of arguments.
*/
int main(int argc, char *argv[]) {
    Settings settings; // The passed settings.
    int * filenameIndices; // Will hold indices of filename locations in argv.
    int filenameIndicesCount = 0; // The count of indices.

    // Grabs settings.
    handle_arguments(argc, argv, &settings, &filenameIndices, &filenameIndicesCount);

    if(settings.ignoreInterrupts)
    {
        signal(SIGINT, SIG_IGN); // Ignore signals if asked of us.
    }

    FILE *openFiles[filenameIndicesCount]; // The set of open file descriptors.

    // Open files.
    int index;
    for(index = 0; index < filenameIndicesCount; index++)
    {
        int argIndex = filenameIndices[index];

        char * mode = (settings.append) ? "a" : "w"; // Chose write mode based on flags.
        openFiles[index] = fopen(argv[argIndex], mode); // Open the file with mode.

        if(!openFiles[index])
        {
            fail_with_error("Could not open file.");
        }
    }

    if(filenameIndices)
        free(filenameIndices); // Free calloced data.

    char inputBuffer[BUFFER_SIZE];

    while(fgets(inputBuffer, BUFFER_SIZE, stdin)) // Receive input.
    {
        for(index = 0; index < filenameIndicesCount; index++)
        {
            // Print input to each file.
            fwrite(inputBuffer, sizeof(char), strlen(inputBuffer), openFiles[index]);
            fflush(openFiles[index]);
        }

        printf("%s", inputBuffer); // Print out the input.
    }

    return 0;
}
コード例 #5
0
ファイル: fsplit.cpp プロジェクト: jenerick/fsplit
int	main ( int argc, char** argv )
{
	/* the initial message displayed at startup */
	char*	init_msg =	(char *)
				" fsplit: portable file splitter\n"
				" by Christian Byrne <*****@*****.**>"
				"\n";

	std::cout << init_msg << '\n';

	if ( argc < 2 )
		std::cout << "error: no arguments given\n";
	else
		handle_arguments ( argc, argv );
	
	return	0;
}
コード例 #6
0
ファイル: main.c プロジェクト: seece/tiraimg
int main(int32_t argc, char** argv) 
{
	handle_arguments(argc, argv);

	if (verbose)
		printf("Input: %s\nOutput: %s\n", input_path, output_path);

	if (action == ACTION_COMPRESS) {
		action_compress_image();
	}

	if (action == ACTION_DECOMPRESS) {
		action_decompress_image();
	}

	exit(EXIT_SUCCESS);
}
コード例 #7
0
ファイル: main.c プロジェクト: domsom/nm-applet-ds
static gboolean
impl_start (NMCEService *self, GHashTable *table, GError **error)
{
	GValue *value;
	const char *type = NULL;
	const char *uuid = NULL;
	gboolean create = FALSE;
	gboolean show = FALSE;
	gboolean show_list;

	value = g_hash_table_lookup (table, ARG_TYPE);
	if (value && G_VALUE_HOLDS_STRING (value)) {
		type = g_value_get_string (value);
		g_assert (type);
	}

	value = g_hash_table_lookup (table, ARG_UUID);
	if (value && G_VALUE_HOLDS_STRING (value)) {
		uuid = g_value_get_string (value);
		g_assert (uuid);
	}

	value = g_hash_table_lookup (table, ARG_CREATE);
	if (value && G_VALUE_HOLDS_BOOLEAN (value))
		create = g_value_get_boolean (value);

	value = g_hash_table_lookup (table, ARG_SHOW);
	if (value && G_VALUE_HOLDS_BOOLEAN (value))
		show = g_value_get_boolean (value);

	show_list = handle_arguments (self->list, type, create, show, uuid, FALSE);
	if (show_list)
		nm_connection_list_present (self->list);

	return TRUE;
}
コード例 #8
0
ファイル: main.c プロジェクト: atulhjp/network-manager-applet
static void
handle_method_call (GDBusConnection       *connection,
                    const gchar           *sender,
                    const gchar           *object_path,
                    const gchar           *interface_name,
                    const gchar           *method_name,
                    GVariant              *parameters,
                    GDBusMethodInvocation *invocation,
                    gpointer               user_data)
{
	NMConnectionList *list = NM_CONNECTION_LIST (user_data);
	char *type = NULL, *uuid = NULL, *import = NULL;
	gboolean create = FALSE, show = FALSE;

	if (g_strcmp0 (method_name, "Start") == 0) {
		if (g_variant_is_of_type (parameters, (const GVariantType *) "(a{sv})")) {
			gs_unref_variant GVariant *dict = NULL;

			g_variant_get (parameters, "(@a{sv})", &dict);
			g_variant_lookup (dict, ARG_TYPE, "s", &type);
			g_variant_lookup (dict, ARG_UUID, "s", &uuid);
			g_variant_lookup (dict, ARG_CREATE, "b", &create);
			g_variant_lookup (dict, ARG_SHOW, "b", &show);
			g_variant_lookup (dict, ARG_IMPORT, "s", &import);
			if (handle_arguments (list, type, create, show, uuid, import, FALSE))
				nm_connection_list_present (list);

			g_dbus_method_invocation_return_value (invocation, NULL);
		} else {
			g_dbus_method_invocation_return_error (invocation,
			                                       G_DBUS_ERROR,
			                                       G_DBUS_ERROR_INVALID_ARGS,
			                                       "Invalid argument type (not a dict)");
		}
	}
}
コード例 #9
0
ファイル: main.c プロジェクト: 309746069/ManifestAmbiguity
int main(int argc, char *argv[])
{
    struct options_t *g_opts;
	FILE *fp;
	char *inbuf;
	size_t insize;
	char *outbuf;
	size_t outsize;
	int ret;
	const char *target_filename;
	/* 处理命令行 */
	g_opts = handle_arguments(argc, argv);
	if (!g_opts) {
		/* 失败 */
		usage();
		return -1;
	}

	/* 处理命令行 */
	if (g_opts->help) {
		show_help();
		return 0;
	}
	if (g_opts->version) {
		show_version();
		return 0;
	}

	target_filename = g_opts->target_file;
	fp = fopen(target_filename, "rb");
	if(fp == NULL)
	{
		fprintf(stderr, "Error: open input file failed.\n");
		return -1;
	}

	fseek(fp, 0, SEEK_END);
	insize = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	inbuf = (char *)malloc(insize * sizeof(char));
	if(inbuf == NULL)
	{
		fprintf(stderr, "Error: init file buffer.\n");
		fclose(fp);
		return -1;
	}

	ret = fread(inbuf, 1, insize, fp);
	if(ret != insize)
	{
		fprintf(stderr, "Error: read file.\n");
		free(inbuf);
		fclose(fp);
		return -1;
	}
	//无论是读取还是修改xml都需要先分析目标xml
	ret = AxmlToXml(&outbuf, &outsize, inbuf, insize);
	if(ret < 0){
		fprintf(stderr, "Error: parse file.\n");
		return -1;
	}
	if(g_opts->parserXml){
        printf("%s", outbuf);
        return 0;
	}
	if(g_opts->modifyXml){
        ret = axmlModify(inbuf, insize, g_opts->output_file);
        if(ret < 0){
		    fprintf(stderr, "Error: modify file.\n");
		    return -1;
	    }
	}
	free(outbuf);
	free(inbuf);
	fclose(fp);

	return ret;
}
コード例 #10
0
ファイル: charon-cmd.c プロジェクト: netklass/strongswan
/**
 * Main function, starts the daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	struct utsname utsname;
	int group;

	/* handle simple arguments */
	handle_arguments(argc, argv, TRUE);

	dbg = dbg_stderr;
	atexit(library_deinit);
	if (!library_init(NULL, "charon-cmd"))
	{
		exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
	}
	if (lib->integrity)
	{
		if (!lib->integrity->check_file(lib->integrity, "charon-cmd", argv[0]))
		{
			exit(SS_RC_DAEMON_INTEGRITY);
		}
	}
	atexit(libhydra_deinit);
	if (!libhydra_init())
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	atexit(libcharon_deinit);
	if (!libcharon_init())
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	for (group = 0; group < DBG_MAX; group++)
	{
		levels[group] = default_loglevel;
	}
	charon->load_loggers(charon, levels, TRUE);

	if (!lookup_uid_gid())
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	lib->settings->set_default_str(lib->settings, "charon-cmd.port", "0");
	lib->settings->set_default_str(lib->settings, "charon-cmd.port_nat_t", "0");
	if (!charon->initialize(charon,
			lib->settings->get_str(lib->settings, "charon-cmd.load", PLUGINS)))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}
	if (!lib->caps->drop(lib->caps))
	{
		exit(SS_RC_INITIALIZATION_FAILED);
	}

	conn = cmd_connection_create();
	atexit(cleanup_conn);
	creds = cmd_creds_create();
	atexit(cleanup_creds);

	/* handle all arguments */
	handle_arguments(argc, argv, FALSE);

	if (uname(&utsname) != 0)
	{
		memset(&utsname, 0, sizeof(utsname));
	}
	DBG1(DBG_DMN, "Starting charon-cmd IKE client (strongSwan %s, %s %s, %s)",
		 VERSION, utsname.sysname, utsname.release, utsname.machine);
	lib->plugins->status(lib->plugins, LEVEL_CTRL);

	/* add handler for SEGV and ILL,
	 * INT, TERM and HUP are handled by sigwait() in run() */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaddset(&action.sa_mask, SIGUSR1);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);

	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start daemon with thread-pool */
	charon->start(charon);
	/* wait for signal */
	return run();
}
コード例 #11
0
ファイル: server.c プロジェクト: dugword/mmorpg
int main(int argc, char *argv[])
{
    struct server_settings settings = {30000, 0, 1};
    handle_arguments(argc, argv, &settings);

    struct player_character hero;
    init_player_character(&hero);

    char stat_buffer[256];

    randomize_player_character_stats(&hero);
    snprintf(stat_buffer, 255, "STR - %i\r\nDEX - %i\r\nCON - %i\r\n", hero.strength, hero.dexterity, hero.constitution);

    if (catch_signal(SIGINT, handle_shutdown) == -1) {
        error("Can't set the interrupt handler");
    } else if (settings.verbose) {
        puts("Interrupt handler set");
    }

    listener_d = open_listener_socket();
    bind_to_port(listener_d, settings.port_number);

    if (listen(listener_d, 10) == -1) {
        error("Can't listen");
    } else if (settings.verbose) {
        printf("Listening on port %i", settings.port_number);
    }

    struct sockaddr_storage client_addr;
    unsigned int address_size = sizeof(client_addr);
    if (settings.verbose) {
        puts("Waiting for connection");
    }

    while(1) {
        int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &address_size);
        if (connect_d == -1) {
            error("Can't open secondary socket");
        } else if (settings.verbose) {
            puts("New connection started");
        }

        if (!fork()) {
            close(listener_d); char input_buffer[512];
            char output_buffer[512];
            char send_buffer[512];
            char action_buffer[3];
            

            send_version(connect_d);

            while (1) {
                get_command(connect_d, action_buffer);
                puts(action_buffer);
                if (action_buffer[0] == 's') {
                    puts("opening chat buffer");
                    listen_to_client(connect_d, input_buffer);
                    parse_command(input_buffer, output_buffer);
                    sprintf(send_buffer, "You said: \"%s\"\r\n", output_buffer);
                    puts(send_buffer);
                    send_to_client(connect_d, send_buffer);
                } else {
                    handle_user_command(connect_d, action_buffer);
                }
            }

            close(connect_d);
            exit(0);
        }
        close(connect_d);
    }

    return 0;
}
コード例 #12
0
// *****************************************************
// main
// *****************************************************
int main( int argc, char **argv )
{
    // polysync return status
    int ret = DTC_NONE;

    // node reference
    ps_node_ref node_ref = PSYNC_NODE_REF_INVALID;

    ps_msg_type rsp_msg_type = PSYNC_MSG_TYPE_INVALID;


    // getopt return
    int optret = 0;

    // no-arguments
    const int GETOP_NOARG_FLAG = (int) '?';


    // look for 'h' first, we don't need to initialize a node if we're just showing help message
    while( (optret = getopt( argc, argv, GETOPT_STRING )) != -1 )
    {
        // check for option character
        if( optret == 'h' )
        {
            // show notes
            printf( "\nIt is recommended to use a relative start time of at least 5,000,000 (5 seconds)\n"
                    "to allow all nodes to handle the commands without looking for their status messages.\n" );

            //  show usage
            printf( "\nusage\n $%s [options]\n", NODE_NAME );
            printf( " $%s -h (options/help)\n", NODE_NAME );
            printf( "\n" );

            // show options help
            printf( "options\n" );
            printf( "(default: send command to start replay logfile session)\n" );
            printf( " -q\t\tsend command to release (quit) logfile session\n" );
            printf( " -w\t\tsend command to start a record (instead of replay) logfile session\n" );
            printf( " -e\t\tsend command to enumerate all available RnR sessions\n" );
            printf( " -E\t\tdisplay the local RnR sessions using the RnR API\n" );
            printf( " -t <N>\t\tset the session identifier to use\n" );
            printf( " -s <N>\t\tset relative start time [microseconds]\n" );
            printf( " -S <N>\t\tset absolute UTC start time, takes precedence over relative [microseconds]\n" );

            // done
            return 0;
        }
        else if( optret == GETOP_NOARG_FLAG )
        {
            printf( "invalid usage, check help\n" );
            return EXIT_FAILURE;
        }
    }

	// init core API
    ret = psync_init(
            NODE_NAME,
            PSYNC_NODE_TYPE_API_USER,
            PSYNC_DEFAULT_DOMAIN,
            PSYNC_SDF_ID_INVALID,
            PSYNC_INIT_FLAG_STDOUT_LOGGING,
            &node_ref );

    // error check
    if( ret != DTC_NONE )
    {
        psync_log_message(
                LOG_LEVEL_ERROR,
                "%s : (%u) -- psync_init returned DTC %d",
                __FILE__,
                __LINE__,
                ret );

        return EXIT_FAILURE;
    }

    // get response message type
     ret = psync_message_get_type_by_name(
             node_ref,
             RESPONSE_MSG_NAME,
             &rsp_msg_type );

     if( ret != DTC_NONE )
     {
         psync_log_error( "psync_message_get_type_by_name - ret: %d", ret );
         return EXIT_FAILURE;
     }

    // set response message subscriber QoS to reliable
    ret = psync_node_set_subscriber_reliability_qos(
            node_ref,
            rsp_msg_type,
            RELIABILITY_QOS_RELIABLE );

    if( ret != DTC_NONE )
    {
        psync_log_error( "psync_node_set_subscriber_reliability_qos - ret: %d", ret );
        return EXIT_FAILURE;
    }

    // register a listener for response messages
    ret = psync_message_register_listener(
            node_ref,
            rsp_msg_type,
            &ps_response_msg_handler,
            node_ref );

    if( ret != DTC_NONE )
    {
        psync_log_error( "psync_message_register_listener - ret: %d", ret );
        return EXIT_FAILURE;
    }

    // process arguments
    handle_arguments( node_ref, argc, argv );

    // release core API
    ret = psync_release( &node_ref );

    // error check
    if( ret != DTC_NONE )
    {
        psync_log_message(
                LOG_LEVEL_ERROR,
                "%s : (%u) -- psync_release returned DTC %d",
                __FILE__,
                __LINE__,
                ret );
    }


	return EXIT_SUCCESS;
}
コード例 #13
0
int main (int argc, char ** argv)
{
  handle_arguments (argc, argv);

  mk::KnowledgeRecord truthy (mk::KnowledgeRecord::Integer (42));
  mk::KnowledgeRecord falsey (mk::KnowledgeRecord::Integer (0));
  mk::KnowledgeRecord struthy ("true");
  mk::KnowledgeRecord sfalsey ("");

  if(truthy)
  {
    std::cout << "SUCCESS  truthy is true" << std::endl;
  }
  else
  {
    std::cout << "ERROR    truthy is false" << std::endl;
  }

  if(falsey)
  {
    std::cout << "ERROR    falsey is true" << std::endl;
  }
  else
  {
    std::cout << "SUCCESS  falsey is false" << std::endl;
  }

  if(truthy && struthy)
  {
    std::cout << "SUCCESS  truthy && struthy is true" << std::endl;
  }
  else
  {
    std::cout << "ERROR    truthy && struthy is false" << std::endl;
  }

  if(truthy && sfalsey)
  {
    std::cout << "ERROR    truthy && sfalsey is true" << std::endl;
  }
  else
  {
    std::cout << "SUCCESS  truthy && sfalsey is false" << std::endl;
  }

  if(truthy || struthy)
  {
    std::cout << "SUCCESS  truthy || sfalsey is true" << std::endl;
  }
  else
  {
    std::cout << "ERROR    truthy || sfalsey is false" << std::endl;
  }

  // These lines compile OK, and work as expected:
  bool bool_false = falsey;
  bool bool_true = truthy;

  if(bool_true)
  {
    std::cout << "SUCCESS  bool_true is true" << std::endl;
  }
  else
  {
    std::cout << "ERROR    bool_true is false" << std::endl;
  }

  if(bool_false)
  {
    std::cout << "ERROR    bool_false is true" << std::endl;
  }
  else
  {
    std::cout << "SUCCESS  bool_false is false" << std::endl;
  }

  // The following lines should cause compile errors if uncommented:

  // naive operator bool() would compile the following:
  //int bad_int = truthy; // bad_int would unexpectedly have 1, not 42
  //int bad_shift = truthy << 3;

  // naive Safe Bool returning void* would compile the following:
  //delete truthy;

  return 0;
}
コード例 #14
0
ファイル: main.c プロジェクト: domsom/nm-applet-ds
int
main (int argc, char *argv[])
{
	GOptionContext *opt_ctx;
	GError *error = NULL;
	NMConnectionList *list;
	DBusGConnection *bus;
	char *type = NULL;
	gboolean create = FALSE;
	gboolean show = FALSE;
	gboolean success;
	char *uuid = NULL;
	NMCEService *service = NULL;
	DBusGProxy *proxy = NULL;
	gboolean show_list;

	GOptionEntry entries[] = {
		{ ARG_TYPE,   0, 0, G_OPTION_ARG_STRING, &type,   "Type of connection to show or create", NM_SETTING_WIRED_SETTING_NAME },
		{ ARG_CREATE, 0, 0, G_OPTION_ARG_NONE,   &create, "Create a new connection", NULL },
		{ ARG_SHOW,   0, 0, G_OPTION_ARG_NONE,   &show,   "Show a given connection type page", NULL },
		{ "edit",     0, 0, G_OPTION_ARG_STRING, &uuid,   "Edit an existing connection with a given UUID", "UUID" },
		{ NULL }
	};

	bindtextdomain (GETTEXT_PACKAGE, NMALOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	gtk_init (&argc, &argv);
	textdomain (GETTEXT_PACKAGE);

	opt_ctx = g_option_context_new (NULL);
	g_option_context_set_summary (opt_ctx, "Allows users to view and edit network connection settings");
	g_option_context_add_main_entries (opt_ctx, entries, NULL);
	success = g_option_context_parse (opt_ctx, &argc, &argv, &error);
	g_option_context_free (opt_ctx);

	if (!success) {
		g_warning ("%s\n", error->message);
		g_error_free (error);
		return 1;
	}

	/* Just one page for both CDMA & GSM, handle that here */
	if (type && g_strcmp0 (type, NM_SETTING_CDMA_SETTING_NAME) == 0)
		type = (char *) NM_SETTING_GSM_SETTING_NAME;

	/* Inits the dbus-glib type system too */
	bus = dbus_g_bus_get (DBUS_BUS_SESSION, NULL);
	if (bus) {
		proxy = dbus_g_proxy_new_for_name (bus,
		                                   "org.freedesktop.DBus",
		                                   "/org/freedesktop/DBus",
		                                   "org.freedesktop.DBus");
		g_assert (proxy);

		/* Check for an existing instance on the bus, and if there
		 * is one, send the arguments to it and exit instead of opening
		 * a second instance of the connection editor.
		 */
		if (try_existing_instance (bus, proxy, type, create, show, uuid))
			return 0;
	}

	loop = g_main_loop_new (NULL, FALSE);

	list = nm_connection_list_new ();
	if (!list) {
		g_warning ("Failed to initialize the UI, exiting...");
		return 1;
	}
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	/* Create our single-instance-app service if we can */
	if (proxy)
		service = nm_ce_service_new (bus, proxy, list);

	/* Show the dialog */
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	/* Figure out what page or editor window we'll show initially */
	show_list = handle_arguments (list, type, create, show, uuid, (create || show || uuid));
	if (show_list)
		nm_connection_list_present (list);

	setup_signals ();
	g_main_loop_run (loop);

	/* Cleanup */
	g_object_unref (list);
	if (service)
		g_object_unref (service);
	if (proxy)
		g_object_unref (proxy);
	if (bus)
		dbus_g_connection_unref (bus);
	return 0;
}
コード例 #15
0
ファイル: main.c プロジェクト: bernied/mutti
int
main(int argc, char** argv)
{
  int result;
  struct stat sb;
  char* file_name;
  char name[100] = "permutation";
  int len = strlen(name);
  uint32* histogram =NULL;
  uint32 gs, hgs;

  // Handle arguments
  convert_card_permutation(args.u, args.i); // LAMb: calculate hi/low from args!
  file_name = handle_arguments(argc, argv, &args);

  int size = args.s;
  uint32* permutation;
  uint32* graph = alloc_graph(size);
  gs = GRAPH_SIZE(size);
  hgs = gs + 1;

  if (args.i || args.a) {
    histogram = (uint32*) calloc(hgs, sizeof(uint32));
  }

  if (args.p)
  {
    permutation = alloc_permutation(size, false);
    str_to_permutation(args.p, permutation, false);
    if (args._2)
    {
      uint32* p2 = alloc_permutation(size, false);
      str_to_permutation(args._2, p2, false);
      apply_permutation(p2, permutation);
      free(p2);
    }

    map_perm_to_graph(permutation, graph);
    if (args.d) {
      graph_to_dot(graph, permutation, name, args.c, args.e);
    }
    if (histogram) {
      count_edges(graph, histogram, size);
    }
  }
  else if (args.l <= 0)
  {
    if (size > 7) {
      error("Can not generate more then 7! files.");
    }
    permutation = alloc_permutation(size, true);
    uint32 numPerms = factorial(size);
    for (int i=0; i < numPerms; i++)
    {
      map_perm_to_graph(permutation, graph);
      if (args.d) {
        graph_to_dot(graph, permutation, make_name(name, i), args.c, args.e);
      }
      if (histogram) {
        count_edges(graph, histogram, size);
      }
      name[len] = '\0';
      lex_permute(permutation+1, size);
    }
  }
  else
  {
    permutation = alloc_permutation(size, true);
    uint32 numPerms = factorial(size);
    for (int i=0; i < numPerms; i++)
    {
      if (i == args.l)
      {
        map_perm_to_graph(permutation, graph);
        if (args.d) {
          graph_to_dot(graph, permutation, make_name(name, i), args.c, args.e);
        }
        name[len] = '\0';
        break;
      }
      lex_permute(permutation+1, size);
    }
  }

  if (args.i)
  {
    for (int i=0; i < hgs; i++) {
      printf("%i\t", i);
    }
    printf("\n");
    for (int i=0; i < hgs; i++) {
      printf("%i\t", histogram[i]);
    }
    printf("\n");
  }

  if (args.a)
  {
    uint64 sum =0, count =0;
    for (int i=0; i < hgs; i++) {
      sum += histogram[i] * i;
      count += histogram[i];
    }
    double d = sum / (double) count;
    printf("average: %llu, %llu, %f\n", sum, count, d);
  }

  if (histogram) free(histogram);
  free(permutation);
  free(graph);
  exit(result);
}
コード例 #16
0
ファイル: main.c プロジェクト: atulhjp/network-manager-applet
int
main (int argc, char *argv[])
{
	GOptionContext *opt_ctx = NULL;
	GError *error = NULL;
	NMConnectionList *list = NULL;
	guint owner_id = 0, registration_id = 0;
	GDBusConnection *bus = NULL;
	gs_free char *type = NULL, *uuid = NULL, *import = NULL;
	gboolean create = FALSE, show = FALSE;
	int ret = 1;

	GOptionEntry entries[] = {
		{ ARG_TYPE,   't', 0, G_OPTION_ARG_STRING, &type,   "Type of connection to show or create", NM_SETTING_WIRED_SETTING_NAME },
		{ ARG_CREATE, 'c', 0, G_OPTION_ARG_NONE,   &create, "Create a new connection", NULL },
		{ ARG_SHOW,   's', 0, G_OPTION_ARG_NONE,   &show,   "Show a given connection type page", NULL },
		{ "edit",     'e', 0, G_OPTION_ARG_STRING, &uuid,   "Edit an existing connection with a given UUID", "UUID" },
		{ ARG_IMPORT, 'i', 0, G_OPTION_ARG_STRING, &import, "Import a VPN connection from given file", NULL },

		/* This is not passed over D-Bus. */
		{ "keep-above", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &nm_ce_keep_above, NULL, NULL },
		{ NULL }
	};

	bindtextdomain (GETTEXT_PACKAGE, NMALOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	gtk_init (&argc, &argv);
	textdomain (GETTEXT_PACKAGE);

	opt_ctx = g_option_context_new (NULL);
	g_option_context_set_summary (opt_ctx, "Allows users to view and edit network connection settings");
	g_option_context_add_main_entries (opt_ctx, entries, NULL);
	if (!g_option_context_parse (opt_ctx, &argc, &argv, &error)) {
		g_printerr ("Failed to parse options: %s\n", error->message);
		goto out;
	}

	/* Just one page for both CDMA & GSM, handle that here */
	if (g_strcmp0 (type, NM_SETTING_CDMA_SETTING_NAME) == 0) {
		g_free (type);
		type = g_strdup (NM_SETTING_GSM_SETTING_NAME);
	}

	bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
	if (bus) {
		/* Check for an existing instance on the bus, and if there
		 * is one, send the arguments to it and exit instead of opening
		 * a second instance of the connection editor.
		 */
		if (try_existing_instance (bus, type, create, show, uuid, import)) {
			/* success */
			ret = 0;
			goto out;
		}
	}

	loop = g_main_loop_new (NULL, FALSE);

	list = nm_connection_list_new ();
	if (!list) {
		g_warning ("Failed to initialize the UI, exiting...");
		goto out;
	}
	g_signal_connect_swapped (list, "done", G_CALLBACK (g_main_loop_quit), loop);

	owner_id = start_service (bus, list, &registration_id);

	/* Figure out what page or editor window we'll show initially */
	if (handle_arguments (list, type, create, show, uuid, import, (create || show || uuid || import)))
		nm_connection_list_present (list);

	g_unix_signal_add (SIGTERM, signal_handler, GINT_TO_POINTER (SIGTERM));
	g_unix_signal_add (SIGINT, signal_handler, GINT_TO_POINTER (SIGINT));

	g_main_loop_run (loop);
	ret = 0;

out:
	if (owner_id)
		g_bus_unown_name (owner_id);
	if (registration_id)
		g_dbus_connection_unregister_object (bus, registration_id);
	if (introspection_data)
		g_dbus_node_info_unref (introspection_data);
	g_clear_error (&error);
	if (opt_ctx)
		g_option_context_free (opt_ctx);
	g_clear_object (&list);
	g_clear_object (&bus);
	return ret;
}