Is there better way to do this?  (Xml Pretty Print | node removing)

Hi all, I have been working at home on a small project to help my Java Jedi training. :-)
My app saves quotes from authors in an xml file.
I have a class [XmlRepository extends Thread] that holds control of an xml file to handle requests for Nodes.
When I remove a node I get a Line Space above the node that was removed, or better put my node gets replaced by a empty line.
Pretty print or correct Node removing.
part of my xml is like this (I have resumed it for readability):
    <entities forUser="ffffffff-ffff-ffff-ffff-ffffffffffff">
        <quotes/>
        <authors>
            <author id="f156c570-c676-4d69-9b15-ae7d859ff771" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Poe</lastNames>
                <firstNames>Edgar Allan</firstNames>
            </author>
            <author id="35dc0c5a-3813-4a10-af49-8d4ea1c2cee0" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Wilde</lastNames>
                <firstNames>Oscar</firstNames>
            </author>
            <author id="317f72ea-add6-4bd2-8c63-d8b373a830ab" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Christie</lastNames>
                <firstNames>Agatha</firstNames>
            </author>
            <author id="28047c89-b647-4c40-b6c7-677feaf2dfda" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Shakespeare</lastNames>
                <firstNames>William</firstNames>
            </author>
        </authors>
    </entities>If I remove A Node ( Edgar Allan Poe (1st in this case)) the resulting Xml when saved is like this (I have added the space indentation just as it is outputted by my code):
    <entities forUser="ffffffff-ffff-ffff-ffff-ffffffffffff">
        <quotes/>
            <author id="35dc0c5a-3813-4a10-af49-8d4ea1c2cee0" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Wilde</lastNames>
                <firstNames>Oscar</firstNames>
            </author>
            <author id="317f72ea-add6-4bd2-8c63-d8b373a830ab" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Christie</lastNames>
                <firstNames>Agatha</firstNames>
            </author>
            <author id="28047c89-b647-4c40-b6c7-677feaf2dfda" languageCode="en" regenerateAs="com.fdt.cognoscere.entities.sources.Author">
                <lastNames>Shakespeare</lastNames>
                <firstNames>William</firstNames>
            </author>
        </authors>
    </entities>this is how I initialize the XML DOM Handlers, and the method for removing a Node:
     * Initializes factory instances and member variables.
    private void initialize() {
        //obtain an instance of a documentFactory create a document documentBuilder
        this.documentFactory = DocumentBuilderFactory.newInstance();
        //Configure the documentFactory to be name-space aware and validate trough an xsd file
        this.documentFactory.setNamespaceAware(true);
        this.documentFactory.setValidating(true);
        this.documentFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        try {
            //obtain an instance of an XPathFactory
            this.xpathFactory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
            //obtain an instance of the xpath evaluator object
            this.xpathEvaluator = this.xpathFactory.newXPath();
            //set namespace mapping configurations
            NamespaceContextMap namespaceMappings = new NamespaceContextMap();
            namespaceMappings.put("xml", "http://www.w3.org/XML/1998/namespace");
            namespaceMappings.put("xmlns", "http://www.w3.org/2000/xmlns/");
            namespaceMappings.put("xsd", "http://www.w3.org/2001/XMLSchema");
            namespaceMappings.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            namespaceMappings.put(this.schemaNamespaceMapping, this.schemaNamespace);
            //add mappings
            this.xpathEvaluator.setNamespaceContext(namespaceMappings);
        } catch (XPathFactoryConfigurationException ex) {
            Logger.getLogger(XmlRepository.class.getName()).log(Level.SEVERE, null, ex);
        try {
            //obtain a trasformer factory to save the file
            this.transformerFactory = TransformerFactory.newInstance();
            this.transformerFactory.setAttribute("indent-number", 4);
            //obtain the transforme
            this.transformer = this.transformerFactory.newTransformer();
            //setup transformer
            this.transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            this.transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            this.transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text");
            this.transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        } catch (TransformerConfigurationException tcex) {
            Logger.getLogger(XmlRepository.class.getName()).log(Level.SEVERE, null, tcex);
     * Removes a node by evaluating the XPATH expression.
     * @param xpath A String instance with the XPATH expression representing the element to remove.
     * @throws com.fdt.cognoscere.storage.exceptions.UnableToRemoveException When an exception occurs that prevents the repository to execute the remove statement.
    public void removeNode(final String xpath) throws UnableToRemoveException {
        Node nodeToRemove = null;
        Node parentNode = null;
        //verify xpath
        if (xpath == null)
            throw new IllegalArgumentException("The xpath argument cannot be null.");
        //verify that the repository is loaded
        if (!this.loaded)
            throw new IllegalStateException("The XmlRepository faild to load properly and it is in an invalid state. It cannot perfom any operation.");
        try {
            //get the node to remove out of the xpath expression
            nodeToRemove = this.getNode(xpath);
            //throw an exception if no node was found to remove
            if (nodeToRemove == null)
                throw new UnableToFindException("The node element trying to be remove does not exist.");
            //obtain the parent node to remove its child
            parentNode = nodeToRemove.getParentNode();
            //remove the node from the parent node
            nodeToRemove = parentNode.removeChild(nodeToRemove);
        } catch.......removed to save space{
        } finally {
            //normalize document
            this.document.normalize();
    }Please tell me if I could do this better,
thanks,
f(t)

franciscodiaztrepat wrote:
When I remove a node I get a Line Space above the node that was removed, or better put my node gets replaced by a empty line.Replaced? No, there's already a new-line character after the node that was removed. And there was one before that node too. You didn't remove either of those, so after the removal there are two consecutive new-line characters. As you can see.
And no, trying to pretty-print the XML document won't remove any of those. It might add whitespace to make the document nicely indented, but it won't ever remove whitespace. If you want whitespace removed then you'll have to do it yourself.
For example, after you remove a node, also remove the node following it if it's a whitespace text node. Or something like that.

Similar Messages

  • I am having trouble transferring files from an old MacBook (2007) to a MacBook Air over a wireless network.  The connection was interrupted and the time was over 24 hours.  Is there a better way to do this?  I'm using Migration assistant.

    I am having trouble transferring files from an old MacBook (2007) to a MacBook Air over a wireless network.  The connection was interrupted and the time was over 24 hours.  Is there a better way to do this?  I'm using Migration assistant.  The lack of an ethernet port on MacBook air does not help.

    William ..
    Alternative data transfer methods suggested here > OS X: How to migrate data from another Mac using Mavericks

  • There's got to be a better way to do this (RAM preview frustration)

    I loaded a 1:20 second Full HD clip into after effects. I need to edit the video based on certain sounds in the video and see if I'm matching them up correctly by previewing it with sound.
    The problem is i'm getting frustrated due to After effects not behaving like Premiere. First who thought it was a good idea not to incorporate sound into after effects? Second, I have an i7 sandy bridge processor, and 16 gbs of ram, yet it still takes time to render the ram preview (with no effects on it yet).
    So ram preview is my only option for sound, but the problem is every time I hit ram preview it starts the video all the way from the beginning. This is frustrating as I want to start at a specific point. Imagine having a longer video where the editing needs to take place at the end.
    There are people out there doing a lot more complicated professional projects, what do you guys do to get around this?
    Why can't after effects do some basic things like premiere like render fast with sound? Is it due to Mercury engine and 64 bits?
    This is one of the best products on the market, surely there is a better way to do this right?

    but the problem is every time I hit ram preview it starts the video all the way from the beginning.
    Window --> Preview, enable the "From current time" option
    yet it still takes time to render the ram preview (with no effects on it yet).
    There is no magic button. If it is compressed, naturally it needs to be decompressed and decoded first. This can consume resources even on fast machines. Furthermore, drive speed matters a lot in such cases. This might actualyl multiply, if you use multiprocessing, so for this kind of simple setup it's usually better to not use it. If your harddrives are fragmented or simply generally slow, frames cannot be loaded as fast and neither will AE be able to use the disk cache. Ergo, convert the footage and move it to the fastest drive in your system.
    what do you guys do to get around this?
    We preview at reduced compo resolution to extend RAM previews and place markers while the RAM preview plays using the * key on the numpad.
    Mylenium

  • Is there a way to import large XML files into HANA efficiently are their any data services provided to do this?

    1. Is there a way to import large XML files into HANA efficiently?
    2. Will it process it node by node or the entire file at a time?
    3. Are there any data services provided to do this?
    This for a project use case i also have an requirement to process bulk XML files, suggest me to accomplish this task

    Hi Patrick,
         I am addressing the similar issue. "Getting data from huge XMLs into Hana."
    Using Odata services can we handle huge data (i.e create schema/load into Hana) On-the-fly ?
    In my scenario,
    I get a folder of different complex XML files which are to be loaded into Hana database.
    Then I gotta transform & cleanse the data.
    Can I use oData services to transform and cleanse the data ?
    If so, how can I create oData services dynamically ?
    Any help is highly appreciated.
    Thank you.
    Regards,
    Alekhya

  • After I watch a podcast I delete it. When I go back in the next day it shows 500-600 episodes I have to delete manually. So 2 questions....  Is there a way to stop this from happening and is there a way to delete all. This is getting frustrating.

    After I watch a podcast I delete it. When I go back in there are 500-600 episodes and I have to delete each one manually. Is there a way to stop this from happening or is there a way to delete all at once. It's getting very frustrating.

    Had all these issues.  Bit the bullet and downloaded the Downcast App ($1.99).  Much better expereince and a lot more features.  Sad.

  • Thunderbird puts a new message at the end of the thread. Is there any way of changing this preference to listing new message at top of the thread?

    Thunderbird puts a new message at the end of the thread.
    Is there any way of changing this preference so that new messages are displayed at the top of the thread.
    This is is more logical. You need to see new message in thread directly, rather than scanning to end of thread to see what is there.

    No it is not possible. The newest message is attached to the message it is in reply to.
    The conversations add-on might better suit your needs. see https://addons.mozilla.org/thunderbird/addon/gmail-conversation-view/?src=ss

  • Is there any way to prevent web.xml from any change ?

    hi all,
    we have a filter in web.xml. Now we want to prevent it from any change in future. I mean after making a war(EAR) no one can change the filter in web.xml. if he chaged it then he will not be able to re deploy the application.Right now it is in web.xml so one can easily change it and then he can redeploy the application.
    Is there any way to prevent web.xml from any change after making EAR(WAR)?
    One can easily make a change in web.xml and redeploy the application to get the result. Now we want to restrict the web.xml as java class for any change after making EAR(or WAR).
    Could some one help me to do this?
    thanks,
    dinesh

    I think you could use some third party software to lock the folder like FolderLock, just make sure others ppl cannot access your file should be fined.
    This is my stupid solution only,cheers.

  • Is there any way to prevent web.xml from any change like java class?

    hi all,
    Is there any way to prevent web.xml from any change after making EAR(WAR)?
    One can easily make a change in web.xml and redeploy the application to get the result. Now we want to restrict the web.xml as java class for any change after making EAR(or WAR).
    Could some one help me to do this?
    thanks,
    dinesh

    hi,
    Not at development level. We want it after deploying the application on server .
    We want to create it (web.xml) at tomcat startup (or in any other web/app server ) before loading any context.
    Is there any way to run a simple java class(not servlet) on tomcat startup(before initializing the contexts)?
    Message was edited by:
    DP_java
    Message was edited by:
    DP_java

  • Since installing Yosemite, my MacBook Pro has become slower.  Is there any way to fix this problem?

    Ever since I installed OS X Yosemite on my mid 2012 MacBook Pro, it has started becoming slower and slower and glitching out.  Is there any way to fix this?  Here is my diagnostics:
    Problem description:
    My Mac is rather slow.  It started happening after I installed OS X Yosemite
    EtreCheck version: 2.0.11 (98)
    Report generated November 10, 2014 at 7:32:23 PM EST
    Hardware Information: ℹ️
      MacBook Pro (13-inch, Mid 2012) (Verified)
      MacBook Pro - model: MacBookPro9,2
      1 2.5 GHz Intel Core i5 CPU: 2-core
      4 GB RAM Upgradeable
      BANK 0/DIMM0
      2 GB DDR3 1600 MHz ok
      BANK 1/DIMM0
      2 GB DDR3 1600 MHz ok
      Bluetooth: Good - Handoff/Airdrop2 supported
      Wireless:  en1: 802.11 a/b/g/n
    Video Information: ℹ️
      Intel HD Graphics 4000 -
      Color LCD 1280 x 800
    System Software: ℹ️
      OS X 10.10 (14A389) - Uptime: 0:36:19
    Disk Information: ℹ️
      APPLE HDD HTS545050A7E362 disk0 : (500.11 GB)
      S.M.A.R.T. Status: Verified
      EFI (disk0s1) <not mounted> : 210 MB
      Recovery HD (disk0s3) <not mounted>  [Recovery]: 650 MB
      Macintosh HD (disk1) /  [Startup]: 496.14 GB (325.60 GB free)
      Encrypted AES-XTS Unlocked
      Core Storage: disk0s2 499.25 GB Online
      MATSHITADVD-R   UJ-8A8 
    USB Information: ℹ️
      Apple Inc. FaceTime HD Camera (Built-in)
      Apple Inc. BRCM20702 Hub
      Apple Inc. Bluetooth USB Host Controller
      Apple Inc. Apple Internal Keyboard / Trackpad
      Apple Computer, Inc. IR Receiver
    Thunderbolt Information: ℹ️
      Apple Inc. thunderbolt_bus
    Gatekeeper: ℹ️
      Mac App Store and identified developers
    Kernel Extensions: ℹ️
      /Library/Application Support/Avast/components/fileshield/unsigned
      [loaded] com.avast.AvastFileShield (2.1.0 - SDK 10.9) Support
      /Library/Application Support/Avast/components/proxy/unsigned
      [loaded] com.avast.PacketForwarder (1.4 - SDK 10.9) Support
      /Library/Extensions
      [loaded] com.logmein.hamachi (1.0.0 - SDK 10.9) Support
      /System/Library/Extensions
      [not loaded] com.paceap.kext.pacesupport.master (5.9.1 - SDK 10.6) Support
      /System/Library/Extensions/PACESupportFamily.kext/Contents/PlugIns
      [not loaded] com.paceap.kext.pacesupport.leopard (5.9.1 - SDK 10.4) Support
      [not loaded] com.paceap.kext.pacesupport.panther (5.9.1 - SDK 10.-1) Support
      [loaded] com.paceap.kext.pacesupport.snowleopard (5.9.1 - SDK 10.6) Support
      [not loaded] com.paceap.kext.pacesupport.tiger (5.9.1 - SDK 10.4) Support
    Launch Agents: ℹ️
      [not loaded] com.adobe.AAM.Updater-1.0.plist Support
      [not loaded] com.adobe.AdobeCreativeCloud.plist Support
      [not loaded] com.avast.userinit.plist Support
      [running] com.logmein.hamachimb.plist Support
      [loaded] com.oracle.java.Java-Updater.plist Support
    Launch Daemons: ℹ️
      [loaded] com.adobe.fpsaud.plist Support
      [loaded] com.avast.init.plist Support
      [loaded] com.avast.uninstall.plist Support
      [loaded] com.avast.update.plist Support
      [running] com.logmein.hamachi.plist Support
      [loaded] com.macpaw.CleanMyMac2.Agent.plist Support
      [loaded] com.microsoft.office.licensing.helper.plist Support
      [loaded] com.oracle.java.Helper-Tool.plist Support
      [running] com.paceap.eden.licensed.plist Support
      [not loaded] org.eyebeam.SelfControl.plist Support
      [loaded] PACESupport.plist Support
    User Launch Agents: ℹ️
      [loaded] com.adobe.AAM.Updater-1.0.plist Support
      [not loaded] com.adobe.ARM.[...].plist Support
      [invalid?] com.avast.home.userinit.plist Support
      [not loaded] com.google.keystone.agent.plist Support
      [loaded] com.macpaw.CleanMyMac2Helper.scheduledScan.plist Support
      [loaded] com.macpaw.CleanMyMac2Helper.trashWatcher.plist Support
      [running] com.spotify.webhelper.plist Support
      [not loaded] com.valvesoftware.steamclean.plist Support
    User Login Items: ℹ️
      iTunesHelper Application (/Applications/iTunes.app/Contents/MacOS/iTunesHelper.app)
      uTorrent UNKNOWN (missing value)
      AdobeResourceSynchronizer ApplicationHidden (/Applications/Adobe Reader.app/Contents/Support/AdobeResourceSynchronizer.app)
    Internet Plug-ins: ℹ️
      AdobeAAMDetect: Version: AdobeAAMDetect 2.0.0.0 - SDK 10.7 Support
      FlashPlayer-10.6: Version: 15.0.0.189 - SDK 10.6 Support
      Default Browser: Version: 600 - SDK 10.10
      AdobePDFViewerNPAPI: Version: 11.0.09 - SDK 10.6 Support
      AdobePDFViewer: Version: 11.0.09 - SDK 10.6 Support
      Flash Player: Version: 15.0.0.189 - SDK 10.6 Support
      QuickTime Plugin: Version: 7.7.3
      SharePointBrowserPlugin: Version: 14.4.5 - SDK 10.6 Support
      Silverlight: Version: 5.1.20913.0 - SDK 10.6 Support
      DirectorShockwave: Version: 12.0.6r147 - SDK 10.6 Support
      JavaAppletPlugin: Version: Java 8 Update 20 Check version
    User Internet Plug-ins: ℹ️
      Unity Web Player: Version: UnityPlayer version 2.6.1f3 Support
      NPRoblox: Version: 1, 2, 8, 25 - SDK 10.9 Support
    Safari Extensions: ℹ️
      Adblock Plus
      Searchme
    3rd Party Preference Panes: ℹ️
      Flash Player  Support
      Java  Support
    Time Machine: ℹ️
      Time Machine not configured!
    Top Processes by CPU: ℹ️
          8% mds
          4% WindowServer
          0% fontd
          0% launchd
          0% com.avast.daemon
    Top Processes by Memory: ℹ️
      163 MB Safari
      120 MB mds_stores
      112 MB com.avast.daemon
      86 MB Finder
      64 MB com.apple.WebKit.WebContent
    Virtual Memory Information: ℹ️
      398 MB Free RAM
      1.75 GB Active RAM
      1.19 GB Inactive RAM
      753 MB Wired RAM
      4.25 GB Page-ins
      1 MB Page-outs

    1. This procedure is a diagnostic test. It changes nothing, for better or worse, and therefore will not, in itself, solve the problem. But with the aid of the test results, the solution may take a few minutes, instead of hours or days.
    Don't be put off by the complexity of these instructions. The process is much less complicated than the description. You do harder tasks with the computer all the time.
    2. If you don't already have a current backup, back up all data before doing anything else. The backup is necessary on general principle, not because of anything in the test procedure. Backup is always a must, and when you're having any kind of trouble with the computer, you may be at higher than usual risk of losing data, whether you follow these instructions or not.
    There are ways to back up a computer that isn't fully functional. Ask if you need guidance.
    3. Below are instructions to run a UNIX shell script, a type of program. As I wrote above, it changes nothing. It doesn't send or receive any data on the network. All it does is to generate a human-readable report on the state of the computer. That report goes nowhere unless you choose to share it. If you prefer, you can act on it yourself without disclosing the contents to me or anyone else.
    You should be wondering whether you can believe me, and whether it's safe to run a program at the behest of a stranger. In general, no, it's not safe and I don't encourage it.
    In this case, however, there are a couple of ways for you to decide whether the program is safe without having to trust me. First, you can read it. Unlike an application that you download and click to run, it's transparent, so anyone with the necessary skill can verify what it does.
    You may not be able to understand the script yourself. But variations of the script have been posted on this website thousands of times over a period of years. The site is hosted by Apple, which does not allow it to be used to distribute harmful software. Any one of the millions of registered users could have read the script and raised the alarm if it was harmful. Then I would not be here now and you would not be reading this message.
    Nevertheless, if you can't satisfy yourself that these instructions are safe, don't follow them. Ask for other options.
    4. Here's a summary of what you need to do, if you choose to proceed:
    ☞ Copy a line of text in this window to the Clipboard.
    ☞ Paste into the window of another application.
    ☞ Wait for the test to run. It usually takes a few minutes.
    ☞ Paste the results, which will have been copied automatically, back into a reply on this page.
    The sequence is: copy, paste, wait, paste again. You don't need to copy a second time. Details follow.
    5. You may have started the computer in "safe" mode. Preferably, these steps should be taken in “normal” mode, under the conditions in which the problem is reproduced. If the system is now in safe mode and works well enough in normal mode to run the test, restart as usual. If you can only test in safe mode, do that.
    6. If you have more than one user, and the one affected by the problem is not an administrator, then please run the test twice: once while logged in as the affected user, and once as an administrator. The results may be different. The user that is created automatically on a new computer when you start it for the first time is an administrator. If you can't log in as an administrator, test as the affected user. Most personal Macs have only one user, and in that case this section doesn’t apply. Don't log in as root.
    7. The script is a single long line, all of which must be selected. You can accomplish this easily by triple-clicking anywhere in the line. The whole line will highlight, though you may not see all of it in the browser window, and you can then copy it. If you try to select the line by dragging across the part you can see, you won't get all of it.
    Triple-click anywhere in the line of text below on this page to select it:
    PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/libexec;clear;cd;p=(Software Hardware Memory Diagnostics Power FireWire Thunderbolt USB Fonts SerialATA 4 1000 25 5120 KiB/s 1024 85 \\b%% 20480 1 MB/s 25000 ports ' com.clark.\* \*dropbox \*genieo\* \*GoogleDr\* \*k.AutoCAD\* \*k.Maya\* vidinst\* ' DYLD_INSERT_LIBRARIES\ DYLD_LIBRARY_PATH -86 "` route -n get default|awk '/e:/{print $2}' `" 25 N\\/A down up 102400 25600 recvfrom sendto CFBundleIdentifier 25 25 25 1000 MB ' com.adobe.AAM.Updater-1.0 com.adobe.CS4ServiceManager com.adobe.CS5ServiceManager com.adobe.fpsaud com.adobe.SwitchBoard com.apple.AirPortBaseStationAgent com.apple.FolderActions.enabled com.apple.FolderActions.folders com.apple.installer.osmessagetracing com.apple.mrt.uiagent com.apple.ReportCrash.Self com.apple.SafariNotificationAgent com.apple.usbmuxd com.google.keystone.agent com.google.keystone.daemon com.microsoft.office.licensing.helper com.oracle.java.Helper-Tool com.oracle.java.JavaUpdateHelper ' ' 879294308 3627668074 1083382502 1274181950 1855907737 464843899 3694147963 1417519526 1233118628 2456546649 2806998573 2636415542 842973933 3301885676 891055588 998894468 695903914 1443423563 ' 51 5120 files );N5=${#p[@]};p[N5]=` networksetup -listnetworkserviceorder|awk ' NR>1 { sub(/^\([0-9]+\) /,"");n=$0;getline;} $NF=="'${p[26]}')" { sub(/.$/,"",$NF);print n;exit;} ' `;f=('\n%s: %s\n' '\n%s\n\n%s\n' '\nRAM details\n%s\n' %s\ %s '%s\n-\t%s\n' );S0() { echo ' { q=$NF+0;$NF="";u=$(NF-1);$(NF-1)="";gsub(/^ +| +$/,"");if(q>='${p[$1]}') printf("%s (UID %s) is using %s '${p[$2]}'",$0,u,q);} ';};s=(' s/[0-9A-Za-z._]+@[0-9A-Za-z.]+\.[0-9A-Za-z]{2,4}/EMAIL/g;/faceb/s/(at\.)[^.]+/\1NAME/g;/\/Shared/!s/(\/Users\/)[^ /]+/\1USER/g;s/[-0-9A-Fa-f]{22,}/UUID/g;' ' s/^ +//;/de: S|[nst]:/p;' ' {sub(/^ +/,"")};/er:/;/y:/&&$2<'${p[10]} ' 1s/://;3,6d;/[my].+:/d;s/^ {4}//;H;${ g;s/\n$//;/s: [^EO]|x([^08]|02[^F]|8[^0])/p;} ' ' 5h;6{ H;g;/P/!p;} ' ' ($1~/^Cy/&&$3>'${p[11]}')||($1~/^Cond/&&$2!~/^N/) ' ' /:$/{ N;/:.+:/d;s/ *://;b0'$'\n'' };/^ *(V.+ [0N]|Man).+ /{ s/ 0x.... //;s/[()]//g;s/(.+: )(.+)/ (\2)/;H;};$b0'$'\n'' d;:0'$'\n'' x;s/\n\n//;/Apple[ ,]|Genesy|Intel|SMSC/d;s/\n.*//;/\)$/p;' ' s/^.*C/C/;H;${ g;/No th|pms/!p;} ' '/= [^GO]/p' '{$1=""};1' ' /Of/!{ s/^.+is |\.//g;p;} ' ' $0&&!/ / { n++;print;} END { if(n<10) print "com.apple.";} ' ' sub(/ :/,"");{ print|"tail -n'${p[12]}'";} ' ' NR==2&&$4<='${p[13]}' { print $4;} ' ' END { $2/=256;if($2>='${p[15]}') print int($2) } ' ' NR!=13{next};{sub(/[+-]$/,"",$NF)};'"`S0 21 22`" 'NR!=2{next}'"`S0 37 17`" ' NR!=5||$8!~/[RW]/{next};{ $(NF-1)=$1;$NF=int($NF/10000000);for(i=1;i<=3;i++){$i="";$(NF-1-i)="";};};'"`S0 19 20`" 's:^:/:p' '/\.kext\/(Contents\/)?Info\.plist$/p' 's/^.{52}(.+) <.+/\1/p' ' /Launch[AD].+\.plist$/ { n++;print;} END { if(n<200) print "/System/";} ' '/\.xpc\/(Contents\/)?Info\.plist$/p' ' NR>1&&!/0x|\.[0-9]+$|com\.apple\.launchctl\.(Aqua|Background|System)$/ { print $3;} ' ' /\.(framew|lproj)|\):/d;/plist:|:.+(Mach|scrip)/s/:[^:]+//p ' '/^root$/p' ' !/\/Contents\/.+\/Contents|Applic|Autom|Frameworks/&&/Lib.+\/Info.plist$/ { n++;print;} END { if(n<1100) print "/System/";} ' '/^\/usr\/lib\/.+dylib$/p' ' /Temp|emac/{next};/(etc|Preferences|Launch[AD].+)\// { sub(".(/private)?","");n++;print;} END { split("'"${p[41]}"'",b);split("'"${p[42]}"'",c);for(i in b) print b[i]".plist\t"c[i];if(n<500) print "Launch";} ' ' /\/(Contents\/.+\/Contents|Frameworks)\/|\.wdgt\/.+\.([bw]|plu)/d;p;' 's/\/(Contents\/)?Info.plist$//;p' ' { gsub("^| |\n","\\|\\|kMDItem'${p[35]}'=");sub("^...."," ") };1 ' p '{print $3"\t"$1}' 's/\'$'\t''.+//p' 's/1/On/p' '/Prox.+: [^0]/p' '$2>'${p[43]}'{$2=$2-1;print}' ' BEGIN { i="'${p[26]}'";M1='${p[16]}';M2='${p[18]}';M3='${p[31]}';M4='${p[32]}';} !/^A/{next};/%/ { getline;if($5<M1) a="user "$2"%, system "$4"%";} /disk0/&&$4>M2 { b=$3" ops/s, "$4" blocks/s";} $2==i { if(c) { d=$3+$4+$5+$6;next;};if($4>M3||$6>M4) c=int($4/1024)" in, "int($6/1024)" out";} END { if(a) print "CPU: "a;if(b) print "I/O: "b;if(c) print "Net: "c" (KiB/s)";if(d) print "Net errors: "d" packets/s";} ' ' /r\[0\] /&&$NF!~/^1(0|72\.(1[6-9]|2[0-9]|3[0-1])|92\.168)\./ { print $NF;exit;} ' ' !/^T/ { printf "(static)";exit;} ' '/apsd|BKAg|OpenD/!s/:.+//p' ' (/k:/&&$3!~/(255\.){3}0/ )||(/v6:/&&$2!~/A/ ) ' ' $1~"lR"&&$2<='${p[25]}';$1~"li"&&$3!~"wpa2";' ' BEGIN { FS=":";p="uniq -c|sed -E '"'s/ +\\([0-9]+\\)\\(.+\\)/\\\2 x\\\1/;s/x1$//'"'";} { n=split($3,a,".");sub(/_2[01].+/,"",$3);print $2" "$3" "a[n]$1|p;b=b$1;} END { close(p);if(b) print("\n\t* Code injection");} ' ' NR!=4{next} {$NF/=10240} '"`S0 27 14`" ' END { if($3~/[0-9]/)print$3;} ' ' BEGIN { L='${p[36]}';} !/^[[:space:]]*(#.*)?$/ { l++;if(l<=L) f=f"\n   "$0;} END { F=FILENAME;if(!F) exit;if(!f) f="\n   [N/A]";"cksum "F|getline C;split(C, A);C="checksum "A[1];"file -b "F|getline T;if(T!~/^(AS.+ (En.+ )?text(, with v.+)?$|(Bo|PO).+ sh.+ text ex|XM)/) F=F" ("T", "C")";else F=F" ("C")";printf("\nContents of %s\n%s\n",F,f);if(l>L) printf("\n   ...and %s more line(s)\n",l-L);} ' ' s/^ ?n...://p;s/^ ?p...:/-'$'\t''/p;' 's/0/Off/p' ' END{print NR} ' ' /id: N|te: Y/{i++} END{print i} ' ' / / { print "'"${p[28]}"'";exit;};1;' '/ en/!s/\.//p' ' NR!=13{next};{sub(/[+-M]$/,"",$NF)};'"`S0 39 40`" ' $10~/\(L/&&$9!~"localhost" { sub(/.+:/,"",$9);print $1": "$9;} ' '/^ +r/s/.+"(.+)".+/\1/p' 's/(.+\.wdgt)\/(Contents\/)?Info\.plist$/\1/p' 's/^.+\/(.+)\.wdgt$/\1/p' ' /l: /{ /DVD/d;s/.+: //;b0'$'\n'' };/s: /{ /V/d;s/^ */- /;H;};$b0'$'\n'' d;:0'$'\n'' x;/APPLE [^:]+$/d;p;' ' /^find: /d;p;' "`S0 44 45`" ' BEGIN{FS="= "} /Path/{print $2} ' ' /^ *$/d;s/^ */   /;' ' s/^.+ |\(.+\)$//g;p ' '/\.appex\/Contents\/Info\.plist$/p' ' /2/{print "WARN"};/4/{print "CRITICAL"};' );c1=(system_profiler pmset\ -g nvram fdesetup find syslog df vm_stat sar ps sudo\ crontab sudo\ iotop top pkgutil 'PlistBuddy 2>&1 -c "Print' whoami cksum kextstat launchctl sudo\ launchctl crontab 'sudo defaults read' stat lsbom mdfind ' for i in ${p[24]};do ${c1[18]} ${c2[27]} $i;done;' defaults\ read scutil sudo\ dtrace sudo\ profiles sed\ -En awk /S*/*/P*/*/*/C*/*/airport networksetup mdutil sudo\ lsof test osascript\ -e sysctl\ -n pluginkit );c2=(com.apple.loginwindow\ LoginHook '" /L*/P*/loginw*' "'tell app \"System Events\" to get properties of login items'|tr , \\\n" 'L*/Ca*/com.ap*.Saf*/E*/* -d 1 -name In*t -exec '"${c1[14]}"' :CFBundleDisplayName" {} \;|sort|uniq' '~ $TMPDIR.. \( -flags +sappnd,schg,uappnd,uchg -o ! -user $UID -o ! -perm -600 \)' '.??* -path .Trash -prune -o -type d -name *.app -print -prune' :${p[35]}\" :Label\" '{/,}L*/{Con,Pref}* -type f ! -size 0 -name *.plist -exec plutil -s {} \;' "-f'%N: %l' Desktop L*/Keyc*" therm sysload boot-args status " -F '\$Time \$(RefProc): \$Message' -k Sender kernel -k Message Req 'bad |Beac|caug|corru|dead[^bl]|FAIL|fail|GPU |hfs: Ru|inval|jnl:|last value [1-9]|n Cause: -|NVDA\(|pagin|proc: t|Roamed|rror|ssert|Thrott|tim(ed? ?|ing )o|WARN' -k Message Rne 'Goog|ksadm|Roame|SMC:|suhel| VALI|ver-r|xpma' -o -o -k Sender fseventsd -k Message Req SL -o -k Sender Req launchd -k Message Req de: " '-du -n DEV -n EDEV 1 10' 'acrx -o comm,ruid,%cpu' '-t1 10 1' '-f -pfc /var/db/r*/com.apple.*.{BS,Bas,Es,J,OSXU,Rem,up}*.bom' '{/,}L*/Lo*/Diag* -type f -regex .\*[cght] ! -name .?\* ! -name \*ag \( -exec grep -lq "^Thread c" {} \; -exec printf \* \; -o -true \) -execdir stat -f:%Sc:%N -t%F {} \;|sort -t: -k2 |tail -n'${p[38]} '/S*/*/Ca*/*xpc* >&- ||echo No' '-L /{S*/,}L*/StartupItems -type f -exec file {} +' '-L /S*/L*/{C*/Sec*A,Ex}* {/,}L*/{A*d,Ca*/*/Ex,Co{mpon,reM},Ex,In{p,ter},iTu*/*P,Keyb,Mail/B,Pr*P,Qu*T,Scripti,Sec,Servi,Spo,Widg}* -path \\*s/Resources -prune -o -type f -name Info.plist' '/usr/lib -type f -name *.dylib' `awk "${s[31]}"<<<${p[23]}` "/e*/{auto,{cron,fs}tab,hosts,{[lp],sy}*.conf,mach_i*/*,pam.d/*,ssh{,d}_config,*.local} {,/usr/local}/etc/periodic/*/* /L*/P*{,/*}/com.a*.{Bo,sec*.ap}*t {/S*/,/,}L*/Lau*/*t .launchd.conf" list getenv /Library/Preferences/com.apple.alf\ globalstate --proxy '-n get default' -I --dns -getdnsservers\ "${p[N5]}" -getinfo\ "${p[N5]}" -P -m\ / '' -n1 '-R -l1 -n1 -o prt -stats command,uid,prt' '--regexp --only-files --files com.apple.pkg.*|sort|uniq' -kl -l -s\ / '-R -l1 -n1 -o mem -stats command,uid,mem' '+c0 -i4TCP:0-1023' com.apple.dashboard\ layer-gadgets '-d /L*/Mana*/$USER&&echo On' '-app Safari WebKitDNSPrefetchingEnabled' "+c0 -l|awk '{print(\$1,\$3)}'|sort|uniq -c|sort -n|tail -1|awk '{print(\$2,\$3,\$1)}'" -m 'L*/{Con*/*/Data/L*/,}Pref* -type f -size 0c -name *.plist.???????|wc -l' kern.memorystatus_vm_pressure_level );N1=${#c2[@]};for j in {0..9};do c2[N1+j]=SP${p[j]}DataType;done;N2=${#c2[@]};for j in 0 1;do c2[N2+j]="-n ' syscall::'${p[33+j]}':return { @out[execname,uid]=sum(arg0) } tick-10sec { trunc(@out,1);exit(0);} '";done;l=(Restricted\ files Hidden\ apps 'Elapsed time (s)' POST Battery Safari\ extensions Bad\ plists 'High file counts' User Heat System\ load boot\ args FileVault Diagnostic\ reports Log 'Free space (MiB)' 'Swap (MiB)' Activity 'CPU per process' Login\ hook 'I/O per process' Mach\ ports kexts Daemons Agents XPC\ cache Startup\ items Admin\ access Root\ access Bundles dylibs Apps Font\ issues Inserted\ dylibs Firewall Proxies DNS TCP/IP Wi-Fi Profiles Root\ crontab User\ crontab 'Global login items' 'User login items' Spotlight Memory Listeners Widgets Parental\ Controls Prefetching SATA Descriptors App\ extensions Lockfiles Memory\ pressure );N3=${#l[@]};for i in 0 1 2;do l[N3+i]=${p[5+i]};done;N4=${#l[@]};for j in 0 1;do l[N4+j]="Current ${p[29+j]}stream data";done;A0() { id -G|grep -qw 80;v[1]=$?;((v[1]==0))&&sudo true;v[2]=$?;v[3]=`date +%s`;clear >&-;date '+Start time: %T %D%n';};for i in 0 1;do eval ' A'$((1+i))'() { v=` eval "${c1[$1]} ${c2[$2]}"|'${c1[30+i]}' "${s[$3]}" `;[[ "$v" ]];};A'$((3+i))'() { v=` while read i;do [[ "$i" ]]&&eval "${c1[$1]} ${c2[$2]}" \"$i\"|'${c1[30+i]}' "${s[$3]}";done<<<"${v[$4]}" `;[[ "$v" ]];};A'$((5+i))'() { v=` while read i;do '${c1[30+i]}' "${s[$1]}" "$i";done<<<"${v[$2]}" `;[[ "$v" ]];};';done;A7(){ v=$((`date +%s`-v[3]));};B2(){ v[$1]="$v";};for i in 0 1;do eval ' B'$i'() { v=;((v['$((i+1))']==0))||{ v=No;false;};};B'$((3+i))'() { v[$2]=`'${c1[30+i]}' "${s[$3]}"<<<"${v[$1]}"`;} ';done;B5(){ v[$1]="${v[$1]}"$'\n'"${v[$2]}";};B6() { v=` paste -d: <(printf "${v[$1]}") <(printf "${v[$2]}")|awk -F: ' {printf("'"${f[$3]}"'",$1,$2)} ' `;};B7(){ v=`grep -Fv "${v[$1]}"<<<"$v"`;};C0() { [[ "$v" ]]&&sed -E "$s"<<<"$v";};C1() { [[ "$v" ]]&&printf "${f[$1]}" "${l[$2]}" "$v"|sed -E "$s";};C2() { v=`echo $v`;[[ "$v" != 0 ]]&&C1 0 $1;};C3() { v=`sed -E "${s[63]}"<<<"$v"`&&C1 1 $1;};for i in 1 2;do for j in 0 2 3;do eval D$i$j'(){ A'$i' $1 $2 $3; C'$j' $4;};';done;done;{ A0;D20 0 $((N1+1)) 2;D10 0 $N1 1;B0;C2 27;B0&&! B1&&C2 28;D12 15 37 25 8;A1 0 $((N1+2)) 3;C0;D13 0 $((N1+3)) 4 3;D23 0 $((N1+4)) 5 4;D13 0 $((N1+9)) 59 50;for i in 0 1 2;do D13 0 $((N1+5+i)) 6 $((N3+i));done;D13 1 10 7 9;D13 1 11 8 10;D22 2 12 9 11;D12 3 13 10 12;D23 4 19 44 13;D23 5 14 12 14;D22 6 36 13 15;D22 38 52 66 54;D22 7 37 14 16;D23 8 15 38 17;D22 9 16 16 18;B1&&{ D22 35 49 61 51;D22 11 17 17 20;for i in 0 1;do D22 28 $((N2+i)) 45 $((N4+i));done;};D22 12 44 54 45;D22 12 39 15 21;A1 13 40 18;B2 4;B3 4 0 19;A3 14 6 32 0;B4 0 5 11;A1 17 41 20;B7 5;C3 22;B4 4 6 21;A3 14 7 32 6;B4 0 7 11;B3 4 0 22;A3 14 6 32 0;B4 0 8 11;B5 7 8;B1&&{ A2 19 26 23;B7 7;C3 23;};A2 18 26 23;B7 7;C3 24;D13 4 21 24 26;B4 4 12 26;B3 4 13 27;A1 4 22 29;B7 12;B2 14;A4 14 6 52 14;B2 15;B6 14 15 4;B3 0 0 30;C3 29;A1 4 23 27;B7 13;C3 30;B3 4 0 65;A3 14 6 32 0;B4 0 16 11;A1 39 50 64;B7 16;C3 52;D13 24 24 32 31;D13 25 37 32 33;A2 23 18 28;B2 16;A2 16 25 33;B7 16;B3 0 0 34;B2 21;A6 47 21&&C0;B1&&{ D13 21 0 32 19;D13 10 42 32 40;D22 29 35 46 39;};D23 14 1 62 42;D12 34 43 53 44;D12 22 20 32 25;D22 0 $((N1+8)) 51 32;D13 4 8 41 6;D12 26 28 35 34;D13 27 29 36 35;A2 27 32 39&&{ B2 19;A2 33 33 40;B2 20;B6 19 20 3;};C2 36;D23 33 34 42 37;B1&&D23 35 45 55 46;D23 32 31 43 38;D12 36 47 32 48;D13 20 42 32 41;D13 37 2 48 43;D13 4 5 32 1;D13 4 3 60 5;D12 26 48 49 49;B3 4 22 57;A1 26 46 56;B7 22;B3 0 0 58;C3 47;D22 4 4 50 0;D12 4 51 32 53;D23 22 9 37 7;A7;C2 2;} 2>/dev/null|pbcopy;exit 2>&-
    Copy the selected text to the Clipboard by pressing the key combination command-C.
    8. Launch the built-in Terminal application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Terminal in the icon grid.
    Click anywhere in the Terminal window and paste by pressing command-V. The text you pasted should vanish immediately. If it doesn't, press the return key.
    9. If you see an error message in the Terminal window such as "Syntax error" or "Event not found," enter
    exec bash
    and press return. Then paste the script again.
    10. If you're logged in as an administrator, you'll be prompted for your login password. Nothing will be displayed when you type it. You will not see the usual dots in place of typed characters. Make sure caps lock is off. Type carefully and then press return. You may get a one-time warning to be careful. If you make three failed attempts to enter the password, the test will run anyway, but it will produce less information. In most cases, the difference is not important. If you don't know the password, or if you prefer not to enter it, press the key combination control-C or just press return  three times at the password prompt. Again, the script will still run.
    If you're not logged in as an administrator, you won't be prompted for a password. The test will still run. It just won't do anything that requires administrator privileges.
    11. The test may take a few minutes to run, depending on how many files you have and the speed of the computer. A computer that's abnormally slow may take longer to run the test. While it's running, there will be nothing in the Terminal window and no indication of progress. Wait for the line
    [Process completed]
    to appear. If you don't see it within half an hour or so, the test probably won't complete in a reasonable time. In that case, close the Terminal window and report what happened. No harm will be done.
    12. When the test is complete, quit Terminal. The results will have been copied to the Clipboard automatically. They are not shown in the Terminal window. Please don't copy anything from there. All you have to do is start a reply to this comment and then paste by pressing command-V again.
    At the top of the results, there will be a line that begins with the words "Start time." If you don't see that, but instead see a mass of gibberish, you didn't wait for the "Process completed" message to appear in the Terminal window. Please wait for it and try again.
    If any private information, such as your name or email address, appears in the results, anonymize it before posting. Usually that won't be necessary.
    13. When you post the results, you might see an error message on the web page: "You have included content in your post that is not permitted," or "You are not authorized to post." That's a bug in the forum software. Please post the test results on Pastebin, then post a link here to the page you created.
    14. This is a public forum, and others may give you advice based on the results of the test. They speak only for themselves, and I don't necessarily agree with them.
    Copyright © 2014 by Linc Davis. As the sole author of this work, I reserve all rights to it except as provided in the Use Agreement for the Apple Support Communities website ("ASC"). Readers of ASC may copy it for their own personal use. Neither the whole nor any part may be redistributed.

  • Better Way To Do This? Selector Operator...

    I'm currently writing the selection operator for the algorithm. The aim of it is
    to rate how the coursework block have been allocated and give there allocation
    a rating...
    How I have done it is have a method that searches through the one of the parent
    timetables. It looks for coursework time blocks. Once it finds one it notes
    this and looks at the next block along. If this is a coursework time block it
    notes this as well. I then perform an operation comparing these two coursework
    time blocks to find out if they are for the same Module. If they are not this
    is not a very effective coursework timetable strategy.
    Because of this I note in an array the the position of these two coursework time
    block and give them a fitness rating of 1000. I then go on to see if the next
    block is a coursework time block. If it is and its not of the same Module ID of
    the two previous then I not these 3 block down in an array and give them a
    fitness rating of 2000.
    My concern is that I am using allot of if and for loop's and the code is
    starting to look untidy at best. Is there any better way of doing this?
    Below Is my code:
          * @param parentOne
          * @param parentTwo
         public void selectionOperator(ArrayList parentOne, ArrayList parentTwo){
              // Store's the fitness rating of sections of the timetable...          
              ArrayList parentOneBlockFitnessRating = new ArrayList ();
              ArrayList parentTwoBlockFitnessRating = new ArrayList ();
              //Loops through the timetable's timeblocks...
              for (int i = 0; i < parentOne.size(); i++) {
                   //Checks to see if the current time block is of the class: CourseworkTimeBlock,
                   //if so it enters this statement...
                   if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                        //A temp store for the current CourseworkTimeBlock...
                        CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentOne.get(i);
                        System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
                        //Checks to see if the next time block along is of the class: CourseworkTimeBlock,
                        //if so it enters this statement...
                        if(parentOne.get(i+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                             //A temp store for the next CourseworkTimeBlock...
                             CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentOne.get(i+1);
                             System.out.println("Got Here Aswell!");
                             //Checks to see if the current and next CourseworkTimeBlock module Id's
                             //are the same, if there arn't then this section is entered...
                             if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
                                  //Checks to see if the second time block along is of the class: CourseworkTimeBlock,
                                  //if so it enters this statement...
                                  if(parentTwo.get(i+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                                       //A temp store for the second CourseworkTimeBlock along...
                                       CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(i+2);
                                       //Checks to see if all 3 of the Module Id's of the CourseworkTimeBlocks match,
                                       //if they don't match this statement is entered...
                                       if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
                                            //ArrayList to store the fitness rating of the current block
                                            //selection...
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(i);
                                            //Position of second block.
                                            blockFitness.add(i+1);
                                            //Position of second block.
                                            blockFitness.add(i+2);
                                            //Fitness Value
                                            blockFitness.add(2000);
                                            //Add block rating to main rating ArrayList...
                                            parentOneBlockFitnessRating.add(blockFitness);
                                       else{
                                            //ArrayList to store the fitness rating of the current block
                                            //selection...
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(i);
                                            //Position of second block.
                                            blockFitness.add(i+1);
                                            //Fitness Value
                                            blockFitness.add(1000);
                                            //Add block rating to main rating ArrayList...
                                            parentOneBlockFitnessRating.add(blockFitness);
              for (int o = 0; o < parentTwo.size(); o++) {
                   if(parentTwo.get(o).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                        CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentTwo.get(o);
                        System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
                        if(parentTwo.get(o+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                             CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentTwo.get(o+1);
                             System.out.println("Got Here Aswell!");
                             if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
                                  if(parentTwo.get(o+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                                       CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(o+2);
                                       if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(o);
                                            //Position of second block.
                                            blockFitness.add(o+1);
                                            //Position of second block.
                                            blockFitness.add(o+2);
                                            //Fitness Value
                                            blockFitness.add(2000);
                                            //Add block rating to main rating ArrayList...
                                            parentTwoBlockFitnessRating.add(blockFitness);
                                       else{
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(o);
                                            //Position of second block.
                                            blockFitness.add(o+1);
                                            //Fitness Value
                                            blockFitness.add(1000);
                                            //Add block rating to main rating ArrayList...
                                            parentTwoBlockFitnessRating.add(blockFitness);
         }As you can see there are allot if statements and some bad coding practice to boot. But I don't know what other ways to do it....
    Any directions of other ways how to do this?
    Many Thanks
    Chris

    Unfortunately, I think you're stuck with a bunch of if-statements.
    Fortunately, I have some things that may help you.
    First, I usually make sure something is of x class via this
    if (someObject instanceof SomeClass) {So, I'd adjust your 'class checking' conditionals from this
    if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock"))to this
    if (parentOne.get(i) instanceof Timetable.CourseworkTimeBlock) {Secondly, your code logic is kind of confusing.
    Why do you have a for-loop that iterates through every CourseworkTimeBlock, if you then (within each possible iteration) check iteration+1 and iteration+2? What happens if those throw an ArrayIndexOutOfBoundsException, or are null?

  • Better Way to do this loop.

    I know there is better ways to do this so that I can merely have it loop infinitely until it hits the max password. I would also like to keep the spot where it has the print Statements because I tend to set some other code in front of it.
    If anyone also has some Ideas so I can have it stop and start in particular positions.
    Like lets say ?!!!!? to ?~~~~?
    Thanks a ton. Below is the code.
       char[] password = new char[20];
       int current_last_letter = 0;
       int max_password = 3;
       while(current_last_letter < max_password)
       for(int counter_gamma = 32; counter_gamma <= 126; counter_gamma++)
           for(int counter_beta = 32; counter_beta <= 126; counter_beta++)
                for(int counter_alpha = 32; counter_alpha <= 126; counter_alpha++) //alpha = increase last character by one
                    password[current_last_letter] = (char)counter_alpha;
                    System.out.print(password);
                    System.out.println("::null");
                if(current_last_letter > 0)
                    password[current_last_letter-1] = (char)counter_beta;
                else
                    counter_beta = 127;
            if(current_last_letter > 1)
                password[current_last_letter-2] = (char)counter_gamma;
            else
                counter_gamma = 127;
       current_last_letter++;
                   

    If I interpreted your code right, you simply want to count in radix '~'-' '+1 (read this carefully).
    Given a password, and a lo/hi value for the character range, the following method returns the
    lexicographically next password. The method returns null if no such password exists --    char[] nextPassword(char[] pw, char lo, char hi) {
          for (int i= pw.lenght; --i >= 0;)
             if (pw[i] < hi) { // next character possible here?
                pw[i]++;
                return pw;
             else // * no, reset to first value and continue;
                pw= lo;
    return null; // all pw-chars reached their hi value
    So, if you initialize a password char array as follows --    char[] pw= new char[20];
       Arrays.fill(pw, ' '); the following fragment handles every possible password --    do {
          handlePassword(pw); // do something with pw
          pw= nextPassword(pw, ' ', '~');
       } while (pw != null); kind regards,
    Jos

  • Is there better way to write SQl Insert Script

    I am running out of ideas while working on one scenario and thought you guys would be able to guide me in right way.
    So, the scenario is I have a Table table1 table1(fieldkey, DisplayName, type) fieldkey - pkey   This table have n number of rows. The value of fieldkey in nth row is n. So if we have 1000 record, then the last row has a fieldkey = 1000.
    Below is my sample data.
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1001, 'COfficer',100);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1002, 'PData',100);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1003, 'EDate',100);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1004, 'PData',200);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1005, 'EDate',300);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1006, 'Owner',400);This way of inserting the row with hardcoded value of fieldkey was creating the problem when the same table was used by other developer for their own new functionality.
    So, I thought of using the max(fieldkey) +1 from that table and use it in my insert script. This script file runs every time during software installation.
    I thought of using count to see if the row with same displaytype and type exists in that table or not. If exisits do not insert new row, if not insert new row.
    It looks like i will have to query the count statement everytime before I insert the row.
    select max(fieldkey) +1 into ll_fieldkey from table1
    select count(*) into ll_count from table1 where display ltrim(upper(name)) = 'COFFICER' and type =100)
    if ll_count >0 then
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    ( ll_fieldkey, 'COfficer',100);
    ll_fieldkey := ll_fieldkey +1
    end if;
    select count(*) into ll_count from table1 where display ltrim(upper(name)) = 'PData' and type =100)
    if ll_count >0 then
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    ( ll_fieldkey, 'PData',100);
    ll_fieldkey := ll_fieldkey +1
    end if;
    ... and so on for all the insert statement. So, i was wondering if there is some better way to handle this situation of inserting the data.
    Thank you

    Hi !
    For check if the same display name and type already exists in table i would use Unique Key , but then again instead of if statement you should code some exception handlers. ... Hm .. Unque key is by may opinion better solution as
    codeing checks .
    For faster inserts that is , smaller code .. if there is no rules for values and the values are fixed , in any case you have to do this 100 inserts. If you can "calculate" values then maybe you can figure out some code .. but effect will be the same as hundred insert stetements one after another .. Procedure with this 100 inserts is not so bad solution.
    You can fill with values a nested table and then use forall ... save exceptions insert and with above mentioned UK , maybe this will be better.
    T
    Edited by: ttt on 10.3.2010 13:01

  • Better way to do this

    When selecting into a variable, is there a better way to do this? I want to make sure I don't get an error if there are no rows found. I think it's inefficient to count the number of occurrences before selecting into the variable. Can I use %NOROWSFOUND or something similar? If so, can you please provide an example? Thanks, Margaret
    Tzi := null;
    SELECT count(BUSINESS_tz)
    INTO Tzi_cnt
    FROM BUSINESS O
    WHERE ID = Fac_id AND BUSINESS_type = 'Store' AND O.Business_seq = (SELECT Business_seq
    FROM Org_lookup
    WHERE Store_seq = 0);
    IF Tzi_cnt > 0
    THEN
    SELECT BUSINESS_tz
    INTO Tzi
    FROM BUSINESS O
    WHERE ID = Fac_id AND BUSINESS_type = 'Store' AND O.Business_seq = (SELECT Business_seq

    the proper way to do this is to use an exception block;
    so
    begin
    Tzi := null;
    SELECT BUSINESS_tz
    INTO Tzi_cnt
    FROM BUSINESS O
    WHERE ID = Fac_id AND BUSINESS_type = 'Store' AND O.Business_seq = (SELECT Business_seq
    FROM Org_lookup
    WHERE Store_seq = 0);
    exception
    when no_data_found
    then
       null;   -- put any code to execute here or raise exception
    end;you can also use sql%rowcount to find out how many rows your sql statement affected:
    eg directly after your sql and before any rollback or commit
    declare
    v_rowcount number;
    begin
    insert into <table_name>
    select * from <other_table>;
    v_rowcount := sql%rowcount;
    end;

  • How to create a function with dynamic sql or any better way to achieve this?

            Hello,
            I have created below SQL query which works fine however when scalar function created ,it
            throws an error "Only functions and extended stored procedures can be executed from within a
            function.". In below code First cursor reads all client database names and second cursor
            reads client locations.
                      DECLARE @clientLocation nvarchar(100),@locationClientPath nvarchar(Max);
                      DECLARE @ItemID int;
                      SET @locationClientPath = char(0);
                      SET @ItemID = 67480;
       --building dynamic sql to replace database name at runtime
             DECLARE @strSQL nvarchar(Max);
             DECLARE @DatabaseName nvarchar(100);
             DECLARE @localClientPath nvarchar(MAX) ;
                      Declare databaselist_cursor Cursor for select [DBName] from [DataBase].[dbo].
                      [tblOrganization] 
                      OPEN databaselist_cursor
                      FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                      WHILE @@FETCH_STATUS = 0
                      BEGIN       
       PRINT 'Processing DATABASE: ' + @DatabaseName;
        SET @strSQL = 'DECLARE organizationlist_cursor CURSOR
        FOR SELECT '+ @DatabaseName +'.[dbo].[usGetLocationPathByRID]
                                   ([LocationRID]) 
        FROM '+ @DatabaseName +'.[dbo].[tblItemLocationDetailOrg] where
                                   ItemId = '+ cast(@ItemID as nvarchar(20))  ;
         EXEC sp_executesql @strSQL;
        -- Open the cursor
        OPEN organizationlist_cursor
        SET @localClientPath = '';
        -- go through each Location path and return the 
         FETCH NEXT FROM organizationlist_cursor into @clientLocation
         WHILE @@FETCH_STATUS = 0
          BEGIN
           SELECT @localClientPath =  @clientLocation; 
           SELECT @locationClientPath =
    @locationClientPath + @clientLocation + ','
           FETCH NEXT FROM organizationlist_cursor INTO
    @clientLocation
          END
           PRINT 'current databse client location'+  @localClientPath;
         -- Close the Cursor
         CLOSE organizationlist_cursor;
         DEALLOCATE organizationlist_cursor;
         FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                    END
                    CLOSE databaselist_cursor;
                    DEALLOCATE databaselist_cursor;
                    -- Trim the last comma from the string
                   SELECT @locationClientPath = SUBSTRING(@locationClientPath,1,LEN(@locationClientPath)-  1);
                     PRINT @locationClientPath;
            I would like to create above query in function so that return value would be used in 
            another query select statement and I am using SQL 2005.
            I would like to know if there is a way to make this work as a function or any better way
            to  achieve this?
            Thanks,

    This very simple: We cannot use dynamic SQL from used-defined functions written in T-SQL. This is because you are not permitted do anything in a UDF that could change the database state (as the UDF may be invoked as part of a query). Since you can
    do anything from dynamic SQL, including updates, it is obvious why dynamic SQL is not permitted as per the microsoft..
    In SQL 2005 and later, we could implement your function as a CLR function. Recall that all data access from the CLR is dynamic SQL. (here you are safe-guarded, so that if you perform an update operation from your function, you will get caught.) A word of warning
    though: data access from scalar UDFs can often give performance problems and its not recommended too..
    Raju Rasagounder Sr MSSQL DBA
          Hi Raju,
           Can you help me writing CLR for my above function? I am newbie to SQL CLR programming.
           Thanks in advance!
           Satya
              

  • IPhoto allowed me to add location to photos taken by camera with no GPS.  Photos doesn't have this facility. is there any way to do this?

    iPhoto allowed me to add location to photos taken by camera with no GPS.  Photos doesn't have this facility. Is there any way to do this?

    From http://geotag.modesittsoftware.com/Photo_GeoTag/FAQs.html
    1. Does Photo GeoTag work with iPhoto and Photos?
    iPhoto and Photos store their image files in various undocumented locations, and they seem to store the image metadata in separate locations.  If you edit an image in one of their sub-folders, iPhoto or Photos may not know about the change.  Instead export the image from iPhoto or Photos, geotag it, and then import it back into iPhoto or Photos to see the geotagged location.  In the future Apple may provide a means of accessing the image files directly, but for now you must geotag the photo before importing it, or if the photo is already in iPhoto or Photos, export, geotag, and then import.
    So it would seem that it isn't much better than using iPhoto 9.6.1 to do the geotagging, exporting the original from that app, & importing it into Photos.

Maybe you are looking for

  • E4500 firmware corrupt after power outage

    Latest firmware with CCC corrupted after power outage. I reseet the e4500 several times and tried to reload the firmware and still no good. Only way I got it back up is to install the older non-CCC version 2.37. Strange all was fine until the power o

  • Is my powerbook electrocuting me?

    I dropped my powerbook, unprotected, a couple of feet yesterday and it landed right on the corner that is closest to the battery (with the laptop open, this is the front left corner on the base [non-screen] portion of the computer). There is a bit of

  • TS3989 Missing pictures

    I am missing a lot of pictures in my photo stream how do I retrieve them

  • Edge Turn-In Shipping Label

    I need a shipping label to turn in my old phone used for Edge up.  The label links included in the recent order under my verizon only include links for returning the new phone.  I need a link that prints a label for a turn-in phone, not a return (pho

  • Can you fix a cracked screen

    my ipod screen has a crack on it and i was wondering if apple can fix the screen. the ipod works like normal its just the screen that is cracked.