Search Results

Search found 5942 results on 238 pages for 'total starnger'.

Page 225/238 | < Previous Page | 221 222 223 224 225 226 227 228 229 230 231 232  | Next Page >

  • Build and migrated to software raid (mdadm) on GPT disk, now can't assemble array

    - by John H
    mdadm, gpt issues, unrecognized partitions. Simplified question: How do I get mdadm to recognize GPT partitions? I have been attempting to convert/copy my Ubuntu 11.10 OS from a single drive to software raid 1. I have done similar in the past, but in this case, I was adding in a drive that has been configured for GPT and I tried to work with that without fully looking into the implications. Currently, I have a non-booting mdadm RAID 1 array of /dev/md127 (the OS assigned that and it keeps picking up). I am booting off of live USB keys, currently System Rescue CD from sysresccd. While gdisk and parted can see all the partitions, most of the OS utilities do not, including mdadm. My main goal is just to make the raid array accessible so I can get pull the data and start fresh (without using GPT). /dev/md127 /dev/sda /dev/sda1 <- GPT type partition /dev/sda1 <- exists within the GPT part, member of md127 /dev/sda2 <- exists within the GPT part, empty /dev/sdb /dev/sdb1 <- GPT type partition /dev/sdb1 <- exists within the GPT part, member of md127 History: POINT A: The original OS was install on sda (actually /dev/sda6). I used a the Ubuntu live usb to add sdb. I got warning from fdisk about GPT so I used gdisk to create a raid partition (sdb1) and mdadm to create a raid1 mirror with a missing drive. I had many issues getting this working (including being unable to get grub to install) but I eventually got it to boot using grub on sda and /dev/md127 off of sdb. So at point A, I had copied my OS from sda6 to md127 on sdb. I then booted into a rescue mode and attempted to get a bootloader onto sdb, which failed. I then discovered my mistake: I had installed the raid onto sdb instead of sdb1, essentially overwriting the sdb1 partition. POINT B: I now had two copies of my data- one on md127/sdb, and one on sda. I destroyed data on sda and created a new GPT table on sda. I then created sda1 for the raid array, and sda2 for a scratch partition. I added sda1 into the raid array and let it rebuild. md127 now covered /dev/sdb and /dev/sda1 as fully active and synced. POINT C: I rebooted onto linux rescue again and was still able to access the raid array. I then removed /dev/sdb from the array and created /dev/sdb1 for the raid. I added sdb1 to the array and let it sync. I was able to mount and access /dev/md127 without issues. Once it completed, both /dev/sda1 and /dev/sdb1 were GPT partitions and actively syncing. POINT D (current): I rebooted again to test if the array would boot and grub failed to load. I booted off of my live thumb drive and found that I can no longer assemble the raid array. mdadm doesn't see the required partitions. -- root@freshdesk /root % uname -a Linux freshdesk 3.0.24-std251-amd64 #2 SMP Sat Mar 17 12:08:55 UTC 2012 x86_64 AMD Athlon(tm) II X4 645 Processor AuthenticAMD GNU/Linux === /proc/partitions and parted look good: root@freshdesk /root % cat /proc/partitions major minor #blocks name 7 0 301788 loop0 8 0 976762584 sda 8 1 732579840 sda1 8 2 244181703 sda2 8 16 732574584 sdb 8 17 732573543 sdb1 8 32 7876607 sdc 8 33 7873349 sdc1 (parted) print all Model: ATA ST31000528AS (scsi) Disk /dev/sda: 1000GB Sector size (logical/physical): 512B/512B Partition Table: gpt Number Start End Size File system Name Flags 1 1049kB 750GB 750GB ext4 2 750GB 1000GB 250GB Linux/Windows data Model: ATA SAMSUNG HD753LJ (scsi) Disk /dev/sdb: 750GB Sector size (logical/physical): 512B/512B Partition Table: gpt Number Start End Size File system Name Flags 1 1049kB 750GB 750GB ext4 Linux RAID raid Model: SanDisk SanDisk Cruzer (scsi) Disk /dev/sdc: 8066MB Sector size (logical/physical): 512B/512B Partition Table: msdos Number Start End Size Type File system Flags 1 31.7kB 8062MB 8062MB primary fat32 boot, lba === # no sda2, and I double the sdb1 is the one shown in parted root@freshdesk /root % blkid /dev/loop0: TYPE="squashfs" /dev/sda1: UUID="75dd6c2d-f0a8-4302-9da4-792cc7d72355" TYPE="ext4" /dev/sdc1: LABEL="PENDRIVE" UUID="1102-3720" TYPE="vfat" /dev/sdb1: UUID="2dd89f15-65bb-ff88-e368-bf24bd0fce41" TYPE="linux_raid_member" root@freshdesk /root % mdadm -E /dev/sda1 mdadm: No md superblock detected on /dev/sda1. # this is probably a result of me attempting to force the array up, putting superblocks on the GPT partition root@freshdesk /root % mdadm -E /dev/sdb1 /dev/sdb1: Magic : a92b4efc Version : 0.90.00 UUID : 2dd89f15:65bbff88:e368bf24:bd0fce41 Creation Time : Fri Mar 30 19:25:30 2012 Raid Level : raid1 Used Dev Size : 732568320 (698.63 GiB 750.15 GB) Array Size : 732568320 (698.63 GiB 750.15 GB) Raid Devices : 2 Total Devices : 2 Preferred Minor : 127 Update Time : Sat Mar 31 12:39:38 2012 State : clean Active Devices : 1 Working Devices : 2 Failed Devices : 1 Spare Devices : 1 Checksum : a7d038b3 - correct Events : 20195 Number Major Minor RaidDevice State this 2 8 17 2 spare /dev/sdb1 0 0 8 1 0 active sync /dev/sda1 1 1 0 0 1 faulty removed 2 2 8 17 2 spare /dev/sdb1 === root@freshdesk /root % mdadm -A /dev/md127 /dev/sda1 /dev/sdb1 mdadm: no recogniseable superblock on /dev/sda1 mdadm: /dev/sda1 has no superblock - assembly aborted root@freshdesk /root % mdadm -A /dev/md127 /dev/sdb1 mdadm: cannot open device /dev/sdb1: Device or resource busy mdadm: /dev/sdb1 has no superblock - assembly aborted

    Read the article

  • My IDE is showing "undeclared FileNotFoundException must be caught or thrown"

    - by Dan Czarnecki
    I am having the following issue above. I have tried actually putting a try-catch statement into the code as you will see below, but I can't get the compiler to get past that. import java.io.*; public class DirectoryStatistics extends DirectorySize { /* Dan Czarnecki October 24, 2013 Class variables: private File directory A File object that holds the pathname of the directory to look in private long sizeInBytes A variable of type long that holds the size of a file/directory (in bytes) private long fileCount A variable of type long that holds the number of files in a directory Constructors: public DirectoryStatistics(File startingDirectory) throws FileNotFoundException Creates a DirectoryStatistics object, given a pathname (inherited from DirectorySize class), and has 3 instance variables that hold the directory to search in, the size of each file (in bytes), and the number of files within the directory Modification history: October 24, 2013 Original version of class */ private File directory; private long sizeInBytes; private long fileCount; public DirectoryStatistics(File startingDirectory) throws FileNotFoundException { super(startingDirectory); try { if(directory == null) { throw new IllegalArgumentException("null input"); } if(directory.isDirectory() == false) { throw new FileNotFoundException("the following input is not a directory!"); } } catch(IOException ioe) { System.out.println("You have not entered a directory. Please try again."); } } public File getDirectory() { return this.directory; } public long getSizeInBytes() { return this.sizeInBytes; } public long getFileCount() { return this.fileCount; } public long setFileCount(long size) { fileCount = size; return size; } public long setSizeInBytes(long size) { sizeInBytes = size; return size; } public void incrementFileCount() { fileCount = fileCount + 1; } public void addToSizeInBytes(long addend) { sizeInBytes = sizeInBytes + addend; } public String toString() { return "Directory" + this.directory + "Size (in bytes) " + this.sizeInBytes + "Number of files: " + this.fileCount; } public int hashCode() { return this.directory.hashCode(); } public boolean equals(DirectoryStatistics other) { return this.equals(other); } } import java.io.*; import java.util.*; public class DirectorySize extends DirectoryProcessor { /* Dan Czarnecki October 17, 2013 Class variables: private Vector<Long> directorySizeList Variable of type Vector<Long> that holds the total file size of files in that directory as well as files within folders of that directory private Vector<File> currentFile Variable of type Vector<File> that holds the parent directory Constructors: public DirectorySize(File startingDirectory) throws FileNotFoundException Creates a DirectorySize object, takes in a pathname (inherited from DirectoryProcessor class, and has a single vector of a DirectoryStatistics object to hold the files and folders within a directory Modification History October 17, 2013 Original version of class Implemented run() and processFile() methods */ private Vector<DirectoryStatistics> directory; /* private Vector<Long> directorySizeList; private Vector<File> currentFile; */ public DirectorySize(File startingDirectory) throws FileNotFoundException { super(startingDirectory); directory = new Vector<DirectoryStatistics>(); } public void processFile(File file) { DirectoryStatistics parent; int index; File parentFile; System.out.println(file.getName()); System.out.println(file.getParent()); parentFile = file.getParentFile(); parent = new DirectoryStatistics(parentFile); System.out.println(parent); parent.equals(parent); index = directory.indexOf(parent); if(index == 0) { directory.elementAt(index).addToSizeInBytes(file.length()); directory.elementAt(index).incrementFileCount(); } if(index < 0) { directory.addElement(parent); directory.lastElement().setSizeInBytes(file.length()); directory.lastElement().incrementFileCount(); } Could someone tell me why I'm getting this issue?

    Read the article

  • Improving TCP performance over a gigabit network lots of connections and high traffic for storage and streaming services

    - by Linux Guy
    I have two servers, Both servers hardware Specification are Processor : Dual Processor RAM : over 128 G.B Hard disk : SSD Hard disk Outging Traffic bandwidth : 3 Gbps network cards speed : 10 Gbps Server A : for Encoding videos Server B : for storage videos andstream videos over web interface like youtube The inbound bandwidth between two servers is 10Gbps , the outbound bandwidth internet bandwidth is 500Mpbs Both servers using public ip addresses in public and private network Both servers transfer and connection on nginx port , and the server B used for streaming media , like youtube stream videos Both servers in same network , when i do ping from Server A to Server B i got high time latency above 1.0ms , the time range time=52.7 ms to time=215.7 ms - This is the output of iftop utility 353Mb 707Mb 1.04Gb 1.38Gb 1.73Gb mqqqqqqqqqqqqqqqqqqqqqqqqqqqvqqqqqqqqqqqqqqqqqqqqqqqqqqqvqqqqqqqqqqqqqqqqqqqqqqqqqqqvqqqqqqqqqqqqqqqqqqqqqqqqqqqvqqqqqqqqqqqqqqqqqqqqqqqqqqq server.example.com => ip.address 6.36Mb 4.31Mb 1.66Mb <= 158Kb 94.8Kb 35.1Kb server.example.com => ip.address 1.23Mb 4.28Mb 1.12Mb <= 17.1Kb 83.5Kb 21.9Kb server.example.com => ip.address 395Kb 3.89Mb 1.07Mb <= 6.09Kb 109Kb 28.6Kb server.example.com => ip.address 4.55Mb 3.83Mb 1.04Mb <= 55.6Kb 45.4Kb 13.0Kb server.example.com => ip.address 649Kb 3.38Mb 1.47Mb <= 9.00Kb 38.7Kb 16.7Kb server.example.com => ip.address 5.00Mb 3.32Mb 1.80Mb <= 65.7Kb 55.1Kb 29.4Kb server.example.com => ip.address 387Kb 3.13Mb 1.06Mb <= 18.4Kb 39.9Kb 15.0Kb server.example.com => ip.address 3.27Mb 3.11Mb 1.01Mb <= 81.2Kb 64.5Kb 20.9Kb server.example.com => ip.address 1.75Mb 3.08Mb 2.72Mb <= 16.6Kb 35.6Kb 32.5Kb server.example.com => ip.address 1.75Mb 2.90Mb 2.79Mb <= 22.4Kb 32.6Kb 35.6Kb server.example.com => ip.address 3.03Mb 2.78Mb 1.82Mb <= 26.6Kb 27.4Kb 20.2Kb server.example.com => ip.address 2.26Mb 2.66Mb 1.36Mb <= 51.7Kb 49.1Kb 24.4Kb server.example.com => ip.address 586Kb 2.50Mb 1.03Mb <= 4.17Kb 26.1Kb 10.7Kb server.example.com => ip.address 2.42Mb 2.49Mb 2.44Mb <= 31.6Kb 29.7Kb 29.9Kb server.example.com => ip.address 2.41Mb 2.46Mb 2.41Mb <= 26.4Kb 24.5Kb 23.8Kb server.example.com => ip.address 2.37Mb 2.39Mb 2.40Mb <= 28.9Kb 27.0Kb 28.5Kb server.example.com => ip.address 525Kb 2.20Mb 1.05Mb <= 7.03Kb 26.0Kb 12.8Kb qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq TX: cum: 102GB peak: 1.65Gb rates: 1.46Gb 1.44Gb 1.48Gb RX: 1.31GB 24.3Mb 19.5Mb 18.9Mb 20.0Mb TOTAL: 103GB 1.67Gb 1.48Gb 1.46Gb 1.50Gb I check the transfer speed using iperf utility From Server A to Server B # iperf -c 0.0.0.2 -p 8777 ------------------------------------------------------------ Client connecting to 0.0.0.2, TCP port 8777 TCP window size: 85.3 KByte (default) ------------------------------------------------------------ [ 3] local 0.0.0.1 port 38895 connected with 0.0.0.2 port 8777 [ ID] Interval Transfer Bandwidth [ 3] 0.0-10.8 sec 528 KBytes 399 Kbits/sec My Current Connections in Server B # netstat -an|grep ":8777"|awk '/tcp/ {print $6}'|sort -nr| uniq -c 2072 TIME_WAIT 28 SYN_RECV 1 LISTEN 189 LAST_ACK 139 FIN_WAIT2 373 FIN_WAIT1 3381 ESTABLISHED 34 CLOSING Server A Network Card Information Settings for eth0: Supported ports: [ TP ] Supported link modes: 100baseT/Full 1000baseT/Full 10000baseT/Full Supported pause frame use: No Supports auto-negotiation: Yes Advertised link modes: 10000baseT/Full Advertised pause frame use: No Advertised auto-negotiation: Yes Speed: 10000Mb/s Duplex: Full Port: Twisted Pair PHYAD: 0 Transceiver: external Auto-negotiation: on MDI-X: Unknown Supports Wake-on: d Wake-on: d Current message level: 0x00000007 (7) drv probe link Link detected: yes Server B Network Card Information Settings for eth2: Supported ports: [ FIBRE ] Supported link modes: 10000baseT/Full Supported pause frame use: No Supports auto-negotiation: No Advertised link modes: 10000baseT/Full Advertised pause frame use: No Advertised auto-negotiation: No Speed: 10000Mb/s Duplex: Full Port: Direct Attach Copper PHYAD: 0 Transceiver: external Auto-negotiation: off Supports Wake-on: d Wake-on: d Current message level: 0x00000007 (7) drv probe link Link detected: yes ifconfig server A eth0 Link encap:Ethernet HWaddr 00:25:90:ED:9E:AA inet addr:0.0.0.1 Bcast:0.0.0.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1202795665 errors:0 dropped:64334 overruns:0 frame:0 TX packets:2313161968 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:893413096188 (832.0 GiB) TX bytes:3360949570454 (3.0 TiB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:2207544 errors:0 dropped:0 overruns:0 frame:0 TX packets:2207544 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:247769175 (236.2 MiB) TX bytes:247769175 (236.2 MiB) ifconfig Server B eth2 Link encap:Ethernet HWaddr 00:25:90:82:C4:FE inet addr:0.0.0.2 Bcast:0.0.0.2 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:39973046980 errors:0 dropped:1828387600 overruns:0 frame:0 TX packets:69618752480 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:3013976063688 (2.7 TiB) TX bytes:102250230803933 (92.9 TiB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:1049495 errors:0 dropped:0 overruns:0 frame:0 TX packets:1049495 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:129012422 (123.0 MiB) TX bytes:129012422 (123.0 MiB) Netstat -i on Server B # netstat -i Kernel Interface table Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg eth2 9000 0 42098629968 0 2131223717 0 73698797854 0 0 0 BMRU lo 65536 0 1077908 0 0 0 1077908 0 0 0 LRU I Turn up send/receive buffers on the network card to 2048 and problem still persist I increase the MTU for server A and problem still persist and i increase the MTU for server B for better connectivity and transfer speed but it couldn't transfer at all The problem is : as you can see from iperf utility, the transfer speed from server A to server B slow when i restart network service in server B the transfer in server A at full speed, after 2 minutes , it's getting slow How could i troubleshoot slow speed issue and fix it in server B ? Notice : if there any other commands i should execute in servers for more information, so it might help resolve the problem , let me know in comments

    Read the article

  • evaluating cost/benefits of using extension methods in C# => 3.0

    - by BillW
    Hi, In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ? < full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text. A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands." While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions. Looking at MS's guidelines at link text, you find : In general, you will probably be calling extension methods far more often than implementing your own. ... In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type. For more information, see Inheritance (C# Programming Guide). ... When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds. And at Ms's link text : Extension methods present no specific security vulnerabilities. They can never be used to impersonate existing methods on a type, because all name collisions are resolved in favor of the instance or static method defined by the type itself. Extension methods cannot access any private data in the extended class. Factors that seem obvious to me would include : I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ? Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ? How frequent use of Extensions would affect run-time performance or memory use : I have no idea. So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing. thanks, Bill

    Read the article

  • KB2667402 update fails to install with 0x80004005. Yet it's also showing as installed

    - by growse
    I've got 15 Windows 2008 R2 x64 servers that I manage with SCCM2012. I've noticed during my Windows updates reporting that there's two boxes that are showing as 'error' for total updates installed. Digging around, it looks like the update that is failing to install is KB2667402. The Software Centre on the server itself shows the following: The software change returned error code 0x80004005(-2147467259). So SCCM thinks it hasn't installed the update. However, if I go to the Programs and Features application and select 'Windows Updates', I can see an entry for KB2667402: If I try and uninstall this, I get an error: An error occurred. Not all of the updates were successfully uninstalled If I try and download the patch from Microsoft directly, I get the same error installing as displayed in Software Centre. The only odd thing about this setup that I can think would affect this is that I run the RDP service on a non-standard port. However, I do this across all the servers, so it seems odd that it would fail on just 2 out of 15. The tail of the WindowsUpdate.log file is below: 2012-06-26 15:33:53:184 3924 1608 COMAPI ------------- 2012-06-26 15:33:53:190 3924 1608 COMAPI -- START -- COMAPI: Install [ClientId = CcmExec] 2012-06-26 15:33:53:190 3924 1608 COMAPI --------- 2012-06-26 15:33:53:190 3924 1608 COMAPI - Allow source prompts: No; Forced: No; Force quiet: Yes 2012-06-26 15:33:53:190 3924 1608 COMAPI - Updates in request: 1 2012-06-26 15:33:53:190 3924 1608 COMAPI - ServiceID = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7} Managed 2012-06-26 15:33:53:199 860 1198 Agent ************* 2012-06-26 15:33:53:199 860 1198 Agent ** START ** Agent: Installing updates [CallerId = CcmExec] 2012-06-26 15:33:53:199 860 1198 Agent ********* 2012-06-26 15:33:53:199 860 1198 Agent * Updates to install = 1 2012-06-26 15:33:53:201 860 1198 Agent * Title = Security Update for Windows Server 2008 R2 x64 Edition (KB2667402) 2012-06-26 15:33:53:201 860 1198 Agent * UpdateId = {48859BE4-1331-4CD2-8E70-3B537180A0D0}.103 2012-06-26 15:33:53:201 860 1198 Agent * Bundles 1 updates: 2012-06-26 15:33:53:201 860 1198 Agent * {D854ECF1-99A7-4D67-B435-2D041BF79565}.103 2012-06-26 15:33:53:204 3924 1608 COMAPI - Updates to install = 1 2012-06-26 15:33:53:204 3924 1608 COMAPI <<-- SUBMITTED -- COMAPI: Install [ClientId = CcmExec] 2012-06-26 15:33:53:221 860 1198 Agent WARNING: failed to calculate prior restore point time with error 0x80070002; setting restore point 2012-06-26 15:33:53:222 860 1198 Agent WARNING: LoadLibrary failed for srclient.dll with hr:8007007e 2012-06-26 15:33:53:322 860 1198 DnldMgr Preparing update for install, updateId = {D854ECF1-99A7-4D67-B435-2D041BF79565}.103. 2012-06-26 15:33:53:325 5700 117c Misc =========== Logging initialized (build: 7.5.7601.17514, tz: +0100) =========== 2012-06-26 15:33:53:325 5700 117c Misc = Process: C:\Windows\system32\wuauclt.exe 2012-06-26 15:33:53:325 5700 117c Misc = Module: C:\Windows\system32\wuaueng.dll 2012-06-26 15:33:53:324 5700 117c Handler ::::::::::::: 2012-06-26 15:33:53:325 5700 117c Handler :: START :: Handler: CBS Install 2012-06-26 15:33:53:325 5700 117c Handler ::::::::: 2012-06-26 15:33:53:330 5700 117c Handler Starting install of CBS update D854ECF1-99A7-4D67-B435-2D041BF79565 2012-06-26 15:33:53:342 5700 117c Handler CBS package identity: Package_for_KB2667402~31bf3856ad364e35~amd64~~6.1.2.0 2012-06-26 15:33:53:366 5700 117c Handler Installing self-contained with source=C:\Windows\SoftwareDistribution\Download\44059e0415033d6f699a50ef69dd5ff2\windows6.1-kb2667402-v2-x64.cab, workingdir=C:\Windows\SoftwareDistribution\Download\44059e0415033d6f699a50ef69dd5ff2\inst 2012-06-26 15:33:56:270 5700 3b8 Handler FATAL: CBS called Error with 0x80004005, 2012-06-26 15:33:56:402 5700 117c Handler FATAL: Completed install of CBS update with type=0, requiresReboot=0, installerError=1, hr=0x80004005 2012-06-26 15:33:56:405 5700 117c Handler ::::::::: 2012-06-26 15:33:56:406 5700 117c Handler :: END :: Handler: CBS Install 2012-06-26 15:33:56:406 5700 117c Handler ::::::::::::: 2012-06-26 15:33:56:433 860 1198 Agent ********* 2012-06-26 15:33:56:433 860 1198 Agent ** END ** Agent: Installing updates [CallerId = CcmExec] 2012-06-26 15:33:56:433 860 1198 Agent ************* 2012-06-26 15:33:56:433 860 d14 AU Can not perform non-interactive scan if AU is interactive-only 2012-06-26 15:33:56:450 3924 e40 COMAPI >>-- RESUMED -- COMAPI: Install [ClientId = CcmExec] 2012-06-26 15:33:56:450 3924 e40 COMAPI - Install call complete (succeeded = 0, succeeded with errors = 0, failed = 1, unaccounted = 0) 2012-06-26 15:33:56:450 3924 e40 COMAPI - Reboot required = No 2012-06-26 15:33:56:450 3924 e40 COMAPI - WARNING: Exit code = 0x00000000; Call error code = 0x80240022 2012-06-26 15:33:56:451 3924 e40 COMAPI --------- 2012-06-26 15:33:56:451 3924 e40 COMAPI -- END -- COMAPI: Install [ClientId = CcmExec] 2012-06-26 15:33:56:451 3924 e40 COMAPI ------------- 2012-06-26 15:33:56:536 860 13a4 AU Triggering Offline detection (non-interactive) 2012-06-26 15:33:56:536 860 d14 AU ############# 2012-06-26 15:33:56:536 860 d14 AU ## START ## AU: Search for updates 2012-06-26 15:33:56:536 860 d14 AU ######### 2012-06-26 15:33:56:539 860 d14 AU <<## SUBMITTED ## AU: Search for updates [CallId = {2DBB046C-2265-421B-A37B-93BDECC6C261}] 2012-06-26 15:33:56:539 860 1788 Agent ************* 2012-06-26 15:33:56:539 860 1788 Agent ** START ** Agent: Finding updates [CallerId = AutomaticUpdates] 2012-06-26 15:33:56:539 860 1788 Agent ********* 2012-06-26 15:33:56:539 860 1788 Agent * Online = No; Ignore download priority = No 2012-06-26 15:33:56:539 860 1788 Agent * Criteria = "IsInstalled=0 and DeploymentAction='Installation' or IsPresent=1 and DeploymentAction='Uninstallation' or IsInstalled=1 and DeploymentAction='Installation' and RebootRequired=1 or IsInstalled=0 and DeploymentAction='Uninstallation' and RebootRequired=1" 2012-06-26 15:33:56:539 860 1788 Agent * ServiceID = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7} Managed 2012-06-26 15:33:56:539 860 1788 Agent * Search Scope = {Machine} 2012-06-26 15:33:58:562 860 1788 Agent * Found 0 updates and 70 categories in search; evaluated appl. rules of 180 out of 1072 deployed entities 2012-06-26 15:33:58:565 860 1788 Agent ********* 2012-06-26 15:33:58:565 860 1788 Agent ** END ** Agent: Finding updates [CallerId = AutomaticUpdates] 2012-06-26 15:33:58:565 860 1788 Agent ************* 2012-06-26 15:33:58:650 860 f2c AU >>## RESUMED ## AU: Search for updates [CallId = {2DBB046C-2265-421B-A37B-93BDECC6C261}] 2012-06-26 15:33:58:650 860 f2c AU # 0 updates detected 2012-06-26 15:33:58:650 860 f2c AU ######### 2012-06-26 15:33:58:650 860 f2c AU ## END ## AU: Search for updates [CallId = {2DBB046C-2265-421B-A37B-93BDECC6C261}] 2012-06-26 15:33:58:650 860 f2c AU ############# 2012-06-26 15:33:58:650 860 f2c AU Featured notifications is disabled. 2012-06-26 15:33:58:651 860 f2c AU Successfully wrote event for AU health state:0 2012-06-26 15:33:58:652 860 f2c AU Successfully wrote event for AU health state:0

    Read the article

  • Using GA in GUI

    - by AlexT
    Sorry if this isn't clear as I'm writing this on a mobile device and I'm trying to make it quick. I've written a basic Genetic Algorithm with a binary encoding (genes) that builds a fitness value and evolves through several iterations using tournament selection, mutation and crossover. As a basic command-line example it seems to work. The problem I've got is with applying a genetic algorithm within a GUI as I am writing a maze-solving program that uses the GA to find a method through a maze. How do I turn my random binary encoded genes and fitness function (add all the binary values together) into a method to control a bot around a maze? I have built a basic GUI in Java consisting of a maze of labels (like a grid) with the available routes being in blue and the walls being in black. To reiterate my GA performs well and contains what any typical GA would (fitness method, get and set population, selection, crossover, etc) but now I need to plug it into a GUI to get my maze running. What needs to go where in order to get a bot that can move in different directions depending on what the GA says? Rough pseudocode would be great if possible As requested, an Individual is built using a separate class (Indiv), with all the main work being done in a Pop class. When a new individual is instantiated an array of ints represent the genes of said individual, with the genes being picked at random from a number between 0 and 1. The fitness function merely adds together the value of these genes and in the Pop class handles selection, mutation and crossover of two selected individuals. There's not much else to it, the command line program just shows evolution over n generations with the total fitness improving over each iteration. EDIT: It's starting to make a bit more sense now, although there are a few things that are bugging me... As Adamski has suggested I want to create an "Agent" with the options shown below. The problem I have is where the random bit string comes into play here. The agent knows where the walls are and has it laid out in a 4 bit string (i.e. 0111), but how does this affect the random 32 bit string? (i.e. 10001011011001001010011011010101) If I have the following maze (x is the start place, 2 is the goal, 1 is the wall): x 1 1 1 1 0 0 1 0 0 1 0 0 0 2 If I turn left I'm facing the wrong way and the agent will move completely off the maze if it moves forward. I assume that the first generation of the string will be completely random and it will evolve as the fitness grows but I don't get how the string will work within a maze. So, to get this straight... The fitness is the result of when the agent is able to move and is by a wall. The genes are a string of 32 bits, split into 16 sets of 2 bits to show the available actions and for the robot to move the two bits need to be passed with four bits from the agent showings its position near the walls. If the move is to go past a wall the move isn't made and it is deemed invalid and if the move is made and if a new wall is found then the fitness goes up. Is that right?

    Read the article

  • Database call crashes Android Application

    - by Darren Murtagh
    i am using a Android database and its set up but when i call in within an onClickListener and the app crashes the code i am using is mButton.setOnClickListener( new View.OnClickListener() { public void onClick(View view) { s = WorkoutChoice.this.weight.getText().toString(); s2 = WorkoutChoice.this.height.getText().toString(); int w = Integer.parseInt(s); double h = Double.parseDouble(s2); double BMI = (w/h)/h; t.setText(""+BMI); long id = db.insertTitle("001", ""+days, ""+BMI); Cursor c = db.getAllTitles(); if (c.moveToFirst()) { do { DisplayTitle(c); } while (c.moveToNext()); } } }); and the log cat for when i run it is: 04-01 18:21:54.704: E/global(6333): Deprecated Thread methods are not supported. 04-01 18:21:54.704: E/global(6333): java.lang.UnsupportedOperationException 04-01 18:21:54.704: E/global(6333): at java.lang.VMThread.stop(VMThread.java:85) 04-01 18:21:54.704: E/global(6333): at java.lang.Thread.stop(Thread.java:1391) 04-01 18:21:54.704: E/global(6333): at java.lang.Thread.stop(Thread.java:1356) 04-01 18:21:54.704: E/global(6333): at com.b00348312.workout.Splashscreen$1.run(Splashscreen.java:42) 04-01 18:22:09.444: D/dalvikvm(6333): GC_FOR_MALLOC freed 4221 objects / 252640 bytes in 31ms 04-01 18:22:09.474: I/dalvikvm(6333): Total arena pages for JIT: 11 04-01 18:22:09.574: D/dalvikvm(6333): GC_FOR_MALLOC freed 1304 objects / 302920 bytes in 29ms 04-01 18:22:09.744: D/dalvikvm(6333): GC_FOR_MALLOC freed 2480 objects / 290848 bytes in 33ms 04-01 18:22:10.034: D/dalvikvm(6333): GC_FOR_MALLOC freed 6334 objects / 374152 bytes in 36ms 04-01 18:22:14.344: D/AndroidRuntime(6333): Shutting down VM 04-01 18:22:14.344: W/dalvikvm(6333): threadid=1: thread exiting with uncaught exception (group=0x400259f8) 04-01 18:22:14.364: E/AndroidRuntime(6333): FATAL EXCEPTION: main 04-01 18:22:14.364: E/AndroidRuntime(6333): java.lang.IllegalStateException: database not open 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1567) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1484) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.b00348312.workout.DataBaseHelper.insertTitle(DataBaseHelper.java:84) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.b00348312.workout.WorkoutChoice$3.onClick(WorkoutChoice.java:84) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.view.View.performClick(View.java:2408) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.view.View$PerformClick.run(View.java:8817) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.os.Handler.handleCallback(Handler.java:587) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.os.Handler.dispatchMessage(Handler.java:92) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.os.Looper.loop(Looper.java:144) 04-01 18:22:14.364: E/AndroidRuntime(6333): at android.app.ActivityThread.main(ActivityThread.java:4937) 04-01 18:22:14.364: E/AndroidRuntime(6333): at java.lang.reflect.Method.invokeNative(Native Method) 04-01 18:22:14.364: E/AndroidRuntime(6333): at java.lang.reflect.Method.invoke(Method.java:521) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 04-01 18:22:14.364: E/AndroidRuntime(6333): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 04-01 18:22:14.364: E/AndroidRuntime(6333): at dalvik.system.NativeStart.main(Native Method) i have notice errors when the application opens but i dont no what thet are from. when i take out the statements to do with the database there is no errors and everthign runs smoothly

    Read the article

  • How to implement dynamic binary search for search and insert operations of n element (C or C++)

    - by iecut
    The idea is to use multiple arrays, each of length 2^k, to store n elements, according to binary representation of n.Each array is sorted and different arrays are not ordered in any way. In the above mentioned data structure, SEARCH is carried out by a sequence of binary search on each array. INSERT is carried out by a sequence of merge of arrays of the same length until an empty array is reached. More Detail: Lets suppose we have a vertical array of length 2^k and to each node of that array there attached horizontal array of length 2^k. That is, to the first node of vertical array, a horizontal array of length 2^0=1 is connected,to the second node of vertical array, a horizontal array of length 2^1= 2 is connected and so on. So the insert is first carried out in the first horizontal array, for the second insert the first array becomes empty and second horizontal array is full with 2 elements, for the third insert 1st and 2nd array horiz. array are filled and so on. I implemented the normal binary search for search and insert as follows: int main() { int a[20]= {0}; int n, i, j, temp; int *beg, *end, *mid, target; printf(" enter the total integers you want to enter (make it less then 20):\n"); scanf("%d", &n); if (n = 20) return 0; printf(" enter the integer array elements:\n" ); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } // sort the loaded array, binary search! for(i = 0; i < n-1; i++) { for(j = 0; j < n-i-1; j++) { if (a[j+1] < a[j]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } printf(" the sorted numbers are:"); for(i = 0; i < n; i++) { printf("%d ", a[i]); } // point to beginning and end of the array beg = &a[0]; end = &a[n]; // use n = one element past the loaded array! // mid should point somewhere in the middle of these addresses mid = beg += n/2; printf("\n enter the number to be searched:"); scanf("%d",&target); // binary search, there is an AND in the middle of while()!!! while((beg <= end) && (*mid != target)) { // is the target in lower or upper half? if (target < *mid) { end = mid - 1; // new end n = n/2; mid = beg += n/2; // new middle } else { beg = mid + 1; // new beginning n = n/2; mid = beg += n/2; // new middle } } // find the target? if (*mid == target) { printf("\n %d found!", target); } else { printf("\n %d not found!", target); } getchar(); // trap enter getchar(); // wait return 0; } Could anyone please suggest how to modify this program or a new program to implement dynamic binary search that works as explained above!!

    Read the article

  • Windows 8, NVIDIA graphics recognition fails

    - by Roy Grubb
    I just installed Windows 8 Pro OEM 64-bit (clean install) and it won't properly recognize my graphics adapter. When I installed Win8, it automatically installed the BasicDisplay.sys driver dated 6/21/2006. 6.2.9200.16384 (win8_rtm.120725-1247). Hardware - Mobo:MSi G41M-P33 Combo CPU:Intel CoreDuo 6600 Graphics:NVIDIA GeForce 9400GT *OS* - Windows 8 Pro 64-bit OEM The graphics adapter worked fine in Windows XP. The PC is a generic box, bought locally and its mobo failed recently, so I replaced it with the G41M. Microsoft wouldn't let me re-activate Windows XP with a different mobo, so I installed Win8, which appears to work except as described next. Win8 only partially recognizes the graphics adapter and won't allow NVIDIA latest driver installer to see that it's an NVIDIA card. As a result, OpenGL doesn't work, and this is needed by the software I most use. Other than that the graphics look OK. When I say 'partially recognizes', I mean that via the Control Panel, I can see that the adapter is described as NVIDIA, but the driver remains stuck at Microsoft Basic Display Adapter no matter what I try, including "Update driver..." in adapter properties. Display Screen Resolution Advanced Settings Adapter shows: Adapter Type: Microsoft Basic Display Adapter Chip Type: NVIDIA DAC Type: NVIDIA Corporation Bios Information: G27 Board - p381n17 Don't know what this means ... no mention of 9400GT Total Available Graphics Memory: 256 MB Dedicated Video Memory: 0 MB In fact the adapter has 512MB on-board video memory. System Video Memory: 0 MB Shared System Memory: 256 MB And Control Panel Device Manager Display adapters just shows Microsoft Basic Display Adapter. No other graphics adapter, and no unknown device or yellow question mark. What I have tried so far: 1. Cleared CMOS and reset. Updated BIOS and all mobo drivers as follows: 1st I used Driver Reviver to see if any driver updates were required. It found some but I didn't use that to get the drivers. Then I switched to MSi's own mobo driver utility Live Update 5. This also showed the board needed to update several so I used it to fetch the new drivers. After that it showed that everything was up to date and I checked with Driver Reviver again, which also reported no drivers now needed updating. Rebooted. Went to the NVIDIA site to get the latest graphics adapter driver. Their auto-detect "Option 2: Automatically find drivers for my NVIDIA products" said "The NVIDIA Smart Scan was unable to evaluate your system hardware. Please use Option 1 to manually find drivers for your NVIDIA products." So I downloaded 310.70-desktop-win8-win7-winvista-64bit-international-whql.exe, which lists 9400 GT under supported products, but when I run it, it says: "NVIDIA Installer cannot continue This graphics driver could not find compatible graphics hardware." Connected the display to the on-board Intel graphics (G41 Intel Express), removed the NVIDIA card and rebooted, changed to internal graphics in CMOS. Again it installs the MS Basic Display Adapter, and can't properly run my s/w that needs OpenGL. It runs on other machines with Intel Express graphics (WinXP and 7) Shut down and pulled out the power cord. Held start button to discharge all capacitors. Removed and re-inserted NVIDIA adapter in PCI-E slot and made sure properly seated. Connected the monitor to the card, screwed plug to socket. Reconnected power cord. Started and checked in BIOS that Primary Graphics Adapter was set to PCI-E. Started Windows. Uninstalled MS Basic Display Adapter in Device Manager. Screen blanks briefly, reappears. No Graphics adapter entry was then visible in Device Manager. Restarted PC. MS Basic Display Adapter Visible again in Device Manager. Clicked in Device Manager View Show hidden devices. No other graphics adapter appears, no unknown devices. Rebooted. Tried Scan for Hardware changes. None detected. Tried right-click on MS Basic Display Adapter Properties Driver Update Driver... Search automatically. It replied that it had determined driver was up to date. I checked that there were no graphic driver-related entries in Programs and Features that I could delete (none). Searched for any other drivers with nvidia in their name and deleted them, just keeping the 306.97 installer exe file. Did a Windows Update. Ran GPU-Z which shows (main items): Microsoft Basic Display Adapter GPU G72 BIOS 5.72.22.76.88 Device ID 10DE - 01D5 DDR2 Bus Width 32 Bit Memory size 64MB Driver Version nvlddmkm 6.2.9200.16384 (ForceWare 0.00) / Win8 64 NVIDIA SLI Unknown in the drop-down at the foot, "Microsoft Basic Display Adapter" is the only option If I swap hard disks in that machine to one with a Ubuntu 10.4 installation (originally installed on the same PC), lspci shows "VGA compatible controller as NVIDIA Corporation Device 01d5 (rev a1) (prog-if 00 [VGA controller])" and "kernel driver in use: nvidia" I'm out of ideas for new things to try and would be really grateful of suggestions. Thanks!

    Read the article

  • How to close a JFrame in the middle of a program

    - by Nick Gibson
    public class JFrameWithPanel extends JFrame implements ActionListener, ItemListener { int packageIndex; double price; double[] prices = {49.99, 39.99, 34.99, 99.99}; DecimalFormat money = new DecimalFormat("$0.00"); JLabel priceLabel = new JLabel("Total Price: "+price); JButton button = new JButton("Check Price"); JComboBox packageChoice = new JComboBox(); JPanel pane = new JPanel(); TextField text = new TextField(5); JButton accept = new JButton("Accept"); JButton decline = new JButton("Decline"); JCheckBox serviceTerms = new JCheckBox("I Agree to the Terms of Service.", false); JTextArea termsOfService = new JTextArea("This is a text area", 5, 10); public JFrameWithPanel() { super("JFrame with Panel"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pane.add(packageChoice); setContentPane(pane); setSize(250,250); setVisible(true); packageChoice.addItem("A+ Certification"); packageChoice.addItem("Network+ Certification "); packageChoice.addItem("Security+ Certifictation"); packageChoice.addItem("CIT Full Test Package"); pane.add(button); button.addActionListener(this); pane.add(text); text.setEditable(false); text.setBackground(Color.WHITE); text.addActionListener(this); pane.add(termsOfService); termsOfService.setEditable(false); termsOfService.setBackground(Color.lightGray); pane.add(serviceTerms); serviceTerms.addItemListener(this); pane.add(accept); accept.addActionListener(this); pane.add(decline); decline.addActionListener(this); } public void actionPerformed(ActionEvent e) { packageIndex = packageChoice.getSelectedIndex(); price = prices[packageIndex]; text.setText("$"+price); Object source = e.getSource(); if(source == accept) { if(serviceTerms.isSelected() == false) { JOptionPane.showMessageDialog(null,"Please accept the terms of service.", "Terms of Service", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(null,"Thank you. We will now move on to registering your product."); pane.dispose(); } } else if(source == decline) { System.exit(0); } } public void itemStateChanged(ItemEvent e) { int select = e.getStateChange(); } public static void main(String[] args) { String value1; int constant = 1, invalidNum = 0, answerParse, packNum, packPrice; JOptionPane.showMessageDialog(null,"Hello!"+"\nWelcome to the CIT Test Program."); JOptionPane.showMessageDialog(null,"IT WORKS!"); } }//class How do I get this frame to close so that my JOptionPane Message Dialogs can continue in the program without me exiting the program completely. EDIT: I tried .dispose() but I get this: cannot find symbol symbol : method dispose() location: class javax.swing.JPanel pane.dispose(); ^

    Read the article

  • how to speed up the code??

    - by kaushik
    i have very huge code about 600 lines plus. cant post the whole thing here. but a particular code snippet is taking so much time,leading to problems. here i post that part of code please tell me what to do speed up the processing.. please suggest the part which may be the reason and measure to improve them if this small part of code is understandable. using_data={} def join_cost(a , b): global using_data #print a #print b save_a=[] save_b=[] print 1 #for i in range(len(m)): #if str(m[i][0])==str(a): save_a=database_index[a] #for i in range(len(m)): # if str(m[i][0])==str(b): #print 'save_a',save_a #print 'save_b',save_b print 2 save_b=database_index[b] using_data[save_a[0]]=save_a s=str(save_a[1]).replace('phone','text') s=str(s)+'.pm' p=os.path.join("c:/begpython/wavnk/",s) x=open(p , 'r') print 3 for i in range(6): x.readline() k2='a' j=0 o=[] while k2 is not '': k2=x.readline() k2=k2.rstrip('\n') oj=k2.split(' ') o=o+[oj] #print o[j] j=j+1 #print j #print o[2][0] temp=long(1232332) end_time=save_a[4] #print end_time k=(j-1) for i in range(k): diff=float(o[i][0])-float(end_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i #print pm_row #print temp #print o[pm_row] #pm_row=3 q=[] print 4 l=str(p).replace('.pm','.mcep') z=open(l ,'r') for i in range(pm_row): z.readline() k3=z.readline() k3=k3.rstrip('\n') q=k3.split(' ') #print q print 5 s=str(save_b[1]).replace('phone','text') s=str(s)+'.pm' p=os.path.join("c:/begpython/wavnk/",s) x=open(p , 'r') for i in range(6): x.readline() k2='a' j=0 o=[] while k2 is not '': k2=x.readline() k2=k2.rstrip('\n') oj=k2.split(' ') o=o+[oj] #print o[j] j=j+1 #print j #print o[2][0] temp=long(1232332) strt_time=save_b[3] #print strt_time k=(j-1) for i in range(k): diff=float(o[i][0])-float(strt_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i #print pm_row #print temp #print o[pm_row] #pm_row=3 w=[] l=str(p).replace('.pm','.mcep') z=open(l ,'r') for i in range(pm_row): z.readline() k3=z.readline() k3=k3.rstrip('\n') w=k3.split(' ') #print w cost=0 for i in range(12): #print q[i] #print w[i] h=float(q[i])-float(w[i]) cost=cost+math.pow(h,2) j_cost=math.sqrt(cost) #print cost return j_cost def target_cost(a , b): a=(b+1)*3 b=(a+1)*2 t_cost=(a+b)*5/2 return t_cost r1='shht:ra_77' r2='grx_18' g=[] nodes=[] nodes=nodes+[[r1]] for i in range(len(y_in_db_format)): g=y_in_db_format[i] #print g #print g[0] g.remove(str(g[0])) nodes=nodes+[g] nodes=nodes+[[r2]] print nodes print "lenght of nodes",len(nodes) lists=[] #lists=lists+[r1] for i in range(len(nodes)): for j in range(len(nodes[i])): lists=lists+[nodes[i][j]] #lists=lists+[r2] print lists distance={} for i in range(len(lists)): if i==0: distance[str(lists[i])]=0 else: distance[str(lists[i])]=long(123231223) #print distance group_dist=[] infinity=long(123232323) for i in range(len(nodes)): distances=[] for j in range(len(nodes[i])): #distances=[] if i==0: distances=distances+[[nodes[i][j], 0]] else: distances=distances+[[nodes[i][j],infinity]] group_dist=group_dist+[distances] #print distances print "group_distances",group_dist #print "check",group_dist[0][0][1] #costs={} #for i in range(len(lists)): #if i==0: # costs[str(lists[i])]=1 #else: # costs[str(lists[i])]=get_selfcost(lists[i]) path=[] for i in range(len(nodes)): mini=[] if i!=(len(nodes)-1): #temp=long(123234324) #Now calculate the cost between the current node and each of its neighbour for k in range(len(nodes[(i+1)])): for j in range(len(nodes[i])): current=nodes[i][j] #print "current_node",current j_distance=join_cost( current , nodes[i+1][k]) #t_distance=target_cost( current , nodes[i+1][k]) t_distance=34 #print distance #print "distance between current and neighbours",distance total_distance=(.5*(float(group_dist[i][j][1])+float(j_distance))+.5*(float(t_distance))) #print "total distance between the intial_nodes and current neighbour",total_distance if int(group_dist[i+1][k][1]) > int(total_distance): group_dist[i+1][k][1]=total_distance #print "updated distance",group_dist[i+1][k][1] a=current #print "the neighbour",nodes[i+1][k],"updated the value",a mini=mini+[[str(nodes[i+1][k]),a]] print mini

    Read the article

  • android program crashing (new to platform)

    - by mutio
    So it is my first real Android program (!hello world), but i do have java experience.The program compiles fine, but on running it crashes as soon as it opens (tried debugging, but it crashes before it hits my breakpoint). Was looking for any advice from anyone who is more experienced with android. package org.me.tipcalculator; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.text.NumberFormat; import android.util.Log; public class TipCalculator extends Activity { public static final String tag = "TipCalculator"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final EditText mealpricefield = (EditText) findViewById(R.id.mealprice); final TextView answerfield = (TextView) findViewById(R.id.answer); final Button button = (Button) findViewById(R.id.calculate); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { Log.i(tag, "onClick invoked."); String mealprice = mealpricefield.getText().toString(); Log.i(tag, "mealprice is [" + mealprice + "]"); String answer = ""; if (mealprice.indexOf("$") == -1) { mealprice = "$" + mealprice; } float fmp = 0.0F; NumberFormat nf = java.text.NumberFormat.getCurrencyInstance(); fmp = nf.parse(mealprice).floatValue(); fmp *= 1.2; Log.i(tag, "Total Meal Price (unformatted) is [" + fmp + "]"); answer = "Full Price, including 20% Tip: " + nf.format(fmp); answerfield.setText(answer); Log.i(tag, "onClick Complete"); } catch(java.text.ParseException pe){ Log.i (tag ,"Parse exception caught"); answerfield.setText("Failed to parse amount?"); } catch(Exception e){ Log.e (tag ,"Failed to Calculate Tip:" + e.getMessage()); e.printStackTrace(); answerfield.setText(e.getMessage()); } } } ); } Just in case it helps heres the xml <?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Android Tip Calculator"/> <EditText android:id="@+id/mealprice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoText="true"/> <Button android:id="@+id/calculate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Calculate Tip"/> <TextView android:id= "@+id/answer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=""/> </LinearLayout>

    Read the article

  • Help with refactoring PHP code

    - by Richard Knop
    I had some troubles implementing Lawler's algorithm but thanks to SO and a bounty of 200 reputation I finally managed to write a working implementation: http://stackoverflow.com/questions/2466928/lawlers-algorithm-implementation-assistance I feel like I'm using too many variables and loops there though so I am trying to refactor the code. It should be simpler and shorter yet remain readable. Does it make sense to make a class for this? Any advice or even help with refactoring this piece of code is welcomed: <?php /* * @name Lawler's algorithm PHP implementation * @desc This algorithm calculates an optimal schedule of jobs to be * processed on a single machine (in reversed order) while taking * into consideration any precedence constraints. * @author Richard Knop * */ $jobs = array(1 => array('processingTime' => 2, 'dueDate' => 3), 2 => array('processingTime' => 3, 'dueDate' => 15), 3 => array('processingTime' => 4, 'dueDate' => 9), 4 => array('processingTime' => 3, 'dueDate' => 16), 5 => array('processingTime' => 5, 'dueDate' => 12), 6 => array('processingTime' => 7, 'dueDate' => 20), 7 => array('processingTime' => 5, 'dueDate' => 27), 8 => array('processingTime' => 6, 'dueDate' => 40), 9 => array('processingTime' => 3, 'dueDate' => 10)); // precedence constrainst, i.e job 2 must be completed before job 5 etc $successors = array(2=>5, 7=>9); $n = count($jobs); $optimalSchedule = array(); for ($i = $n; $i >= 1; $i--) { // jobs not required to precede any other job $arr = array(); foreach ($jobs as $k => $v) { if (false === array_key_exists($k, $successors)) { $arr[] = $k; } } // calculate total processing time $totalProcessingTime = 0; foreach ($jobs as $k => $v) { if (true === array_key_exists($k, $arr)) { $totalProcessingTime += $v['processingTime']; } } // find the job that will go to the end of the optimal schedule array $min = null; $x = 0; $lastKey = null; foreach($arr as $k) { $x = $totalProcessingTime - $jobs[$k]['dueDate']; if (null === $min || $x < $min) { $min = $x; $lastKey = $k; } } // add the job to the optimal schedule array $optimalSchedule[$lastKey] = $jobs[$lastKey]; // remove job from the jobs array unset($jobs[$lastKey]); // remove precedence constraint from the successors array if needed if (true === in_array($lastKey, $successors)) { foreach ($successors as $k => $v) { if ($lastKey === $v) { unset($successors[$k]); } } } } // reverse the optimal schedule array and preserve keys $optimalSchedule = array_reverse($optimalSchedule, true); // add tardiness to the array $i = 0; foreach ($optimalSchedule as $k => $v) { $optimalSchedule[$k]['tardiness'] = 0; $j = 0; foreach ($optimalSchedule as $k2 => $v2) { if ($j <= $i) { $optimalSchedule[$k]['tardiness'] += $v2['processingTime']; } $j++; } $i++; } echo '<pre>'; print_r($optimalSchedule); echo '</pre>';

    Read the article

  • algorithm q: Fuzzy matching of structured data

    - by user86432
    I have a fairly small corpus of structured records sitting in a database. Given a tiny fraction of the information contained in a single record, submitted via a web form (so structured in the same way as the table schema), (let us call it the test record) I need to quickly draw up a list of the records that are the most likely matches for the test record, as well as provide a confidence estimate of how closely the search terms match a record. The primary purpose of this search is to discover whether someone is attempting to input a record that is duplicate to one in the corpus. There is a reasonable chance that the test record will be a dupe, and a reasonable chance the test record will not be a dupe. The records are about 12000 bytes wide and the total count of records is about 150,000. There are 110 columns in the table schema and 95% of searches will be on the top 5% most commonly searched columns. The data is stuff like names, addresses, telephone numbers, and other industry specific numbers. In both the corpus and the test record it is entered by hand and is semistructured within an individual field. You might at first blush say "weight the columns by hand and match word tokens within them", but it's not so easy. I thought so too: if I get a telephone number I thought that would indicate a perfect match. The problem is that there isn't a single field in the form whose token frequency does not vary by orders of magnitude. A telephone number might appear 100 times in the corpus or 1 time in the corpus. The same goes for any other field. This makes weighting at the field level impractical. I need a more fine-grained approach to get decent matching. My initial plan was to create a hash of hashes, top level being the fieldname. Then I would select all of the information from the corpus for a given field, attempt to clean up the data contained in it, and tokenize the sanitized data, hashing the tokens at the second level, with the tokens as keys and frequency as value. I would use the frequency count as a weight: the higher the frequency of a token in the reference corpus, the less weight I attach to that token if it is found in the test record. My first question is for the statisticians in the room: how would I use the frequency as a weight? Is there a precise mathematical relationship between n, the number of records, f(t), the frequency with which a token t appeared in the corpus, the probability o that a record is an original and not a duplicate, and the probability p that the test record is really a record x given the test and x contain the same t in the same field? How about the relationship for multiple token matches across multiple fields? Since I sincerely doubt that there is, is there anything that gets me close but is better than a completely arbitrary hack full of magic factors? Barring that, has anyone got a way to do this? I'm especially keen on other suggestions that do not involve maintaining another table in the database, such as a token frequency lookup table :). This is my first post on StackOverflow, thanks in advance for any replies you may see fit to give.

    Read the article

  • Running code when all threads are finished processing.

    - by rich97
    Quick note: Java and Android noob here, I'm open to you telling me I'm stupid (as long as you tell me why.) I have an android application which requires me start multiple threads originating from various classes and only advance to the next activity once all threads have done their job. I also want to add a "failsafe" timeout in case one the the threads takes too long (HTTP request taking too long or something.) I searched Stack Overflow and found a post saying that I should create a class to keep a running total of open threads and then use a timer to poll for when all the threads are completed. I think I've created a working class to do this for me, it's untested as of yet but has no errors showing in eclipse. Is this a correct implementation? Are there any APIs that I should be made aware of (such as classes in the Java or Android APIs that could be used in place of the abstract classes at the bottom of the class?) package com.dmp.geofix.libs; import java.util.ArrayList; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; public class ThreadMonitor { private Timer timer = null; private TimerTask timerTask = null; private OnSuccess onSuccess = null; private OnError onError = null; private static ArrayList<Thread> threads; private final int POLL_OPEN_THREADS = 100; private final int TIMEOUT = 10000; public ThreadMonitor() { timerTask = new PollThreadsTask(); } public ThreadMonitor(OnSuccess s) { timerTask = new PollThreadsTask(); onSuccess = s; } public ThreadMonitor(OnError e) { timerTask = new PollThreadsTask(); onError = e; } public ThreadMonitor(OnSuccess s, OnError e) { timerTask = new PollThreadsTask(); onSuccess = s; onError = e; } public void start() { Iterator<Thread> i = threads.iterator(); while (i.hasNext()) { i.next().start(); } timer = new Timer(); timer.schedule(timerTask, 0, POLL_OPEN_THREADS); } public void finish() { Iterator<Thread> i = threads.iterator(); while (i.hasNext()) { i.next().interrupt(); } threads.clear(); timer.cancel(); } public void addThread(Thread t) { threads.add(t); } public void removeThread(Thread t) { threads.remove(t); t.interrupt(); } class PollThreadsTask extends TimerTask { private int timeElapsed = 0; @Override public void run() { timeElapsed += POLL_OPEN_THREADS; if (timeElapsed <= TIMEOUT) { if (threads.isEmpty() == false) { if (onSuccess != null) { onSuccess.run(); } } } else { if (onError != null) { onError.run(); } finish(); } } } public abstract class OnSuccess { public abstract void run(); } public abstract class OnError { public abstract void run(); } }

    Read the article

  • How to make multiple wires quickly in Verilog?

    - by user1334858
    I am trying to make 24 wires in total very quickly but I keep getting the error: Error (10170): Verilog HDL syntax error at your_ALU_mux.v(81) near text "="; expecting ".", or an identifier Here is my code: module your_ALU_mux(your_out, operandA, operandB, opcode, switches, address); input [7:0] operandA, operandB, address; input [3:0] opcode, switches; output [7:0] your_out; wire [0:7] Bnot, newb, newa; wire Cin, Cout; not (Bnot[0], operandB[0]), (Bnot[1], operandB[1]), (Bnot[2], operandB[2]), (Bnot[3], operandB[3]), (Bnot[4], operandB[4]), (Bnot[5], operandB[5]), (Bnot[6], operandB[6]), (Bnot[7], operandB[7]); // Getting A' and B' if (address == 16'h00 || address == 16'h01) // Add A + B if (address == 16'h00) // newa = A newa[0] = operandA[0]; newa[1] = operandA[1]; newa[2] = operandA[2]; newa[3] = operandA[3]; newa[4] = operandA[4]; newa[5] = operandA[5]; newa[6] = operandA[6]; newa[7] = operandA[7]; // newb = B' newb[0] = Bnot[0]; newb[1] = Bnot[1]; newb[2] = Bnot[2]; newb[3] = Bnot[3]; newb[4] = Bnot[4]; newb[5] = Bnot[5]; newb[6] = Bnot[6]; newb[7] = Bnot[7]; // Carry in = 1 Cin = 1; // A-B else if (address == 16'h01) // newb = B newb[0] = operandB[0]; newb[1] = operandB[1]; newb[2] = operandB[2]; newb[3] = operandB[3]; newb[4] = operandB[4]; newb[5] = operandB[5]; newb[6] = operandB[6]; newb[7] = operandB[7]; // newa = A newa[0] = operandA[0]; newa[1] = operandA[1]; newa[2] = operandA[2]; newa[3] = operandA[3]; newa[4] = operandA[4]; newa[5] = operandA[5]; newa[6] = operandA[6]; newa[7] = operandA[7]; // Carry in = 0 Cin = 0; end RippleCarryAdd A+B(.S0(your_out[0]), .S1(your_out[1],.S2(your_out[2],.S3(your_out[3],.S4(your_out[4],.S5(your_out[5] S6.(your_out[6]), S7.(your_out[7], .Cout(Cout),.Cin(Cin), .A0(newa[0]),.A1(newa[1]),.A2(newa[2]),.A3(newa[3]),.A4(newa[4]),.A5(newa[5]), .A6(newa[6]),.A7(newa[7]), .B0(newb[0]),.B1(newb[1]),.B2(newb[2]),.B3(newb[3]),.B4(newb[4]), .B5(newb[5]),.B6(newb[6]),.B7(newb[7])); endmodule I also get in error saying: Error (10170): Verilog HDL syntax error at your_ALU_mux.v(66) near text "if"; expecting "endmodule" And the it brings me to my first if statement. Is this the wrong way of going about creating wires and them using them?

    Read the article

  • Replace conditional with polymorphism refactoring or similar?

    - by Anders Svensson
    Hi, I have tried to ask a variant of this question before. I got some helpful answers, but still nothing that felt quite right to me. It seems to me this shouldn't really be that hard a nut to crack, but I'm not able to find an elegant simple solution. (Here's my previous post, but please try to look at the problem stated here as procedural code first so as not to be influenced by the earlier explanation which seemed to lead to very complicated solutions: http://stackoverflow.com/questions/2772858/design-pattern-for-cost-calculator-app ) Basically, the problem is to create a calculator for hours needed for projects that can contain a number of services. In this case "writing" and "analysis". The hours are calculated differently for the different services: writing is calculated by multiplying a "per product" hour rate with the number of products, and the more products are included in the project, the lower the hour rate is, but the total number of hours is accumulated progressively (i.e. for a medium-sized project you take both the small range pricing and then add the medium range pricing up to the number of actual products). Whereas for analysis it's much simpler, it is just a bulk rate for each size range. How would you be able to refactor this into an elegant and preferably simple object-oriented version (please note that I would never write it like this in a purely procedural manner, this is just to show the problem in another way succinctly). I have been thinking in terms of factory, strategy and decorator patterns, but can't get any to work well. (I read Head First Design Patterns a while back, and both the decorator and factory patterns described have some similarities to this problem, but I have trouble seeing them as good solutions as stated there. The decorator example seems very complicated for just adding condiments, but maybe it could work better here, I don't know. And the factory pattern example with the pizza factory...well it just seems to create such a ridiculous explosion of classes, at least in their example. I have found good use for factory patterns before, but I can't see how I could use it here without getting a really complicated set of classes) The main goal would be to only have to change in one place (loose coupling etc) if I were to add a new parameter (say another size, like XSMALL, and/or another service, like "Administration"). Here's the procedural code example: public class Conditional { private int _numberOfManuals; private string _serviceType; private const int SMALL = 2; private const int MEDIUM = 8; public int GetHours() { if (_numberOfManuals <= SMALL) { if (_serviceType == "writing") return 30 * _numberOfManuals; if (_serviceType == "analysis") return 10; } else if (_numberOfManuals <= MEDIUM) { if (_serviceType == "writing") return (SMALL * 30) + (20 * _numberOfManuals - SMALL); if (_serviceType == "analysis") return 20; } else //i.e. LARGE { if (_serviceType == "writing") return (SMALL * 30) + (20 * (MEDIUM - SMALL)) + (10 * _numberOfManuals - MEDIUM); if (_serviceType == "analysis") return 30; } return 0; //Just a default fallback for this contrived example } } All replies are appreciated! I hope someone has a really elegant solution to this problem that I actually thought from the beginning would be really simple... Regards, Anders

    Read the article

  • Trying to sentinel loop this program. [java]

    - by roger34
    Okay, I spent all this time making this for class but I have one thing that I can't quite get: I need this to sentinel loop continuously (exiting upon entering x) so that the System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); line comes back up after they enter the first round of information. Also, I can't leave this up long on the (very) off chance a classmate might see this and steal the code. Full code following: import java.util.Scanner; public class Project1 { public static void main (String args[]){ Scanner inp = new Scanner( System.in ); double totalPay; System.out.println("What type of Employee? Enter 'o' for Office " + "Clerical, 'f' for Factory, or 's' for Saleperson. Enter 'x' to exit." ); String response= inp.nextLine(); while (!response.toLowerCase().equals("o")&&!response.toLowerCase().equals("f") &&!response.toLowerCase().equals("s")&&!response.toLowerCase().equals("x")){ System.out.print("\nInvalid selection,please enter your choice again:\n"); response=inp.nextLine(); } char choice = response.toLowerCase().charAt( 0 ); switch (choice){ case 'o': System.out.println("Enter your hourly rate:"); double officeRate=inp.nextDouble(); System.out.println("Enter the number of hours worked:"); double officeHours=inp.nextDouble(); totalPay = officeCalc(officeRate,officeHours); taxCalc(totalPay); break; case 'f': System.out.println("How many Widgets did you produce during the week?"); double widgets=inp.nextDouble(); totalPay=factoryCalc(widgets); taxCalc(totalPay); break; case 's': System.out.println("What were your total sales for the week?"); double totalSales=inp.nextDouble(); totalPay=salesCalc(totalSales); taxCalc(totalPay); break; } } public static double taxCalc(double totalPay){ double federal=totalPay*.22; double state =totalPay*.055; double netPay = totalPay - federal - state; federal =federal*Math.pow(10,2); federal =Math.round(federal); federal= federal/Math.pow(10,2); state =state*Math.pow(10,2); state =Math.round(state); state= state/Math.pow(10,2); totalPay =totalPay*Math.pow(10,2); totalPay =Math.round(totalPay); totalPay= totalPay/Math.pow(10,2); netPay =netPay*Math.pow(10,2); netPay =Math.round(netPay); netPay= netPay/Math.pow(10,2); System.out.printf("\nTotal Pay \t: %1$.2f.\n", totalPay); System.out.printf("State W/H \t: %1$.2f.\n", state); System.out.printf("Federal W/H : %1$.2f.\n", federal); System.out.printf("Net Pay \t: %1$.2f.\n", netPay); return totalPay; } public static double officeCalc(double officeRate,double officeHours){ double overtime=0; if (officeHours>=40) overtime = officeHours-40; else overtime = 0; if (officeHours >= 40) officeHours = 40; double otRate = officeRate * 1.5; double totalPay= (officeRate * officeHours) + (otRate*overtime); return totalPay; } public static double factoryCalc(double widgets){ double totalPay=widgets*.35 +300; return totalPay; } public static double salesCalc(double totalSales){ double totalPay = totalSales * .05 + 500; return totalPay; } }

    Read the article

  • Magento Onepage Success Conversion Tracking Design Pattern

    - by user1734954
    My intent is to track conversions through multiple channels by inserting third party javascript (for example google analytics, optimizely, pricegrabber etc.) into the footer of onepage success . I've accomplished this by adding a block to the footer reference inside of the checkout success node within local.xml and everything works appropriately. My questions are more about efficiency and extensibility. It occurred to me that it would be better to combine all of the blocks into a single block reference and then use a various methods acting on a single call to the various related models to provide the data needed for insertion into the javascript for each of the conversion tracking scripts. Some examples of the common data that conversion tracking may rely on(pseudo): Order ID , Order Total, Order.LineItem.Name(foreach) and so on Currently for each of the scripts I've made a call to the appropriate model passing the customers last order id as the load value and the calling a get() assigning the return value to a variable and then iterating through the data to match the values with the expectations of the given third party service. All of the data should be pulled once when checkout is complete each third party services may expect different data in different formats Here is an example of one of the conversion tracking template files which loads at the footer of checkout success. $order = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId()); $amount = number_format($order->getGrandTotal(),2); $customer = Mage::helper('customer')->getCustomer()->getData(); ?> <script type="text/javascript"> popup_email = '<?php echo($customer['email']);?>'; popup_order_number = '<?php echo $this->getOrderId() ?>'; </script> <!-- PriceGrabber Merchant Evaluation Code --> <script type="text/javascript" charset="UTF-8" src="https://www.pricegrabber.com/rating_merchrevpopjs.php?retid=<something>"></script> <noscript><a href="http://www.pricegrabber.com/rating_merchrev.php?retid=<something>" target=_blank> <img src="https://images.pricegrabber.com/images/mr_noprize.jpg" border="0" width="272" height="238" alt="Merchant Evaluation"></a></noscript> <!-- End PriceGrabber Code --> Having just a single piece of code like this is not that big of a deal, but we are doing similar things with a number of different third party services. Pricegrabber is one of the simpler examples. A more sophisticated tracking service expects a comma separated list of all of the product names, ids, prices, categories , order id etc. I would like to make it all more manageable so my idea to do the following: combine all of the template files into a single file Develop a helper class or library to deliver the data to the conversion template Goals Include Extensibility Minimal Model Calls Minimal Method Calls The Questions 1. Is a Mage helper the best route to take? 2. Is there any design pattern you may recommend for the "helper" class? 3. Why would this the design pattern you've chosen be best for this instance?

    Read the article

  • Cart coding help

    - by user228390
    I've made a simple Javascript code for a shopping basket but now I have realised that I have made a error with making it and don't know how to fix it. What I have is Javascript file but I have also included the images source and the addtocart button as well, but What I am trying to do now is make 2 files one a .HTML file and another .JS file, but I can't get it to because when I make a button in the HTML file to call the function from the .JS file it won't work at all. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD><TITLE>shopping</TITLE> <META http-equiv=Content-Type content="text/html; charset=UTF-8"> <STYLE type=text/CSS> fieldset{width:300px} legend{font-size:24px;font-family:comic sans ms;color:#004455} </STYLE> <META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD> <BODY scroll="auto"> <div id="products"></div><hr> <div id="inCart"></div> <SCRIPT type="text/javascript"> var items=['Xbox~149.99','StuffedGizmo~19.98','GadgetyGoop~9.97']; var M='?'; var product=[]; var price=[]; var stuff=''; function wpf(product,price){var pf='<form><FIELDSET><LEGEND>'+product+'</LEGEND>'; pf+='<img src="../images/'+product+'.jpg" alt="'+product+'" ><p>price '+M+''+price+'</p> <b>Qty</b><SELECT>'; for(i=0;i<6;i++){pf+='<option value="'+i+'">'+i+'</option>'} pf+='</SELECT>'; pf+='<input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form>'; return pf } for(j=0;j<items.length;j++){ product[j]=items[j].substring(0,items[j].indexOf('~')); price[j]=items[j].substring(items[j].indexOf('~')+1,items[j].length); stuff+=''+wpf(product[j],price[j])+''; } document.getElementById('products').innerHTML=stuff; function cart(){ var order=[]; var tot=0 for(o=0,k=0;o<document.forms.length;o++){ if(document.forms[o].elements[1].value!=0){ qnty=document.forms[o].elements[1].value; order[k]=''+product[o]+'_'+qnty+'*'+price[o]+''; tot+=qnty*price[o];k++ } } document.getElementById('inCart').innerHTML=order.join('<br>')+'<h3>Total '+tot+'</h3>'; } </SCRIPT> <input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form> </BODY></HTML>

    Read the article

  • Need help to properly remove duplicates in NHibernate

    - by Michael D. Kirkpatrick
    Here is the problem I am having. I have a database with over 100 records in it. I am paging through the data to get 9 results at a time. When I added a check to see if items are active, it caused the results to start doubling up. A little background: "Product" is the actual product line "ProductSkus" are the actual products that exist in the product line When there is more then 1 ProductSku within Product, it causes a duplicate entry to be returned. See the NHibernate Query below: result = this.Session.CreateCriteria<Model.Product>() .Add(Expression.Eq("IsActive", true)) .AddOrder(new Order("Name", true)) .SetFirstResult(indexNumber).SetMaxResults(maxNumber) // This part of the query duplicates the products .CreateAlias("ProductSkus", "ProdSkus", JoinType.InnerJoin) .Add(Expression.Eq("ProdSkus.IsActive", true)) .CreateAlias("ProductToSubcategory", "ProdToSubcat") .CreateAlias("ProdToSubcat.ProductSubcategory", "ProdSubcat") .Add(Expression.Eq("ProdSubcat.ID", subCatId)) // This part takes out the duplicate products - Removes too many items... // Turns out that with .SetFirstResult(indexNumber).SetMaxResults(maxNumber) // it gets 9 records back then the duplicates are removed. // Example: // Total Records over 100 // Max = 9 // 4 Duplicates removed // Yields 5 records when there should be 9 // Why??? This line is ran in NHibernate on the data after it has been extracted from the SQL server. .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer()) .List<Model.Product>(); I added the DistinctRootEntityResultTransformer to clean up the duplicates. The problem is that it pulls 9 records back that contains duplicates. DistinctRootEntityResultTransformer then cleans up the duplicates in the 9 records. I am basically needing a distinct statement to be ran on the SQL server to begin with. However, distinct on SQL is not going to work since NHibernate by default wants to add every field from every table in the select part of the statement. I am only using the fields that belong to the root table to begin with (Model.Product). If I can tell NHibernate to not add the fields to the joined tables into the select part of the statement along with adding Distinct, it would work. I use NHibernare Profiler to see the actual query: SELECT top 9 this_.ID as ID351_3_, this_.Name as Name351_3_, this_.Description as Descript3_351_3_, this_.IsActive as IsActive351_3_, this_.ManufacturerID as Manufact5_351_3_, prodskus1_.ID as ID373_0_, prodskus1_.Description as Descript2_373_0_, prodskus1_.PartNumber as PartNumber373_0_, prodskus1_.Price as Price373_0_, prodskus1_.IsKit as IsKit373_0_, prodskus1_.IsActive as IsActive373_0_, prodskus1_.IsFeaturedProduct as IsFeatur7_373_0_, prodskus1_.DateAdded as DateAdded373_0_, prodskus1_.Weight as Weight373_0_, prodskus1_.TimesViewed as TimesVi10_373_0_, prodskus1_.TimesOrdered as TimesOr11_373_0_, prodskus1_.ProductID as ProductID373_0_, prodskus1_.OverSizedBoxID as OverSiz13_373_0_, prodtosubc2_.ID as ID362_1_, prodtosubc2_.MasterSubcategory as MasterSu2_362_1_, prodtosubc2_.ProductID as ProductID362_1_, prodtosubc2_.ProductSubcategoryID as ProductS4_362_1_, prodsubcat3_.ID as ID352_2_, prodsubcat3_.Name as Name352_2_, prodsubcat3_.ProductCategoryID as ProductC3_352_2_, prodsubcat3_.ImageID as ImageID352_2_, prodsubcat3_.TriggerShow as TriggerS5_352_2_ FROM Product this_ inner join ProductSku prodskus1_ on this_.ID = prodskus1_.ProductID and (prodskus1_.IsActive = 1) inner join ProductToSubcategory prodtosubc2_ on this_.ID = prodtosubc2_.ProductID inner join ProductSubcategory prodsubcat3_ on prodtosubc2_.ProductSubcategoryID = prodsubcat3_.ID WHERE this_.IsActive = 1 /* @p0 */ and prodskus1_.IsActive = 1 /* @p1 */ and prodsubcat3_.ID = 3 /* @p2 */ ORDER BY this_.Name asc If I hand modify the query and run it directly on the SQL server I get the result set I want (I removed all the extra fields in the select section and added DISTINCT): SELECT DISTINCT top 9 this_.ID as ID351_3_, this_.Name as Name351_3_, this_.Description as Descript3_351_3_, this_.IsActive as IsActive351_3_, this_.ManufacturerID as Manufact5_351_3_, FROM Product this_ inner join ProductSku prodskus1_ on this_.ID = prodskus1_.ProductID and (prodskus1_.IsActive = 1) inner join ProductToSubcategory prodtosubc2_ on this_.ID = prodtosubc2_.ProductID inner join ProductSubcategory prodsubcat3_ on prodtosubc2_.ProductSubcategoryID = prodsubcat3_.ID WHERE this_.IsActive = 1 /* @p0 */ and prodskus1_.IsActive = 1 /* @p1 */ and prodsubcat3_.ID = 3 /* @p2 */ ORDER BY this_.Name asc The big question I now must ask is... What must I change in the NHibernate Query to ultimately get the exact same result? Thanks in advance.

    Read the article

  • Error inserting data in binary tree

    - by chepe263
    I copied this code (in spanish) http://www.elrincondelc.com/nuevorincon/index.php?pag=codigos&id=4 and wrote a new one. This is my code: #include <cstdlib> #include <conio.h> #include <iostream> using namespace std; struct nodoarbol { int dato; struct nodoarbol *izq; struct nodoarbol *der; }; typedef nodoarbol Nodo; typedef Nodo *Arbol; void insertar(Arbol *, int); void inorden(Arbol); void postorden(Arbol); void preorden(Arbol); void insertar(Arbol *raiz, int nuevo){ if (*raiz==NULL){ *raiz = (Nodo *)malloc(sizeof(Nodo)); if (*raiz != NULL){ (*raiz)->dato=nuevo; (*raiz)->der=NULL; (*raiz)->izq=NULL; } else{ cout<<"No hay memoria suficiente u ocurrio un error"; } } else{ if (nuevo < (*raiz)->dato) insertar( &((*raiz)->izq), nuevo ); else if (nuevo > (*raiz)->dato) insertar(&((*raiz)->der), nuevo); } }//inseertar void inorden(Arbol raiz){ if (raiz != NULL){ inorden(raiz->izq); cout << raiz->dato << " "; inorden(raiz->der); } } void preorden(Arbol raiz){ if (raiz != NULL){ cout<< raiz->dato << " "; preorden(raiz->izq); preorden(raiz->der); } } void postorden(Arbol raiz){ if (raiz!=NULL){ postorden(raiz->izq); postorden(raiz->der); cout<<raiz->dato<<" "; } } int main() { int i; i=0; int val; Arbol raiz = NULL; for (i=0; i<10; i++){ cout<<"Inserte un numero"; cin>>val; insertar( (raiz), val); } cout<<"\nPreorden\n"; preorden(raiz); cout<<"\nIneorden\n"; inorden(raiz); cout<<"\nPostorden\n"; postorden(raiz); return 0; } I'm using netbeans 7.1.1, mingw32 compiler This is the output: make[2]: Leaving directory `/q/netbeans c++/NetBeansProjects/treek' make[1]: Leaving directory `/q/netbeans c++/NetBeansProjects/treek' main.cpp: In function 'int main()': main.cpp:110:30: error: cannot convert 'Arbol {aka nodoarbol*}' to 'Nodo** {aka nodoarbol**}' for argument '1' to 'void insertar(Nodo**, int)' make[2]: *** [build/Release/MinGW-Windows/main.o] Error 1 make[1]: *** [.build-conf] Error 2 make: *** [.build-impl] Error 2 BUILD FAILED (exit value 2, total time: 11s) I don't understand what's wrong since i just copied the code (and rewrite it to my own code). I'm really good in php, asp.net (vb) and other languages but c is a headche for me. I've been struggling with this problem for about an hour. Could somebody tell me what could it be?

    Read the article

  • java ioexception error=24 too many files open

    - by MattS
    I'm writing a genetic algorithm that needs to read/write lots of files. The fitness test for the GA is invoking a program called gradif, which takes a file as input and produces a file as output. Everything is working except when I make the population size and/or the total number of generations of the genetic algorithm too large. Then, after so many generations, I start getting this: java.io.FileNotFoundException: testfiles/GradifOut29 (Too many open files). (I get it repeatedly for many different files, the index 29 was just the one that came up first last time I ran it). It's strange because I'm not getting the error after the first or second generation, but after a significant amount of generations, which would suggest that each generation opens up more files that it doesn't close. But as far as I can tell I'm closing all of the files. The way the code is set up is the main() function is in the Population class, and the Population class contains an array of Individuals. Here's my code: Initial creation of input files (they're random access so that I could reuse the same file across multiple generations) files = new RandomAccessFile[popSize]; for(int i=0; i<popSize; i++){ files[i] = new RandomAccessFile("testfiles/GradifIn"+i, "rw"); } At the end of the entire program: for(int i=0; i<individuals.length; i++){ files[i].close(); } Inside the Individual's fitness test: FileInputStream fin = new FileInputStream("testfiles/GradifIn"+index); FileOutputStream fout = new FileOutputStream("testfiles/GradifOut"+index); Process process = Runtime.getRuntime().exec ("./gradif"); OutputStream stdin = process.getOutputStream(); InputStream stdout = process.getInputStream(); Then, later.... try{ fin.close(); fout.close(); stdin.close(); stdout.close(); process.getErrorStream().close(); }catch (IOException ioe){ ioe.printStackTrace(); } Then, afterwards, I append an 'END' to the files to make parsing them easier. FileWriter writer = new FileWriter("testfiles/GradifOut"+index, true); writer.write("END"); try{ writer.close(); }catch(IOException ioe){ ioe.printStackTrace(); } My redirection of stdin and stdout for gradif are from this answer. I tried using the try{close()}catch{} syntax to see if there was a problem with closing any of the files (there wasn't), and I got that from this answer. It should also be noted that the Individuals' fitness tests run concurrently. UPDATE: I've actually been able to narrow it down to the exec() call. In my most recent run, I first ran in to trouble at generation 733 (with a population size of 100). Why are the earlier generations fine? I don't understand why, if there's no leaking, the algorithm should be able to pass earlier generations but fail on later generations. And if there is leaking, then where is it coming from? UPDATE2: In trying to figure out what's going on here, I would like to be able to see (preferably in real-time) how many files the JVM has open at any given point. Is there an easy way to do that?

    Read the article

  • Linux/Apache performance very slow even on local network

    - by klausch
    I have an Ubuntu server machine running Apache and MYSQL. System and version info is as follows: Linux kernel 3.0.0.-12 Apache/2.2.20 MySQL Ver 14.14.Distrib 5.1.58 I am running a few websites on this server, some HTML only, some PHP/MySQL. THe [problem is that response time is very slow, both on static as well as the dynamic sites. Sometimes it takes more than 10 seconds before a response is given, this makes the sites very slow and almost unusable. The problem occurs even when requesting from the local network. I have added the involved subdomains to my /etc/hosts file, and abolve all the problem is not solved by using IP numbers instead of URL's. So there is no DNS lookup issue. I have modified the log format by showing the response times and sometimes a files takes 12 seconds to be served, see the jquery~.js file in the example screenshot. I have no explanation for this extremely long response time, but is is not even the only issue here, some other files takes a long time to be served too, but do not show a long response time in the log file. So probably different tissues are involved here. I cannot find a solution until now, any suggestions??? THanx in advance, Klaas link to screenshot picture from access logfile Some extra configuration info: apache2.conf (comment is removed) LockFile ${APACHE_LOCK_DIR}/accept.lock PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 <IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 MaxClients 150 MaxRequestsPerChild 0 </IfModule> <IfModule mpm_worker_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0 </IfModule> <IfModule mpm_event_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxClients 150 MaxRequestsPerChild 0 </IfModule> User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} AccessFileName .htaccess <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy all </Files> DefaultType text/plain HostnameLookups Off ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn Include mods-enabled/*.load Include mods-enabled/*.conf Include httpd.conf Include ports.conf LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\" %T/%D" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent Include conf.d/ Include sites-enabled/ And the virtual hostfile for one of the slow sites, in fact it is pretty straightforward... <VirtualHost *:80> ServerAdmin [email protected] ServerSignature EMail ServerName toenjoy.drsklaus.nl DocumentRoot /var/www/toenjoy.drsklaus.nl <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/toenjoy.drsklaus.nl/> Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig AuthType Basic AuthName "To Enjoy" AuthUserFile /etc/.htpasswd Require user petraaa Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> </VirtualHost> And the output of free -m: klaas@ubuntu-server:/etc/apache2$ free -m total used free shared buffers cached Mem: 1997 1401 595 0 144 1017 -/+ buffers/cache: 238 1758 Swap: 2035 0 2035 and I have no indication that swapping occurs on the moments the site is slow. I have runned top and it does not appear to be a CPU issue. I have the impression that the spawning of a apache thread could maybe be the bottleneck but it is just a suggestion. Maybe this gives some extra information! EDIT: The problem seemed to be gone for some time but occurs again! And not only with Apache, also connecting using SSH takes a tremendous time, sometimes it takes up to 15 seconds before the keyphrase is asked for. Also scp works very slowly. The behavious is really unpredoctable and makes the server very hard to use. Any ideas...?

    Read the article

  • SharePoint 2007 Object Model: How can I make a new site collection, move the original main site to b

    - by program247365
    Here's my current setup: one site collection on a SharePoint 2007 (MOSS Enterprise) box (32 GB total in size) one main site with many subsites (mostly created from the team site template, if that matters) that is part of the one site collection on the box What I'm trying to do*: *If there is a better order, or method for the following, I'm open to changing it Create a new site collection, with a main default site, on same SP instance (this is done, easy to do in SP Object Model) Move rootweb (a) to be a subsite in the new location, under the main site Current structure: rootweb (a) \ many sub sites (sub a) What new structure should look like: newrootweb(b) \ oldrootweb (a) \ old many sub sites (sub a) Here's my code for step #2: Notes: * SPImport in the object model under SharePoint.Administration, is what is being used here * This code currently errors out with "Object reference not an instance of an object", when it fires the error event handler using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using Microsoft.SharePoint.Deployment; public static bool FullImport(string baseFilename, bool CommandLineVerbose, bool bfileCompression, string fileLocation, bool HaltOnNonfatalError, bool HaltOnWarning, bool IgnoreWebParts, string LogFilePath, string destinationUrl) { #region my try at import string message = string.Empty; bool bSuccess = false; try { SPImportSettings settings = new SPImportSettings(); settings.BaseFileName = baseFilename; settings.CommandLineVerbose = CommandLineVerbose; settings.FileCompression = bfileCompression; settings.FileLocation = fileLocation; settings.HaltOnNonfatalError = HaltOnNonfatalError; settings.HaltOnWarning = HaltOnWarning; settings.IgnoreWebParts = IgnoreWebParts; settings.IncludeSecurity = SPIncludeSecurity.All; settings.LogFilePath = fileLocation; settings.WebUrl = destinationUrl; settings.SuppressAfterEvents = true; settings.UpdateVersions = SPUpdateVersions.Append; settings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll; SPImport import = new SPImport(settings); import.Started += delegate(System.Object o, SPDeploymentEventArgs e) { //started message = "Current Status: " + e.Status.ToString() + " " + e.ObjectsProcessed.ToString() + " of " + e.ObjectsTotal + " objects processed thus far."; message = e.Status.ToString(); }; import.Completed += delegate(System.Object o, SPDeploymentEventArgs e) { //done message = "Current Status: " + e.Status.ToString() + " " + e.ObjectsProcessed.ToString() + " of " + e.ObjectsTotal + " objects processed."; }; import.Error += delegate(System.Object o, SPDeploymentErrorEventArgs e) { //broken message = "Error Message: " + e.ErrorMessage.ToString() + " Error Type: " + e.ErrorType + " Error Recommendation: " + e.Recommendation + " Deployment Object: " + e.DeploymentObject.ToString(); System.Console.WriteLine("Error"); }; import.ProgressUpdated += delegate(System.Object o, SPDeploymentEventArgs e) { //something happened message = "Current Status: " + e.Status.ToString() + " " + e.ObjectsProcessed.ToString() + " of " + e.ObjectsTotal + " objects processed thus far."; }; import.Run(); bSuccess = true; } catch (Exception ex) { bSuccess = false; message = string.Format("Error: The site collection '{0}' could not be imported. The message was '{1}'. And the stacktrace was '{2}'", destinationUrl, ex.Message, ex.StackTrace); } #endregion return bSuccess; } Here is the code calling the above method: [TestMethod] public void MOSS07_ObjectModel_ImportSiteCollection() { bool bSuccess = ObjectModelManager.MOSS07.Deployment.SiteCollection.FullImport("SiteCollBAckup.cmp", true, true, @"C:\SPBACKUP\SPExports", false, false, false, @"C:\SPBACKUP\SPExports", "http://spinstancename/TestImport"); Assert.IsTrue(bSuccess); }

    Read the article

< Previous Page | 221 222 223 224 225 226 227 228 229 230 231 232  | Next Page >