Search Results

Search found 19539 results on 782 pages for 'pretty print'.

Page 85/782 | < Previous Page | 81 82 83 84 85 86 87 88 89 90 91 92  | Next Page >

  • Java: over-typed structures? To have many types in Object[]?

    - by HH
    Term over-type structure = a data structure that accepts different types, can be primitive or user-defined. I think ruby supports many types in structures such as tables. I tried a table with types 'String', 'char' and 'File' in Java but errs. How can I have over-typed structure in Java? How to show types in declaration? What about in initilization? Suppose a structure: INDEX VAR FILETYPE //0 -> file FILE //1 -> lineMap SizeSequence //2 -> type char //3 -> binary boolean //4 -> name String //5 -> path String Code import java.io.*; import java.util.*; public class Object { public static void print(char a) { System.out.println(a); } public static void print(String s) { System.out.println(s); } public static void main(String[] args) { Object[] d = new Object[6]; d[0] = new File("."); d[2] = 'T'; d[4] = "."; print(d[2]); print(d[4]); } } Errors Object.java:18: incompatible types found : java.io.File required: Object d[0] = new File("."); ^ Object.java:19: incompatible types found : char required: Object d[2] = 'T'; ^

    Read the article

  • What is a more "ruby way" to write this code?

    - by steadfastbuck
    This was a homework assignment for my students (I am a teaching assistant) in c and I am trying to learn Ruby, so I thought I would code it up. The goal is to read integers from a redirected file and print some simple information. The first line in the file is the number of elements, and then each integer resides on its own line. This code works (although perhaps inefficiently), but how can I make the code more Ruby-like? #!/usr/bin/ruby -w # first line is number of inputs (Don't need it) num_inputs = STDIN.gets.to_i # read inputs as ints h = Hash.new STDIN.each do |n| n = n.to_i h[n] = 1 unless h[n] and h[n] += 1 end # find smallest mode h.sort.each do |k,v| break puts "Mode is: #{k}", "\n" if v == h.values.max end # mode unique? v = h.values.sort print "Mode is unique: " puts v.pop == v.pop, "\n" # print number of singleton odds, # odd elems repeated odd number times in desc order # even singletons in desc order odd_once = 0 odd = Array.new even = Array.new h.each_pair do |k, v| odd_once += 1 if v == 1 and k.odd? odd << k if v.odd? even << k if v == 1 and k.even? end puts "Number of elements with an odd value that appear only once: #{odd_once}", "\n" puts "Elements repeated an odd number of times:" puts odd.sort.reverse, "\n" puts "Elements with an even value that appear exactly once:" puts even.sort.reverse, "\n" # print fib numbers in the hash class Fixnum def is_fib? l, h = 0, 1 while h <= self return true if h == self l, h = h, l+h end end end puts "Fibonacci numbers:" h.keys.sort.each do |n| puts n if n.is_fib? end

    Read the article

  • Loop through Array with conditional output based on key/value pair

    - by Daniel C
    I have an array with the following columns: Task Status I would like to print out a table that shows a list of the Tasks, but not the Status column. Instead, for Tasks where the Status = 0, I want to add a tag <del> to make the completed task be crossed out. Here's my current code: foreach ($row as $key => $val){ if ($key != 'Status') print "<td>$val</td>"; else if ($val == '0') print "<td><del>$val</del></td>"; } This seems to be correct, but when I print it out, it prints all the tasks with the <del> tag. So basically the "else" clause is being run every time. Here is the var_dump($row): array 'Task' => string 'Task A' (length=6) 'Status' => string '3' (length=1) array 'Task' => string 'Task B' (length=6) 'Status' => string '0' (length=1)

    Read the article

  • Heapsort not working in Python for list of strings using heapq module

    - by VSN
    I was reading the python 2.7 documentation when I came across the heapq module. I was interested in the heapify() and the heappop() methods. So, I decided to write a simple heapsort program for integers: from heapq import heapify, heappop user_input = raw_input("Enter numbers to be sorted: ") data = map (int, user_input.split(",")) new_data = [] for i in range(len(data)): heapify(data) new_data.append(heappop(data)) print new_data This worked like a charm. To make it more interesting, I thought I would take away the integer conversion and leave it as a string. Logically, it should make no difference and the code should work as it did for integers: from heapq import heapify, heappop user_input = raw_input("Enter numbers to be sorted: ") data = user_input.split(",") new_data = [] for i in range(len(data)): heapify(data) print data new_data.append(heappop(data)) print new_data Note: I added a print statement in the for loop to see the heapified list. Here's the output when I ran the script: `$ python heapsort.py Enter numbers to be sorted: 4, 3, 1, 9, 6, 2 [' 1', ' 3', ' 2', ' 9', ' 6', '4'] [' 2', ' 3', '4', ' 9', ' 6'] [' 3', ' 6', '4', ' 9'] [' 6', ' 9', '4'] [' 9', '4'] ['4'] [' 1', ' 2', ' 3', ' 6', ' 9', '4']` The reasoning I applied was that since the strings are being compared, the tree should be the same if they were numbers. As is evident, the heapify didn't work correctly after the third iteration. Could someone help me figure out if I am missing something here? I'm running Python 2.4.5 on RedHat 3.4.6-9. Thanks, VSN

    Read the article

  • Threaded Python port scanner

    - by Amnite
    I am having issues with a port scanner I'm editing to use threads. This is the basics for the original code: for i in range(0, 2000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close() This takes approx 33 minutes to complete. So I thought I'd thread it to make it run a little faster. This is my first threading project so it's nothing too extreme, but I've ran the following code for about an hour and get no exceptions yet no output. Am I just doing the threading wrong or what? import threading from socket import * import time a = 0 b = 0 c = "" d = "" def ScanLow(): global a global c for i in range(0, 1000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : c = "Port %d: OPEN\n" % (i,) s.close() a += 1 def ScanHigh(): global b global d for i in range(1001, 2000): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((TargetIP, i)) if(result == 0) : d = "Port %d: OPEN\n" % (i,) s.close() b += 1 Target = raw_input("Enter Host To Scan:") TargetIP = gethostbyname(Target) print "Start Scan On Host ", TargetIP Start = time.time() threading.Thread(target = ScanLow).start() threading.Thread(target = ScanHigh).start() e = a + b while e < 2000: f = raw_input() End = time.time() - Start print c print d print End g = raw_input()

    Read the article

  • const object in c++

    - by Codenotguru
    I have a question on constant objects. In the following program: class const_check{ int a; public: const_check(int i); void print() const; void print2(); }; const_check::const_check(int i):a(i) {} void const_check::print() const { int a=19; cout<<"The value in a is:"<<a; } void const_check::print2() { int a=10; cout<<"The value in a is:"<<a; } int main(){ const_check b(5); const const_check c(6); b.print2(); c.print(); } void print() is constant member function of the class const_check, so according to the definition of constants if any attempt to change int a it should result in an error but the program works fine for me.I think i am having some confusion here, can anybody tell me why the compiler is not flagging it as an error??

    Read the article

  • Why is this giving me an infinite loop?

    - by Chase Yuan
    I was going through a code used to calculate investments until it has doubled and I received an infinite loop that I can't seem to solve. Can anyone figure out why this is giving me an infinite loop? I've gone through myself but I can't seem to find the problem. The "period" referred is how many times per year the interest is compounded. double account = 0; //declares the variables to be used double base = 0; double interest = 0; double rate = 0; double result = 0; double times = 0; int years = 0; int j; System.out.println("This is a program that calculates interest."); Scanner kbReader = new Scanner(System.in); //enters in all data System.out.print("Enter account balance: "); account = kbReader.nextDouble(); System.out.print("Enter interest rate (as decimal): "); rate = kbReader.nextDouble(); System.out.println(" " + "Years to double" + " " + "Ending balance"); base = account; result = account; for (j=0; j<3; j++){ System.out.print("Enter period: "); times = kbReader.nextDouble(); while (account < base*2){ interest = account * rate / times; account = interest + base; years++; } account = (((int)(account * 100))/100.0); //results System.out.print(" " + i + " " + account + "\n"); account = result; } The code should ask for three "periods", or three different times the entered data is compounded per year (ex annually, monthly, daily etc.) Thanks a lot!

    Read the article

  • Foreign-key-like merge in R

    - by skyl
    I'm merging a bunch of csv with 1 row per id/pk/seqn. > full = merge(demo, lab13am, by="seqn", all=TRUE) > full = merge(full, cdq, by="seqn", all=TRUE) > full = merge(full, mcq, by="seqn", all=TRUE) > full = merge(full, cfq, by="seqn", all=TRUE) > full = merge(full, diq, by="seqn", all=TRUE) > print(length(full$ridageyr)) [1] 9965 > print(summary(full$ridageyr)) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.00 11.00 19.00 29.73 48.00 85.00 Everything is great. But, I have another file which has multiple rows per id like: "seqn","rxd030","rxd240b","nhcode","rxq250" 56,2,"","",NA,NA,"" 57,1,"ACETAMINOPHEN","01200",2 57,1,"BUDESONIDE","08800",1 58,1,"99999","",NA 57 has two rows. So, if I naively try to merge this file, I have a ton more rows and my data gets all skewed up. > full = merge(full, rxq, by="seqn", all=TRUE) > print(length(full$ridageyr)) [1] 15643 > print(summary(full$ridageyr)) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.00 14.00 41.00 40.28 66.00 85.00 Is there a normal idiomatic way to deal with data like this? Suppose I want a way to make a simple model like MYSPECIAL_FACTOR <- somehow() glm(MYSPECIAL_FACTOR ~ full$ridageyr, family=binomial) where MYSPECIAL_FACTOR is, say, whether or not rxd240b == "ACETAMINOPHEN" for the observations which are unique by seqn. You can reproduce by running the first bit of this.

    Read the article

  • Is there any way to output the actual array in c++

    - by user2511129
    So, I'm beginning C++, with a semi-adequate background of python. In python, you make a list/array like this: x = [1, 2, 3, 4, 5, 6, 7, 8, 9] Then, to print the list, with the square brackets included, all you do is: print x That would display this: [1, 2, 3, 4, 5, 6, 7, 8, 9] How would I do the exact same thing in c++, print the brackets and the elements, in an elegant/clean fashion? NOTE I don't want just the elements of the array, I want the whole array, like this: {1, 2, 3, 4, 5, 6, 7, 8, 9} When I use this code to try to print the array, this happens: input: #include <iostream> using namespace std; int main() { int anArray[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << anArray << endl; } The output is where in memory the array is stored in (I think this is so, correct me if I'm wrong): 0x28fedc As a sidenote, I don't know how to create an array with many different data types, such as integers, strings, and so on, so if someone can enlighten me, that'd be great! Thanks for answering my painstakingly obvious/noobish questions!

    Read the article

  • Undefined method 'size' for #<File:text.txt> (NoMethodError)

    - by user1354456
    This is the code I am running, it does fine until I get to line 15. The command I run is: ruby ex16.rb text.txt. This is a practice sample I'm writing which is meant to be a simple little text editor: filename = ARGV.first script = $0 puts "We're going to erase #{filename}." puts "if you don't want that, hit CTRL-C (^C)." puts "If you do want that, hit RETURN." print "? " STDIN.gets puts "Opening the file..." target = File.open(filename, 'w') puts "Truncating the file. Goodbye!" target.truncate(target.size) puts "Now I'm going to ask you for three lines." print "line 1: "; line1 = STDIN.gets.chomp() print "line 2: "; line2 = STDIN.gets.chomp() print "line 3: "; line3 = STDIN.gets.chomp()undefined method 'size' puts "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") puts "And finally, we close it." target.close()

    Read the article

  • Empty value when iterating a dictionary with .iteritems() method

    - by ptpatil
    I am having some weird trouble with dictionaries, I am trying to iterate pairs from a dictionary to pass to another function. The loop for the iterator though for some reason always returns empty values. Here is the code: def LinktoCentral(self, linkmethod): if linkmethod == 'sim': linkworker = Linker.SimilarityLinker() matchlist = [] for k,v in self.ToBeMatchedTable.iteritems(): matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items())) Now if I insert a print line above the for loop: matchlist = [] print self.ToBeMatchedTable.items() for k,v in self.ToBeMatchedTable.iteritems(): matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items())) I get the data that is supposed to be in the dictionary printed out. The values of the dictionary are list objects. An example tuple I get from the dictionary when printing just above the for loop: >>> (1, ['AARP/United Health Care', '8002277789', 'PO Box 740819', 'Atlanta', 'GA', '30374-0819', 'Paper', '3676']) However, the for loop gives empty lists to the linkworker.GetBestMatch method. If I put a print line just below the for loop, here is what I get: Code: matchlist = [] for k,v in self.ToBeMatchedTable.iteritems(): print self.ToBeMatchedTable.items() matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items())) ## Place holder for line to send match list to display window return matchlist Result of first iteration: >>> (0, ['', '', '', '', '', '', '', '']) I literally have no idea whats going on, there is nothing else going on while this loop is executed. Any stupid mistakes I made?

    Read the article

  • How to deal with a poor team leader and a tester manager from hell? [closed]

    - by Google
    Let me begin by explaining my situation and give a little context to the situation. My company has around 15 developers but we're split up on two different areas. We have a fresh product team and the old product team. The old product team does mostly bug fixes/maintenance and a feature here and there. The fresh product had never been released and was new from the ground up. I am on the fresh product team. The team consists of three developers (myself, another developer and a senior developer). The senior is also our team leader. Our roles are as follows: Myself: building the administration client as well as build/release stuff Other dev: building the primary client Team lead: building the server In addition to the dev team, we interact with the test manager often. By "we" I mean me since I do the build stuff and give him the builds to test. Trial 1: The other developer on my team and I have both tried to talk to our manager about our team leader. About two weeks before release we went in his office and had a closed door meeting before our team lead got to work. We expressed our concerns about the product, its release date and our team leader. We expressed our team leader had a "rosey" image of the product's state. Our manager seemed to listen to what we said and thanked us for taking the initiative to speak with him about it. He got us an extra two weeks before release. The situation with the leader didn't change. In fact, it got a little worse. While we were using the two weeks to fix issues he was slacking off quite a bit. Just to name a few things, he installed Windows 8 on his dev machine during this time (claimed him machine was broke), he wrote a plugin for our office messenger that turned turned messages into speech, and one time when I went in his office he was making a 3D model in Blender (for "fun"). He felt the product was "pretty good" and ready for release. During this time I dealt with the test manager on a daily basis. Every bug or issue that popped up he would pretty much attack me personally (regardless of which component the bug was in). The test manager would often push his "views" of what needed to be done with the product. He virtually ordered me to change text on our installer and to add features to the installer and administration client. I tried to express how his suggestions were "valid ideas" but it was too close to release to do those kinds of things and to make matters worse, our technical writer had already finished documentation and such a change would not only affect the dev team but would affect the technical writer and marketing as well. I expressed I wasn't going to make those changes without marketing's consent as well as the technical writer and my manager's. He pretty much said I don't care about the product and said I don't do my job. I would like to take a moment to say I take my job seriously and I do my best. I am the kind of person that goes to work 30-40 mins early and usually leaves 30 minutes later than everyone else. Saying I don't care or do my job is just insulting. His "attacks" on me grew from day to day. Every bug that popped up he would usually comment on in some manner that jabbed me and the other developer. "Oh that bug! Yeah that should have been fixed by now, figures! If someone would do their job!" and other similar kinds of comments. Keep in mind 8 out of 10 bugs were in the server and had nothing to do with me and the other developer. That didn't seem to matter.. On one occasion they got pretty bad and we almost got into a yelling match so I decided to stop talking to him all together. I carried all communication through office email (with my manager cc'd). He never attacked me via email. He still attempted to get aggressive with me in person but I completely ignore him and my only response to any question is, "Ask my team leader." or "Ask a product manager." The product launched after our two week extension. Trial 2: The day after the product launch our team leader went on vacation (thanks....). At this time we got a lot of questions from the tech support... major issues with the product. All of these issues were bugs marked "resolved" by our lovely team leader (a typical situation that often popped up). This is where we currently are. The other developer has been with the company for about three years (I've been there only five months) and told me he was going to speak with our manager alone and hoped it would help get our concerns across a little better in a one-on-one. He spoke with the manager and directly addressed all of our concerns regarding our team leader and the test manager giving us (mostly me) hell. Our manager basically said he understood how hard we work and said he noticed it and there's no doubt about it. He said he spoke with the test manager about his temper. Regarding the team leader, he didn't say a whole lot. He suggested we sit down with the team leader and address our concerns (isn't that the manager's job?). We're still waiting to see if anything has changed but we doubt it. What can we do next? 1) Talk to the team leader (may stress relationship and make work awkward) I admit the team leader is generally a nice guy. He is just a horrible leader and working closely with him is painful. I still don't believe bringing this directly to the team leader would help at all and may negatively impact the situation. 2) I could quit. Other than this situation the job is pretty fantastic. I really like my other coworkers and we have quite a bit of freedom. 3) I could take the situation with the team leader to one of the owners. I would then be throwing my manager under the bus. 4) I could take the situation with the test manager to HR. Any suggestions? Comments?

    Read the article

  • Nashorn, the rhino in the room

    - by costlow
    Nashorn is a new runtime within JDK 8 that allows developers to run code written in JavaScript and call back and forth with Java. One advantage to the Nashorn scripting engine is that is allows for quick prototyping of functionality or basic shell scripts that use Java libraries. The previous JavaScript runtime, named Rhino, was introduced in JDK 6 (released 2006, end of public updates Feb 2013). Keeping tradition amongst the global developer community, "Nashorn" is the German word for rhino. The Java platform and runtime is an intentional home to many languages beyond the Java language itself. OpenJDK’s Da Vinci Machine helps coordinate work amongst language developers and tool designers and has helped different languages by introducing the Invoke Dynamic instruction in Java 7 (2011), which resulted in two major benefits: speeding up execution of dynamic code, and providing the groundwork for Java 8’s lambda executions. Many of these improvements are discussed at the JVM Language Summit, where language and tool designers get together to discuss experiences and issues related to building these complex components. There are a number of benefits to running JavaScript applications on JDK 8’s Nashorn technology beyond writing scripts quickly: Interoperability with Java and JavaScript libraries. Scripts do not need to be compiled. Fast execution and multi-threading of JavaScript running in Java’s JRE. The ability to remotely debug applications using an IDE like NetBeans, Eclipse, or IntelliJ (instructions on the Nashorn blog). Automatic integration with Java monitoring tools, such as performance, health, and SIEM. In the remainder of this blog post, I will explain how to use Nashorn and the benefit from those features. Nashorn execution environment The Nashorn scripting engine is included in all versions of Java SE 8, both the JDK and the JRE. Unlike Java code, scripts written in nashorn are interpreted and do not need to be compiled before execution. Developers and users can access it in two ways: Users running JavaScript applications can call the binary directly:jre8/bin/jjs This mechanism can also be used in shell scripts by specifying a shebang like #!/usr/bin/jjs Developers can use the API and obtain a ScriptEngine through:ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); When using a ScriptEngine, please understand that they execute code. Avoid running untrusted scripts or passing in untrusted/unvalidated inputs. During compilation, consider isolating access to the ScriptEngine and using Type Annotations to only allow @Untainted String arguments. One noteworthy difference between JavaScript executed in or outside of a web browser is that certain objects will not be available. For example when run outside a browser, there is no access to a document object or DOM tree. Other than that, all syntax, semantics, and capabilities are present. Examples of Java and JavaScript The Nashorn script engine allows developers of all experience levels the ability to write and run code that takes advantage of both languages. The specific dialect is ECMAScript 5.1 as identified by the User Guide and its standards definition through ECMA international. In addition to the example below, Benjamin Winterberg has a very well written Java 8 Nashorn Tutorial that provides a large number of code samples in both languages. Basic Operations A basic Hello World application written to run on Nashorn would look like this: #!/usr/bin/jjs print("Hello World"); The first line is a standard script indication, so that Linux or Unix systems can run the script through Nashorn. On Windows where scripts are not as common, you would run the script like: jjs helloWorld.js. Receiving Arguments In order to receive program arguments your jjs invocation needs to use the -scripting flag and a double-dash to separate which arguments are for jjs and which are for the script itself:jjs -scripting print.js -- "This will print" #!/usr/bin/jjs var whatYouSaid = $ARG.length==0 ? "You did not say anything" : $ARG[0] print(whatYouSaid); Interoperability with Java libraries (including 3rd party dependencies) Another goal of Nashorn was to allow for quick scriptable prototypes, allowing access into Java types and any libraries. Resources operate in the context of the script (either in-line with the script or as separate threads) so if you open network sockets and your script terminates, those sockets will be released and available for your next run. Your code can access Java types the same as regular Java classes. The “import statements” are written somewhat differently to accommodate for language. There is a choice of two styles: For standard classes, just name the class: var ServerSocket = java.net.ServerSocket For arrays or other items, use Java.type: var ByteArray = Java.type("byte[]")You could technically do this for all. The same technique will allow your script to use Java types from any library or 3rd party component and quickly prototype items. Building a user interface One major difference between JavaScript inside and outside of a web browser is the availability of a DOM object for rendering views. When run outside of the browser, JavaScript has full control to construct the entire user interface with pre-fabricated UI controls, charts, or components. The example below is a variation from the Nashorn and JavaFX guide to show how items work together. Nashorn has a -fx flag to make the user interface components available. With the example script below, just specify: jjs -fx -scripting fx.js -- "My title" #!/usr/bin/jjs -fx var Button = javafx.scene.control.Button; var StackPane = javafx.scene.layout.StackPane; var Scene = javafx.scene.Scene; var clickCounter=0; $STAGE.title = $ARG.length>0 ? $ARG[0] : "You didn't provide a title"; var button = new Button(); button.text = "Say 'Hello World'"; button.onAction = myFunctionForButtonClicking; var root = new StackPane(); root.children.add(button); $STAGE.scene = new Scene(root, 300, 250); $STAGE.show(); function myFunctionForButtonClicking(){   var text = "Click Counter: " + clickCounter;   button.setText(text);   clickCounter++;   print(text); } For a more advanced post on using Nashorn to build a high-performing UI, see JavaFX with Nashorn Canvas example. Interoperable with frameworks like Node, Backbone, or Facebook React The major benefit of any language is the interoperability gained by people and systems that can read, write, and use it for interactions. Because Nashorn is built for the ECMAScript specification, developers familiar with JavaScript frameworks can write their code and then have system administrators deploy and monitor the applications the same as any other Java application. A number of projects are also running Node applications on Nashorn through Project Avatar and the supported modules. In addition to the previously mentioned Nashorn tutorial, Benjamin has also written a post about Using Backbone.js with Nashorn. To show the multi-language power of the Java Runtime, there is another interesting example that unites Facebook React and Clojure on JDK 8’s Nashorn. Summary Nashorn provides a simple and fast way of executing JavaScript applications and bridging between the best of each language. By making the full range of Java libraries to JavaScript applications, and the quick prototyping style of JavaScript to Java applications, developers are free to work as they see fit. Software Architects and System Administrators can take advantage of one runtime and leverage any work that they have done to tune, monitor, and certify their systems. Additional information is available within: The Nashorn Users’ Guide Java Magazine’s article "Next Generation JavaScript Engine for the JVM." The Nashorn team’s primary blog or a very helpful collection of Nashorn links.

    Read the article

  • HTG Explains: Should You Buy Extended Warranties?

    - by Chris Hoffman
    Buy something at an electronics store and you’ll be confronted by a pushy salesperson who insists you need an extended warranty. You’ll also see extended warranties pushed hard when shopping online. But are they worth it? There’s a reason stores push extended warranties so hard. They’re almost always pure profit for the store involved. An electronics store may live on razor-thin product margins and make big profits on extended warranties and overpriced HDMI cables. You’re Already Getting Multiple Warranties First, back up. The product you’re buying already includes a warranty. In fact, you’re probably getting several different types of warranties. Store Return and Exchange: Most electronics stores allow you to return a malfunctioning product within the first 15 or 30 days and they’ll provide you with a new one. The exact period of time will vary from store to store. If you walk out of the store with a defective product and have to swap it for a new one within the first few weeks, this should be easy. Manufacturer Warranty: A device’s manufacturer — whether the device is a laptop, a television, or a graphics card — offers their own warranty period. The manufacturer warranty covers you after the store refuses to take the product back and exchange it. The length of this warranty depends on the type of product. For example, a cheap laptop may only offer a one-year manufacturer warranty, while a more expensive laptop may offer a two-year warranty. Credit Card Warranty Extension: Many credit cards offer free extended warranties on products you buy with that credit card. Credit card companies will often give you an additional year of warranty. For example, if you buy a laptop with a two year warranty and it fails in the third year, you could then contact your credit card company and they’d cover the cost of fixing or replacing it. Check your credit card’s benefits and fine print for more information. Why Extended Warranties Are Bad You’re already getting a fairly long warranty period, especially if you have a credit card that offers you a free extended warranty — these are fairly common. If the product you get is a “lemon” and has a manufacturing error, it will likely fail pretty soon — well within your warranty period. The extended warranty matters after all your other warranties are exhausted. In the case of a laptop with a two-year warranty that you purchase with a credit card giving you a one-year warranty extension, your extended warranty will kick in three years after you purchase the laptop. In that many years, your current laptop will likely feel pretty old and laptops that are as good — or better — will likely be pretty cheap. If it’s a television, better television displays will be available at a lower price point. You’ll either want to upgrade to a newer model or you’ll be able to buy a new, just-as-good product for very cheap. You’ll only have to pay out-of-pocket if your device fails after the normal warranty period — in over two or three years for typical laptops purchased with a decent credit card. Save the money you would have spent on the warranty and put it towards a future upgrade. How Much Do Extended Warranties Cost? Let’s look at an example from a typical pushy retail outlet, Best Buy. We went to Best Buy’s website and found a pretty standard $600 Samsung laptop. This laptop comes with a one-year warranty period. If purchased with a fairly common credit card, you can easily get a two-year warranty period on this laptop without spending an additional penny. (Yes, such credit cards are available with no yearly fees.) During the check-out process, Best Buy tries to sell you a Geek Squad “Accidental Protection Plan.” To get an additional year of Best Buy’s extended warranty, you’d have to pay $324.98 for a “3-Year Accidental Protection Plan”. You’d basically be paying more than half the price of your laptop for an additional year of warranty — remember, the standard warranties would cover you anyway for the first two years. If this laptop did break sometime between two and three years from now, we wouldn’t be surprised if you could purchase a comparable laptop for about $325 anyway. And, if you don’t need to replace it, you’ve saved that money. Best Buy would object that this isn’t a standard extended warranty. It’s a supercharged warranty plan that will also provide coverage if you spill something on your laptop or drop it and break it. You just have to ask yourself a question. What are the odds that you’ll drop your laptop or spill something on it? They’re probably pretty low if you’re a typical human being. Is it worth spending more than half the price of the laptop just in case you’ll make an uncommon mistake? Probably not. There may be occasional exceptions to this — some Apple users swear by Apple’s AppleCare, for example — but you should generally avoid buying these things. There’s a reason stores are so pushy about extended warranties, and it’s not because they want to help protect you. It’s because they’re making lots of profit from these plans, and they’re making so much profit because they’re not a good deal for customers. Image Credit: Philip Taylor on Flickr     

    Read the article

  • EM12c: Using the LIST verb in emcli

    - by SubinDaniVarughese
    Many of us who use EM CLI to write scripts and automate our daily tasks should not miss out on the new list verb released with Oracle Enterprise Manager 12.1.0.3.0. The combination of list and Jython based scripting support in EM CLI makes it easier to achieve automation for complex tasks with just a few lines of code. Before I jump into a script, let me highlight the key attributes of the list verb and why it’s simply excellent! 1. Multiple resources under a single verb:A resource can be set of users or targets, etc. Using the list verb, you can retrieve information about a resource from the repository database.Here is an example which retrieves the list of administrators within EM.Standard mode$ emcli list -resource="Administrators" Interactive modeemcli>list(resource="Administrators")The output will be the same as standard mode.Standard mode$ emcli @myAdmin.pyEnter password :  ******The output will be the same as standard mode.Contents of myAdmin.py scriptlogin()print list(resource="Administrators",jsonout=False).out()To get a list of all available resources use$ emcli list -helpWith every release of EM, more resources are being added to the list verb. If you have a resource which you feel would be valuable then go ahead and contact Oracle Support to log an enhancement request with product development. Be sure to say how the resource is going to help improve your daily tasks. 2. Consistent Formatting:It is possible to format the output of any resource consistently using these options:  –column  This option is used to specify which columns should be shown in the output. Here is an example which shows the list of administrators and their account status$ emcli list -resource="Administrators" -columns="USER_NAME,REPOS_ACCOUNT_STATUS" To get a list of columns in a resource use:$ emcli list -resource="Administrators" -help You can also specify the width of the each column. For example, here the column width of user_type is set to 20 and department to 30. $ emcli list -resource=Administrators -columns="USER_NAME,USER_TYPE:20,COST_CENTER,CONTACT,DEPARTMENT:30"This is useful if your terminal is too small or you need to fine tune a list of specific columns for your quick use or improved readability.  –colsize  This option is used to resize column widths.Here is the same example as above, but using -colsize to define the width of user_type to 20 and department to 30.$ emcli list -resource=Administrators -columns="USER_NAME,USER_TYPE,COST_CENTER,CONTACT,DEPARTMENT" -colsize="USER_TYPE:20,DEPARTMENT:30" The existing standard EMCLI formatting options are also available in list verb. They are: -format="name:pretty" | -format="name:script” | -format="name:csv" | -noheader | -scriptThere are so many uses depending on your needs. Have a look at the resources and columns in each resource. Refer to the EMCLI book in EM documentation for more information.3. Search:Using the -search option in the list verb makes it is possible to search for a specific row in a specific column within a resource. This is similar to the sqlplus where clause. The following operators are supported:           =           !=           >           <           >=           <=           like           is (Must be followed by null or not null)Here is an example which searches for all EM administrators in the marketing department located in the USA.$emcli list -resource="Administrators" -search="DEPARTMENT ='Marketing'" -search="LOCATION='USA'" Here is another example which shows all the named credentials created since a specific date.  $emcli list -resource=NamedCredentials -search="CredCreatedDate > '11-Nov-2013 12:37:20 PM'"Note that the timestamp has to be in the format DD-MON-YYYY HH:MI:SS AM/PM Some resources need a bind variable to be passed to get output. A bind variable is created in the resource and then referenced in the command. For example, this command will list all the default preferred credentials for target type oracle_database.Here is an example$ emcli list -resource="PreferredCredentialsDefault" -bind="TargetType='oracle_database'" -colsize="SetName:15,TargetType:15" You can provide multiple bind variables. To verify if a column is searchable or requires a bind variable, use the –help option. Here is an example:$ emcli list -resource="PreferredCredentialsDefault" -help 4. Secure accessWhen list verb collects the data, it only displays content for which the administrator currently logged into emcli, has access. For example consider this usecase:AdminA has access only to TargetA. AdminA logs into EM CLIExecuting the list verb to get the list of all targets will only show TargetA.5. User defined SQLUsing the –sql option, user defined sql can be executed. The SQL provided in the -sql option is executed as the EM user MGMT_VIEW, which has read-only access to the EM published MGMT$ database views in the SYSMAN schema. To get the list of EM published MGMT$ database views, go to the Extensibility Programmer's Reference book in EM documentation. There is a chapter about Using Management Repository Views. It’s always recommended to reference the documentation for the supported MGMT$ database views.  Consider you are using the MGMT$ABC view which is not in the chapter. During upgrade, it is possible, since the view was not in the book and not supported, it is likely the view might undergo a change in its structure or the data in it. Using a supported view ensures that your scripts using -sql will continue working after upgrade.Here’s an example  $ emcli list -sql='select * from mgmt$target' 6. JSON output support    JSON (JavaScript Object Notation) enables data to be displayed in a collection of name/value pairs. There is lot of reading material about JSON on line for more information.As an example, we had a requirement where an EM administrator had many 11.2 databases in their test environment and the developers had requested an Administrator to change the lifecycle status from Test to Production which meant the admin had to go to the EM “All targets” page and identify the set of 11.2 databases and then to go into each target database page and manually changes the property to Production. Sounds easy to say, but this Administrator had numerous targets and this task is repeated for every release cycle.We told him there is an easier way to do this with a script and he can reuse the script whenever anyone wanted to change a set of targets to a different Lifecycle status. Here is a jython script which uses list and JSON to change all 11.2 database target’s LifeCycle Property value.If you are new to scripting and Jython, I would suggest visiting the basic chapters in any Jython tutorials. Understanding Jython is important to write the logic depending on your usecase.If you are already writing scripts like perl or shell or know a programming language like java, then you can easily understand the logic.Disclaimer: The scripts in this post are subject to the Oracle Terms of Use located here.  1 from emcli import *  2  search_list = ['PROPERTY_NAME=\'DBVersion\'','TARGET_TYPE= \'oracle_database\'','PROPERTY_VALUE LIKE \'11.2%\'']  3 if len(sys.argv) == 2:  4    print login(username=sys.argv[0])  5    l_prop_val_to_set = sys.argv[1]  6      l_targets = list(resource="TargetProperties", search=search_list,   columns="TARGET_NAME,TARGET_TYPE,PROPERTY_NAME")  7    for target in l_targets.out()['data']:  8       t_pn = 'LifeCycle Status'  9      print "INFO: Setting Property name " + t_pn + " to value " +       l_prop_val_to_set + " for " + target['TARGET_NAME']  10      print  set_target_property_value(property_records=      target['TARGET_NAME']+":"+target['TARGET_TYPE']+":"+      t_pn+":"+l_prop_val_to_set)  11  else:  12   print "\n ERROR: Property value argument is missing"  13   print "\n INFO: Format to run this file is filename.py <username>   <Database Target LifeCycle Status Property Value>" You can download the script from here. I could not upload the file with .py extension so you need to rename the file to myScript.py before executing it using emcli.A line by line explanation for beginners: Line  1 Imports the emcli verbs as functions  2 search_list is a variable to pass to the search option in list verb. I am using escape character for the single quotes. In list verb to pass more than one value for the same option, you should define as above comma separated values, surrounded by square brackets.  3 This is an “if” condition to ensure the user does provide two arguments with the script, else in line #15, it prints an error message.  4 Logging into EM. You can remove this if you have setup emcli with autologin. For more details about setup and autologin, please go the EM CLI book in EM documentation.  5 l_prop_val_to_set is another variable. This is the property value to be set. Remember we are changing the value from Test to Production. The benefit of this variable is you can reuse the script to change the property value from and to any other values.  6 Here the output of the list verb is stored in l_targets. In the list verb I am passing the resource as TargetProperties, search as the search_list variable and I only need these three columns – target_name, target_type and property_name. I don’t need the other columns for my task.  7 This is a for loop. The data in l_targets is available in JSON format. Using the for loop, each pair will now be available in the ‘target’ variable.  8 t_pn is the “LifeCycle Status” variable. If required, I can have this also as an input and then use my script to change any target property. In this example, I just wanted to change the “LifeCycle Status”.  9 This a message informing the user the script is setting the property value for dbxyz.  10 This line shows the set_target_property_value verb which sets the value using the property_records option. Once it is set for a target pair, it moves to the next one. In my example, I am just showing three dbs, but the real use is when you have 20 or 50 targets. The script is executed as:$ emcli @myScript.py subin Production The recommendation is to first test the scripts before running it on a production system. We tested on a small set of targets and optimizing the script for fewer lines of code and better messaging.For your quick reference, the resources available in Enterprise Manager 12.1.0.4.0 with list verb are:$ emcli list -helpWatch this space for more blog posts using the list verb and EM CLI Scripting use cases. I hope you enjoyed reading this blog post and it has helped you gain more information about the list verb. Happy Scripting!!Disclaimer: The scripts in this post are subject to the Oracle Terms of Use located here. Stay Connected: Twitter | Facebook | YouTube | Linkedin | Newsletter mt=8">Download the Oracle Enterprise Manager 12c Mobile app

    Read the article

  • Beginning Java (Working with Arrays; Class Assignment)

    - by Jason
    I am to the point where I feel as if I correctly wrote the code for this homework assignment. We were given a skeleton and 2 classes that we had to import (FileIOHelper and Student). /* * Created: *** put the date here *** * * Author: *** put your name here *** * * The program will read information about students and their * scores from a file, and output the name of each student with * all his/her scores and the total score, plus the average score * of the class, and the name and total score of the students with * the highest and lowest total score. */ // import java.util.Scanner; import java.io.*; // C:\Users\Adam\info.txt public class Lab6 { public static void main(String[] args) throws IOException { // Fill in the body according to the following comments Scanner key boardFile = new Scanner(System.in); // Input file name String filename = getFileName(keyboardFile); //Open the file // Input number of students int numStudents = FileIOHelper.getNumberOfStudents(filename); Student students[] = new Student[numStudents]; // Input all student records and create Student array and // integer array for total scores int totalScore[] = new int[students.length]; for (int i = 0; i < students.length; i++){ for(int j = 1; j < 4; j++){ totalScore[i] = totalScore[i] + students[i].getScore(j); } } // Compute total scores and find students with lowest and // highest total score int maxScore = 0; int minScore = 0; for(int i = 0; i < students.length; i++){ if(totalScore[i] >= totalScore[maxScore]){ maxScore = i; } else if(totalScore[i] <= totalScore[minScore]){ minScore = i; } } // Compute average total score int allScores = 0; int average = 0; for (int i = 0; i < totalScore.length; i++){ allScores = allScores + totalScore[i]; } average = allScores / totalScore.length; // Output results outputResults(students, totalScore, maxScore, minScore, average); } // Given a Scanner in, this method prompts the user to enter // a file name, inputs it, and returns it. private static String getFileName(Scanner in) { // Fill in the body System.out.print("Enter the name of a file: "); String filename = in.next(); return filename; // Do not declare the Scanner variable in this method. // You must use the value this method receives in the // argument (in). } // Given the number of students records n to input, this // method creates an array of Student of the appropriate size, // reads n student records using the FileIOHelper, and stores // them in the array, and finally returns the Student array. private static Student[] getStudents(int n) { Student[] myStudents = new Student[n]; for(int i = 0; i <= n; i++){ myStudents[i] = FileIOHelper.getNextStudent(); } return myStudents; } // Given an array of Student records, an array with the total scores, // the indices in the arrays of the students with the highest and // lowest total scores, and the average total score for the class, // this method outputs a table of all the students appropriately // formatted, plus the total number of students, the average score // of the class, and the name and total score of the students with // the highest and lowest total score. private static void outputResults( Student[] students, int[] totalScores, int maxIndex, int minIndex, int average ) { // Fill in the body System.out.println("\nName \t\tScore1 \tScore2 \tScore3 \tTotal"); System.out.println("--------------------------------------------------------"); for(int i = 0; i < students.length; i++){ outputStudent(students[i], totalScores[i], average); System.out.println(); } System.out.println("--------------------------------------------------------"); outputNumberOfStudents(students.length); outputAverage(average); outputMaxStudent(students[maxIndex], totalScores[maxIndex]); outputMinStudent(students[minIndex], totalScores[minIndex]); System.out.println("--------------------------------------------------------"); } // Given a Student record, the total score for the student, // and the average total score for all the students, this method // outputs one line in the result table appropriately formatted. private static void outputStudent(Student s, int total, int avg) { System.out.print(s.getName() + "\t"); for(int i = 1; i < 4; i++){ System.out.print(s.getScore(i) + "\t"); } System.out.print(total + "\t"); if(total < avg){ System.out.print("-"); }else if(total > avg){ System.out.print("+"); }else{ System.out.print("="); } } // Given the number of students, this method outputs a message // stating what the total number of students in the class is. private static void outputNumberOfStudents(int n) { System.out.println("The total number of students in this class is: \t" + n); } // Given the average total score of all students, this method // outputs a message stating what the average total score of // the class is. private static void outputAverage(int average) { System.out.println("The average total score of the class is: \t" + average); } // Given the Student with highest total score and the student's // total score, this method outputs a message stating the name // of the student and the highest score. private static void outputMaxStudent( Student student, int score ) { System.out.println(student.getName() + " got the maximum total score of: \t" + score); } // Given the Student with lowest total score and the student's // total score, this method outputs a message stating the name // of the student and the lowest score. private static void outputMinStudent( Student student, int score ) { System.out.println(student.getName() + " got the minimum total score of: \t" + score); } } But now I get an error at the line totalScore[i] = totalScore[i] + students[i].getScore(j); Exception in thread "main" java.lang.NullPointerException at Lab6.main(Lab6.java:42)

    Read the article

  • JVM process resident set size "equals" max heap size, not current heap size

    - by Volune
    After a few reading about jvm memory (here, here, here, others I forgot...), I am expecting the resident set size of my java process to be roughly equal to the current heap space capacity. That's not what the numbers are saying, it seems to be roughly equal to the max heap space capacity: Resident set size: # echo 0 $(cat /proc/1/smaps | grep Rss | awk '{print $2}' | sed 's#^#+#') | bc 11507912 # ps -C java -O rss | gawk '{ count ++; sum += $2 }; END {count --; print "Number of processes =",count; print "Memory usage per process =",sum/1024/count, "MB"; print "Total memory usage =", sum/1024, "MB" ;};' Number of processes = 1 Memory usage per process = 11237.8 MB Total memory usage = 11237.8 MB Java heap # jmap -heap 1 Attaching to process ID 1, please wait... Debugger attached successfully. Server compiler detected. JVM version is 24.55-b03 using thread-local object allocation. Garbage-First (G1) GC with 18 thread(s) Heap Configuration: MinHeapFreeRatio = 10 MaxHeapFreeRatio = 20 MaxHeapSize = 10737418240 (10240.0MB) NewSize = 1363144 (1.2999954223632812MB) MaxNewSize = 17592186044415 MB OldSize = 5452592 (5.1999969482421875MB) NewRatio = 2 SurvivorRatio = 8 PermSize = 20971520 (20.0MB) MaxPermSize = 85983232 (82.0MB) G1HeapRegionSize = 2097152 (2.0MB) Heap Usage: G1 Heap: regions = 2560 capacity = 5368709120 (5120.0MB) used = 1672045416 (1594.586769104004MB) free = 3696663704 (3525.413230895996MB) 31.144272834062576% used G1 Young Generation: Eden Space: regions = 627 capacity = 3279945728 (3128.0MB) used = 1314914304 (1254.0MB) free = 1965031424 (1874.0MB) 40.089514066496164% used Survivor Space: regions = 49 capacity = 102760448 (98.0MB) used = 102760448 (98.0MB) free = 0 (0.0MB) 100.0% used G1 Old Generation: regions = 147 capacity = 1986002944 (1894.0MB) used = 252273512 (240.5867691040039MB) free = 1733729432 (1653.413230895996MB) 12.702574926293766% used Perm Generation: capacity = 39845888 (38.0MB) used = 38884120 (37.082786560058594MB) free = 961768 (0.9172134399414062MB) 97.58628042120682% used 14654 interned Strings occupying 2188928 bytes. Are my expectations wrong? What should I expect? I need the heap space to be able to grow during spikes (to avoid very slow Full GC), but I would like to have the resident set size as low as possible the rest of the time, to benefit the other processes running on the server. Is there a better way to achieve that? Linux 3.13.0-32-generic x86_64 java version "1.7.0_55" Running in Docker version 1.1.2 Java is running elasticsearch 1.2.0: /usr/bin/java -Xms5g -Xmx10g -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -Xss256k -Djava.awt.headless=true -XX:+UseG1GC -XX:MaxGCPauseMillis=350 -XX:InitiatingHeapOccupancyPercent=45 -XX:+AggressiveOpts -XX:+UseCompressedOops -XX:-OmitStackTraceInFastThrow -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintClassHistogram -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCApplicationConcurrentTime -Xloggc:/opt/elasticsearch/logs/gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt elasticsearch/logs/heapdump.hprof -XX:ErrorFile=/opt/elasticsearch/logs/hs_err.log -Des.logger.port=99999 -Des.logger.host=999.999.999.999 -Delasticsearch -Des.foreground=yes -Des.path.home=/opt/elasticsearch -cp :/opt/elasticsearch/lib/elasticsearch-1.2.0.jar:/opt/elasticsearch/lib/*:/opt/elasticsearch/lib/sigar/* org.elasticsearch.bootstrap.Elasticsearch There actually are 5 elasticsearch nodes, each in a different docker container. All have about the same memory usage. Some stats about the index: size: 9.71Gi (19.4Gi) docs: 3,925,398 (4,052,694)

    Read the article

  • Finding all domains registered in a nameserver

    - by Florian
    Up until now, I was pretty confident that it was pretty much impossible to list all the domains handled by a nameserver. But apparently, there exists a couple of websites on the Internet that are able to list all the domains registered in a namerserver. For example: http://www.gwebtools.com/ns-spy/udns1.ultradns.net Or all domains pointing to a specific IP : http://www.robtex.com/ip/190.7.200.92.html (These DNS/IP were picked at random) Do you know how it's done ?

    Read the article

  • Fedora 10 setting up HPLIP for HP Deskjet F4488

    - by Shyam
    I had set up a newly purchased HP F4488 using HPLIP, I installed it on my Fedora 10 desktop and it worked fine for the past 2 days. Suddenly, it is failing to print. The scanner works and the photocopier works. When a print job is initialized there is an error and the printer gets disabled. What is the problem? Is there anything that I should fix additionally to make it work?

    Read the article

  • Microsoft Word 2007 Landscape Printing

    - by Greg Ogle
    When printing document in landscape mode using Microsoft Word 2007, it is print portrait and scaling (varies a little per printer). I made a new document with just text and the text is getting chopped even in print preview. It seems rather weird. Am I doing something wrong?

    Read the article

  • Disable header/footer printing from Chrome

    - by Toby
    The Chrome browser doesn't have any settings for changing or disabling header and footer data that gets printed when you go File Print. Apparently this is being developed but until it is does anyone know how to disable this in Windows XP. Chrome on the Mac and Ubuntu doesn't do it so I assume it is down to a system setting that by default doesn't print header/footer information unless software over-rides this?

    Read the article

  • Huge Image Problem

    - by Amira Elsayed
    Hi All, I have a great problem , and I have no idea how to solve it , I have create a chart (Mind map) in Smart draw, what I want now is to print this Mind map , the mind map is very large when i Export it as Image I have a big image , so can any one tell me if there is any software that can divide this big image into small parts of size (A4) to be able to print it on several papers and show it to my boss please help as soon as you can Thanks in Advance

    Read the article

  • OneNote 2007 - recommendation(s) of a good place/tutorials to learn features

    - by studiohack23
    I'm pretty familiar with Office 2007, however, I have just recently acquired OneNote 2007. It is such a big and powerful tool, that I'm pretty much lost on the features and how to use it. I don't really know where to start. I'm looking for some recommendation(s) on a good place to learn more about OneNote and its features and what it does...for what it's worth, I'm a student, so student perspectives on how to use/learn OneNote would be awesome! Thanks!

    Read the article

  • Where to upload cgi script on Linux Debian VPS with Plesk ?

    - by Rebol Tutorial
    I'm newbie to Linux. I have uploaded rebol ( a script langage similar to perl from http://www.rebol.com/view-platforms.html ) the linux debian version to /usr/bin on my VPS Where do I upload this script : Code: #!/usr/bin/rebol -c REBOL [Title: "Cgi Test in Rebol"] print "content-type: text/html^/" print ["Date/time is:" now] as I have 2 domain names on this VPS, I can't find where the domain folder are to do so.

    Read the article

  • How to port Apache rewrite rules to cherokee?

    - by saint
    I'm pretty new to cherokee, it's great and pretty straight forward except URL Rewrites. Is there a straight forward guide to it? Let me know. Also how would I port this: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] Thanks

    Read the article

< Previous Page | 81 82 83 84 85 86 87 88 89 90 91 92  | Next Page >