Daily Archives

Articles indexed Monday October 28 2013

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

  • 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

  • Intercept creation of activities when the application is restored

    - by Johan Bilien
    Most of our activities access a user-specific model. All these activities inherit from a ModelActivity base class, which provides a getModel() call. When one of these activities detect that the user has signed out (through the AccountManager callback), it sticks to its existing model, but prepares to exit back to the root activity (which is not user-specific) by starting its intent with FLAG_ACTIVITY_CLEAR_TOP. If however the user deletes an account while the app is not running, we run into trouble when the activity is restored. Now the activity needs to handle there not being a model, which makes the code more complicated and bug-prone. Ideally we would intercept the application restore process before the activity is created. Then we would check whether we have an account and a model, and if not clear up the saved stack of activities, and restart from our root activity instead of the last saved activity. But as far as I can tell the first place where we can run code is in the onCreate callback of the activity. Is there a way to run some code when the application is restored from background-saving, but before the saved activity is created?

    Read the article

  • How to access private static target field in aspect in AspectJ?

    - by LihO
    I have a simple class Main with private static int x and an aspect that should output the old value of x before it is reassigned: public class Main { private static int x; public static void main(String[] args) { foo(7); } public static void foo(int y) { x = y; } } and MonitorX.aj: public aspect MonitorX { before() : set(static int Main.x){ System.out.println(Main.x); } } which doesn't work since I can't access private x using Main.x. I've also tried: before(int t) : set(static int Main.x) && target(t){ System.out.println(t); } which doesn't work either (nothing is outputted, if I try to output string, it seems that the aspect isn't invoked at all). However printing out the new value that is being assigned works: before(int newVal) : set(static int Main.x) && args(newVal){ System.out.println(newVal); } What am I missing?

    Read the article

  • Initializing AngularJS service factory style

    - by wisemanIV
    I have a service that retrieves data via REST. I want to store the resulting data in service level variable for use in multiple controllers. When I put all the REST logic directly into controllers everything works fine but when I attempt to move the retrieval / storing of data into a service the controller is not being updated when the data comes back. I've tried lots of different ways of maintain the binding between service and controller. Controller: myApp.controller('SiteConfigCtrl', ['$scope', '$rootScope', '$route', 'SiteConfigService', function ($scope, $rootScope, $route, SiteConfigService) { $scope.init = function() { console.log("SiteConfigCtrl init"); $scope.site = SiteConfigService.getConfig(); } } ]); Service: myApp.factory('SiteConfigService', ['$http', '$rootScope', '$timeout', 'RESTService', function ($http, $rootScope, $timeout, RESTService) { var siteConfig = {} ; RESTService.get("https://domain/incentiveconfig", function(data) { siteConfig = data; }); return { getConfig:function () { console.debug("SiteConfigService getConfig:"); console.debug(siteConfig); return siteConfig; } }; } ]);

    Read the article

  • refresh page with ajax jquery without use of reload function

    - by Ronak Patel
    I am performing delete records by using jquery ajax in php. I want to refresh that content without the use of location.reload() function. I tried this, $("#divSettings").html(this); but, it's not working. What's the correct logic to get updated content in div. Thanks. Code: function deletePoll(postId){ $.ajax({ type: "POST", url: "../internal_request/ir_display_polls.php", data: { postId: postId }, success: function(result) { location.reload(); //$("#divSettings").html(this); } }); }

    Read the article

  • Java List to Excel Columns

    - by Nitin
    Correct me where I'm going wrong. I'm have written a program in Java which will get list of files from two different directories and make two (Java list) with the file names. I want to transfer the both the list (downloaded files list and Uploaded files list) to an excel. What the result i'm getting is those list are transferred row wise. I want them in column wise. Given below is the code: public class F { static List<String> downloadList = new ArrayList<>(); static List<String> dispatchList = new ArrayList<>(); public static class FileVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String name = file.toRealPath().getFileName().toString(); if (name.endsWith(".pdf") || name.endsWith(".zip")) { downloadList.add(name); } if (name.endsWith(".xml")) { dispatchList.add(name); } return FileVisitResult.CONTINUE; } } public static void main(String[] args) throws IOException { try { Path downloadPath = Paths.get("E:\\report\\02_Download\\10252013"); Path dispatchPath = Paths.get("E:\\report\\01_Dispatch\\10252013"); FileVisitor visitor = new FileVisitor(); Files.walkFileTree(downloadPath, visitor); Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor); Files.walkFileTree(dispatchPath, visitor); Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor); System.out.println("Download File List" + downloadList); System.out.println("Dispatch File List" + dispatchList); F f = new F(); f.UpDown(downloadList, dispatchList); } catch (Exception ex) { Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex); } } int rownum = 0; int colnum = 0; HSSFSheet firstSheet; Collection<File> files; HSSFWorkbook workbook; File exactFile; { workbook = new HSSFWorkbook(); firstSheet = workbook.createSheet("10252013"); Row headerRow = firstSheet.createRow(rownum); headerRow.setHeightInPoints(40); } public void UpDown(List<String> download, List<String> upload) throws Exception { List<String> headerRow = new ArrayList<>(); headerRow.add("Downloaded"); headerRow.add("Uploaded"); List<List> recordToAdd = new ArrayList<>(); recordToAdd.add(headerRow); recordToAdd.add(download); recordToAdd.add(upload); F f = new F(); f.CreateExcelFile(recordToAdd); f.createExcelFile(); } void createExcelFile() { FileOutputStream fos = null; try { fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls")); HSSFCellStyle hsfstyle = workbook.createCellStyle(); hsfstyle.setBorderBottom((short) 1); hsfstyle.setFillBackgroundColor((short) 245); workbook.write(fos); } catch (Exception e) { } } public void CreateExcelFile(List<List> l1) throws Exception { try { for (int j = 0; j < l1.size(); j++) { Row row = firstSheet.createRow(rownum); List<String> l2 = l1.get(j); for (int k = 0; k < l2.size(); k++) { Cell cell = row.createCell(k); cell.setCellValue(l2.get(k)); } rownum++; } } catch (Exception e) { } finally { } } } (The purpose is to verify the files Downloaded and Uploaded for the given date) Thanks.

    Read the article

  • why does my <br> not work ?

    - by Vince
    I am returning a PHP array back to a JQuery call for appending into a div called "name-data". I want my array to be listed vertically, so I concatenate a br tag in the PHP however, when it gets to the HTML page the br is not being rendered, it just comes out as text. I have tried the various forms of br all without luck. I am new to JQuery - What am I doing wrong ? Many Thanks ! PHP: $result = mysqli_query($con,"SELECT FirstName FROM customer limit 5"); while($row = mysqli_fetch_array($result)) { echo $row['FirstName']."<br />"; } JQuery: $('input#name-submit').on('click',function(){ var name = $('input#name').val(); if($.trim(name) !=''){ $.post('search.php',{name:name}, function(data){ $('div#name-data').text(data); }); } }); HTML Name:<input type="text" id="name"> <input type="submit" id="name-submit" value="grab"> <div id="name-data"> </div>

    Read the article

  • Polymorphic behavior not being implemented

    - by Garrett A. Hughes
    The last two lines of this code illustrate the problem: the compiler works when I use the reference to the object, but not when I assign the reference to an array element. The rest of the code is in the same package in separate files. BioStudent and ChemStudent are separate classes, as well as Student. package pkgPoly; public class Poly { public static void main(String[] arg) { Student[] stud = new Student[3]; // create a biology student BioStudent s1 = new BioStudent("Tom"); // create a chemistry student ChemStudent s2 = new ChemStudent("Dick"); // fill the student body with studs stud[0] = s0; stud[1] = s1; // compiler complains that it can't find symbol getMajor on next line System.out.println("major: " + stud[0].getMajor() ); // doesn't compile; System.out.println("major: " + s0.getMajor() ); // works: compiles and runs correctly } }

    Read the article

  • Localized Android app without using "res" folder. Is there a downside?

    - by user312916
    I am developing a game with Unity 3D and want to use custom code to get strings in the various languages I will be supporting. I've read articles about using the Android "res/values-xx/" directories (such as this page: http://developer.android.com/training/basics/supporting-devices/languages.html). If I do not store my translated strings in this way is there a downside? My main concern is whether the Google Play store may not know what languages my app is localized for.

    Read the article

  • Java JCheckBox ArrayList help needed

    - by user2929626
    I'm new to Java and struggling with something which I'm sure must have a simple answer but I can't seem to find it. I have an array of checkbox objects defined as: ArrayList<JCheckBox> checkBoxList A JPanel is created with a grid layout and the checkboxes are added to the JPanel and the ArrayList: for (int i = 0; i < 256; i++) { JCheckBox c = new JCheckBox(); c.setSelected(false); checkBoxList.add(c); mainPanel.add(c); } Yes, there are 256 checkboxes! The panel is added to a JFrame and eventually the GUI is displayed. The user can select any combination of the 256 checkboxes. My class implements Serializable and this ArrayList of checkboxes can be saved and restored using 'Save' and 'Load' GUI buttons. My code to load the saved object is as below: public class LoadListener implements ActionListener { public void actionPerformed(ActionEvent a) { try { // Prompt the user for a load file JFileChooser fileLoad = new JFileChooser(); fileLoad.showOpenDialog(mainFrame); // Create a object/file input stream linking to the selected file ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileLoad.getSelectedFile())); // Read the checkBox array list checkBoxList = (ArrayList<JCheckBox>) is.readObject(); is.close(); } catch (Exception ex) { ex.printStackTrace(); } } On loading the ArrayList object, the values of the checkboxes are correctly populated, however I want to update the checkboxes on the GUI to reflect this. Is there an easy way to do this? I assumed as the array of checkboxes had the correct values that I could just repaint the panel / frame but this doesn't work. I'd like to understand why - does my loaded array of checkbox objects no longer reflect the checkbox objects on the GUI? Any help would be much appreciated. Thanks!

    Read the article

  • A "Trig" Calculating Class

    - by Clinton Scott
    I have been trying to create a gui that calculates trigonometric functions based off of the user's input. I have had success in the GUI part, but my class that I wrote to hold information using inheritance seems to be messed up, because when I run it gives an error saying: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constructor ArcTrigCalcCon in class TrigCalc.ArcTrigCalcCon cannot be applied to given types; required: double,double,double,double,double,double found: java.lang.Double,java.lang.Double,java.lang.Double reason: actual and formal argument lists differ in length at TrigCalc.TrigCalcGUI.(TrigCalcGUI.java:31) at TrigCalc.TrigCalcGUI.main(TrigCalcGUI.java:87) Java Result: 1 and says it is the object causing the problem. Below Will be my code. First I will put up my inheritance class with cosecant secant and cotangent and then my original class with the original 3 trig functions: { public ArcTrigCalcCon(double s, double cs, double t, double csc, double sc, double ct) { // Inherit from the Trig Calc class super(s, cs, t); cosecant = 1/s; secant = 1/cs; cotangent = 1/t; } public void setCsc(double csc) { cosecant = csc; } public void setSec(double sc) { secant = sc; } public void setCot(double ct) { cotangent = ct; } } Here is the first Trigonometric class: public class TrigCalcCon { public double sine; public double cosine; public double tangent; public TrigCalcCon(double s, double cs, double t) { sine = s; cosine = cs; tangent = t; } public void setSin(double s) { sine = s; } public void setCos(double cs) { cosine = cs; } public void setTan(double t) { tangent = t; } public void set(double s, double cs, double t) { sine = s; cosine = cs; tangent = t; } public double getSin() { return Math.sin(sine); } public double getCos() { return Math.cos(cosine); } public double getTan() { return Math.tan(tangent); } } and here is the demo class to run the gui: public class TrigCalcGUI extends JFrame implements ActionListener { // Instance Variables private String input; private Double s, cs, t, csc, sc, ct; private JPanel mainPanel, sinPanel, cosPanel, tanPanel, cscPanel, secPanel, cotPanel, buttonPanel, inputPanel, displayPanel; // Panel Display private JLabel sinLabel, cosLabel, tanLabel, secLabel, cscLabel, cotLabel, inputLabel; private JTextField sinTF, cosTF, tanTF, secTF, cscTF, cotTF, inputTF; //Text Fields for sin, cos, and tan, and inverse private JButton calcButton, clearButton; // Calculate and Exit Buttons // Object ArcTrigCalcCon trC = new ArcTrigCalcCon(s, cs, t); public TrigCalcGUI() { // title bar text. super("Trig Calculator"); // Corner exit button action. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create main panel to add each panel to mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(3,2)); displayPanel = new JPanel(); displayPanel.setLayout(new GridLayout(3,2)); // Assign Panel to each variable inputPanel = new JPanel(); sinPanel = new JPanel(); cosPanel = new JPanel(); tanPanel = new JPanel(); cscPanel = new JPanel(); secPanel = new JPanel(); cotPanel = new JPanel(); buttonPanel = new JPanel(); // Call each constructor buildInputPanel(); buildSinCosTanPanels(); buildCscSecCotPanels(); buildButtonPanel(); // Add each panel to content pane displayPanel.add(sinPanel); displayPanel.add(cscPanel); displayPanel.add(cosPanel); displayPanel.add(secPanel); displayPanel.add(tanPanel); displayPanel.add(cotPanel); // Add three content panes to GUI mainPanel.add(inputPanel, BorderLayout.NORTH); mainPanel.add(displayPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); //add mainPanel this.add(mainPanel); // size of window to content this.pack(); // display window setVisible(true); } public static void main(String[] args) { new TrigCalcGUI(); } private void buildInputPanel() { inputLabel = new JLabel("Enter a Value: "); inputTF = new JTextField(5); inputPanel.add(inputLabel); inputPanel.add(inputTF); } // Building Constructor for sinPanel cosPanel, and tanPanel private void buildSinCosTanPanels() { // Set layout and border for sinPanel sinPanel.setLayout(new GridLayout(2,2)); sinPanel.setBorder(BorderFactory.createTitledBorder("Sine")); // sinTF = new JTextField(5); sinTF.setEditable(false); sinPanel.add(sinTF); // Set layout and border for cosPanel cosPanel.setLayout(new GridLayout(2,2)); cosPanel.setBorder(BorderFactory.createTitledBorder("Cosine")); cosTF = new JTextField(5); cosTF.setEditable(false); cosPanel.add(cosTF); // Set layout and border for tanPanel tanPanel.setLayout(new GridLayout(2,2)); tanPanel.setBorder(BorderFactory.createTitledBorder("Tangent")); tanTF = new JTextField(5); tanTF.setEditable(false); tanPanel.add(tanTF); } // Building Constructor for cscPanel secPanel, and cotPanel private void buildCscSecCotPanels() { // Set layout and border for cscPanel cscPanel.setLayout(new GridLayout(2,2)); cscPanel.setBorder(BorderFactory.createTitledBorder("Cosecant")); // cscTF = new JTextField(5); cscTF.setEditable(false); cscPanel.add(cscTF); // Set layout and border for secPanel secPanel.setLayout(new GridLayout(2,2)); secPanel.setBorder(BorderFactory.createTitledBorder("Secant")); secTF = new JTextField(5); secTF.setEditable(false); secPanel.add(secTF); // Set layout and border for cotPanel cotPanel.setLayout(new GridLayout(2,2)); cotPanel.setBorder(BorderFactory.createTitledBorder("Cotangent")); cotTF = new JTextField(5); cotTF.setEditable(false); cotPanel.add(cotTF); } private void buildButtonPanel() { // Create buttons and add events calcButton = new JButton("Calculate"); calcButton.addActionListener(new CalcButtonListener()); clearButton = new JButton("Clear"); clearButton.addActionListener(new ClearButtonListener()); buttonPanel.add(calcButton); buttonPanel.add(clearButton); } @Override public void actionPerformed(ActionEvent e) { } private class CalcButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Declare boolean variable boolean incorrect = true; // Set input variable to input text field text input = inputTF.getText(); ImageIcon newIcon; ImageIcon frowny = new ImageIcon(TrigCalcGUI.class.getResource("/Sad_Face.png")); Image gm = frowny.getImage(); Image newFrowny = gm.getScaledInstance(100, 100, java.awt.Image.SCALE_FAST); newIcon = new ImageIcon(newFrowny); // If boolean is true, throw exception if(incorrect) { try{Double.parseDouble(input); incorrect = false;} catch(NumberFormatException nfe) { String s = "Invalid Input " + "/n Input Must Be a Numerical value." + "/nPlease Press Ok and Try Again"; JOptionPane.showMessageDialog(null, s, "Invalid", JOptionPane.ERROR_MESSAGE, newIcon); inputTF.setText(""); inputTF.requestFocus(); } } // If boolean is not true, proceed with output if (incorrect != true) { /* Set each text field's output to the String double value * of inputTF */ sinTF.setText(input); cosTF.setText(input); tanTF.setText(input); cscTF.setText(input); secTF.setText(input); cotTF.setText(input); } } } /** * Private inner class that handles the event when * the user clicks the Exit button. */ private class ClearButtonListener implements ActionListener { public void actionPerformed(ActionEvent ae) { // Clear field sinTF.setText(""); cosTF.setText(""); tanTF.setText(""); cscTF.setText(""); secTF.setText(""); cotTF.setText(""); // Clear textfield and set cursor focus to field inputTF.setText(""); inputTF.requestFocus(); } } }

    Read the article

  • How to put .com at the end of email addressed by regex?

    - by terces907
    Example I received a email-list from my friends but the problem is some people typed an email in full form ([email protected]) and some people typed (xxx@xxx without .com). And i want to improve it into the same format. How can i improve it if i want to edit them on vi? In my emaillist.txt foo@gmail [email protected] bas@gmail [email protected] mike@abc john@email My try: i tried to use an easy regex like this to catch the pattern like xxx@xxx :%s/\(\w*@\w*\)/\0.com/g and :%s/\(\w*@\w*[^.com]\)/\0.com/g But the problem is this regex include [email protected] also And the result become like this after i enter the command above [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] So, My expectation after substitution is should be like this: [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] How to use regex in this situation?

    Read the article

  • Header Guard Issues - Getting Swallowed Alive

    - by gjnave
    I'm totally at wit's end: I can't figure out how my dependency issues. I've read countless posts and blogs and reworked my code so many times that I can't even remember what almost worked and what didnt. I continually get not only redefinition errors, but class not defined errors. I rework the header guards and remove some errors simply to find others. I somehow got everything down to one error but then even that got broke while trying to fix it. Would you please help me figure out the problem? card.cpp #include <iostream> #include <cctype> #include "card.h" using namespace std; // ====DECL====== Card::Card() { abilities = 0; flavorText = 0; keywords = 0; artifact = 0; classType = new char[strlen("Card") + 1]; classType = "Card"; } Card::~Card (){ delete name; delete abilities; delete flavorText; artifact = NULL; } // ------------ Card::Card(const Card & to_copy) { name = new char[strlen(to_copy.name) +1]; // creating dynamic array strcpy(to_copy.name, name); type = to_copy.type; color = to_copy.color; manaCost = to_copy.manaCost; abilities = new char[strlen(to_copy.abilities) +1]; strcpy(abilities, to_copy.abilities); flavorText = new char[strlen(to_copy.flavorText) +1]; strcpy(flavorText, to_copy.flavorText); keywords = new char[strlen(to_copy.keywords) +1]; strcpy(keywords, to_copy.keywords); inPlay = to_copy.inPlay; tapped = to_copy.tapped; enchanted = to_copy.enchanted; cursed = to_copy.cursed; if (to_copy.type != ARTIFACT) artifact = to_copy.artifact; } // ====DECL===== int Card::equipArtifact(Artifact* to_equip){ artifact = to_equip; } Artifact * Card::unequipArtifact(Card * unequip_from){ Artifact * to_remove = artifact; artifact = NULL; return to_remove; // put card in hand or in graveyard } int Card::enchant( Card * to_enchant){ to_enchant->enchanted = true; cout << "enchanted" << endl; } int Card::disenchant( Card * to_disenchant){ to_disenchant->enchanted = false; cout << "Enchantment Removed" << endl; } // ========DECL===== Spell::Spell() { currPower = basePower; currToughness = baseToughness; classType = new char[strlen("Spell") + 1]; classType = "Spell"; } Spell::~Spell(){} // --------------- Spell::Spell(const Spell & to_copy){ currPower = to_copy.currPower; basePower = to_copy.basePower; currToughness = to_copy.currToughness; baseToughness = to_copy.baseToughness; } // ========= int Spell::attack( Spell *& blocker ){ blocker->currToughness -= currPower; currToughness -= blocker->currToughness; } //========== int Spell::counter (Spell *& to_counter){ cout << to_counter->name << " was countered by " << name << endl; } // ============ int Spell::heal (Spell *& to_heal, int amountOfHealth){ to_heal->currToughness += amountOfHealth; } // ------- Creature::Creature(){ summoningSick = true; } // =====DECL====== Land::Land(){ color = NON; classType = new char[strlen("Land") + 1]; classType = "Land"; } // ------ int Land::generateMana(int mana){ // ... // } card.h #ifndef CARD_H #define CARD_H #include <cctype> #include <iostream> #include "conception.h" class Artifact; class Spell; class Card : public Conception { public: Card(); Card(const Card &); ~Card(); protected: char* name; enum CardType { INSTANT, CREATURE, LAND, ENCHANTMENT, ARTIFACT, PLANESWALKER}; enum CardColor { WHITE, BLUE, BLACK, RED, GREEN, NON }; CardType type; CardColor color; int manaCost; char* abilities; char* flavorText; char* keywords; bool inPlay; bool tapped; bool cursed; bool enchanted; Artifact* artifact; virtual int enchant( Card * ); virtual int disenchant (Card * ); virtual int equipArtifact( Artifact* ); virtual Artifact* unequipArtifact(Card * ); }; // ------------ class Spell: public Card { public: Spell(); ~Spell(); Spell(const Spell &); protected: virtual int heal( Spell *&, int ); virtual int attack( Spell *& ); virtual int counter( Spell*& ); int currToughness; int baseToughness; int currPower; int basePower; }; class Land: public Card { public: Land(); ~Land(); protected: virtual int generateMana(int); }; class Forest: public Land { public: Forest(); ~Forest(); protected: int generateMana(); }; class Creature: public Spell { public: Creature(); ~Creature(); protected: bool summoningSick; }; class Sorcery: public Spell { public: Sorcery(); ~Sorcery(); protected: }; #endif conception.h -- this is an "uber class" from which everything derives class Conception{ public: Conception(); ~Conception(); protected: char* classType; }; conception.cpp Conception::Conception{ Conception(){ classType = new char[11]; char = "Conception"; } game.cpp -- this is an incomplete class as of this code #include <iostream> #include <cctype> #include "game.h" #include "player.h" Battlefield::Battlefield(){ card = 0; } Battlefield::~Battlefield(){ delete card; } Battlefield::Battlefield(const Battlefield & to_copy){ } // =========== /* class Game(){ public: Game(); ~Game(); protected: Player** player; // for multiple players Battlefield* root; // for battlefield getPlayerMove(); // ask player what to do addToBattlefield(); removeFromBattlefield(); sendAttack(); } */ #endif game.h #ifndef GAME_H #define GAME_H #include "list.h" class CardList(); class Battlefield : CardList{ public: Battlefield(); ~Battlefield(); protected: Card* card; // make an array }; class Game : Conception{ public: Game(); ~Game(); protected: Player** player; // for multiple players Battlefield* root; // for battlefield getPlayerMove(); // ask player what to do addToBattlefield(); removeFromBattlefield(); sendAttack(); Battlefield* field; }; list.cpp #include <iostream> #include <cctype> #include "list.h" // ========== LinkedList::LinkedList(){ root = new Node; classType = new char[strlen("LinkedList") + 1]; classType = "LinkedList"; }; LinkedList::~LinkedList(){ delete root; } LinkedList::LinkedList(const LinkedList & obj) { // code to copy } // --------- // ========= int LinkedList::delete_all(Node* root){ if (root = 0) return 0; delete_all(root->next); root = 0; } int LinkedList::add( Conception*& is){ if (root == 0){ root = new Node; root->next = 0; } else { Node * curr = root; root = new Node; root->next=curr; root->it = is; } } int LinkedList::remove(Node * root, Node * prev, Conception* is){ if (root = 0) return -1; if (root->it == is){ root->next = root->next; return 0; } remove(root->next, root, is); return 0; } Conception* LinkedList::find(Node*& root, const Conception* is, Conception* holder = NULL) { if (root==0) return NULL; if (root->it == is){ return root-> it; } holder = find(root->next, is); return holder; } Node* LinkedList::goForward(Node * root){ if (root==0) return root; if (root->next == 0) return root; else return root->next; } // ============ Node* LinkedList::goBackward(Node * root){ root = root->prev; } list.h #ifndef LIST_H #define LIST_H #include <iostream> #include "conception.h" class Node : public Conception { public: Node() : next(0), prev(0), it(0) { it = 0; classType = new char[strlen("Node") + 1]; classType = "Node"; }; ~Node(){ delete it; delete next; delete prev; } Node* next; Node* prev; Conception* it; // generic object }; // ---------------------- class LinkedList : public Conception { public: LinkedList(); ~LinkedList(); LinkedList(const LinkedList&); friend bool operator== (Conception& thing_1, Conception& thing_2 ); protected: virtual int delete_all(Node*); virtual int add( Conception*& ); // virtual Conception* find(Node *&, const Conception*, Conception* ); // virtual int remove( Node *, Node *, Conception* ); // removes question with keyword int display_all(node*& ); virtual Node* goForward(Node *); virtual Node* goBackward(Node *); Node* root; // write copy constrcutor }; // ============= class CircularLinkedList : public LinkedList { public: // CircularLinkedList(); // ~CircularLinkedList(); // CircularLinkedList(const CircularLinkedList &); }; class DoubleLinkedList : public LinkedList { public: // DoubleLinkedList(); // ~DoubleLinkedList(); // DoubleLinkedList(const DoubleLinkedList &); protected: }; // END OF LIST Hierarchy #endif player.cpp #include <iostream> #include "player.h" #include "list.h" using namespace std; Library::Library(){ root = 0; } Library::~Library(){ delete card; } // ====DECL========= Player::~Player(){ delete fname; delete lname; delete deck; } Wizard::~Wizard(){ delete mana; delete rootL; delete rootH; } // =====Player====== void Player::changeName(const char[] first, const char[] last){ char* backup1 = new char[strlen(fname) + 1]; strcpy(backup1, fname); char* backup2 = new char[strlen(lname) + 1]; strcpy(backup1, lname); if (first != NULL){ fname = new char[strlen(first) +1]; strcpy(fname, first); } if (last != NULL){ lname = new char[strlen(last) +1]; strcpy(lname, last); } return 0; } // ========== void Player::seeStats(Stats*& to_put){ to_put->wins = stats->wins; to_put->losses = stats->losses; to_put->winRatio = stats->winRatio; } // ---------- void Player::displayDeck(const LinkedList* deck){ } // ================ void CardList::findCard(Node* root, int id, NodeCard*& is){ if (root == NULL) return; if (root->it.id == id){ copyCard(root->it, is); return; } else findCard(root->next, id, is); } // -------- void CardList::deleteAll(Node* root){ if (root == NULL) return; deleteAll(root->next); root->next = NULL; } // --------- void CardList::removeCard(Node* root, int id){ if (root == NULL) return; if (root->id = id){ root->prev->next = root->next; // the prev link of root, looks back to next of prev node, and sets to where root next is pointing } return; } // --------- void CardList::addCard(Card* to_add){ if (!root){ root = new Node; root->next = NULL; root->prev = NULL; root->it = &to_add; return; } else { Node* original = root; root = new Node; root->next = original; root->prev = NULL; original->prev = root; } } // ----------- void CardList::displayAll(Node*& root){ if (root == NULL) return; cout << "Card Name: " << root->it.cardName; cout << " || Type: " << root->it.type << endl; cout << " --------------- " << endl; if (root->classType == "Spell"){ cout << "Base Power: " << root->it.basePower; cout << " || Current Power: " << root->it.currPower << endl; cout << "Base Toughness: " << root->it.baseToughness; cout << " || Current Toughness: " << root->it.currToughness << endl; } cout << "Card Type: " << root->it.currPower; cout << " || Card Color: " << root->it.color << endl; cout << "Mana Cost" << root->it.manaCost << endl; cout << "Keywords: " << root->it.keywords << endl; cout << "Flavor Text: " << root->it.flavorText << endl; cout << " ----- Class Type: " << root->it.classType << " || ID: " << root->it.id << " ----- " << endl; cout << " ******************************************" << endl; cout << endl; // ------- void CardList::copyCard(const Card& to_get, Card& put_to){ put_to.type = to_get.type; put_to.color = to_get.color; put_to.manaCost = to_get.manaCost; put_to.inPlay = to_get.inPlay; put_to.tapped = to_get.tapped; put_to.class = to_get.class; put_to.id = to_get.id; put_to.enchanted = to_get.enchanted; put_to.artifact = to_get.artifact; put_to.class = to_get.class; put.to.abilities = new char[strlen(to_get.abilities) +1]; strcpy(put_to.abilities, to_get.abilities); put.to.keywords = new char[strlen(to_get.keywords) +1]; strcpy(put_to.keywords, to_get.keywords); put.to.flavorText = new char[strlen(to_get.flavorText) +1]; strcpy(put_to.flavorText, to_get.flavorText); if (to_get.class = "Spell"){ put_to.baseToughness = to_get.baseToughness; put_to.basePower = to_get.basePower; put_to.currToughness = to_get.currToughness; put_to.currPower = to_get.currPower; } } // ---------- player.h #ifndef player.h #define player.h #include "list.h" // ============ class CardList() : public LinkedList(){ public: CardList(); ~CardList(); protected: virtual void findCard(Card&); virtual void addCard(Card* ); virtual void removeCard(Node* root, int id); virtual void deleteAll(); virtual void displayAll(); virtual void copyCard(const Conception*, Node*&); Node* root; } // --------- class Library() : public CardList(){ public: Library(); ~Library(); protected: Card* card; int numCards; findCard(Card&); // get Card and fill empty template } // ----------- class Deck() : public CardList(){ public: Deck(); ~Deck(); protected: enum deckColor { WHITE, BLUE, BLACK, RED, GREEN, MIXED }; char* deckName; } // =============== class Mana(int amount) : public Conception { public: Mana() : displayTotal(0), classType(0) { displayTotal = 0; classType = new char[strlen("Mana") + 1]; classType = "Mana"; }; protected: int accrued; void add(); void remove(); int displayTotal(); } inline Mana::add(){ accrued += 1; } inline Mana::remove(){ accrued -= 1; } inline Mana::displayTotal(){ return accrued; } // ================ class Stats() : public Conception { public: friend class Player; friend class Game; Stats() : wins(0), losses(0), winRatio(0) { wins = 0; losses = 0; if ( (wins + losses != 0) winRatio = wins / (wins + losses); else winRatio = 0; classType = new char[strlen("Stats") + 1]; classType = "Stats"; } protected: int wins; int losses; float winRatio; void int getStats(Stats*& ); } // ================== class Player() : public Conception{ public: Player() : wins(0), losses(0), winRatio(0) { fname = NULL; lname = NULL; stats = NULL; CardList = NULL; classType = new char[strlen("Player") + 1]; classType = "Player"; }; ~Player(); Player(const Player & obj); protected: // member variables char* fname; char* lname; Stats stats; // holds previous game statistics CardList* deck[]; // hold multiple decks that player might use - put ll in this private: // member functions void changeName(const char[], const char[]); void shuffleDeck(int); void seeStats(Stats*& ); void displayDeck(int); chooseDeck(); } // -------------------- class Wizard(Card) : public Player(){ public: Wizard() : { mana = NULL; rootL = NULL; rootH = NULL}; ~Wizard(); protected: playCard(const Card &); removeCard(Card &); attackWithCard(Card &); enchantWithCard(Card &); disenchantWithCard(Card &); healWithCard(Card &); equipWithCard(Card &); Mana* mana[]; Library* rootL; // Library Library* rootH; // Hand } #endif

    Read the article

  • Apply [ThreadStatic] attribute to a method in external assembly

    - by Sen Jacob
    Can I use an external assembly's static method like [ThreadStatic] method? Here is my situation. The assembly class (which I do not have access to its source) has this structure public class RegistrationManager() { private RegistrationManager() {} public static void RegisterConfiguration(int ID) {} public static object DoWork() {} public static void UnregisterConfiguration(int ID) {} } Once registered, I cannot call the DoWork() with a different ID without unregistering the previously registered one. Actually I want to call the DoWork() method with different IDs simultaneously with multi-threading. If the RegisterConfiguration(int ID) method was [ThreadStatic], I could have call it in different threads without problems with calls, right? So, can I apply the [ThreadStatic] attribute to this method or is there any other way I can call the two static methods same time without waiting for other thread to unregister it? If I check it like the following, it should work. for(int i=0; i < 10; i++) { new Thread(new ThreadStart(() => Checker(i))).Start(); } public string Checker(int i) { public static void RegisterConfiguration(i); // Now i cannot register second time public static object DoWork(i); Thread.Sleep(5000); // DoWork() may take a little while to complete before unregistered public static void UnregisterConfiguration(i); }

    Read the article

  • How to Refresh combobox in Visual Basic

    - by phenomenon09
    When a button is clicked, it populates a combo box with all the databases you have created. Another button creates a new database. How do I refresh my combobox to add the newly added database? Here's how I populate my combo box at the start: rs.Open "show databases", conn While Not rs.EOF If rs!Database <> "information_schema" Then Combo1.AddItem rs!Database End If rs.MoveNext Wend cmdOK.Enabled = False cmdCancel.Enabled = False frmLogin.Height = 3300 rs.Close

    Read the article

  • I can't delete record in Codeigniter

    - by jomblo
    I'm learning CRUD in codeigniter. I have table name "posting" and the coloumns are like this (id, title, post). I successed to create a new post (both insert into database and display in the view). But I have problem when I delete my post in the front-end. Here is my code: Model Class Post_Model extends CI_Model{ function index(){ //Here is my homepage code } function delete_post($id) { $this->db->where('id', $id); $this->db->delete('posting'); } } Controller Class Post extends CI_Controller{ function delete() { $this->load->model('Post_Model'); $this->Post_Model->delete_post("id"); redirect('Post/index/', 'refresh'); } } After click "delete" in the homepage, there was nothing happens. While I'm looking into my database, my records still available. Note: (1) to delete record, I'm following the codeigniter manual / user guide, (2) I found a message error (Undefined variable: id) after hiting the "delete" button in the front-end Any help or suggestion, please

    Read the article

  • Why changing the images name on server results in calling the old ones?

    - by moderns
    I am running a slideshow on Ubuntu 12.04.1 that loads the images (slide1.jpg, slide2.jpg, slide3.jpg.., slide5.jpg) using the Javascript and styles as below: document.getElementById('slide_area').className='slide'+step; .slide1{background-image: url(../upload/slide1.jpg)} .slide2{background-image: url(../upload/slide2.jpg)} .slide3{background-image: url(../upload/slide3.jpg)} .slide4{background-image: url(../upload/slide4.jpg)} .slide5{background-image: url(../upload/slide5.jpg)} When I change the images names (show1.jpg, show2.jpg, show3.jpg.., show5.jpg) and also change the style as below: .slide1{background-image: url(../upload/show1.jpg)} .slide2{background-image: url(../upload/show2.jpg)} .slide3{background-image: url(../upload/show3.jpg)} .slide4{background-image: url(../upload/show4.jpg)} .slide5{background-image: url(../upload/show5.jpg)} And open the network section on Chrome, I see the server is calling the new name and old name for images! I added the header in the index.php: header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); Nothing worked out with me and the slideshow doesn't work properly when I change the name of images even when clearing the browser cache as I load images sequentially (one by one) depending on imageObject.complete property! But without changing the name everything is going perfect and the images are loaded smoothly! Thank you for your help!

    Read the article

  • Which are the most important media queries to use in creating mobile responsive design?

    - by Matt
    There are a lot different media queries for mobile screen sizes. It can be overwhelming to accomodate all of them when designing a responsive mobile site. Which are the most important ones to use when designing for mobile? I found this article that does a pretty good job of outlining the available media queries: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/. /* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /* Styles */ } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) { /* Styles */ } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { /* Styles */ } /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { /* Styles */ } /* iPads (landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) { /* Styles */ } /* iPads (portrait) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) { /* Styles */ } /* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) { /* Styles */ } /* Large screens ----------- */ @media only screen and (min-width : 1824px) { /* Styles */ } /* iPhone 4 ----------- */ @media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) { /* Styles */ }

    Read the article

  • PHP SDK Requires two logins...doesn't recognize first

    - by Jay Konieczny
    I am using the following code to authenticate whether users are logged in or not. While users can log in, they have to click the login button twice. Additionally, sometimes even after they click the log-in button twice, my "user info" part of the page (earlier in the page than the content) shows them as logged out while the actual page shows them as logged in. Here is the code. Could someone suggest a better way of handling log-ins? function isLoggedIn($facebook) { if (isset($facebook) and $facebook->getUser() != 0) { // UserID exists, but user may still not be logged in. Let's check: try { $facebook->api('/me', 'GET'); // If this succeeds, then they are logged in. return true; } catch(FacebookApiException $e) { // Some kind of error, so not logged in. if(session_id() === '') session_destroy(); return false; } } else { if(session_id() === '') session_destroy(); return false; } } Thanks!

    Read the article

  • Learn to Take a Punch, Learn to Counter, Keep Moving Forward

    - by D'Arcy Lussier
    Originally posted on: http://geekswithblogs.net/dlussier/archive/2013/10/28/154483.aspxDuring a boxing workout a few months ago our trainer had us do something called “breadbaskets”. That’s where you hold your arms up and a partner punches you in your midsection – your breadbasket. I put my arms up, and braced for impact. The trainer came over, saw I was a bit nervous, and coached me through. I can see the fear in your eyes. Don’t be afraid to take the punch. Tighten your core, breathe through the hit. Don’t panic. Over the summer we’d do counter drills as well. This is where a partner throws a punch, you defend but also throw one back – a counter punch. You never just sit back and take a beating, you deflect the blow and come back with one more powerful. These lessons on fighting can apply to all aspects of our lives and any attempts at success that we have. I saw this image recently and agree with it 100%: Success is never a straight forward line. It’s messy, its wrought with failures, its learning over time and applying those life lessons. It’s learning how to take punches and lose your fear, its seeing a punch coming and countering it, but most of all its not giving up and continually moving forward. We do stairs at boxing, which is running up and down three flights of stairs. I’m not anywhere near incredible shape and after doing multiple stairs in a single workout you can feel gassed, tired, even discouraged after hitting the second floor and seeing everyone else running by you. I read a quote from Martin Luther King Jr. that I cling to throughout my day: You want to be successful? Take the punches, but learn how to take them. Counter them. and no matter what, always move forward.

    Read the article

  • How do you setup FTP with IIS Manager Users in an NLB environment with shared IIS configs?

    - by William Jens
    I've setup a 2 node NLB cluster and used the following to share IIS configs between them. http://blogs.technet.com/b/meamcs/archive/2012/05/30/configuring-iis-7-5-shared-configuration.aspx The IIS configs and content is located on a network share via a UNC path. This works - updating IIS settings on one node, is visible in another node and my website works on the individual nodes and the cluster as whole. I'm able to setup an FTP site and successfully connect with my Windows login. However, I want to use IIS Manager Authentication as defined in: http://www.iis.net/learn/publish/using-the-ftp-service/configure-ftp-with-iis-manager-authentication-in-iis-7 I've tried using "Network Service" with the FTP COM object as well as a dedicated user account that exists on all three hosts, but every time I try to login with an IIS user I get something like the following: IISWMSVC_AUTHENTICATION_UNABLE_TO_READ_CONFIG An unexpected error occurred while retrieving the authentication information. Exception:System.Runtime.InteropServices.COMException (0x8007052E): Filename: Error: at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath) at Microsoft.Web.Administration.Configuration.GetSectionInternal(ConfigurationSection section, String sectionPath, String locationPath) at Microsoft.Web.Management.Server.ConfigurationAuthenticationProvider.GetSection(ServerManager serverManager) Process:dllhost User=NT AUTHORITY\NETWORK SERVICE Can anyone point me in the right direction here?

    Read the article

  • ssh accepts any password

    - by nodapic
    I'm recovering a server from getting hacked and there is one thing I can't fix: When I ssh (or scp) to the server, no matter what password I give, it lets me log in. I don't know much about the ssh protocol but I'm pretty sure it's not supposed to do that. I've checked in the sshd_config file and the only changes are the ones that I've made (as far as I can remember). Another thought that I had was that there might be something screwed up in the /etc/passwd file that I'm missing. Has anyone seen this?

    Read the article

  • Apache DirectorySlash ignores X-Forwarded-Proto header

    - by Sharique Abdullah
    It seems that Apache's DirectorySlash directive is causing issues when using it behind Amazon ELB on HTTPS protocol. So say I access a URL: https://myserver.com/svn/MyProject it would redirect me to: http://myserver.com/svn/MyProject/ My ELB configuration forwards port 443 to port 80 on Apache, but Apache should be aware of the X-Forwarded-Porto header in the request and thus keep the protocol as https in the redirect URL too. Any thoughts?

    Read the article

  • What happens when the USB key or SD card I've installed VMware ESXi on fails?

    - by ewwhite
    An SD (SDHC) card installed in an HP ProLiant DL380p Gen8 server running VMware ESXi just failed. I encountered some rather ominous looking messages on the vCenter console and in the HP ProLiant ILO event log... Lost connectivity to the device ... backing the boot filesystem. As a result, host configuration changes will not be saved to persistent storage. Embedded Flash/SD-CARD: Error writing media 0, physical block 848880: Stack Exception. VMware advocates the use of USB and SD (SDHC) boot devices for ESXi. It was one of the main reasons the smaller footprint ESXi was developed (versus the older ESX). I've spent much time highlighting the differences between ESXi's installable and embedded modes to coworkers and clients. However, these failures do seem to happen. In this case, this is my third instance. Luckily, this is a vSphere cluster with SAN storage. What steps should be taken to remediate this failure?

    Read the article

  • Apply rewrite rule for all but all the files (recursive) in a subdirectory?

    - by user784637
    I have an .htaccess file in the root of the website that looks like this RewriteRule ^some-blog-post-title/ http://website/read/flowers/a-new-title-for-this-post/ [R=301,L] RewriteRule ^some-blog-post-title2/ http://website/read/flowers/a-new-title-for-this-post2/ [R=301,L] <IfModule mod_rewrite.c> RewriteEngine On ## Redirects for all pages except for files in wp-content to website/read RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !/wp-content RewriteRule ^(.*)$ http://website/read/$1 [L,QSA] #RewriteRule ^http://website/read [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> My intent is to redirect people to the new blog post location if they propose one of those special blog posts. If that's not the case then they should be redirected to http://website.com/read. Nothing from http://website.com/wp-content/* should be redirected. So far conditions 1 and 3 are being met. How can I meet condition 2?

    Read the article

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