mardi 31 janvier 2017

C++ Array of an object (created) inside another Class

I have two classes inside a header file, the 2nd class dependent on the 1st. Including this header file in a .cpp file where I implement the constructor prototype for the Flight class. Compiling gives me the following error:

Error: no matching function for call to ‘Passenger::Passenger()’
      Flight::Flight(int maxPassenger, int flightNo) {

Here's the two classes in my header file

/*
 *Passenger Class:
 */
class Passenger
{
 public:
  int flightNo;
  string lastName;
  string firstName;
  int seatNo;
 public:
  Passenger(int flightNo, string lastName,string firstName,  int seatNo); 
};
/*
 *Flight Class:
 */
class Flight {
 public:
  int maxPassenger;
  int currentPos;
  int flightNo;
  Passenger list[20];
 public:
  Flight (int maxPassenger, int flightNo);
}

And Here's the constructor implementation:

Flight::Flight(int maxPassenger, int flightNo) {
  maxPassenger = maxPassenger;
  //  list = new Passenger [maxPassenger];
  flightNo = flightNo;
}

I can understand that there is a conflict in the constructors. But I can't figure out exactly what's wrong. Any help would be very appreciated.




ES6... this is a huge reach out. JavaScript ES2015 trying to understand Class, inheritance, encapsulation, & polymorphism

I'm having a hard time understanding (Barney Style) what's being asked... I am slightly familiar with C# so it kind of makes sense but I have not been properly introduced to ES6 yet this assignment has been given to me... I am playing catch up but also looking to see a solid example on how these instruction coincide with real code.

(not sure what to expect, and sorry if some people are offended, just looking to the best help on the web right now).

CHALLENGE:

*3 Class files minimum

Show one level of inheritance with polymorphism (Method override) Make sure the Abstract class is NOT instantiated

Composition and/or aggregation is used. The 'owner' object has at least one object

A looping process is used to create instances of at least one of your objects

Store all references of the objects in a Data Structure (array / list)

All classes must make sense and serve a purpose to the scenario that you choose

All instantiated classes must have 2 instance / members variables and one method other than the constructor. Make sure the values for at least one of the instance variables value is unique to each instance

After all objects are instantiated, call a function named displayInfo() that will display all the objects and their instances variables and a static variable in the console.

Effectively utilize random number(s)

The output may look something like this: (remember, the code that generates the output is in the displayInfo() function)*




How to access self of class instance from a function assigned to a method?

I assigned a custom function to a class method, however I can't seem to access self from within it.

class Handler():
    def __init__(self):
        self.func = None
        self.name = "Fourty Two"

    def run(self):
        if self.func: self.func()


def custom_func(self): # error: missing required argument: self
    print(self.name)

handler = Handler()
handler.func = custom_func
handler.run()

Is this sort of thing possible? How can it be done?




C++ error "was not declared in this scope" classes

I keep getting an error that a variable that I declared in a .h file isn't declared in the scope in the .cpp file.

Robot.h:

#pragma once
#include "Fighter.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Robot: public Fighter {
public:    
    Robot(string robotname, int robothitpoints, int robotstreangth, int robotspeed, int robotmagic):Fighter(robotname, robothitpoints, robotstreangth, robotspeed, robotmagic) {
        maximum_energy = 2*magic; current_energy = 2*magic; bonus_damage = 0;
    }
    ~Robot(){};

    //Class functions here

protected: 
    int current_energy;
    int maximum_energy;
    int bonus_damage;
};

Robot.cpp:

#include "Robot.h"

    int Robot::getDamage() {
        return strength;
    }

    void Robot::reset() {
        hit_points = maximumHP;
        current_energy = magic*2;
        bonus_damage = 0;
    }

    void Robot::regenerate() {
        int hit_points_to_add = hit_points + (strength/6);

        if (hit_points_to_add <= 1) {
            if((hit_points + 1) >= maximumHP) {
                hit_points = maximumHP;
            }
            else {
                hit_points = hit_points + 1;
            }

        }
        else {
            if((hit_points + hit_points_to_add) >= maximumHP) {
                hit_points = maximumHP;
            }
            else {
                hit_points = hit_points + hit_points_to_add;
            }
        }

    }

    bool Robot::useAbility() {
        if (current_energy >= ROBOT_ABILITY_COST) {
            double bonus_damage_calc = (strength  * ((current_energy/maximum_energy)^4));
            bonus_damage = bonus_damage_calc;
            return true;
        }
        else {
            return false;
        }
    }

The Robot.cpp file is giving me errors every time it uses a variable defined in the Robot.h file. The rest of the variables are declared in the Fighter.h file (the Robot class inherits from the Fighter class)




How to create new fragment based on Firebase Topic Message

I have a firebase messaging service, which has a method:

public void onMessageReceived(RemoteMessage message)

that is called when a message is sent to a particular topic. I want to create a fragment in an activity based on this message. How do I pass this information to the activity? I can't create a static method in the activity since the getSupportFragmentManager() method is non-static and must be called in order to create a fragment.




How do I increment to a certain limit that I can define?

I'm working on creating classes and methods and in one of them, I'm looking to increase one variable but not beyond the input of the other variable.

class Vehicle{
   let name: String
   let weight: Double
   let maxSpeed: Double
   var speed: Double = 0
   var heading: Double = 0

init(name: String, weight: Double, maxSpeed: Double) {
    self.name = name
    self.weight = weight
    self.maxSpeed = maxSpeed
}

func accelerate() {
    speed += maxSpeed/10
}

In the method, I'm incrementing the speed by 1/10th of the maxSpeed but I don't want speed in the accelerate method to exceed the maxSpeed (since that wouldn't make much sense). Is there any way to set a range on how high/low speed could go?




HTMLAgilityPack get class innerText

I am trying to get the innerText of a class. This is my code:

using (HttpClient clientduplicate = new HttpClient())
                            {
                                clientduplicate.DefaultRequestHeaders.Add("User-Agent",
                                                 "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");
                                using (HttpResponseMessage responseduplicate = await clientduplicate.GetAsync(@"http://ift.tt/2kOfDNJ")
                                using (HttpContent contentduplicate = responseduplicate.Content)
                                {
                                    try
                                    {
                                        string resultduplicate = await contentduplicate.ReadAsStringAsync();
                                        var websiteduplicate = new HtmlDocument();
                                        websiteduplicate.LoadHtml(resultduplicate);
                                        var titlesduplicate = websiteduplicate.DocumentNode.Descendants("div").FirstOrDefault(o => o.GetAttributeValue("class", "") == "arial_14 clear WYSIWYG newsPage");
                                        var match = Regex.Match(titlesduplicate.InnerText, @"(.*?)<!--", RegexOptions.Singleline).Groups[1].Value;
                                        Debug.WriteLine(match.TrimStart());
                                    }
                                    catch(Exception ex1)
                                    {
                                        var dialog2 = new MessageDialog(ex1.Message);
                                        await dialog2.ShowAsync();
                                    }
                                }
                            }

Now the problem is that this will also return me the text on the picture. I can find a workaround but I was wondering if there is an other approach on this. Something simpler/faster.

Plus when I use this on other articles/URLs there are other minor bugs.




C# Hashtable in Class / Print to console

So I've been working on trying to figure out how to do this for awhile now and thought I'd try here. I have an object class "Character" with a hashtable inside of it for weapons. I'm just trying to print the weapon to the console when I print the character stats for approval, but having a hard time figuring out a simple way to do this.

Advs is the Character object array, if there's any information I forgot to include please let me know, first time posting. The i.weapons.value is what I'm trying to fix, everything else prints to console correctly, that gives me strange values that look like pointers to the hashtable on print. Thanks ahead of time.

    private static void ChStats(Character[] Advs) {
        foreach (Character i in Advs) {
            Console.WriteLine("Name: {0}\nClass: {1}\nLevel: {2}\nHealth: {3}\nStrength: {4}\nIntellect: {5}\nAgility: {6}\nSanity: {7}\nWeapon: {8}\n", 
                i.name, i.characterClass, i.lvl, i.hlth, i.str, i.itl, i.agi, i.san, i.weapons.value);
        }




Using white space in a char array in a class

so I realize this is technically a duplicate question, so I apologize for that, however my code is acting strange and I'm at a loss. I am not a programmer, I'm not even taking classes, but someone asked me for some help on an assignment and I was going back through old programs I wrote for classes and decided to play around and see if I could make them more efficient. So, here are the code snippets that I am having errors with, I would post the entire code but it's long and 98% of it is not relevant to my question anyways...

class Exam {    
//properties
private:
char m_fileName[50];
public:
//Default Constructor
Exam() {
    m_fileName;
}

//functions
void setFile(){
    cout << "Enter the name of the Exam: ";
    cin >> m_fileName;
        for(unsigned int l = 0; l < 50; l++)
             {
                      m_fileName[l] = toupper(m_fileName[l]);
             }

}

char* getFile(){
    return m_fileName;
}

};

In main I create an array of Exam objects called testFile[50]. It goes to a menu with a switch statement, blah blah. When I choose to create a new test file, it goes to the following code:

        case 3: {
        testFile[f].setFile();
        cin.ignore();
        cout << endl << "Enter the amount of questions, Max. of 50: ";
        cin >> numQuestions;
        if (numQuestions > 50) {
            throw -1;
        }

ofstream write(testFile[f].getFile());

So, here is the issue I can't seem to solve. I'd like to be able to type test files such as "Test A" or "Test B" or whatever, and have the char array (m_fileName) read in the white space. I know, to typically do that, you need to use getline or some other form, because "cin" stops reading when it hits white space. Well, literally any other form of input other than how it is, throws:

3 [main] chrisjohnson_ip3 9684 cygwin_exception::open_stackdumpfile: Dumping stack trace to chrisjohnson_ip3.exe.stackdump

directly after "Enter the name of the Exam: " and other times it will throw it when it asks to enter the amount of questions (without letting me input anything). I'm sure it's something really stupid that I'm missing, but I've been trying to figure this out for hours, so I figured I would call in the big guns. If you need me to post any more of the code or be more specific on something, please let me know. Thank you for your time and knowledge :)




how to prevent compiler optimization (in a virtual function)

In the following code, the variables lastX, lastY in function virtual void updateMousePosition(double time) and the variable lastFrameTime in the function virtual void updateKeyboard(double time) are optimized by the compliler.

Note: all the above-mentioned variables are member variables.

the statements this->lastFrameTime = time; in virtual void updateKeyboard(double time) and this->lastX = static_cast<GLfloat>(this->xpos); this->lastY = static_cast<GLfloat>(this->ypos); in virtual void updateKeyboard(double time) are not being called.

How to rectify this? I don't want the compiler to "optimise" this part of the code. I've already tried adding the __attribute__((optimize("O0"))) to the function and still, it's the same.

CODE

class CameraController
{
  public:
    Camera *camera;

    double xpos{0}, ypos{0}, lastFrameTime{0}, deltaTime{0};
    volatile GLfloat lastX{0}, lastY{0}, xoffset{0}, yoffset{0};

    CameraController(
        Camera *camera = nullptr,
        mylib::Window *window = nullptr) : camera(std::move(camera)),
                                           window(window)
    {
        std::cout << "construct" << std::endl;
        if (window != nullptr)
        {
            // for keyboard
            lastFrameTime = glfwGetTime();

            // for mouse
            glfwSetInputMode(window->getWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
            glfwSetCursorPos(window->getWindow(), window->width, window->height);
            glfwGetCursorPos(window->getWindow(), &xpos, &ypos);
            lastX = static_cast<GLfloat>(xpos);
            lastY = static_cast<GLfloat>(ypos);
        }
    }

    static void update(CameraController cc, double time)
    {
        cc.updateKeyboard(time);
        cc.updateMousePosition(time);
    }

    virtual void updateKeyboard(double time)
    {
        if (window != nullptr)
        {
            this->deltaTime = time - lastFrameTime;
            std::clog << "delta: " << deltaTime << "\tLFT: " << lastFrameTime
                      << std::endl;
            this->lastFrameTime = time;

            // W - key press
            if (glfwGetKey(window->getWindow(), GLFW_KEY_W) == GLFW_PRESS)
            {
                camera->processKeyboard(mylib::FORWARD, deltaTime);
            }
            // S - key press
            if (glfwGetKey(window->getWindow(), GLFW_KEY_S) == GLFW_PRESS)
            {
                camera->processKeyboard(mylib::BACKWARD, deltaTime);
            }
            // A - key press
            if (glfwGetKey(window->getWindow(), GLFW_KEY_A) == GLFW_PRESS)
            {
                camera->processKeyboard(mylib::LEFT, deltaTime);
            }
            // D - key press
            if (glfwGetKey(window->getWindow(), GLFW_KEY_D) == GLFW_PRESS)
            {
                camera->processKeyboard(mylib::RIGHT, deltaTime);
            }
        }
    }

    virtual void updateMousePosition(double time)
    {
        if (window != nullptr)
        {
            std::cout << "BEFORE\t\t" << this->xoffset << ", " << this->yoffset
                      << "\tlast: (" << this->lastX << ", " << this->lastY << ")"
                      << "\tpos: (" << this->xpos << ", " << this->ypos << ")" <<     std::endl;
            glfwGetCursorPos(window->getWindow(), &this->xpos, &this->ypos);
            this->xoffset = static_cast<GLfloat>(this->xpos - this->lastX);
            // reversed y cord, botton to top
            this->yoffset = static_cast<GLfloat>(this->lastY - this->ypos);

            std::cout << this->xoffset << ", " << this->yoffset
                      << "\tlast: (" << this->lastX << ", " << this->lastY << ")"
                      << "\tpos: (" << this->xpos << ", " << this->ypos << ")" <<     std::endl;
            this->lastX = static_cast<GLfloat>(this->xpos);
            this->lastY = static_cast<GLfloat>(this->ypos);
            camera->processMouseMovement(this->xoffset, this->yoffset);
        }
    }

  protected:
    mylib::Window *window{nullptr};

  private:

};




RPG Game inventory system

Okay, so I've looked all over this site and a few others (but please let me know if there is a link to a similar question), and I get all the details of how an inventory system should work. My question is coming from a very broad, general perspective. And this is just for a console text RPG. How should I structure my classes for items? What I'm thinking/have so far is something like this:

    // Item.h

    class Item {
    public:
        int Id;
        std::string Name;
        bool CanUse, CanEquip;

        virtual void Use();
    }

    class Weapon: public Item {
    public:
        int Attack, Defense, Health; // stat changes when equipped
        void Use() { std::cout << "Can't use\n"; }

    }

    class Sword: public Weapon {
        // constructor defining stat changes for a sword
        // and to define Name = "Sword"
    }

So should I be inheriting that many times or is there something easier I could be doing? Eventually, I'll have other various kinds of weapons, but it seems to me that inheriting each of them from Weapon is much more cumbersome than some other way I could be doing it?

Perhaps I could have an enumeration or struct within Weapon that defines each type of weapon? If I do it like the code above, I would probably actually move the virtual void Use(); function into a class, class Consumables: public Item since those should be the only "usable" things.

Thanks in advance to anyone willing to help. I have taught myself everything I know with books and online tutorials, so I'm quite inexperienced :)




PHP: How can I get the value of each error from my array?

I'm trying to echo out a message that tells the user that they have put in some invalid data by grabbing the array and the associated value with it from the validation classes that I have created. So to put this into perspective a bit more, I have validation classes e.g. number validator, email validator, that will check to see if the user has put in the correct information in their form. Now inside the validator classes are functions which will check to see if the data is valid and will loop through the errors in a separate 'Validatorset' class. All I need to do is get the array values from the class and into the form page, but have no idea how. Any help is appreciated.

ValidatorSet Class - This class loops through the errors if there are any.

public function getErrors()
{
    $errors = array();
    foreach($this as $key=>$validator) {
        $validator->validate(); // Seperate built in validator function
        if($validator->hasError()) // Checks if there are errors 
            $errors[$key] = $validator->getError();
    }
    return $errors;
}

Example of one of my Validator Classes - Email Validator

class EmailValidator extends Validator {

public function validate()
{
    if($this->isValidatable()) {
        if(filter_var($this->value, FILTER_VALIDATE_EMAIL) === FALSE) {
            $this->errorMessage = 'Not a valid email address';
        }
        $this->validated = true;
    }
}
}

My Registration Form page - Example of how I am trying to echo out the errors $username is where I would like to echo out the array of arrays with the associated errror values with them.

if($_POST){ // Here I am just declaring the variable $email as a new validator class
    if(isset($_POST["submit"])){
        $email = new EmailValidator(strip_tags($_POST['email']), true);
    }


    <form method = "post">
    <fieldset>
        <legend>Enter your registration details</legend>

<label for="email">Email: </label>
        <div class = "error_display"> * <?php echo $emailErr ?> </div>
        <input type="email" required name="email" id="email" value = "<?php if(isset($errorMessage)){ echo @$_POST['email'];} ?>">




Java : arrays. Have a look at the following codeblock

class MemorySensor extends BasicSensor{
    private int memoryPositions;
    private double memory[];

    public MemorySensor(double value, int memoryPositions){
        super(value);
        this.memoryPositions = memoryPositions;
        memory = new double[memoryPositions];
        memory[0] = value;
    }

    public double[] getOldValues(){
        return memory;
    }

    public void setValue(double value){
        for(int i = memoryPositions -1 ; i >= 1;i--){
            memory[i] = memory[i-1];
        }
        memory[0] = value;
    }            

    void printAllValues(){
        System.out.print("(");
        for (int i=0; i < memoryPositions-1; i++){
            System.out.print(memory[i]+ ", ");
        }
        System.out.println(memory[memoryPositions-1]+ ")");       
    }
}

Can anyone shed some light on "memory = new double[memoryPositions];" in context to this code?




create a repeating array which consists of subclass objects

I have the following class:

open class A
{

open class subA
    {
        open var data : String = ""
    }

}

And I want to create an array of SubA using the repeating method. I tried the following:

var list : [A.SubA] = [A.SubA](repeating: A.SubA(), count: 5)

and that gives an error: Cannot call value of non-function type [A.SubA.Type]

but If I try the following, I have no issue:

var list : [A] = [A](repeating: A(), count: 5)




How i can make a selectable object in any Php class?

When i use the some php frameworks or libraries i can write code like this:

$avariable = new aClass();
$avariable->someFunction()->somevalue

(I want to create structure like this.)

I try create a class name Customer

class Customer {
  public function getCustomer($name,$email,$age){
    ...
    $customer = new \stdClass();
    $customer->description = 'Description';

    return $customer;
  }
}

And then try $customer= new Customer(); $customer->getCustomer('name','email','age')->description ;

Why my code is not work

$customer->getCustomer('name','email','age')->description;

thanks




Mine sweeper status

I wrote a code that is supposed to build a simple minesweeper game.

I hit a problem with my get_status() function.

the thing is it only returns GameStatus.NotStarted no matter what i do (Run example at the end)

Cell class:

class BoardCell(object):
    """
    Represents a cell in the minesweeper board game and is current status in the game

    """
    def __init__(self):
        """
        Initializes a board cell with no neighboring mines and status is hidden

        Args:
            None

        Returns:
            None (alters self)
        """
        self.isHidden = True
        self.isMine = False
        self.score = 0
        pass

    def is_mine(self):
        """
        returns true if this cell contains a mine false otherwise

        Args:
            None

        Returns:
            true if this cell contains a mine false otherwise
        """
        return self.isMine
        pass

    def is_hidden(self):
        """
        returns true if this cell is hidden false otherwise

        Args:
            None

        Returns:
            true if this cell is hidden false otherwise
        """
        return self.isHidden
        pass
    def get_cell_value(self):
        """
        returns the number of adjacent mines

        Args:
            None

        Returns:
            the number of adjacent mines in int or the charcter '*' if this cell is a mine
        """
        if self.isMine:
            return '*'
        else:
            return self.score
        pass

    def uncover_cell(self):
        """
        uncovers this cell. when a cell is uncovered then is status is the value of the mines near it or * if the
        cell is a mine
        Args:
            None

        Returns:
            None (alters self)

        """
        self.isHidden = False
        pass

    def update_cell_value(self, cellValue):
        """
        updates the value of the how many neighboring mines this cell has

        Args:
            cellValue - the new number of the how many neighboring mines this cell has

        Returns:
            None (alters self)
        """
        self.score = cellValue
        pass

    def add_one_to_cell_value(self):
        """
        adds one to the number of near mine

        Args:
            None

        Returns:
            None (alters self)
        """
        self.score += 1
        return
        pass

    def set_has_mine(self):
        """
        changes this cell to a cell with a mine in it

        Args:
            None

        Returns:
            None (alters self)
        """
        self.isMine = True
        self.score = -1
        pass

Board class:

class Board(object):
    """Represents a board of minesweeper game and its current progress."""

    def __init__(self, rows, columns):
        """Initializes an empty hidden board.

        The board will be in the specified dimensions, without mines in it,
        and all of its cells are in hidden state.

        Args:
            rows: the number of rows in the board
            columns: the number of columns in the board

        Returns:
            None (alters self)
        """
        self.numRows = rows
        self.numColumns = columns
        # starts a board with row*col board cells
        self.board = [[BoardCell() for _ in range(columns)] for _ in range(rows)]
        self.numOfMines = 0

    def put_mines(self, mines, seed=None):
        """Randomly scatter the requested number of mines on the board.

        At the beggining, all cells on the board are hidden and with no mines
        at any of them. This method scatters the requested number of mines
        throughout the board randomly, only if the board is in the beginning
        state (as described here). A cell can host only one mine.
        This method not only scatters the mines on the board, but also updates
        the cells around it (so they will hold the right digit).

        Args:
            mines: the number of mines to scatter
            seed: the seed to give the random function. Default value None

        Returns:
            None (alters self)

        """
        #a list of neighboring
        neighbors = lambda x, y: [(x2, y2) for x2 in range(x - 1, x + 2)
                                  for y2 in range(y - 1, y + 2)
                                  if (-1 < x < self.numRows and
                                      -1 < y < self.numColumns and
                                      (x != x2 or y != y2) and
                                      (0 <= x2 < self.numRows) and
                                      (0 <= y2 < self.numColumns))]
        #SPREAD MINES
        listOfCellsIndex = [(numRow, numCol) for numRow in range(self.numRows) for numCol in range(self.numColumns)]
        # randomly choosing cells in the board to place mines in
        random.seed(seed)
        listOfMineCells = random.sample(listOfCellsIndex, mines)
        for x,y in listOfMineCells:
            self.board[x][y].set_has_mine()
            self.numOfMines += 1
        #CALCULATE CELL SCORE
        for row,col in listOfCellsIndex:
            #iterate over every point
            if not self.board[row][col].is_mine() :
                for x, y in neighbors(row, col):
                    #iterate over every neighbor
                    if self.board[x][y].is_mine() :
                        self.board[row][col].add_one_to_cell_value()


    def print_board(self):
        """prints the board according to the game format
            DO NOT CHANGE ANYTHING IN THIS FUNCTION!!!!!!!
        Args:
            None
        Returns:
            None
        """
        # creates the printing format
        printFormatString = "%-2s " * self.numColumns
        printFormatString += "%-2s"
        # prints the first line of the board which is the line containing the indexes of the columns
        argList = [" "]
        argList.extend([str(i) for i in range(self.numColumns)])
        print printFormatString % tuple(argList)
        # goes over the board rows and prints each one
        for i in range(self.numRows):
            argList = [str(i)]
            for j in range(self.numColumns):
                if self.board[i][j].is_hidden():
                    argList.append("H")
                else:
                    argList.append(str(self.board[i][j].get_cell_value()))
            print printFormatString % tuple(argList)

    def load_board(self, lines):
        """Loads a board from a sequence of lines.

        This method is used to load a saved board from a sequence of strings
        (that usually represent lines). Each line represents a row in the table
        in the following format:
            XY XY XY ... XY
        Where X is one of the characters: 0-8, * and Y is one of letters: H, S.
        0-8 = number of adjusting mines (0 is an empty, mine-free cell)
        * = represents a mine in this cell
        H = this cell is hidden

        The lines can have multiple whitespace of any kind before and after the
        lines of cells, but between each XY pair there is exactly one space.
        Empty or whitespace-only lines are possible between valid lines, or after/before them.
        It is safe to assume that the values are correct (the number represents the number of mines around
        a given cell) and the number of mines is also legal.

        Note that this method doesn't get the first two rows of the file (the
        dimensions) on purpose - they are handled in __init__.

        Args:
            lines: a sequence (list or tuple) of lines with the above restrictions

        Returns:
            None (alters self)
        """
        columnCounter = 0
        rowCounter = 0
        for x in lines:
            for y in x.split():
                if y[0] == '*':
                    self.board[rowCounter][columnCounter].set_has_mine()
                else:
                    self.board[rowCounter][columnCounter].update_cell_value(int(y[0]))
                if y[1] == "S":
                    self.board[rowCounter][columnCounter].uncover_cell()
                columnCounter += 1
            rowCounter += 1
            columnCounter = 0
        pass

    def get_value(self, row, column):
        """Returns the value of the cell at the given indices.

        The return value is a string of one character, out of 0-8 + '*'.

        Args:
            row: row index (integer)
            column: column index (integer)

        Returns:
            If the cell is empty and has no mines around it, return '0'.
            If it has X mines around it (and none in it), return 'X' (digit
            character between 1-8).
            If it has a mine in it return '*'.

        """

        return str(self.board[row][column].get_cell_value())
        pass

    def is_hidden(self, row, column):
        """Returns if the given cell is in hidden or uncovered state.

        Args:
            row: row index (integer)
            column: column index (integer)

        Returns:
            True if the cell is hidden, or False if it's uncovered (can be seen).
        """
        return self.board[row][column].is_hidden

    def uncover(self, row, column):
        """Changes the status of a cell from hidden to seen.

        Args:
            row: row index (integer)
            column: column index (integer)

        Returns:
            None (alters self)
        """
        self.board[row][column].uncover_cell()
        pass

Game class

class Game(object):
    """Handles a game of minesweeper by supplying UI to Board object."""

    def __init__(self, board):
        """Initializes a Game object with the given Board object.

        The Board object can be a board in any given status or stage.

        Args:
            board: a Board object to continue (or start) playing.

        Returns:
            None (alters self)
        """
        self.board = board
        self.gameStatus = self.get_status()
        pass

    def get_status(self):
        """Returns the current status of the game.

        The current status of the game is as followed:
            NotStarted: if all cells are hidden.
            InProgress: if some cells are hidden and some are uncovered, and
            no cell with a mine is uncovered.
            Lose: a cell with mine is uncovered.
            Win: All non-mine cells are uncovered, and all mine cells are
            covered.

        Returns:
            one of GameStatus values (doesn't alters self)

        """
        hiddenCells = 0
        for x in range(self.board.numRows):
            for y in range(self.board.numColumns):
                if self.board.is_hidden(x, y):
                    hiddenCells += 1
                #if a mine is uncovered
                if not self.board.is_hidden(x, y) and self.board.get_value(x, y) == '*':
                    return GameStatus.Lose
        #if the amount of hidden cells equals amount of total cells
        if hiddenCells == self.board.numColumns * self.board.numRows:
            return GameStatus.NotStarted
        #if the amount of hidden cells equals the amount of mines
        #notice i already checked if the game isn't lost
        if hiddenCells == self.board.numColumns * self.board.numRows - self.board.numOfMines:
            return GameStatus.Win
        #if everything else fails
        return GameStatus.InProgress
        pass

    def make_move(self, row, column):
        """Makes a move by uncovering the given cell and unrippling it's area.

        The move flow is as following:
        1. Uncover the cell
        2. If the cell is a mine - return
        3. if the cell is not a mine, ripple (if value = 0) and uncover all
            adjacent cells, and recursively on this cells if needed (if they are empty cells)

        Args:
            row: row index (integer)
            column: column index (integer)

        Returns:
            the cell's value.
        """
        neighbors = lambda x, y: [(x2, y2) for x2 in range(x - 1, x + 2)
                                  for y2 in range(y - 1, y + 2)
                                  if (-1 < x < self.board.numRows and
                                      -1 < y < self.board.numColumns and
                                      (x != x2 or y != y2) and
                                      (0 <= x2 < self.board.numRows) and
                                      (0 <= y2 < self.board.numColumns))]
        #if values are legitimate
        if not self.board.is_hidden(row, column):
            print "Illegal move values"
        if row > self.board.numRows or row < 0 or \
           column > self.board.numColumns or column < 0:
            print "Illegal move values"
            return

        self.board.uncover(row, column)
        if self.board.board[row][column].is_mine():
            return
        if self.board.get_value(row, column) != str(0):
            return
        if self.board.get_value(row, column) == str(0):
            for t, s in neighbors(row, column):
                if self.board.board[t][s].is_hidden():
                    self.make_move(t, s)
        pass

    def run(self):
        """
        Runs the game loop.

        At each turn, prints the following:
        current state of the board
        game status
        available actions
        And then wait for input and act accordingly.
        More details are in the project's description.

        Returns:
            None
        """
        self.board.print_board()
        #if the game is allready over
        if self.gameStatus == GameStatus.Lose or \
           self.gameStatus == GameStatus.Win:
            if self.gameStatus == GameStatus.Lose:
                print "Game status: Lose"
            if self.gameStatus == GameStatus.Win:
                print "Game status: Win"
            print "Available actions: (1) Exit"
            choice = raw_input().strip()
            while choice != '1':
                print "Illegal choice"
                self.run()
            if choice == '1':
                print "Goodbye :)"
                return
        #if the game isn't over yet
        if self.gameStatus == GameStatus.InProgress or \
           self.gameStatus == GameStatus.NotStarted:
            if self.gameStatus == GameStatus.InProgress:
                print "Game status: InProgress"
            if self.gameStatus == GameStatus.NotStarted:
                print "Game status: NotStarted"
            print "Available actions: (1) Exit | (2) Move"
            choice = raw_input()
            while choice != "1" and choice != "2":
                print "Illegal choice"
                self.run()
            if choice == '1':
                print "Goodbye :)"
                return
                pass
            if choice == '2':
                pointNums = raw_input("Enter row then column (space separated): ").split()
                self.make_move(int(pointNums[0]), int(pointNums[1]))
                self.run()

Not "Lose"

Not "InProgress"




Do chrome extensions support ECMA6?

Background

I am making a chrome extension that prints a log once a page reloads. I have all my functions in one bug page, and so lately I decided to make my code readable and refactor it using classes.

Problem

I managed to get my extension up and running, but now, every time I load the page, a get a lot of errors.

Namely I get the error of this is not defined in my cat's constructor!

init.js:

window.onload = function() {
  let cat = new Cat("Boby");
  console.log(cat.toString());
};

mammal.js:

class Mammal{
  constructor(name){
    this.name = name;
    this.kingdom = "mammalia";
  }
}

cat.js:

class Cat extends Mammal{
  constructor(name){
    this.name = name;
    this.type = "Cat";
  }

  toString(){
    return this.type + " from kingdom " + this.kingdom + " has name " + this.name;
  }
}

At first I thought I had a problem with my JSON, since each class is in a separate file, perhaps the files were not being loaded in the correct order.

manifest.json:

{
  "manifest_version": 2,
  "name": "MyExtension",
  "description": "some tool",
  "version": "1.3.1",
  "permissions": [
    "storage",
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "content_scripts": [
  {
    "matches": ["myWebsite"],
    "run_at": "document_end",
    "js": [
      "caseList/init.js",
      "caseList/cat.js",
      "caseList/mammal.js"
    ]
  }]
}

However, after much debugging and testing nothing works! The only thing that seems to 'work' is if I change class Cat extends Mammal to class Cat.

But since cats are lovely mammals, I don't want to do that!

Question:

  1. How can I fix this code, while keeping class inheritance and separated files?



How to pass Zxing barcode info to another class

I would like to pass the info read from the bar code using Zxing to a separate activity/class

How would I go about doing this?

here is my activity code in my MainActivity.java

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                startActivity(new Intent(MainActivity.this, showdata.class));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

I get the results just fine but I want to access these results from a separate class.




initializing c++ classes globally

I am a beginner in c++ classes and using dlib face detector. In the example code for use with webcam, the face detection and pose model are loaded inside the main function like this:

int main(){
    frontal_face_detector detector = get_frontal_face_detector();
    shape_predictor pose_model;
    deserialize("shape_predictor_68_face_landmarks.dat") >> pose_model;

}

However, my project is structured in a way that dlib face detection is called through another function instead of main as in the example. Therefore, I need to make the models global so that the function that performs dlib knows what 'detector' and 'pose_model' are without having to pass it in as arguments to that function. Is there anyway to do that? If I load the models inside the function itself then it gets loaded everytime I call the function, thereby reducing performance.

static dlib::frontal_face_detector detector; static dlib::shape_predictor pose_model;

Currently I am using 'static' to load them inside the function itself but I am not sure if that is correct C++? Apologies for weird format of the question as this is my first question on this forum. Appreciate the understanding and help!! Thanks




How to structure Swift code with several related CGPoint arrays

Pardon me if this sounds quite trivial. I am trying to find a way to organize my code, whether creating a new class or a data structure of some sort. I have several CGPoints,

var arrayOfPoints = [P1, P2, P3, P4, P5,..,P30]

When one is randomly selected, it can move to a number of other points based on the complexity value compVal. For example, if compVal = 1, P1 can move to [P2, P5], and if compVal = 2, P1 can move to [P3, P4, P6] and so on till compVal = 15, this applies to all other P's to P30. How can I structure this functionality in such a way that is orderly and efficient, bearing in mind that I may need to filter some of the positions out occasionally?




Fatal error: Call to a member function execute() on null 3

I have created a class that extends my db class.

class RegisterUser extends db{
  public function __construct($input) {
      $this->input = $input;
      self::register();
 }

  public function register(){
    $options = [
        'cost' => 11,
        'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
    ];
    parent::insert('users',array('username'=>$this->input['name'],'email_address'=>$this->input['email'],'password'=>password_hash($this->input['password'], PASSWORD_DEFAULT,$options)));
  }

}

This is the error the I get:Fatal error: Call to a member function execute() on null in C:\xampp\htdocs\OOPProject\classes\db.class.php on line 115




Cant use EOF in cpp

I need to write a program to get and print the details of a student The method I opted for is to store the information of the student in a file and then display the contents of the file. I have written th following code:

using namespace std;

#include<iostream>

#include<stdio.h>

class Info
{
        FILE *fp ;
        char c ;
    public:
        void getData()
        {
            cout<<"Enter Student Info:\n" ;
            fp = fopen("info.txt","w") ;
            do
            {
                fputc(c,fp) ;
            }while(c!=EOF) ;
            fclose(fp) ;
        }

        void displayData()
        {
            cout<<"\tSTUDENT INFO\n\n" ;
            fp = fopen("info.txt","r") ;
            do
            {
                fgetc(fp) ;
            }while(c!=EOF) ;
            fclose(fp) ;
        }
} ;

int main()
{
    Info student ;
    student.getData() ;
    student.displayData() ;

    return 1;
}

The problem I am getting is while executing the program I am able to input data but i cant stop it I have used ctrl + d but it does nothing I have used it at the end of line, at the beginning of line but nothing happens

I have to force exit the program by ctrl+c and when i check the file size of created "info.txt" file it is very huge in GB

Please Help




Python: Accessing data from one class in another

I have been trying to get data from one class to another. I have looked for answers on how to do this and I found one that looked like it would work. However I am getting errors when I try it. The post I have been using is How would I access variables from one class to another?

import tkinter as tk
from tkinter import ttk

LARGE_FONT= ("Verdana", 12)

class UnitConverter(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, MetricImperial, ImperialMetric, MassMtoI, VolumeMtoI, LengthMtoI, TemperatureMtoI, 
                  MassItoM, VolumeItoM, LengthItoM, TemperatureItoM, KilogramsToPounds, GramsToOunces, 
                  LitersToGallons, LitersToQuarts, KilometersToMiles, MetersToFeet, TemperatureMtoI, 
                  CentimetersToInches, CelsiusToFahrenheit, PoundsToKilograms, OuncesToGrams, GallonsToLiters, 
                  QuartsToLiters, MilesToKilometers, FeetToMeters, InchesToCentimeters, FahrenheitToCelsius):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()
        self.page_name = page_name
        print(self.page_name)
        return self.page_name

class Store(UnitConverter):

    def __init__(self):
        self.variable1 = tk.StringVar()
        self.variable2 = tk.DoubleVar()
        self.var1 = UnitConverter.page_name  

    def onValidate(self, d, i, P, s, S, v, V, W):

        # Letting the first characeter be a negative sign
        if (i == '0' and S == '-'):
            return True
        # Letting the first character be a positive sign            
        if (i == '0' and S == '+'):
            return True
        # Chcking to see if decimal is correct
        if (d == '1' and S == '.' and '.' not in s):
            return True
        # Checking to see if the input is a number, 0 - 9.
        if (d == '1' and S not in '0123456789'):
            return False
        else:
            return True

    def Calculate(self, *args):

        oldValue = self.variable1 
        newValue = self.variable2

        try:
            value = float(oldValue.get())
            newValue.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
        except ValueError:
            pass
        return newValue.get()

object1 = UnitConverter()
var1 = object1.show_frame()
object2 = Store()
print (var1)

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = ttk.Label(self, text="Pick your conversion.", font=LARGE_FONT)
        label.pack(padx=10,pady=10)
        button = ttk.Button(self, text="Metric to Imperial", command=lambda: controller.show_frame("MetricImperial"))
        button.pack(padx=5,pady=5)
        button2 = ttk.Button(self, text="Imperial to Metric", command=lambda: controller.show_frame("ImperialMetric"))
        button2.pack(padx=5,pady=5)

app = UnitConverter()
app.title("Unit Converter")
app.mainloop()

With this I get AttributeError: type object 'UnitConverter' has no attribute 'page_name'

I have also tried the following:

import tkinter as tk
from tkinter import ttk

LARGE_FONT= ("Verdana", 12)

class UnitConverter(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)    

        self.frames = {}

        for F in (StartPage, MetricImperial, ImperialMetric, MassMtoI, VolumeMtoI, LengthMtoI, TemperatureMtoI, 
                  MassItoM, VolumeItoM, LengthItoM, TemperatureItoM, KilogramsToPounds, GramsToOunces, 
                  LitersToGallons, LitersToQuarts, KilometersToMiles, MetersToFeet, TemperatureMtoI, 
                  CentimetersToInches, CelsiusToFahrenheit, PoundsToKilograms, OuncesToGrams, GallonsToLiters, 
                  QuartsToLiters, MilesToKilometers, FeetToMeters, InchesToCentimeters, FahrenheitToCelsius):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()
        self.page_name = page_name
        print(self.page_name)
        return self.page_name

class Store(UnitConverter):

    def __init__(self):
        self.variable1 = tk.StringVar()
        self.variable2 = tk.DoubleVar()
        UnitConverter.__init__(self)    

    def onValidate(self, d, i, P, s, S, v, V, W):

        # Letting the first characeter be a negative sign
        if (i == '0' and S == '-'):
            return True
        # Letting the first character be a positive sign            
        if (i == '0' and S == '+'):
            return True
        # Chcking to see if decimal is correct
        if (d == '1' and S == '.' and '.' not in s):
            return True
        # Checking to see if the input is a number, 0 - 9.
        if (d == '1' and S not in '0123456789'):
            return False
        else:
            return True

    def Calculate(self, *args):

        oldValue = self.variable1 
        newValue = self.variable2

        try:
            value = float(oldValue.get())
            newValue.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
        except ValueError:
            pass
        return newValue.get()

object1 = UnitConverter()
var1 = object1.show_frame()
object2 = Store()
print (var1)

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = ttk.Label(self, text="Pick your conversion.", font=LARGE_FONT)
        label.pack(padx=10,pady=10)
        button = ttk.Button(self, text="Metric to Imperial", command=lambda: controller.show_frame("MetricImperial"))
        button.pack(padx=5,pady=5)
        button2 = ttk.Button(self, text="Imperial to Metric", command=lambda: controller.show_frame("ImperialMetric"))
        button2.pack(padx=5,pady=5)


app = UnitConverter()
app.title("Unit Converter")
app.mainloop()

With this attempt I get the following error:

RecursionError: maximum recursion depth exceeded while calling a Python object

I am doing this to teach myself Python. As you can see I have a long ways to go. I want to get the page_name so that I can do the unit conversion correctly. If I know the page name I can pull the conversion factors from a list, know if the values can be negative and so on.




How to make array on my object/class in vb


I am trying to learn to create an array of objects, but I keep running into errors and am hoping someone can explain what I am doing wrong in my code.

Friend Class myPosition
Friend x1 As Integer
Friend y1 As Integer
Friend x2 As Integer
Friend y2 As Integer
End Class

Dim product(,) As myPosition

For product_y = 0 To max_product_y - 1
For product_x = 0 To max_product_x - 1

izdelek_risba(product_y, product_x).x1 = 1
izdelek_risba(product_y, product_x).y1 = 2
izdelek_risba(product_y, product_x).x2 = 3
izdelek_risba(product_y, product_x).y2 = 4

Next product_x
Next product_y


Thanks for your time :-)




newInstance() cannot find constructor that exist

I think that I am missing something. I am trying to do next thing:

Class.forName(className).getConstructor(getParameterTypes(parameters)).newInstance(parameters);

I am getting error

java.lang.NoSuchMethodException: MyClass.<init>(java.lang.Class)

My class name is full class name(with packages). Method getParameterTypes is returning class java.lang.Class. parameters variable is type of Class and in MyClass I have constructor that is accepting Class. Do someone know what is the problem?




can we have class code inside main() in c++? [duplicate]

This question already has an answer here:

Can we have/declare a class inside main like this

void main() {
class my_class {
    int i;
public:
    my_class(int a){i=a;};
};
...
}




Python function not defined inspite of being declared in a class

I have declared a function isPrecisied() in the class GradientDescent and calling it inside another function ( gd () ). I have created an instance of class and then calling a function with it (b.gd()) which contains the isPrecisied() function in the following manner

        import numpy as np
        import matplotlib.pyplot as plt

        class GradientDescent:
            def __init__(self,x,y,yhat,alpha=0.01,pre=0.1):
                self.x=x # This is the x array
                self.y=y  # y is the array  
                self.yhat=yhat  # yhat is the array
                self.precision=pre
                self.alpha=alpha

            def isPrecisied(self,e):
                if (np.sum(e)/2)>self.precision:
                    return False
                return True

            def gd(self):
                self.beta=[0.0]*len(self.y)
                error=[]
                while True:
                    for j in range(0,len(self.y),1):
                        temp=self.beta[0]+np.sum(np.multiply(self.beta,self.x))
                        error.append(np.square(self.y[j]-temp))
                    t=isPrecisied(error)
                    print(np.sum(error)/2)
                    if t==False:
                        self.beta=np.subtract(self.beta,self.alpha*np.array(self.beta))
                    else:
                        return self.beta


                #take the average precision by 1/2*summition((y-yhat)^2)

                #B0(t+1) = B0(t) – alpha * error(of individual not combined)


        a = GradientDescent([1,2,3,4,5],[10,20,30,40,50],[11,21,30,38,48])
        b=a.gd()

I got the error:

Traceback (most recent call last):

  File "<ipython-input-10-744f30ba0c28>", line 2, in <module>
    b=a.gd()

  File "<ipython-input-9-13f85a04a1e0>", line 23, in gd
    t=isPrecisied(error)

NameError: name 'isPrecisied' is not defined

Please let me know where I am making a mistake.




How do I sort a list of class objetcs based on only one of the instance variables?

I wanted to arrange my class objects in ascending order of their total prices.

Note - I did use selection sort to sort my objects but any type of sorting is welcome.

This content so that s.o. will stop being an annoyance:

        def __init__(self):
            self.code = raw_input("Enter the code")
            self.desc = raw_input("Enter desc")
            self.price = int(raw_input("Enter the price"))

            self.stock = int(raw_input('Enter the stock'))##Declaring my instances.
            self.total= 0
        @staticmethod        
        def compute_discount(l):
            for i in range(len(l)):

                if l[i].price>45000:
                    l[i].total = l[i].price * 0.8
                else:
                    l[i].total = l[i].price * 0.9
            phones.display(l)##Computing Total
        @staticmethod
        def arrange(l):
            print '%10s%30s%10s%15s%10s'%('CODE','DESCRIPTION','PRICE','FINAL PRICE','STOCK')
            for i in range(len(l)-1,0,-1):
                p = 0
                for j in range(1,i+1):
                    if l[j].total > l[p]:
                        p = j
                temp = l[i]
                l[i] = l[j]
                l[j] = temp
                for j in range(len(l)):
                    print '%10s%30s%10d%15f%10d'%(l[j].code,l[j].desc,l[j].price,l[j].total,l[j].stock)##My attempt at displaying a sorted(selection) listand displaying my objets accordingly.

    ##Top level
    #top level codes
    l = []
    for i in range(0,3):
        ob = phones()
        l.append(ob)

    while 1:
                choice = int(raw_input('''   Enter your choice
                                            1)Compute and display discounts
                                            2)Arrange
                                            3)find out products with less stock
                                            4)exit''')
                )
                if choice ==1:
                    ob.compute_discount(l)
                if choice ==2:
                    phones.arrange(l)
                if choice ==3:
                    phones.find(l)
                elif choice ==4:
                    break




How can I move this into a other class

I am working on a Four in a row game. But I have run into a problem with it. I have been able to make the game work. But I would like to know if I can move my public void fillBoard() and public void presentBoard() into another class. This is because I would like to make the code more organised.

package com.company;

public class Main {

    public static void main(String[] args)
    {
        GameMechanics game = new GameMechanics();
        game.play();
    }
}


package com.company;

import java.util.Scanner;

public class GameMechanics
{

    /*
    This is my local variables
    */

    public Scanner scanner = new Scanner(System.in);
    public char token;
    public int column;
    public int player = 2;
    public int turn = 2;
    public int count = 0;
    public boolean gameRunning = true;

    public void play()
    {
        this.createBoard();
        //While gameRunning is true, the methods inside the { } will run, and that's the 4InARow game
        while (gameRunning)
        {
            this.presentBoard();
            this.changeTurn();
            this.dropToken();
            this.gameWon();
        }
        presentBoard();

    }

    public void gameWon()
    {
        this.winConHorizontal();
        this.winConVertical();
    }

    private char[][] board = new char[6][7];

    //Creating my board and assign "space" to all the fields in the array.
    public void createBoard() {
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                board[i][j] = ' ';
            }
        }
    }

    //Presents the board, it prints the board with |"space"| so it looks more like a gameboard.
    public void presentBoard() {
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                if (j == 0) {
                    System.out.print("|");
                }
                System.out.print(board[i][j] + "|");
            }
            System.out.println();
        }
    }

    public void changeTurn() {
        if (this.turn == this.player) {
            this.turn = 1;
            this.token = 'X';
        } else {
            this.turn++;
            this.token = 'O';
        }
    }

    public void dropToken() {
        System.out.println("player " + turn + ": press 1-7 to drop the token");
        column = scanner.nextInt() - 1;
        //If pressed any intValue outside the board, it will tell you to try again.
        if (column >= 7 || column <= -1)
        {
            System.out.println("place the token inside the bord");
            changeTurn();
        } else {
            //Drops the token and replace it with playerChar.
            for (int i = 5; i > -1; i--) {
                if (board[i][column] == ' ')
                {
                    board[i][column] = token;
                    break;
                }
            }
        }
    }

    public boolean winConHorizontal() {

        while (gameRunning) {
            for (int i = 0; 6 > i; i ++) {
                for (int j = 0; 7 > j; j ++) {
                    if (board[i][j] == this.token) {
                        count ++;
                    } else {
                        count = 0;
                    }
                    if (count >= 4) {
                        System.out.println("player " + (turn) + " Wins!!!!");
                        gameRunning = false;
                    }
                }
            }
            break;
        }
        return gameRunning;
    }

    public boolean winConVertical() {

        while (gameRunning) {
            for (int i = 0; 7 > i; i ++) {
                for (int j = 0; 6 > j; j ++) {
                    if (board[j][i] == this.token) {
                        count ++;
                    } else {
                        count = 0;
                    }
                    if (count >= 4) {
                        System.out.println("player " + (turn) + " Wins!!!!");
                        gameRunning = false;
                    }
                }
            }
            break;
        }
        return gameRunning;
    }
}




How to update instances by updating static variables?

My class Time can display time depending on the static variables hours in a day and minutes in an hour. I would like to be able to print the updated time by simply changing my static variables.

in my main(), I want to declare some Time instances based on the default static variables (24 hrs in a day, and 60 min in an hour).

Time a;
Time b(5);
Time c(61);

cout << "a = " << a << "\t";
cout << "b = " << b << "\t";
cout << "c = " << c << "\n";

// output is a =  0:00  b =  0:05 c =  1:01

Time::set_hr_in_day(60);

Time::set_min_in_hr(24);
cout << "a = " << a << "\t";
cout << "b = " << b << "\t";
//output should be a =  0:00    b =  0:05   c =  2:13

However, the code still prints out the numbers for the default static variables.

Any ideas as to how I can fix this? Btw, I am trying to create a class to test against a given driver, so changing my main function isn't an option.

Here is the rest of my code:

the header file

#ifndef TIME_H
#define TIME_H

#include <iostream>

using namespace std;

class Time {
private:
    int hour;
    int minute;
    static int dayhrs;
    static int hrsmin;

public:

    Time();
    Time(int min);
    Time(int hr, int min);
    Time(double hrs);
    int minutes() { return minute; };
    int hours() { return hour; };

    static void set_hr_in_day(int hr);
    static void set_min_in_hr(int min);
    static int dailyhr() { return dayhrs; };
    static int hourlymin() { return hrsmin; };

friend ostream& operator<<(ostream& os, const Time& t);


};



#endif

implementation

#include "time.h"
#include <iostream>

using namespace std;

int Time::dayhrs = 24;//default
int Time::hrsmin = 60;

void Time::set_hr_in_day(int hr) {
    dayhrs = hr;
}

void Time::set_min_in_hr(int min) {
    hrsmin = min;
}


Time::Time() {
    hour = 0;
    minute = 0;
}

Time::Time(int min) {
    if (min > (Time::hourlymin() - 1)) {
        hour = min / Time::hourlymin();
        minute = min % Time::hourlymin();
    }
    else {
        hour = 0;
        minute = min;
    }

}

Time::Time(int hr, int min) {
    if (min > (Time::hourlymin() - 1)) {
        hour = min / Time::hourlymin() + hr;
        minute = min % Time::hourlymin();
    }
    else {
        hour = hr;
        minute = min;
    }

    if (hour > (Time::dailyhr() - 1))
        hour = hour % (Time::dailyhr());
}

Time::Time(double hrs) {
    double fraction = 0;
    fraction = hrs - (int)hrs;
    minute = fraction * Time::hourlymin();
    if (fraction * Time::hourlymin() - (int)(fraction * Time::hourlymin()) >= 0.5)
        minute += 1;
    hour = hrs - fraction;
    if (hour > (Time::dailyhr() - 1))
        hour = hour % (Time::dailyhr());
}



ostream& operator<<(ostream& os, const Time& t)
{
    if (t.minute > 9)
        os << t.hour << ":" << t.minute;
    else
        os << t.hour << ":0" << t.minute;
    return os;
}

driver

#include <iostream>
#include "time.h"

using std::cout;

int main() {
    cout << "*****************************************\n";
    cout << "Welcome to 'San Angel'!\n";
    cout << "[ 1 day = 24 hours, 1 hour = 60 minutes ]\n\n";

    Time a;
    Time b(5);
    Time c(61);
    Time d(47, 59);
    Time X(5.0);
    Time Y(1.5);
    Time Z(25.1);

    cout << "a = " << a << "\t";
    cout << "b = " << b << "\t";
    cout << "c = " << c << "\n";
    cout << "d = " << d << "\t";
    cout << "X = " << X << "\t";
    cout << "Y = " << Y << "\n";
    cout << "\t\tZ = " << Z << "\n";


    Time::set_hr_in_day(60);
    Time::set_min_in_hr(24);
    cout << "*****************************************\n";
    cout << "Welcome to the land of the remembered!\n";
    cout << "[ 1 day = 60 hours, 1 hour = 24 minutes ]\n\n";

    cout << "a = " << a << "\t";
    cout << "b = " << b << "\t";
    cout << "c = " << c << "\n";
    cout << "d = " << d << "\t";
    cout << "X = " << X << "\t";
    cout << "Y = " << Y << "\n";
    cout << "\t\tZ = " << Z << "\n";

return 0;

}
/**

OUTPUT:

*****************************************
Welcome to 'San Angel'!
[ 1 day = 24 hours, 1 hour = 60 minutes ]

a =  0:00   b =  0:05   c =  1:01
d = 23:59   X =  5:00   Y =  1:30
Z =  1:06
*****************************************
Welcome to the land of the remembered!
[ 1 day = 60 hours, 1 hour = 24 minutes ]

a =  0:00   b =  0:05   c =  2:13
d = 59:23   X = 12:12   Y =  3:18
Z =  2:18 */




How can I do running class from alert rules in axapta

Hi everybody I want to create alert rule in axapta. But some class will run when rules run.I want to that class work with that rules. How can i do this?




lundi 30 janvier 2017

MVC 5 - Ineffective direct changes on Classes

I working on project made by mvc 5

Anytime i change classes or controllers , To be able to see the changes I am forced to transfer all my files to the server again

What is the problem of that ?

why i cant change my classes without visual studio




Issue with error C2679: binary '+=': no operator found which takes a right-hand operand of type 'int'

everyone. I'm working on a piece of code for school, defining a Time class with various functions such as adding and setting time. The issue I have right now is overloading my "+=" operator.

Time& Time::operator+=(Time& a) {
    *this = a + *this;
    return *this;
}

I have overloaded the "+" operators already, so I am just calling on it for my "+=" operator.

 Time operator+(Time a, Time b) {

        int sumhr = a.hour + b.hour;
        int summin = a.minute + b.minute;

        if (summin > 59) {
            sumhr += summin / 60;
            summin = summin % 60;
        }

        if (sumhr > 23)
            sumhr = sumhr % 24;

        return Time(sumhr, summin);
    }

    Time operator+(Time a, int addminutes) {
        Time t = a + Time(addminutes);
        return t;
    }

    Time operator+(Time a, double addhours) {
        Time t = a + Time(addhours);

        return t;
    }

In my int main(), I am using:

Time c(61);
c += 120;
cout << "\tc += 120;\t\t";
cout << "c = " << c << "\n";

which gives me the error. I'm not sure what I'm doing wrong, since I overloaded the "+" operator with int and double parameters already. Would appreciate any feedback. Thank you!




Django Models Option Save

i just want to ask how it works that method "save", in this model? I just trying to add this to my code, but i really dont know how it works.. Those lines help me to save the slugify if theres is not an id in the model? Thank you so much.

class Category(models.Model):

name = models.CharField(max_length=50)
slug = models.SlugField(editable=False)

def save(self, *args, **kwargs):
    if not self.id:
        self.slug = slugify(self.name)
    super(Category, self).save(*args, **kwargs)

def __unicode__(self):
    return self.name




How can I make a class method work with another class method in an array?

For class I am suppose to make a program to simulate a police officer issuing a parking ticket to a car that is parked for too long. I am suppose to create four classes, ParkedCar, ParkingMeter, ParkingTicket, and PoliceOfficer. I'm just stuck on the main method because I have to make an array of two cars and make another array of two ParkingMeter, and make one car a violation, and the other a non-violation. How can I do this?

ParkedCar Class

// a class of  type ParkedCar
public class ParkedCar {

// the class fields
private String make;
private String model;
private String color;
private String licenseNumber;
private int minutesParked;

// the class constructor
public ParkedCar(String mk, String mdel, String col, String lic, int minParked) {

    // assign the constrictor fields to the class fields
    make = mk;
    model = mdel;
    color = col;
    licenseNumber = lic;
    minutesParked = minParked;
}

// the copy constructor
public ParkedCar copy(ParkedCar car2) {
    ParkedCar copyObject = new ParkedCar(make, model, color, licenseNumber, minutesParked);
    return copyObject;
}

// getter method for make of a car
public String getMake() {
    return make;
}

// setter method for make of a car
public void setMake(String make) {
    this.make = make;
}

// getter method for model of a car
public String getModel() {
    return model;
}

// setter method for model of a car
public void setModel(String model) {
    this.model = model;
}

// getter method for color of a car
public String getColor() {
    return color;
}

// setter method for a color of a car
public void setColor(String color) {
    this.color = color;
}

// getter method for a car licence number
public String getLicenseNumber() {
    return licenseNumber;
}

// setter method for a car licence number
public void setLicenseNumber(String licenseNumber) {
    this.licenseNumber = licenseNumber;
}

// getter method for minutes parked
public int getMinutesParked() {
    return minutesParked;
}

// setter method for minutes parked
public void setMinutesParked(int minutesParked) {
    this.minutesParked = minutesParked;
}
}

ParkingMeter Class

// a class of type ParkingMeter
public class ParkingMeter {

// the class fields
private int minutesPurchased;

// the class constructor
public ParkingMeter(int numMinPurchased) {

    // assign the constrictor fields to the class fields
    this.minutesPurchased = numMinPurchased;
}

// getter method for minutes purchased
public int getMinutesPurchased() {
    return minutesPurchased;
}

// setter method for minutes purchased
public void setMinutesPurchased(int minutesPurchased) {
    this.minutesPurchased = minutesPurchased;
}
}

PoliceOfficer Class

// a class of type PoliceOfficer
public class PoliceOfficer {

// the class fields
private String name;
private String badgeNumber;

// the class constructor
public PoliceOfficer(String officeName, String badgeNumber) {

    // assign the constrictor fields to the class fields
    name = officeName;
    this.badgeNumber = badgeNumber;
}

// the copy constructor
public PoliceOfficer copy(PoliceOfficer officer) {
    PoliceOfficer copyObject = new PoliceOfficer(name, badgeNumber);
    return copyObject;
}

// the method patrol looks at the number of minutes a car has been parked and the
// number of minutes purchased
public ParkingTicket patrol(ParkedCar car, ParkingMeter meter) {

    ParkingTicket ticket = null;

    // Calculate the total number of minutes parked over minutes
    // purchased
    int illegalMinutes = car.getMinutesParked()
            - meter.getMinutesPurchased();

    // if illegalMinutes, give ticket
    if (illegalMinutes > 0) {
        // yes, it is illegally parked.
        ticket = new ParkingTicket(car, this, illegalMinutes);
    }
    return ticket;
}

// a getter method to get name of officer
public String getName() {
    return name;
}

// a setter method to set name of officer
public void setName(String name) {
    this.name = name;
}

// a getter method to get officer badge number
public String getBadgeNumber() {
    return badgeNumber;
}

// a setter method to set officer badge number
public void setBadgeNumber(String badgeNumber) {
    this.badgeNumber = badgeNumber;
}
}

ParkingTicket Class

// a class of type ParkingTicket
public class ParkingTicket {

// the class fields
private ParkedCar car;
private PoliceOfficer officer;
private double fine;
private int minutes;
public final double BASE_FINE = 25.0;
public final double HOURLY_FINE = 10.0;

// the class constructor
public ParkingTicket(ParkedCar aCar, PoliceOfficer anOfficer, int meterMins) {

    // assign the constrictor fields to the class fields
    car = aCar;
    officer = anOfficer;
    minutes = meterMins;
}

// a copy constructor
public ParkingTicket copy(ParkingTicket ticket) {
    ParkingTicket copyObject = new ParkingTicket(car, officer, minutes);
    return copyObject;
}

// The method calculateFine calculates the amount of a parking fine
public void calculateFine() {

    double hours = minutes / 60.0;
    int hoursAsInt = (int) hours;

    if ((hours - hoursAsInt) > 0) {
        hoursAsInt++;
    }

    // Assign the base fine.
    fine = BASE_FINE;

    // Add the additional hourly fines.
    fine += (hoursAsInt * HOURLY_FINE);
}

// getter method to get a car
public ParkedCar getCar() {
    return car;
}

// setter method to set a car
public void setCar(ParkedCar car) {
    this.car = car;
}

// getter method to get officer
public PoliceOfficer getOfficer() {
    return officer;
}

// setter method to set officer
public void setOfficer(PoliceOfficer officer) {
    this.officer = officer;
}

// getter method to get fine
public double getFine() {
    return fine;
}

// setter method to set fine
public void setFine(double fine) {
    this.fine = fine;
}

// getter method to get minutes
public int getMinutes() {
    return minutes;
}

// setter method to set minutes
public void setMinutes(int minutes) {
    this.minutes = minutes;
}

public String toString() {
    return "ParkingTicket [car=" + car + ", officer=" + officer
            + ", fine=" + fine + ", minutes=" + minutes
            + ", BASE_FINE=" + BASE_FINE + ", HOURLY_FINE="
            + HOURLY_FINE + "]";
}
}

The Main Method

// a class of type PatrolSimulation
public class PatrolSimulation {

// the main method
public static void main(String[] args) {

    // an array of 2 Car objects, with various minutesParked values
    ParkedCar[] car = new ParkedCar[2];
    car[0] = new ParkedCar("Volkswagen", "1972", "Red", "147RHZM", 100);
    car[1] = new ParkedCar("Volkswagen", "1972", "Red", "147RHZM", 30);

    // an array of 2 ParkingMeter objects, with minutes so that
    // the first Car object is in violation, while the second is not
    ParkingMeter[] meter = new ParkingMeter[2];
    meter[0] = new ParkingMeter(30);
    meter[1] = new ParkingMeter(40);

    // an array of 2 ParkingTicket objects
    ParkingTicket[] ticket = new ParkingTicket[2];

    // a PoliceOfficer object
    PoliceOfficer officer = new PoliceOfficer("Sargent Cody", "007");

}
}

The Main Method Pseudocode

// Create an array of 2 Car objects, with various minutesParked values  
// Create an array of 2 ParkingMeter objects, with minutes so that  
// the first Car object is in violation, while the second is not  

// Create an array of 2 ParkingTicket objects  

// Create a PoliceOfficer object. Give the officer a name and badge
// number  

// Have the officer patrol each of the Car and ParkingMeter object  
// combinations (index i for the array of Car objects should be  
// matched with index i for the array of ParkingMeter objects, which 
// should be matched with index i of the array of ParkingTicket 
// objects)  

 // After the PoliceOfficer has patrolled the cars and parking  
// meters, walk over the array of ParkingTickets and invoke the  
// toString method if a ticket has been issued, otherwise indicate 
// that a ticket has not been issued  




What is "Self" inside "If" Statement of Instance Method

What does "self" refer to when it's inside an "if" statement (or is it called block?) that is inside an instance method?

I'm referring to my code in the last method: "apply_discount"

I thought it'd get me the @total and @discount instance variables, but it's not doing so.

So, basically, how would I get these variables from the my place in the "if" statement I'm referring to by using "self"?

Or should I use another way?

class CashRegister

    attr_accessor :total, :discount

    def initialize(discount = 0)
        @total = 0
        @discount = discount
    end

    def add_item(title, price, quantity = 0)
        if quantity > 0
            self.total += (price * quantity)
        else
            self.total += price
        end
    end

    def apply_discount
        # total = self.total
        # discount = self.discount
        if self.discount > 0
            self.total = self.total - (self.total * (self.discount / 100.0))
            "After the discount, the total comes to $#{self.total}."
        else
            "There is no discount to apply."
        end
    end
end

Thanks for your help!




Java Programming Help for 2 files with a controlling class

First java class is the primary one which invokes other classes. I will copy the code for the two files. I cannot compile this code and I do not know why.

When I had the program in one file it ran fine, but the instructor wants it in two files. Can someone explain to me what I am doing, or did incorrectly?

File 1:

public class Wk2ToddFoughty {        
    public static void main(String[] args) {
        SalaryCalc FinalSalaryCalc = new SalaryCalc();            
        FinalSalaryCalc.SalaryCalc();               
    }
}

File 2:

import java.util.Scanner;

class SalaryCalc {                                  
      Scanner in = new Scanner(System.in);
      System.out.println("Enter your annual sales: $");          
      double sales = in.nextDouble();
      double salary = 35000.00;
      double commission = (sales * .015);
      double totalSalary = salary + sales;
      System.out.println("Your Salary + Commission is: $" + totalSalary );   
}




How to spyOn a static class method with Jasmine

I have a class with a static method that I want to test in Jasmine. I understand that static methods are not callable on instances of the class. So besides thte fact that it cannot find the method to spyOn, my test does not pass, but how would one go about testing static methods in a class with Jasmine?

Thanks!

class Foo {
    static foobar (a, b) {
      return a * b
    }
}

Jasmine Test

it ('should test a static method', () => {
    let foo = new Foo()
    spyOn(foo, 'foobar')
    foo.foobar(2,3)
    expect(foo.foobar).toBe(6)
})




Trying to remove last element in a list using a Node class and a Linked List class

For this code, I'm trying to remove the last add object of a list using a Node class and a LinkedList class. So far:

class Node:
    def __init__(self, init_data):
        self.data = init_data
        self.next = None

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next

    def set_data(self, new_data):
        self.data = new_data

    def set_next(self, new_next):
        self.next = new_next

class LinkedList:

    def __init__(self):
        self.head = None

    def print_all(self):
        current = self.head
        while current != None:
            print(current.get_data())
            current = current.get_next()

    def add(self, item):
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node

    def remove_from_tail(self):
        current = self.head
        previous = current
        while current.get_next() != None:
            previous = current
            current = current.get_next()
        previous.set_next(None)
        return current

        return False

when trying to run the following lines,

my_list = LinkedList()

my_list.add('dog')
my_list.add('cat')
my_list.add('bit')
my_list.add('ask')

print(my_list.remove_from_tail())
print(my_list.remove_from_tail())

my_list.print_all()

I'm getting the following output:

<__main__.Node object at 0x00000000033A19E8>
<__main__.Node object at 0x00000000033A1A58>
ask
bit

when I should be getting:

dog
cat
ask
bit

I appreciate any help I can get to understand what I'm doing wrong.




Failure to calculate expression in object class (java) wrong sum being computed

I have written a class that describes a polynomial object. I collect and send the array of coefficients to the class and the value that the user desires to have the polynomial calculated for BUT for some mysterious reason that only java knows the class keeps sending back a completely wrong calculation of the polynomial. I have worked at this for 3 hours and can't find a solution this this treacherous problem.What is wrong the class?I have included the tester class plus the actual class. This is the output of the program by the way: 2 2 2 2 (these are the coefficients that I have entered} You are evaluating for a value of: 2.0 The sum of the polynomial is: 32.0

2x^0+2x^1+2x^2+2x^3 (As you can see this is the wrong answer its supposed to be 30)

import javax.swing.JOptionPane;


    public class copy1D{

        public static void main(String[]args)
        {

            String input;
            int degree;
            double number;


            input = JOptionPane.showInputDialog(" what is the degree of the polynomial?");
            degree = Integer.parseInt(input);
            degree= degree+1;
            int [] array = new int [degree];

            //creating array of coefficients
            for ( int i =0; i<=array.length-1; i++)
            {
                input = JOptionPane.showInputDialog(" Enter coefficients:");
                array[i] = Integer.parseInt(input);
            }

            //Printing out the coefficients to ensure they are correct
            for ( int i =0; i<=array.length-1; i++)
            {
                System.out.print(array[i] + " ");
            }



            Class1D c1d = new Class1D(degree, array);


            input = JOptionPane.showInputDialog(" Enter the number for which to evaluate the expression:");
                number = Integer.parseInt(input);
                System.out.println(" You are evaluating for a value of: " + number);
                System.out.println(" The sum of the polynomial is:");
            System.out.println(c1d.Evaluathepolynomial(number));

                for (int z=0; z <= array.length-1; z++)
                {
                    if (z<array.length-1)
                    System.out.print(array[z] + "x^" + z + "+");
                    if (z==array.length-1)
                    System.out.print(array[z] + "x^" + z);
                }



        }

    }


public class Class1D {

private int degree;
private int [] coefficient;
private double evaluation=0;

    public Class1D(int degree){
    this.degree =degree;
    }

    public Class1D(int degree, int[] a){

    this.degree =degree;
    this.coefficient = a.clone();
}

      public int []getCoefficient() {
          return coefficient;

      }
    public double Evaluathepolynomial(double value){
        for (int i =0; i<this.degree; i++)
        {
            this.evaluation= Math.pow(value,i) *this.coefficient[i];

            this.evaluation+= evaluation;

        }
        return evaluation;

}
}




How would I combine two different scripts?

So I am writing a program to display information on a screen like a clock, graph, news feed etc. My friend is working out how to make those things and I am combining them and displaying them. So far I've managed to display the clock but I'm getting stuck on how to progress. My script has a class with definitions inside it but most of the scripts my friend gives me do not have a class and I don't know how to combine them. I've tried a few things but I'm very new to python so I am wondering if anyone could give me some advice. Here are the two scripts:

from tkinter import *
from PIL import ImageTk, Image
import os
import time
import requests
import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        # call the __init__ method of Tk class to create the main window
        tk.Tk.__init__(self)

        # background image
        img = ImageTk.PhotoImage(Image.open("0.png"))
        panel = Label(self, image=img)
        panel.pack()

        # clock
        self.label = tk.Label(self, text="", font=('comic',50,'bold'),
                          bg='#464545', fg='#1681BE')
        self.label.place(height=204, width=484, x=1384, y=824)       
        self.update_clock()



        # window geometry
        w, h = self.winfo_screenwidth(), self.winfo_screenheight()
        self.geometry("%dx%d+0+0" % (w, h))

        self.overrideredirect(True)
        self.mainloop()

    def update_clock(self):
       now = time.strftime('%H:%M:%S')
       self.label.configure(text=now)
       self.after(1000, self.update_clock)


app = App()

and

import requests
import tkinter as tk

response = requests.get("http://ift.tt/2kLTDDr")

data = response.json()

Run = ""

for item in data ['articles']:
    Run +=(item["description"]+ " ")


root = tk.Tk()
deli = 100           # milliseconds of delay per character
svar = tk.StringVar()
labl = tk.Label(root, textvariable=svar, height=10 )

def shif():
    shif.msg = shif.msg[1:] + shif.msg[0]
    svar.set(shif.msg)
    root.after(deli, shif)

shif.msg = Run
shif()
labl.pack()
root.mainloop()

Thanks for any comments and advice, it's really appreciated




Finding Max of Array of Objects/Writing To File

I am trying to find the max score from the array of objects. The code for that is everything below the int maxValue = -1; line of code. I am also trying to write that bands information to an external file:

import java.io.FileWriter;


public class App {


public static void main(String[] args) {

    Bands[] bands = new Bands[5];

    bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
    bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
    bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
    bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
    bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");

    bands[0].compete();
    bands[1].compete();
    bands[2].compete();
    bands[3].compete();
    bands[4].compete();

    for (int i = 0; i < 5; i++) {
        String bandInfo = bands[i].getInfo();
        System.out.println(bandInfo);
    }

    System.out.println("");


    //DOESNT WORK BEYOND THIS POINT



    int maxValue = -1;

    for (int i = 0; i < bands.length; i++) {
        if (bands[i].compete() > maxValue) {
            maxValue = bands[i].compete();
        }
    }

    try {
        FileWriter fw = new FileWriter("src/winners.txt", true);
        fw.write(bandInfo + "\n");
        fw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And then here is my Bands class code:

import java.util.Random;

public class Bands {

private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;

public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
    this.singerName = singerName;
    this.guitarName = guitarName;
    this.bassistName = bassistName;
    this.drummerName = drummerName;
    this.bandName = bandName;
    this.Hometown = Hometown;
    this.income = income;
    this.genre = genre;
    this.score = -1;
}

public void compete()
{     
    Random rand = new Random();
    this.score = rand.nextInt(20);
}

public String getInfo()
{
    String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName + 
                      ", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " + 
                      this.genre + ", Final Score: " + this.score;

    return bandInfo;
}
}




C++ object private members incrementing when they're not supposed to

So I have a Player class and one of the private members is int wins:

class Player {
private:
int wins;
int losses;
public:
void increment_win(int win_loss);
....
};

This is the increment_win() function:

void Player::increment_win(int win_loss){
if (win_loss%2 == 0)
wins++;
else
losses++;
}

In my main.cpp file I first declare a vector of player objects and then a player object within main().

std::vector<Player> players;
Player aPlayer;

My constructor sets wins = 0; I then iterate through a certain number of times:

for (int i =0; i < 6; i++){
    aPlayer.increment_kill(i);
    players.push_back(aPlayer);
    Player aPlayer;
}

When I cout the vector "players" and access the private member "wins" using a member function

int Player::get_wins() const{
return wins;
}

I get an increasing number of wins for each object. If obj1 in the vector had 1 win, then object two would have 2, and so on. Anyone know why?




How can I improve my code with classes and methods?

i have this code in Ruby made to search words through any webpage.

I wonder if it's possible to improve it with Class/Methods, make it more beautiful and functional using Object Oriented. Anyone could help me, please?

require 'open-uri'

puts "Type URL you wanna search:"
url = gets.chomp
puts "Type the word you want to search:"
pattern = gets.chomp   

page = open(url.to_s).read
tags = page.scan(pattern)

puts "It has #{tags.length} matches for: #{pattern} "




Multiple Instances of a Class Issues

I really don't understand why the below issue is occurring,

    Mark testMark1 = new Mark("English", 70);
    Mark testMark2 = new Mark("Maths", 50);

    String i = testMark1.getSubject();
    double j = testMark1.getRawMark();

Even though I have created two separate objects of type Mark with two different constructors, the variables i and j are set to the properties of testMark2.

I have looked online and cannot find the answer.

Thanks in advance.




How do you call a class (that's not an activity) in an activity class in Android Studio?

I'm learning Android Studio and I decided to create a Java class and then call it in MainActivity. However, the app crashes on startup - see below. I just don't understand what the error means. Any thoughts?

MainActivity.java

   package com.example.daniel.hamblaster;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        generateText obj = new generateText();
        obj.generate();

    }
}

Java class:

package com.example.daniel.hamblaster;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class generateText extends AppCompatActivity {

    Button myButton = (Button) findViewById(R.id.myButton);

    public void generate() {
        myButton.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    TextView myText = (TextView) findViewById(R.id.myText);
                    myText.setText("blablaba");
                }
            }
        );
    }
}

Error:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.daniel.hamblaster, PID: 5560 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.daniel.hamblaster/com.example.daniel.hamblaster.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:120) at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:151) at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:31) at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:55) at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:33) at android.support.v7.app.AppCompatDelegateImplN.(AppCompatDelegateImplN.java:33) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185) at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:525) at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:193) at com.example.daniel.hamblaster.generateText.(generateText.java:9) at com.example.daniel.hamblaster.MainActivity.onCreate(MainActivity.java:14) at android.app.Activity.performCreate(Activity.java:6679) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6119)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)  Application terminated.




Calling a String Method in Main

I am just trying to call a simple method that returns a string and for some reason, I am blanking and cannot remember for the life of me how to properly do this. I am trying to calling the method getInfo() in the Bands class and to print out the string bandInfo thats inside it:

public class App {


public static void main(String[] args) {

    Bands[] bands = new Bands[5];

    bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
    bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
    bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
    bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
    bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");

    bands[0].compete();
    bands[1].compete();
    bands[2].compete();
    bands[3].compete();
    bands[4].compete();

    for (int i = 0; i < 5; i++) {
        String bandInfo = getInfo(bandInfo);
    }
}
}

And here is my Bands class code:

import java.util.Random;

public class Bands {

private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;

public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
    this.singerName = singerName;
    this.guitarName = guitarName;
    this.bassistName = bassistName;
    this.drummerName = drummerName;
    this.bandName = bandName;
    this.Hometown = Hometown;
    this.income = income;
    this.genre = genre;
    this.score = -1;
}

public void compete()
{     
    Random rand = new Random();
    this.score = rand.nextInt(20);

}

public String getInfo()
{
    String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName + 
                      ", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " + 
                      this.genre + ", Final Score: " + this.score;

    return bandInfo;
}
}