Search Results

Search found 417 results on 17 pages for 'sb chatterjee'.

Page 12/17 | < Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Why should main() be short?

    - by Stargazer712
    I've been programming for over 9 years, and according to the advice of my first programming teacher, I always keep my main() function extremely short. At first I had no idea why. I just obeyed without understanding, much to the delight of my professors. After gaining experience, I realized that if I designed my code correctly, having a short main() function just sortof happened. Writing modularized code and following the single responsibility principle allowed my code to be designed in "bunches", and main() served as nothing more than a catalyst to get the program running. Fast forward to a few weeks ago, I was looking at Python's souce code, and I found the main() function: /* Minimal main program -- everything is loaded from the library */ ... int main(int argc, char **argv) { ... return Py_Main(argc, argv); } Yay Python. Short main() function == Good code. Programming teachers were right. Wanting to look deeper, I took a look at Py_Main. In its entirety, it is defined as follows: /* Main program */ int Py_Main(int argc, char **argv) { int c; int sts; char *command = NULL; char *filename = NULL; char *module = NULL; FILE *fp = stdin; char *p; int unbuffered = 0; int skipfirstline = 0; int stdin_is_interactive = 0; int help = 0; int version = 0; int saw_unbuffered_flag = 0; PyCompilerFlags cf; cf.cf_flags = 0; orig_argc = argc; /* For Py_GetArgcArgv() */ orig_argv = argv; #ifdef RISCOS Py_RISCOSWimpFlag = 0; #endif PySys_ResetWarnOptions(); while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { if (c == 'c') { /* -c is the last option; following arguments that look like options are left for the command to interpret. */ command = (char *)malloc(strlen(_PyOS_optarg) + 2); if (command == NULL) Py_FatalError( "not enough memory to copy -c argument"); strcpy(command, _PyOS_optarg); strcat(command, "\n"); break; } if (c == 'm') { /* -m is the last option; following arguments that look like options are left for the module to interpret. */ module = (char *)malloc(strlen(_PyOS_optarg) + 2); if (module == NULL) Py_FatalError( "not enough memory to copy -m argument"); strcpy(module, _PyOS_optarg); break; } switch (c) { case 'b': Py_BytesWarningFlag++; break; case 'd': Py_DebugFlag++; break; case '3': Py_Py3kWarningFlag++; if (!Py_DivisionWarningFlag) Py_DivisionWarningFlag = 1; break; case 'Q': if (strcmp(_PyOS_optarg, "old") == 0) { Py_DivisionWarningFlag = 0; break; } if (strcmp(_PyOS_optarg, "warn") == 0) { Py_DivisionWarningFlag = 1; break; } if (strcmp(_PyOS_optarg, "warnall") == 0) { Py_DivisionWarningFlag = 2; break; } if (strcmp(_PyOS_optarg, "new") == 0) { /* This only affects __main__ */ cf.cf_flags |= CO_FUTURE_DIVISION; /* And this tells the eval loop to treat BINARY_DIVIDE as BINARY_TRUE_DIVIDE */ _Py_QnewFlag = 1; break; } fprintf(stderr, "-Q option should be `-Qold', " "`-Qwarn', `-Qwarnall', or `-Qnew' only\n"); return usage(2, argv[0]); /* NOTREACHED */ case 'i': Py_InspectFlag++; Py_InteractiveFlag++; break; /* case 'J': reserved for Jython */ case 'O': Py_OptimizeFlag++; break; case 'B': Py_DontWriteBytecodeFlag++; break; case 's': Py_NoUserSiteDirectory++; break; case 'S': Py_NoSiteFlag++; break; case 'E': Py_IgnoreEnvironmentFlag++; break; case 't': Py_TabcheckFlag++; break; case 'u': unbuffered++; saw_unbuffered_flag = 1; break; case 'v': Py_VerboseFlag++; break; #ifdef RISCOS case 'w': Py_RISCOSWimpFlag = 1; break; #endif case 'x': skipfirstline = 1; break; /* case 'X': reserved for implementation-specific arguments */ case 'U': Py_UnicodeFlag++; break; case 'h': case '?': help++; break; case 'V': version++; break; case 'W': PySys_AddWarnOption(_PyOS_optarg); break; /* This space reserved for other options */ default: return usage(2, argv[0]); /*NOTREACHED*/ } } if (help) return usage(0, argv[0]); if (version) { fprintf(stderr, "Python %s\n", PY_VERSION); return 0; } if (Py_Py3kWarningFlag && !Py_TabcheckFlag) /* -3 implies -t (but not -tt) */ Py_TabcheckFlag = 1; if (!Py_InspectFlag && (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') Py_InspectFlag = 1; if (!saw_unbuffered_flag && (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') unbuffered = 1; if (!Py_NoUserSiteDirectory && (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') Py_NoUserSiteDirectory = 1; if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { char *buf, *warning; buf = (char *)malloc(strlen(p) + 1); if (buf == NULL) Py_FatalError( "not enough memory to copy PYTHONWARNINGS"); strcpy(buf, p); for (warning = strtok(buf, ","); warning != NULL; warning = strtok(NULL, ",")) PySys_AddWarnOption(warning); free(buf); } if (command == NULL && module == NULL && _PyOS_optind < argc && strcmp(argv[_PyOS_optind], "-") != 0) { #ifdef __VMS filename = decc$translate_vms(argv[_PyOS_optind]); if (filename == (char *)0 || filename == (char *)-1) filename = argv[_PyOS_optind]; #else filename = argv[_PyOS_optind]; #endif } stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); if (unbuffered) { #if defined(MS_WINDOWS) || defined(__CYGWIN__) _setmode(fileno(stdin), O_BINARY); _setmode(fileno(stdout), O_BINARY); #endif #ifdef HAVE_SETVBUF setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); #else /* !HAVE_SETVBUF */ setbuf(stdin, (char *)NULL); setbuf(stdout, (char *)NULL); setbuf(stderr, (char *)NULL); #endif /* !HAVE_SETVBUF */ } else if (Py_InteractiveFlag) { #ifdef MS_WINDOWS /* Doesn't have to have line-buffered -- use unbuffered */ /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); #else /* !MS_WINDOWS */ #ifdef HAVE_SETVBUF setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); #endif /* HAVE_SETVBUF */ #endif /* !MS_WINDOWS */ /* Leave stderr alone - it should be unbuffered anyway. */ } #ifdef __VMS else { setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); } #endif /* __VMS */ #ifdef __APPLE__ /* On MacOS X, when the Python interpreter is embedded in an application bundle, it gets executed by a bootstrapping script that does os.execve() with an argv[0] that's different from the actual Python executable. This is needed to keep the Finder happy, or rather, to work around Apple's overly strict requirements of the process name. However, we still need a usable sys.executable, so the actual executable path is passed in an environment variable. See Lib/plat-mac/bundlebuiler.py for details about the bootstrap script. */ if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') Py_SetProgramName(p); else Py_SetProgramName(argv[0]); #else Py_SetProgramName(argv[0]); #endif Py_Initialize(); if (Py_VerboseFlag || (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { fprintf(stderr, "Python %s on %s\n", Py_GetVersion(), Py_GetPlatform()); if (!Py_NoSiteFlag) fprintf(stderr, "%s\n", COPYRIGHT); } if (command != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ _PyOS_optind--; argv[_PyOS_optind] = "-c"; } if (module != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' so that PySys_SetArgv correctly sets sys.path[0] to '' rather than looking for a file called "-m". See tracker issue #8202 for details. */ _PyOS_optind--; argv[_PyOS_optind] = "-c"; } PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && isatty(fileno(stdin))) { PyObject *v; v = PyImport_ImportModule("readline"); if (v == NULL) PyErr_Clear(); else Py_DECREF(v); } if (command) { sts = PyRun_SimpleStringFlags(command, &cf) != 0; free(command); } else if (module) { sts = RunModule(module, 1); free(module); } else { if (filename == NULL && stdin_is_interactive) { Py_InspectFlag = 0; /* do exit on SystemExit */ RunStartupFile(&cf); } /* XXX */ sts = -1; /* keep track of whether we've already run __main__ */ if (filename != NULL) { sts = RunMainFromImporter(filename); } if (sts==-1 && filename!=NULL) { if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n", argv[0], filename, errno, strerror(errno)); return 2; } else if (skipfirstline) { int ch; /* Push back first newline so line numbers remain the same */ while ((ch = getc(fp)) != EOF) { if (ch == '\n') { (void)ungetc(ch, fp); break; } } } { /* XXX: does this work on Win/Win64? (see posix_fstat) */ struct stat sb; if (fstat(fileno(fp), &sb) == 0 && S_ISDIR(sb.st_mode)) { fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename); fclose(fp); return 1; } } } if (sts==-1) { /* call pending calls like signal handlers (SIGINT) */ if (Py_MakePendingCalls() == -1) { PyErr_Print(); sts = 1; } else { sts = PyRun_AnyFileExFlags( fp, filename == NULL ? "<stdin>" : filename, filename != NULL, &cf) != 0; } } } /* Check this environment variable at the end, to give programs the * opportunity to set it from Python. */ if (!Py_InspectFlag && (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') { Py_InspectFlag = 1; } if (Py_InspectFlag && stdin_is_interactive && (filename != NULL || command != NULL || module != NULL)) { Py_InspectFlag = 0; /* XXX */ sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0; } Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */ #endif #ifdef __INSURE__ /* Insure++ is a memory analysis tool that aids in discovering * memory leaks and other memory problems. On Python exit, the * interned string dictionary is flagged as being in use at exit * (which it is). Under normal circumstances, this is fine because * the memory will be automatically reclaimed by the system. Under * memory debugging, it's a huge source of useless noise, so we * trade off slower shutdown for less distraction in the memory * reports. -baw */ _Py_ReleaseInternedStrings(); #endif /* __INSURE__ */ return sts; } Good God Almighty...it is big enough to sink the Titanic. It seems as though Python did the "Intro to Programming 101" trick and just moved all of main()'s code to a different function called it something very similar to "main". Here's my question: Is this code terribly written, or are there other reasons reasons to have a short main function? As it stands right now, I see absolutely no difference between doing this and just moving the code in Py_Main() back into main(). Am I wrong in thinking this?

    Read the article

  • Why should main() be short?

    - by Stargazer712
    I've been programming for over 9 years, and according to the advice of my first programming teacher, I always keep my main() function extremely short. At first I had no idea why. I just obeyed without understanding, much to the delight of my professors. After gaining experience, I realized that if I designed my code correctly, having a short main() function just sortof happened. Writing modularized code and following the single responsibility principle allowed my code to be designed in "bunches", and main() served as nothing more than a catalyst to get the program running. Fast forward to a few weeks ago, I was looking at Python's souce code, and I found the main() function: /* Minimal main program -- everything is loaded from the library */ ... int main(int argc, char **argv) { ... return Py_Main(argc, argv); } Yay python. Short main() function == Good code. Programming teachers were right. Wanting to look deeper, I took a look at Py_Main. In its entirety, it is defined as follows: /* Main program */ int Py_Main(int argc, char **argv) { int c; int sts; char *command = NULL; char *filename = NULL; char *module = NULL; FILE *fp = stdin; char *p; int unbuffered = 0; int skipfirstline = 0; int stdin_is_interactive = 0; int help = 0; int version = 0; int saw_unbuffered_flag = 0; PyCompilerFlags cf; cf.cf_flags = 0; orig_argc = argc; /* For Py_GetArgcArgv() */ orig_argv = argv; #ifdef RISCOS Py_RISCOSWimpFlag = 0; #endif PySys_ResetWarnOptions(); while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) { if (c == 'c') { /* -c is the last option; following arguments that look like options are left for the command to interpret. */ command = (char *)malloc(strlen(_PyOS_optarg) + 2); if (command == NULL) Py_FatalError( "not enough memory to copy -c argument"); strcpy(command, _PyOS_optarg); strcat(command, "\n"); break; } if (c == 'm') { /* -m is the last option; following arguments that look like options are left for the module to interpret. */ module = (char *)malloc(strlen(_PyOS_optarg) + 2); if (module == NULL) Py_FatalError( "not enough memory to copy -m argument"); strcpy(module, _PyOS_optarg); break; } switch (c) { case 'b': Py_BytesWarningFlag++; break; case 'd': Py_DebugFlag++; break; case '3': Py_Py3kWarningFlag++; if (!Py_DivisionWarningFlag) Py_DivisionWarningFlag = 1; break; case 'Q': if (strcmp(_PyOS_optarg, "old") == 0) { Py_DivisionWarningFlag = 0; break; } if (strcmp(_PyOS_optarg, "warn") == 0) { Py_DivisionWarningFlag = 1; break; } if (strcmp(_PyOS_optarg, "warnall") == 0) { Py_DivisionWarningFlag = 2; break; } if (strcmp(_PyOS_optarg, "new") == 0) { /* This only affects __main__ */ cf.cf_flags |= CO_FUTURE_DIVISION; /* And this tells the eval loop to treat BINARY_DIVIDE as BINARY_TRUE_DIVIDE */ _Py_QnewFlag = 1; break; } fprintf(stderr, "-Q option should be `-Qold', " "`-Qwarn', `-Qwarnall', or `-Qnew' only\n"); return usage(2, argv[0]); /* NOTREACHED */ case 'i': Py_InspectFlag++; Py_InteractiveFlag++; break; /* case 'J': reserved for Jython */ case 'O': Py_OptimizeFlag++; break; case 'B': Py_DontWriteBytecodeFlag++; break; case 's': Py_NoUserSiteDirectory++; break; case 'S': Py_NoSiteFlag++; break; case 'E': Py_IgnoreEnvironmentFlag++; break; case 't': Py_TabcheckFlag++; break; case 'u': unbuffered++; saw_unbuffered_flag = 1; break; case 'v': Py_VerboseFlag++; break; #ifdef RISCOS case 'w': Py_RISCOSWimpFlag = 1; break; #endif case 'x': skipfirstline = 1; break; /* case 'X': reserved for implementation-specific arguments */ case 'U': Py_UnicodeFlag++; break; case 'h': case '?': help++; break; case 'V': version++; break; case 'W': PySys_AddWarnOption(_PyOS_optarg); break; /* This space reserved for other options */ default: return usage(2, argv[0]); /*NOTREACHED*/ } } if (help) return usage(0, argv[0]); if (version) { fprintf(stderr, "Python %s\n", PY_VERSION); return 0; } if (Py_Py3kWarningFlag && !Py_TabcheckFlag) /* -3 implies -t (but not -tt) */ Py_TabcheckFlag = 1; if (!Py_InspectFlag && (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') Py_InspectFlag = 1; if (!saw_unbuffered_flag && (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') unbuffered = 1; if (!Py_NoUserSiteDirectory && (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0') Py_NoUserSiteDirectory = 1; if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') { char *buf, *warning; buf = (char *)malloc(strlen(p) + 1); if (buf == NULL) Py_FatalError( "not enough memory to copy PYTHONWARNINGS"); strcpy(buf, p); for (warning = strtok(buf, ","); warning != NULL; warning = strtok(NULL, ",")) PySys_AddWarnOption(warning); free(buf); } if (command == NULL && module == NULL && _PyOS_optind < argc && strcmp(argv[_PyOS_optind], "-") != 0) { #ifdef __VMS filename = decc$translate_vms(argv[_PyOS_optind]); if (filename == (char *)0 || filename == (char *)-1) filename = argv[_PyOS_optind]; #else filename = argv[_PyOS_optind]; #endif } stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0); if (unbuffered) { #if defined(MS_WINDOWS) || defined(__CYGWIN__) _setmode(fileno(stdin), O_BINARY); _setmode(fileno(stdout), O_BINARY); #endif #ifdef HAVE_SETVBUF setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ); setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ); #else /* !HAVE_SETVBUF */ setbuf(stdin, (char *)NULL); setbuf(stdout, (char *)NULL); setbuf(stderr, (char *)NULL); #endif /* !HAVE_SETVBUF */ } else if (Py_InteractiveFlag) { #ifdef MS_WINDOWS /* Doesn't have to have line-buffered -- use unbuffered */ /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ); #else /* !MS_WINDOWS */ #ifdef HAVE_SETVBUF setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ); setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ); #endif /* HAVE_SETVBUF */ #endif /* !MS_WINDOWS */ /* Leave stderr alone - it should be unbuffered anyway. */ } #ifdef __VMS else { setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); } #endif /* __VMS */ #ifdef __APPLE__ /* On MacOS X, when the Python interpreter is embedded in an application bundle, it gets executed by a bootstrapping script that does os.execve() with an argv[0] that's different from the actual Python executable. This is needed to keep the Finder happy, or rather, to work around Apple's overly strict requirements of the process name. However, we still need a usable sys.executable, so the actual executable path is passed in an environment variable. See Lib/plat-mac/bundlebuiler.py for details about the bootstrap script. */ if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') Py_SetProgramName(p); else Py_SetProgramName(argv[0]); #else Py_SetProgramName(argv[0]); #endif Py_Initialize(); if (Py_VerboseFlag || (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) { fprintf(stderr, "Python %s on %s\n", Py_GetVersion(), Py_GetPlatform()); if (!Py_NoSiteFlag) fprintf(stderr, "%s\n", COPYRIGHT); } if (command != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' */ _PyOS_optind--; argv[_PyOS_optind] = "-c"; } if (module != NULL) { /* Backup _PyOS_optind and force sys.argv[0] = '-c' so that PySys_SetArgv correctly sets sys.path[0] to '' rather than looking for a file called "-m". See tracker issue #8202 for details. */ _PyOS_optind--; argv[_PyOS_optind] = "-c"; } PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind); if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) && isatty(fileno(stdin))) { PyObject *v; v = PyImport_ImportModule("readline"); if (v == NULL) PyErr_Clear(); else Py_DECREF(v); } if (command) { sts = PyRun_SimpleStringFlags(command, &cf) != 0; free(command); } else if (module) { sts = RunModule(module, 1); free(module); } else { if (filename == NULL && stdin_is_interactive) { Py_InspectFlag = 0; /* do exit on SystemExit */ RunStartupFile(&cf); } /* XXX */ sts = -1; /* keep track of whether we've already run __main__ */ if (filename != NULL) { sts = RunMainFromImporter(filename); } if (sts==-1 && filename!=NULL) { if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n", argv[0], filename, errno, strerror(errno)); return 2; } else if (skipfirstline) { int ch; /* Push back first newline so line numbers remain the same */ while ((ch = getc(fp)) != EOF) { if (ch == '\n') { (void)ungetc(ch, fp); break; } } } { /* XXX: does this work on Win/Win64? (see posix_fstat) */ struct stat sb; if (fstat(fileno(fp), &sb) == 0 && S_ISDIR(sb.st_mode)) { fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename); fclose(fp); return 1; } } } if (sts==-1) { /* call pending calls like signal handlers (SIGINT) */ if (Py_MakePendingCalls() == -1) { PyErr_Print(); sts = 1; } else { sts = PyRun_AnyFileExFlags( fp, filename == NULL ? "<stdin>" : filename, filename != NULL, &cf) != 0; } } } /* Check this environment variable at the end, to give programs the * opportunity to set it from Python. */ if (!Py_InspectFlag && (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') { Py_InspectFlag = 1; } if (Py_InspectFlag && stdin_is_interactive && (filename != NULL || command != NULL || module != NULL)) { Py_InspectFlag = 0; /* XXX */ sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0; } Py_Finalize(); #ifdef RISCOS if (Py_RISCOSWimpFlag) fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */ #endif #ifdef __INSURE__ /* Insure++ is a memory analysis tool that aids in discovering * memory leaks and other memory problems. On Python exit, the * interned string dictionary is flagged as being in use at exit * (which it is). Under normal circumstances, this is fine because * the memory will be automatically reclaimed by the system. Under * memory debugging, it's a huge source of useless noise, so we * trade off slower shutdown for less distraction in the memory * reports. -baw */ _Py_ReleaseInternedStrings(); #endif /* __INSURE__ */ return sts; } Good God Almighty...it is big enough to sink the Titanic. It seems as though Python did the "Intro to Programming 101" trick and just moved all of main()'s code to a different function called it something very similar to "main". Here's my question: Is this code terribly written, or are there other reasons to have a short main function? As it stands right now, I see absolutely no difference between doing this and just moving the code in Py_Main() back into main(). Am I wrong in thinking this?

    Read the article

  • Routing PC-speaker sounds to the sound card

    - by bobobobo
    Well, my computer didn't come with a stock PC speaker I noticed also that laptops tend to not have PC speakers either, but they make bios/beep sounds through their normal speakers. How can I configure my desktop machine to behave that way? I have a SB-XFI card

    Read the article

  • Any game kills my sound

    - by LoopyWolf
    Every time I quit a game such as Braid, Fallout3, AVP all sound on the PC dies (Control Panel No Audio Devices) I installed a new sound card (SB Audigy) and updated to the latest drivers, and it still happens. It happens with steam games and without. Anybody know what's wrong and how I can fix it? I'm on Win XP SP 2

    Read the article

  • Palit GeForce 8800GT 512MB Minimum Power Requirement?

    - by Wesley
    Hi all, I am building a system for a friend. The potential specs are like this so far: ASUS A8N-VM motherboard AMD Athlon 64 3200+ @ 2.0 GHz Any 7200RPM SATA HDD Palit GeForce 8800GT 512MB GDDR3 PCIe One DVD/CD combo drive Creative SB Live! 5.1 sound card I was wondering what wattage of power supply would be able to support this hardware. I had a 350W in mind... would that do? Thanks in advance.

    Read the article

  • How much power supply does a typical PC build need?

    - by Wesley
    I am building a system for a friend. The potential specs are like this so far: ASUS A8N-VM motherboard AMD Athlon 64 3200+ @ 2.0 GHz Any 7200RPM SATA HDD Palit GeForce 8800GT 512MB GDDR3 PCIe One DVD/CD combo drive Creative SB Live! 5.1 sound card I was wondering what wattage of power supply would be able to support this hardware. I had a 350W in mind... would that do?

    Read the article

  • Ubuntu 12.10 - Graphics driver shows Gallium 0.4 instead of intel HD

    - by nlooije
    I have a hybrid Intel/Nvidia system using bumblebee on Ubuntu 12.10 with specs: Clevo W150HR, SB i7-2720qm, 8GB RAM, 128GB Crucial M4 SSD + 500GB HDD It is reported to use software rendering (through Gallium driver) rather than accelerated through the intel HD driver. Reinstalling the intel driver has no effect: sudo apt-get install --reinstall xserver-xorg-video-intel The result is a rather sluggish desktop. Is there any way to blacklist the gallium driver? Or force the intel driver instead? Edit 1 - Ubuntu 12.04 shows the driver as Intel SandyBridge out of the box, but 12.10 does not even after running the above command. Edit 2 - Xorg.0.log shows: (--) intel(0): Integrated Graphics Chipset: Intel(R) Sandybridge Mobile (GT1) (WW) intel(0): Disabling hardware acceleration on this pre-production hardware. Edit 3 - It turns out that SandyBridge rev.7 systems are known to be unstable per this link. Accordingly in the xserver-xorg-video-intel if it detects this rev. it disables it with the warning in above log.

    Read the article

  • Installation taking a very long time

    - by user290522
    I am installing Ubuntu 14.04(32-bit) on my laptop (Compaq Presario V2000), and after about 7 hours, it is still in Congiguring bcmwl-kernel-source (i386) mode. The messages I read are as follows: ubuntu kernel: [22814.858163] ACPI: \_SB_.PCI0.LPC0.LPC0.ACAD: ACPI_NOTIFY_BUS_CHECK event: unsupported with the numbers in the square brackets increasing. I have had Windows XP professional on this laptop, and I am erasing it. I am not sure if I should turn off the laptop, and start all over again. About 4 years ago I installed Ubuntu on this laptop, and that was very fast. The only problem I encountered was my wireless, and could not make it to work, and switched back to Windows. I appreciate any comments regarding this installation taking such a long time.

    Read the article

  • sound stopped working after upgrade to 11.10 on Tuesday 20th March

    - by Hugh Barney
    My sound card stopped working after a set of updates were installed 2 days ago. The sound card is detected, the volume is not muted and the speakers work, I can make the speakers hum if I touch the jack plug lead that normally plugs into the card. hugh@lindisfarne:~$ lspci -v | grep -A7 -i "audio" 07:01.0 Multimedia audio controller: Creative Labs CA0106 Soundblaster Subsystem: Creative Labs SB0570 [SB Audigy SE] Flags: bus master, medium devsel, latency 32, IRQ 16 I/O ports at c000 [size=32] Capabilities: Kernel driver in use: CA0106 Kernel modules: snd-ca0106 I've tried reverting those upgraded packages that look like the could impact the kernal - but to no avail. alsamixer does not have anything muted, I've been though all the sound card debug/troubleshooting pages I can find. Kernal driver is attached. So whats gone pop ? I will boot from CD to check - but I am pretty sure this is a sw and not a hw problem.

    Read the article

  • Headset undetected when plugged in

    - by tough
    I have recently installed Ubuntu 12.04 in my machine which was running windows 7. I have been trying to configure the audio to work exactly as it used to work in Windows but never been able to do so. I have followed this link exactly. I am still not getting the required configuration. aslamixer command shows me with 5 adjustable controls as shown below Master "adjustable" Speaker "adjustable" PCM "adjustable" Front "adjustable" AND Beep "adjustable" Mic Jack Mic In or Lin In S/PDIF OO "in a box" S/PDIF D OO "in a box" S/PDIF P DIGITAL or Analog M It does not detect the headset jack when plugged in. I here mean to say that the sound form the speakers does not go off when I plug in my headset jack. How can I make this working. Some other googling also did not help. I am on Hp Pavilion DV7 machine. The chip is IDT 92HD75B3X5 and the card is HDA ATI SB.

    Read the article

  • Loud and annoying noise on login

    - by searchfgold6789
    I have a PC with Kubuntu 13.10 64-bit on it. The problem is that whenever I log in (automatic log in is enabled), there is a loud double-click noise that sounds from the speakers whether the volume is muted or not. I have two sound cards; the motherboard audio, which is disabled in the BIOS, and the Creative! Labs Sound Blaster X-Fi SB0460, which I have normal speakers plugged into. Does anyone know how to fix this? Relative lspci lines: 00:01.1 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] BeaverCreek HDMI Audio [Radeon HD 6500D and 6400G-6600G series] 02:05.0 Multimedia audio controller: Creative Labs SB X-Fi Using default Phonon backend. (I am not really sure what other information to provide, but will gladly edit in anything upon request.)

    Read the article

  • Regular wireless dropouts on new lenovo T440s in Ubuntu 14.04

    - by user290670
    Over the last 24 hours my wireless has dropped out regularly. I've tested to make sure it isn't my router (my phone and everyone in the house isn't having problems using the wifi). This is a brand-new installation of Ubuntu 14.04 and according to uname I'm running kernel 3.13.0-24-generic. Now, my laptop has an Intel 7260AC dual band wireless card and I've read that Ubuntu has been having trouble with these. I notice that at http://www.intel.com/support/wireless/wlan/sb/CS-034398.htm There are some updated drivers for my kernel version. However I have no idea how to update the kernel to use these drivers instead so that I can see if this will fix it. Can anyone help? These dropouts are really annoying. EDIT: Upgrading to 3.14.6 did not help.

    Read the article

  • XNA Sprite Clipping Incorrectly During Rotation

    - by user1226947
    I'm having a bit of trouble getting my sprites in XNA to draw. Seemingly if you use SpriteBatch to draw then XNA will not draw it if for example (mPosition.X + mSpriteTexture.Width < 0) as it assumes it is offscreen. However, it seems to make this decision before it applies a rotation. This rotation can mean that even though (mPosition.X + mSpriteTexture.Width < 0), some of the sprite is still visible on screen. My question is, is there a way to get it to draw further outside the viewport or temporarily disable sprite clipping during a certain spriteBatch.draw(...)? sb.Draw(mSpriteTexture, mPosition, new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height), Color.White, Globals.VectorToAngle(mOrientation), new Vector2(halfWidth, halfHeight), scale, SpriteEffects.None, 0);

    Read the article

  • Setting Up Audio on a Server Install

    - by tdcrenshaw
    I'm running on a clean install of 10.10 Server edition and have alsa-base, alsa-tools, alsa-utils, alsaplayer, and alsa-firmware-loader installed. At one point I installed pulseaudio, but I have since removed it. I've tried the following lspci | grep audio 00:1f.5 Multimedia audio controller: Intel Corporation 82801DB/DBL/DBM (ICH4/ICH4-L/ICH4-M) AC'97 Audio Controller (rev 01) 01:06.0 Multimedia audio controller: Creative Labs [SB Live! Value] EMU10k1X aplay -l aplay: device_list:235: no soundcards found... alsamixer can not open mixer: No such file or directory When I search for modules with find /lib/modules/`uname -r` | grep snd I do get a list of modules I'm not very experienced with alsa setup, so I'm not sure where to go from here

    Read the article

  • Retrieving Json Array

    - by Rahul Varma
    Hi, I am trying to retrieve the values from the following url: http://rentopoly.com/ajax.php?query=Bo. I want to get the values of all the suggestions to be displayed in a list view one by one. This is how i want to do... public class AlertsAdd { public ArrayList<JSONObject> retrieveJSONArray(String urlString) { String result = queryRESTurl(urlString); ArrayList<JSONObject> ALERTS = new ArrayList<JSONObject>(); if (result != null) { try { JSONObject json = new JSONObject(result); JSONArray alertsArray = json.getJSONArray("suggestions"); for (int a = 0; a < alertsArray.length(); a++) { JSONObject alertitem = alertsArray.getJSONObject(a); ALERTS.add(alertitem); } return ALERTS; } catch (JSONException e) { Log.e("JSON", "There was an error parsing the JSON", e); } } JSONObject myObject = new JSONObject(); try { myObject.put("suggestions",myObject.getJSONArray("suggestions")); ALERTS.add(myObject); } catch (JSONException e1) { Log.e("JSON", "There was an error creating the JSONObject", e1); } return ALERTS; } private String queryRESTurl(String url) { // URLConnection connection; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result = convertStreamToString(instream); instream.close(); return result; } } catch (ClientProtocolException e) { Log.e("REST", "There was a protocol based error", e); } catch (IOException e) { Log.e("REST", "There was an IO Stream related error", e); } return null; } /** * To convert the InputStream to String we use the * BufferedReader.readLine() method. We iterate until the BufferedReader * return null which means there's no more data to read. Each line will * appended to a StringBuilder and returned as String. */ private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } Here's the adapter code... public class AlertsAdapter extends ArrayAdapter<JSONObject> { public AlertsAdapter(Activity activity, List<JSONObject> alerts) { super(activity, 0, alerts); } @Override public View getView(int position, View convertView, ViewGroup parent) { Activity activity = (Activity) getContext(); LayoutInflater inflater = activity.getLayoutInflater(); View rowView = inflater.inflate(R.layout.list_text, null); JSONObject imageAndText = getItem(position); TextView textView = (TextView) rowView.findViewById(R.id.last_build_stat); try { textView.setText((String)imageAndText.get("suggestions")); } catch (JSONException e) { textView.setText("JSON Exception"); } return rowView; } } Here's the logcat... 04-30 13:09:46.656: INFO/ActivityManager(584): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.WorldToyota/.Alerts } 04-30 13:09:50.417: ERROR/JSON(924): There was an error parsing the JSON 04-30 13:09:50.417: ERROR/JSON(924): org.json.JSONException: JSONArray[0] is not a JSONObject. 04-30 13:09:50.417: ERROR/JSON(924): at org.json.JSONArray.getJSONObject(JSONArray.java:268) 04-30 13:09:50.417: ERROR/JSON(924): at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:30) 04-30 13:09:50.417: ERROR/JSON(924): at com.WorldToyota.Alerts.onCreate(Alerts.java:20) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 04-30 13:09:50.417: ERROR/JSON(924): at android.os.Handler.dispatchMessage(Handler.java:99) 04-30 13:09:50.417: ERROR/JSON(924): at android.os.Looper.loop(Looper.java:123) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.main(ActivityThread.java:4203) 04-30 13:09:50.417: ERROR/JSON(924): at java.lang.reflect.Method.invokeNative(Native Method) 04-30 13:09:50.417: ERROR/JSON(924): at java.lang.reflect.Method.invoke(Method.java:521) 04-30 13:09:50.417: ERROR/JSON(924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 04-30 13:09:50.417: ERROR/JSON(924): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 04-30 13:09:50.417: ERROR/JSON(924): at dalvik.system.NativeStart.main(Native Method) 04-30 13:09:50.688: ERROR/JSON(924): There was an error creating the JSONObject 04-30 13:09:50.688: ERROR/JSON(924): org.json.JSONException: JSONObject["suggestions"] not found. 04-30 13:09:50.688: ERROR/JSON(924): at org.json.JSONObject.get(JSONObject.java:287) 04-30 13:09:50.688: ERROR/JSON(924): at org.json.JSONObject.getJSONArray(JSONObject.java:362) 04-30 13:09:50.688: ERROR/JSON(924): at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:41) 04-30 13:09:50.688: ERROR/JSON(924): at com.WorldToyota.Alerts.onCreate(Alerts.java:20) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 04-30 13:09:50.688: ERROR/JSON(924): at android.os.Handler.dispatchMessage(Handler.java:99) 04-30 13:09:50.688: ERROR/JSON(924): at android.os.Looper.loop(Looper.java:123) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.main(ActivityThread.java:4203) 04-30 13:09:50.688: ERROR/JSON(924): at java.lang.reflect.Method.invokeNative(Native Method) 04-30 13:09:50.688: ERROR/JSON(924): at java.lang.reflect.Method.invoke(Method.java:521) 04-30 13:09:50.688: ERROR/JSON(924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 04-30 13:09:50.688: ERROR/JSON(924): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 04-30 13:09:50.688: ERROR/JSON(924): at dalvik.system.NativeStart.main(Native Method) Plz help me parsing this script and displaying the values in list format....

    Read the article

  • Remove redundant xml namespaces from soapenv:Body

    - by drachenstern
    If you can tell me the magic google term that instantly gives me clarification, that would be helpful. Here's the part that's throwing an issue when I try to manually deserialize from a string: xsi:type="ns1:errorObject" xmlns:ns1="http://www.example.org/Version_3.0" xsi:type="ns2:errorObject" xmlns:ns2="http://www.example.org/Version_3.0" xsi:type="ns3:errorObject" xmlns:ns3="http://www.example.org/Version_3.0" Here's how I'm deserializing by hand to test it: (in an aspx.cs page with a label on the front to display the value in that I can verify by reading source) (second block of XML duplicates the first but without the extra namespaces) using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string sourceXml = @"<?xml version=""1.0""?> <InitiateActivityResponse xmlns=""http://www.example.org/Version_3.0""> <InitiateActivityResult> <errorObject errorString=""string 1"" eventTime=""2010-05-21T21:19:15.775Z"" nounType=""Object"" objectID=""object1"" xsi:type=""ns1:errorObject"" xmlns:ns1=""http://www.example.org/Version_3.0"" /> <errorObject errorString=""string 2"" eventTime=""2010-05-21T21:19:15.791Z"" nounType=""Object"" objectID=""object2"" xsi:type=""ns2:errorObject"" xmlns:ns2=""http://www.example.org/Version_3.0"" /> <errorObject errorString=""string 3"" eventTime=""2010-05-21T21:19:15.806Z"" nounType=""Object"" objectID=""object3"" xsi:type=""ns3:errorObject"" xmlns:ns3=""http://www.example.org/Version_3.0"" /> </InitiateActivityResult> </InitiateActivityResponse> "; sourceXml = @"<?xml version=""1.0""?> <InitiateActivityResponse xmlns=""http://www.example.org/Version_3.0""> <InitiateActivityResult> <errorObject errorString=""string 1"" eventTime=""2010-05-21T21:19:15.775Z"" nounType=""Object"" objectID=""object1"" /> <errorObject errorString=""string 2"" eventTime=""2010-05-21T21:19:15.791Z"" nounType=""Object"" objectID=""object2"" /> <errorObject errorString=""string 3"" eventTime=""2010-05-21T21:19:15.806Z"" nounType=""Object"" objectID=""object3"" /> </InitiateActivityResult> </InitiateActivityResponse> "; InitiateActivityResponse fragment = new InitiateActivityResponse(); Type t = typeof( InitiateActivityResponse ); StringBuilder sb = new StringBuilder(); TextWriter textWriter = new StringWriter( sb ); TextReader textReader = new StringReader( sourceXml ); XmlTextReader xmlTextReader = new XmlTextReader( textReader ); XmlSerializer xmlSerializer = new XmlSerializer( t ); object obj = xmlSerializer.Deserialize( xmlTextReader ); fragment = (InitiateActivityResponse)obj; xmlSerializer.Serialize( textWriter, fragment ); //I have a field on my public page that I write to from sb.ToString(); } } Consuming a webservice, I have a class like thus: (all examples foreshortened to as little as possible to show the problem, if boilerplate is missing, my apologies) (this is where I think I want to remove the troublespot) [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute( "code" )] [System.Web.Services.WebServiceBindingAttribute( Name = "MyServerSoapSoapBinding", Namespace = "http://www.example.org/Version_3.0" )] public partial class MyServer : System.Web.Services.Protocols.SoapHttpClientProtocol { public MsgHeader msgHeader { get; set; } public MyServer () { this.Url = "localAddressOmittedOnPurpose"; } [System.Web.Services.Protocols.SoapHeaderAttribute( "msgHeader" )] [System.Web.Services.Protocols.SoapDocumentMethodAttribute( "http://www.example.org/Version_3.0/InitiateActivity", RequestNamespace = "http://www.example.org/Version_3.0", ResponseNamespace = "http://www.example.org/Version_3.0", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped )] [return: System.Xml.Serialization.XmlElementAttribute( "InitiateActivityResponse" )] public InitiateActivityResponse InitiateActivity(string inputVar) { object[] results = Invoke( "InitiateActivity", new object[] { inputVar } ); return ( (InitiateActivityResponse)( results[0] ) ); } } Class descriptions [System.SerializableAttribute] [System.Diagnostics.DebuggerStepThroughAttribute] [System.ComponentModel.DesignerCategoryAttribute( "code" )] [XmlType( Namespace = "http://www.example.org/Version_3.0", TypeName = "InitiateActivityResponse" )] [XmlRoot( Namespace = "http://www.example.org/Version_3.0" )] public class InitiateActivityResponse { [XmlArray( ElementName = "InitiateActivityResult", IsNullable = true )] [XmlArrayItem( ElementName = "errorObject", IsNullable = false )] public errorObject[] errorObject { get; set; } } [System.SerializableAttribute] [System.Diagnostics.DebuggerStepThroughAttribute] [System.ComponentModel.DesignerCategoryAttribute( "code" )] [XmlTypeAttribute( Namespace = "http://www.example.org/Version_3.0" )] public class errorObject { private string _errorString; private System.DateTime _eventTime; private bool _eventTimeSpecified; private string _nounType; private string _objectID; [XmlAttributeAttribute] public string errorString { get { return _errorString; } set { _errorString = value; } } [XmlAttributeAttribute] public System.DateTime eventTime { get { return _eventTime; } set { _eventTime = value; } } [XmlIgnoreAttribute] public bool eventTimeSpecified { get { return _eventTimeSpecified; } set { _eventTimeSpecified = value; } } [XmlAttributeAttribute] public string nounType { get { return _nounType; } set { _nounType = value; } } [XmlAttributeAttribute] public string objectID { get { return _objectID; } set { _objectID = value; } } } SOAP as it's being received (as seen by Fiddler2) <?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <MsgHeader soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" AppName="AppName" AppVersion="1.0" Company="Company" Pwd="" UserID="" xmlns="http://www.example.org/Version_3.0"/> </soapenv:Header> <soapenv:Body> <InitiateActivityResponse xmlns="http://www.example.org/Version_3.0"> <InitiateActivityResult> <errorObject errorString="Explanatory string for request 1" eventTime="2010-05-24T21:21:37.477Z" nounType="Object" objectID="12345" xsi:type="ns1:errorObject" xmlns:ns1="http://www.example.org/Version_3.0"/> <errorObject errorString="Explanatory string for request 2" eventTime="2010-05-24T21:21:37.493Z" nounType="Object" objectID="45678" xsi:type="ns2:errorObject" xmlns:ns2="http://www.example.org/Version_3.0"/> <errorObject errorString="Explanatory string for request 3" eventTime="2010-05-24T21:21:37.508Z" nounType="Object" objectID="98765" xsi:type="ns3:errorObject" xmlns:ns3="http://www.example.org/Version_3.0"/> </InitiateActivityResult> </InitiateActivityResponse> </soapenv:Body> </soapenv:Envelope> Okay, what should I have not omitted? No I won't post the WSDL, it's hosted behind a firewall, for a vertical stack product. No, I can't change the data sender. Is this somehow automagically handled elsewhere and I just don't know what I don't know? I think I want to do some sort of message sink leading into this method, to intercept the soapenv:Body, but obviously this is for errors, so I'm not going to get errors every time. I'm not entirely sure how to handle this, but some pointers would be nice.

    Read the article

  • MIPS: removing non alpha-numeric characters from a string

    - by Kron
    I'm in the process of writing a program in MIPS that will determine whether or not a user entered string is a palindrome. It has three subroutines which are under construction. Here is the main block of code, subroutines to follow with relevant info: .data Buffer: .asciiz " " # 80 bytes in Buffer intro: .asciiz "Hello, please enter a string of up to 80 characters. I will then tell you if that string was a palindrome!" .text main: li $v0, 4 # print_string call number la $a0, intro # pointer to string in memory syscall li $v0, 8 #syscall code for reading string la $a0, Buffer #save read string into buffer li $a1, 80 #string is 80 bytes long syscall li $s0, 0 #i = 0 li $t0, 80 #max for i to reach la $a0, Buffer jal stripNonAlpha li $v0, 4 # print_string call number la $a0, Buffer # pointer to string in memory syscall li $s0, 0 jal findEnd jal toUpperCase li $v0, 4 # print_string call number la $a0, Buffer # pointer to string in memory syscall Firstly, it's supposed to remove all non alpha-numeric characters from the string before hand, but when it encounters a character designated for removal, all characters after that are removed. stripNonAlpha: beq $s0, $t0, stripEnd #if i = 80 end add $t4, $s0, $a0 #address of Buffer[i] in $t4 lb $s1, 0($t4) #load value of Buffer[i] addi $s0, $s0, 1 #i = i + 1 slti $t1, $s1, 48 #if ascii code is less than 48 bne $t1, $zero, strip #remove ascii character slti $t1, $s1, 58 #if ascii code is greater than 57 #and slti $t2, $s1, 65 #if ascii code is less than 65 slt $t3, $t1, $t2 bne $t3, $zero, strip #remove ascii character slti $t1, $s1, 91 #if ascii code is greater than 90 #and slti $t2, $s1, 97 #if ascii code is less than 97 slt $t3, $t1, $t2 bne $t3, $zero, strip #remove ascii character slti $t1, $s1, 123 #if ascii character is greater than 122 beq $t1, $zero, strip #remove ascii character j stripNonAlpha #go to stripNonAlpha strip: #add $t5, $s0, $a0 #address of Buffer[i] in $t5 sb $0, 0($t4) #Buffer[i] = 0 #addi $s0, $s0, 1 #i = i + 1 j stripNonAlpha #go to stripNonAlpha stripEnd: la $a0, Buffer #save modified string into buffer jr $ra #return Secondly, it is supposed to convert all lowercase characters to uppercase. toUpperCase: beq $s0, $s2, upperEnd add $t4, $s0, $a0 lb $s1, 0($t4) addi $s1, $s1, 1 slti $t1, $s1, 97 #beq $t1, $zero, upper slti $t2, $s1, 123 slt $t3, $t1, $t2 bne $t1, $zero, upper j toUpperCase upper: add $t5, $s0, $a0 addi $t6, $t6, -32 sb $t6, 0($t5) j toUpperCase upperEnd: la $a0, Buffer jr $ra The final subroutine, which checks if the string is a palindrome isn't anywhere near complete at the moment. I'm having trouble finding the end of the string because I'm not sure what PC-SPIM uses as the carriage return character. Any help is appreciated, I have the feeling most of my problems result from something silly and stupid so feel free to point out anything, no matter how small.

    Read the article

  • How to configure a Custom Datacontract Serializer or XMLSerializer

    - by user364445
    Im haveing some xml that have this structure <Person Id="*****" Name="*****"> <AccessControlEntries> <AccessControlEntry Id="*****" Name="****"/> </AccessControlEntries> <AccessControls /> <IdentityGroups> <IdentityGroup Id="****" Name="*****" /> </IdentityGroups></Person> and i also have this entities [DataContract(IsReference = true)] public abstract class EntityBase { protected bool serializing; [DataMember(Order = 1)] [XmlAttribute()] public string Id { get; set; } [DataMember(Order = 2)] [XmlAttribute()] public string Name { get; set; } [OnDeserializing()] public void OnDeserializing(StreamingContext context) { this.Initialize(); } [OnSerializing()] public void OnSerializing(StreamingContext context) { this.serializing = true; } [OnSerialized()] public void OnSerialized(StreamingContext context) { this.serializing = false; } public abstract void Initialize(); public string ToXml() { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); } return sb.ToString(); } } [DataContract()] public abstract class Identity : EntityBase { private EntitySet<AccessControlEntry> accessControlEntries; private EntitySet<IdentityGroup> identityGroups; public Identity() { Initialize(); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "AccessControlEntries")] public EntitySet<AccessControlEntry> AccessControlEntries { get { if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false))) { return null; } return accessControlEntries; } set { accessControlEntries.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] [Association(Name = "IdentityGroups")] public EntitySet<IdentityGroup> IdentityGroups { get { if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false))) { return null; } return identityGroups; } set { identityGroups.Assign(value); } } private void attach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Add(this); } private void dettach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Remove(this); } private void attach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } private void dettach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } public override void Initialize() { this.accessControlEntries = new EntitySet<AccessControlEntry>( new Action<AccessControlEntry>(this.attach_accessControlEntry), new Action<AccessControlEntry>(this.dettach_accessControlEntry)); this.identityGroups = new EntitySet<IdentityGroup>( new Action<IdentityGroup>(this.attach_IdentityGroup), new Action<IdentityGroup>(this.dettach_IdentityGroup)); } } [XmlType(TypeName = "AccessControlEntry")] public class AccessControlEntry : EntityBase, INotifyPropertyChanged { private EntitySet<Service> services; private EntitySet<Identity> identities; private EntitySet<Permission> permissions; public AccessControlEntry() { services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service)); identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity)); permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission)); } [DataMember(Order = 3, EmitDefaultValue = false)] public EntitySet<Permission> Permissions { get { if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false))) { return null; } return permissions; } set { permissions.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] public EntitySet<Identity> Identities { get { if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false))) { return null; } return identities; } set { identities.Assign(identities); } } [DataMember(Order = 5, EmitDefaultValue = false)] public EntitySet<Service> Services { get { if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false))) { return null; } return services; } set { services.Assign(value); } } private void attach_Permission(Permission entity) { entity.AccessControlEntires.Add(this); } private void dettach_Permission(Permission entity) { entity.AccessControlEntires.Remove(this); } private void attach_Identity(Identity entity) { entity.AccessControlEntries.Add(this); } private void dettach_Identity(Identity entity) { entity.AccessControlEntries.Remove(this); } private void attach_Service(Service entity) { entity.AccessControlEntries.Add(this); } private void dettach_Service(Service entity) { entity.AccessControlEntries.Remove(this); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } #endregion public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "Person")] public class Person : Identity { private EntityRef<Login> login; [DataMember(Order = 3)] [XmlAttribute()] public string Nombre { get; set; } [DataMember(Order = 4)] [XmlAttribute()] public string Apellidos { get; set; } [DataMember(Order = 5)] public Login Login { get { return login.Entity; } set { var previousValue = this.login.Entity; if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.login.Entity = null; previousValue.Person = null; } this.login.Entity = value; if ((value != null)) value.Person = this; } } } public override void Initialize() { base.Initialize(); } } [DataContract()] [XmlType(TypeName = "Login")] public class Login : EntityBase { private EntityRef<Person> person; [DataMember(Order = 3)] public string UserID { get; set; } [DataMember(Order = 4)] public string Contrasena { get; set; } [DataMember(Order = 5)] public Domain Dominio { get; set; } public Person Person { get { return person.Entity; } set { var previousValue = this.person.Entity; if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.person.Entity = null; previousValue.Login = null; } this.person.Entity = value; if ((value != null)) value.Login = this; } } } public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "IdentityGroup")] public class IdentityGroup : Identity { private EntitySet<Identity> memberIdentities; public IdentityGroup() { Initialize(); } public override void Initialize() { this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity)); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "MemberIdentities")] public EntitySet<Identity> MemberIdentites { get { if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false))) { return null; } return memberIdentities; } set { memberIdentities.Assign(value); } } private void attach_Identity(Identity entity) { entity.IdentityGroups.Add(this); } private void dettach_Identity(Identity entity) { entity.IdentityGroups.Remove(this); } } [DataContract()] [XmlType(TypeName = "Group")] public class Group : Identity { public override void Initialize() { throw new NotImplementedException(); } } but the ToXml() response something like this <Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person> but what i want is something like this <Person Id="****" Name="***" Nombre="****"> <AccessControlEntries/> <IdentityGroups/> </Person>

    Read the article

  • ASP.NET File Picker

    - by Patrick
    I am trying to find a File Picker that runs on ASPX.Net. I need it to insert images in TinyMCE since the one with TinyMCE is licensed. I have been looking for a Silverlight solution, like Silverlight Bridge. I tried to implement SLFileManager that is based on SB, but with little success. I need to be able to upload images, delete/rename etc and also insert the image inside TinyMCE. Any ideas?

    Read the article

  • change cat-art.php into cat/art.php

    - by user338635
    Hi i got a problem with changing urls. I have files: cat-art.php (cat- category, art- title of an article) and i would like to have nicer access to them: cat/art.php so i wrote some code in .htaccess but it doesnt work. RewriteCond %{REQUEST_URI} ^/([^-]+)/([^-]+).html$ RewriteRule ^([^-]+)/([^-]+).html$ $1-$2.html [L] Can sb help me please? Thanks for your help

    Read the article

  • Raw XML Push from input stream captures only the first line of XML

    - by pqsk
    I'm trying to read XML that is being pushed to my java app. I originally had this in my glassfish server working. The working code in glassfish is as follows: public class XMLPush implements Serializable { public void processXML() { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getReader (); String s = null; while((s = br.readLine ()) != null) { sb.append ( s ); } //other code to process xml ........... ............................. }catch(Exception ex) { XMLCreator.exceptionOutput ( "processXML","Exception",ex); } .... ..... }//processXML }//class It works perfect, but my client is unable to have glassfish on their server. I tried grabbing the raw xml from php, but I couldn't get it to work. I decided to open up a socket and listen for the xml push manually. Here is my code for receiving the push: public class ListenerService extends Thread { private BufferedReader reader = null; private String line; public ListenerService ( Socket connection )thows Exception { this.reader = new BufferedReader ( new InputStreamReader ( connection.getInputStream () ) ); this.line = null; }//ListenerService @Override public void run () { try { while ( (this.line = this.reader.readLine ()) != null) { System.out.println ( this.line ); ........ }//while } System.out.println ( ex.toString () ); } } catch ( Exception ex ) { ... }//catch }//run I haven't done much socket programing, but from what I read for the past week is that passing the xml into a string is bad. What am I doing wrong and why is it that in glassfish server it works, and when I just open a socket myself it doesn't? this is all that I receive from the push: PUT /?XML_EXPORT_REASON=ResponseLoop&TIMESTAMP=1292559547 HTTP/1.1 Host: ************************ Accept: */* Content-Length: 470346 Expect: 100-continue <?xml version="1.0" encoding="UTF-8" ?> Where did the xml go? Is it because I am placing it in a string? I just need to grab the xml and save it into a file and then process it. Everything else works, but this.Any help would be greatly appreciated.

    Read the article

  • JDOM Parser and Namespace how to get clean Content

    - by senzacionale
    MY xml: <?xml version="1.0"?> <company xmlns="http://www.xx.com/xx"> <staff> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>200000</salary> </staff> </company> Reader in = new StringReader(message); Document document = (Document)saxBuilder.build(in); Element rootNode = document.getRootElement(); List<?> list = rootNode.getChildren("staff", Namespace.getNamespace("xmlns="http://www.infonova.com/MediationFeed"")); XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getCompactFormat()); for (int ii = 0; ii < list.size(); ii++) { Element node = (Element)list.get(ii); StringWriter sw = new StringWriter(); outp.output(node.getContent(), sw); StringBuffer sb = sw.getBuffer(); String xml = sb.toString(); } but my xml object looks like this <firstname xmlns="http://www.xx.com/xx">yong</firstname> <lastname xmlns="http://www.xx.com/xx">mook kim</lastname> <nickname xmlns="http://www.xx.com/xx">mkyong</nickname> <salary xmlns="http://www.xx.com/xx">100000</salary> every elemnt has namespace. why this? i don't want namespace... I want the same output as is in xml example like <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary>

    Read the article

  • std::ostream interface to an OLE IStream

    - by PaulH
    I have a Visual Studio 2008 C++ application using IStreams. I would like to use the IStream connection in a std::ostream. Something like this: IStream* stream = /*create valid IStream instance...*/; IStreamBuf< WIN32_FIND_DATA > sb( stream ); std::ostream os( &sb ); WIN32_FIND_DATA d = { 0 }; // send the structure along the IStream os << d; To accomplish this, I've implemented the following code: template< class _CharT, class _Traits > inline std::basic_ostream< _CharT, _Traits >& operator<<( std::basic_ostream< _CharT, _Traits >& os, const WIN32_FIND_DATA& i ) { const _CharT* c = reinterpret_cast< const _CharT* >( &i ); const _CharT* const end = c + sizeof( WIN32_FIND_DATA ) / sizeof( _CharT ); for( c; c < end; ++c ) os << *c; return os; } template< typename T > class IStreamBuf : public std::streambuf { public: IStreamBuf( IStream* stream ) : stream_( stream ) { setp( reinterpret_cast< char* >( &buffer_ ), reinterpret_cast< char* >( &buffer_ ) + sizeof( buffer_ ) ); }; virtual ~IStreamBuf() { sync(); }; protected: traits_type::int_type FlushBuffer() { int bytes = std::min< int >( pptr() - pbase(), sizeof( buffer_ ) ); DWORD written = 0; HRESULT hr = stream_->Write( &buffer_, bytes, &written ); if( FAILED( hr ) ) { return traits_type::eof(); } pbump( -bytes ); return bytes; }; virtual int sync() { if( FlushBuffer() == traits_type::eof() ) return -1; return 0; }; traits_type::int_type overflow( traits_type::int_type ch ) { if( FlushBuffer() == traits_type::eof() ) return traits_type::eof(); if( ch != traits_type::eof() ) { *pptr() = ch; pbump( 1 ); } return ch; }; private: /// data queued up to be sent T buffer_; /// output stream IStream* stream_; }; // class IStreamBuf Yes, the code compiles and seems to work, but I've not had the pleasure of implementing a std::streambuf before. So, I'd just like to know if it's correct and complete. Thanks, PaulH

    Read the article

  • How do I get the PreviewDialog of Apache FOP to actually display my document?

    - by JRSofty
    Search as I may I have not found a solution to my problem here and I'm hoping the combined minds of StackOverflow will push me in the right direction. My problem is as follows, I'm developing a print and print preview portion of a messaging system's user agent. I was given specific XSLT templates that after transforming XML will produce a Formatting Objects document. With Apache FOP I've been able to render the FO document into PDF which is all fine and good, but I would also like to display it in a print preview dialog. Apache FOP contains such a class called PreviewDialog which requires in its constructor a FOUserAgent, which I can generate, and an object implementing the Renderable Interface. The Renderable Interface has one implementing class in the FOP package which is called InputHandler which takes in its constructor a standard io File object. Now here is where the trouble begins. I'm currently storing the FO document as a temp file and pass this as a File object to an InputHandler instance which is then passed to the PreviewDialog. I see the dialog appear on my screen and along the bottom in a status bar it says that it is generating the document, and that is all it does. Here is the code I'm trying to use. It isn't production code so it's not pretty: import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; import org.apache.fop.cli.InputHandler; import org.apache.fop.render.awt.viewer.PreviewDialog; public class PrintPreview { public void showPreview(final File xslt, final File xmlSource) { boolean err = false; OutputStream out = null; Transformer transformer = null; final String tempFileName = this.getTempDir() + this.generateTempFileName(); final String tempFoFile = tempFileName + ".fo"; final String tempPdfFile = tempFileName + ".pdf"; System.out.println(tempFileName); final TransformerFactory transformFactory = TransformerFactory .newInstance(); final FopFactory fopFactory = FopFactory.newInstance(); try { transformer = transformFactory .newTransformer(new StreamSource(xslt)); final Source src = new StreamSource(xmlSource); out = new FileOutputStream(tempFoFile); final Result res = new StreamResult(out); transformer.transform(src, res); System.out.println("XSLT Transform Completed"); } catch (final TransformerConfigurationException e) { err = true; e.printStackTrace(); } catch (final FileNotFoundException e) { err = true; e.printStackTrace(); } catch (final TransformerException e) { err = true; e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("Initializing Preview"); transformer = null; out = null; final File fo = new File(tempFoFile); final File pdf = new File(tempPdfFile); if (!err) { final FOUserAgent ua = fopFactory.newFOUserAgent(); try { transformer = transformFactory.newTransformer(); out = new FileOutputStream(pdf); out = new BufferedOutputStream(out); final Fop fop = fopFactory.newFop( MimeConstants.MIME_PDF, ua, out); final Source foSrc = new StreamSource(fo); final Result foRes = new SAXResult(fop.getDefaultHandler()); transformer.transform(foSrc, foRes); System.out.println("Transformation Complete"); } catch (final FOPException e) { err = true; e.printStackTrace(); } catch (final FileNotFoundException e) { err = true; e.printStackTrace(); } catch (final TransformerException e) { err = true; e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (!err) { System.out.println("Attempting to Preview"); final InputHandler inputHandler = new InputHandler(fo); PreviewDialog.createPreviewDialog(ua, inputHandler, true); } } // perform the clean up // f.delete(); } private String getTempDir() { final String p = "java.io.tmpdir"; return System.getProperty(p); } private String generateTempFileName() { final String charset = "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890"; final StringBuffer sb = new StringBuffer(); Random r = new Random(); int seed = r.nextInt(); r = new Random(seed); for (int i = 0; i < 8; i++) { final int n = r.nextInt(71); seed = r.nextInt(); sb.append(charset.charAt(n)); r = new Random(seed); } return sb.toString(); } } Any help on this would be appreciated.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17  | Next Page >