lundi 30 novembre 2015

Python/Pygame errors in class inheritance

So I've been working with classes and inheritance and from my limited understanding, I've gathered that attributes should be inherited. However, the first set of code below throws this error: 'AttributeError: type object 'Characters' has no attribute 'posX' with the below code:

class Characters(object):
def __init__(self,health,posX,posY,width,height,dead,moveSpeed,yMove,xMove):
    self.health = health
    self.posX = posX
    self.posY = posY
    self.width = width
    self.height = height
    self.dead = dead
    #self.image = image
    self.yMove = yMove
    self.xMove = xMove


class Player(Characters):
def __init__(self,images,gameOver):
    self.images = (config.get('player'))
    self.gameOver = gameOver


def move(self):

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            self.gameOver = True

    keysPressed = pygame.key.get_pressed()

    if keysPressed[pygame.K_w]:
        Characters.yMove = -Characters.moveSpeed
        Characters.image = self.images[1]
    if keysPressed[pygame.K_s]:
        Characters.yMove = Characters.moveSpeed
        Characters.image = self.images[0]
    if keysPressed[pygame.K_a]:
        Characters.xMove = -Characters.moveSpeed
        Characters.image = self.images[2]
    if keysPressed[pygame.K_d]:
        Characters.xMove = Characters.moveSpeed
        Characters.image = pygame.transform.flip(self.images[2],True,False)

    Characters.posX += Characters.xMove
    Characters.posY += Characters.yMove

And with the below code, it throws the error: AttributeError: 'pygame.Surface' object has no attribute 'posX'

class Player(Characters):
def __init__(self,images,gameOver,posX,posY):
    self.images = (config.get('player'))
    self.gameOver = gameOver
    self.posX = posX
    self.posY = posY

def move(self):

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            self.gameOver = True

    keysPressed = pygame.key.get_pressed()

    if keysPressed[pygame.K_w]:
        Characters.yMove = -Characters.moveSpeed
        Characters.image = self.images[1]
    if keysPressed[pygame.K_s]:
        Characters.yMove = Characters.moveSpeed
        Characters.image = self.images[0]
    if keysPressed[pygame.K_a]:
        Characters.xMove = -Characters.moveSpeed
        Characters.image = self.images[2]
    if keysPressed[pygame.K_d]:
        Characters.xMove = Characters.moveSpeed
        Characters.image = pygame.transform.flip(self.images[2],True,False)

    self.posX += Characters.xMove
    self.posY += Characters.yMove

I have tried using *args and **kwargs, the super method, and Parent.__init__(self, attr1, attr2,...), but it still throws the same errors. Is there something I'm doing wrong?




Read user input into global string C#

I'm reading files into DataTables but need to use different file names for different version of my product. How can I get the product version number as entered by a user set as a global variable in a class?

I want to apply a case statement to the "using (TextFieldParser)" line so it will use the correct files for the correct versions.

static public DataTable VolumeImport()
{
    DataTable Volumes = new DataTable();
    Volumes.Columns.Add("MediaId", typeof(string));
    Volumes.Columns.Add("MediaTypeName", typeof(string));
    Volumes.Columns.Add("MediaGroupName", typeof(string));
    Volumes.Columns.Add("Barcode", typeof(string));
    Volumes.Columns.Add("PoolName", typeof(string));

    using (TextFieldParser volumes = new TextFieldParser("C:\\Input Files\\752.dat"))

    {
        volumes.TextFieldType = FieldType.Delimited;
        volumes.Delimiters = new string[] { "," };
        volumes.HasFieldsEnclosedInQuotes = true;
        volumes.TrimWhiteSpace = true;


        string[] deviceprops;

        while (!volumes.EndOfData)
        {
            deviceprops = volumes.ReadFields();
            Volumes.Rows.Add((deviceprops[3]).Replace("'", String.Empty), (deviceprops[7]).Replace("'", String.Empty), (deviceprops[8]).Replace("'", String.Empty),
            (deviceprops[16]).Replace("'", String.Empty), (deviceprops[50]).Replace("'", String.Empty));
        }
    }
    return Volumes;
}

I've add the following but it doesn't ever ask for the version. I suspect this is because its not part of the void Main

public class Version
{
    public string nbuversion { get; set; }

    public void GetVersion()
    {
        Console.WriteLine("Enter the Version:"); // Prompt for version
        string nbuversion = Console.ReadLine();
    }
}




C++ chain inheritance

Im trying to create a percent savings program for a supermarket with 3 inherited classes (PersonData -> CustomerData -> PreferredCustomer). The entire program has to follow this UML diagram:

UML diagram

I am having problems with the third class; specifically initializing values in the first constructor of the class. Im getting an error message in visual studio: "redefinition of formal parameter Pa" and "redefinition of formal parameter "dl".

This is the constructor with the errors:

PreferredCustomer(string aLname, string aFname, string aAddress, 
        string aCity, string aState, int aZip, string aPhone, int cn, 
        bool ml, double Pa, double dl)   // constructor 1
{
    double Pa;
    double dl;
}

The parameters in this third child constructor have been overloaded from the parent constructor. Arguments cn, ml, Pa, dl have all been added into this parameter.

I'm not sure why i am getting these errors? Also, should i be creating a virtual function or using pointers? Thank you for any help.

My program source code (for reference):

#include <iostream>
#include <string>
using namespace std;

class PersonData // PersonData parent class defined
{
private:
    string lastName;
    string firstName;
    string address;
    string city;
    string state;
    string phone;
    int zip;

public:
    PersonData() // Default Constructor initialization
    {
        lastName = " ";
        firstName = " ";
        address = " ";
        city = " ";
        state = " ";
        zip = 0;
        phone = " ";
    }

    PersonData(string aLname, string aFname, string aAddress, string aCity, string aState, int aZip, string aPhone) // Constructor 1
    {
        lastName = aLname;
        firstName = aFname;
        address = aAddress;
        city = aCity;
        state = aState;
        zip = aZip;
        phone = aPhone;
    }

    // Accesor Functions
    string getLastName() const
    {
        return lastName;
    }

    string getFirstName() const
    {
        return firstName;
    }

    string getAddress() const
    {
        return address;
    }

    string getCity() const
    {
        return city;
    }

    string getState() const
    {
        return state;
    }

    int getZip() const
    {
        return zip;
    }

    string getPhone() const
    {
        return phone;
    }

    // Mutator Functions
    void setLastName(string aLname)
    {
        lastName = aLname;
    }

    void setFirstName(string aFname)
    {
        firstName = aFname;
    }

    void setAddress(string aAddress)
    {
        address = aAddress;
    }

    void setCity(string aCity)
    {
        city = aCity;
    }

    void setState(string aState)
    {
        state = aState;
    }

    void setZip(int aZip)
    {
        zip = aZip;
    }

    void setPhone(string aPhone)
    {
        phone = aPhone;
    }
};

class CustomerData :public PersonData // CustomerData child class of PersonData base class
{
private:
    int customerNumber;
    bool mailingList;

public:
    CustomerData() // Default constructor
    {
        customerNumber = 0;
        mailingList = 0;
    }

    CustomerData(int cNum, bool mailL) // Constructor 1
    {
        setCustomerNumber(cNum);
        setMailingList(mailL);
    }

    // Accessor Functions for child class
    int getCustomerNumber() const
    {
        return customerNumber;
    }

    bool getMailingList() const
    {
        if (mailingList != 0)
        {

            cout << "On Mailing List!: ";
            return mailingList;
        }

        else (mailingList == 0);
        {
            cout << "Not on mailing list!: ";
            return mailingList;
        }
    }

    // Mutator Functions for child class
    void setCustomerNumber(int cNum)
    {
        customerNumber = cNum;
    }

    void setMailingList(bool mailL)
    {
        mailingList = mailL;
    }
};

class PreferredCustomer :public CustomerData // child class of CustomerData child class
{
private:
    double purchasesAmount;
    double discountLevel;
public:

    PreferredCustomer() // default constructor
    {
            purchasesAmount = 0;
            discountLevel = 0;
    }

    PreferredCustomer(string aLname, string aFname, string aAddress, 
        string aCity, string aState, int aZip, string aPhone, int cn, 
        bool ml, double Pa, double dl)   // constructor 1
    {
        double Pa;
        double dl;
    }

    // Mutator Functions
    void setPurchasesAmount(double Pa)
    {
        purchasesAmount = Pa;
    }

    // Accessor Functions
    double getPurchasesAmount() const
    {
        return purchasesAmount;
    }

    double getDiscountLevel() const
    {
        return discountLevel;
    }

    void addPurchase(double P) const
    {

    }
};

int main()
{
    CustomerData Cdata;       // for access of child class functions
    PersonData Pdata;         // for access of parent class functions
    PreferredCustomer PCdata; // for access of preferred customer class functions
    string     temp1;         // Temporary variable for string values
    int        temp2,         // Temporary variable for integer values
        max = 100,            // For-loop maximum loop value
        i;                    // i variable
    bool       temp3;         // Temporary variable for bool values

    for (i = 1; i <= max; i++)
    {
        // Input Data
        cout << "Please input first Name: ";
        getline(cin, temp1);
        Pdata.setFirstName(temp1);

        cout << "Please input last Name: ";
        getline(cin, temp1);
        Pdata.setLastName(temp1);

        cout << "Please input address: ";
        getline(cin, temp1);
        Pdata.setAddress(temp1);

        cout << "Please input city: ";
        getline(cin, temp1);
        Pdata.setCity(temp1);

        cout << "Please input state: ";
        getline(cin, temp1);
        Pdata.setState(temp1);

        cout << "Please input Zip code: ";
        cin >> temp2;
        Pdata.setZip(temp2);

        cin.ignore(); // discards unread char from cin

        cout << "Please input Phone Number: ";
        getline(cin, temp1);
        Pdata.setPhone(temp1);

        cout << "Enter 1 to be included in mail list," << endl;
        cout << "Enter 0 to not be included in mail list: ";
        cin >> temp3;
        Cdata.setMailingList(temp3);

        Cdata.setCustomerNumber(i); // set customer number

        cout << endl << endl;

        cout << "Name: " << Pdata.getFirstName() << ", " << Pdata.getLastName() << " \n";
        cout << "Customer Number: " << Cdata.getCustomerNumber() << "\n";
        cout << "Address: " << Pdata.getAddress() << "\n";
        cout << "City: " << Pdata.getCity() << "\n";
        cout << "State: " << Pdata.getState() << "\n";
        cout << "Phone: " << Pdata.getPhone() << "\n";
        cout << "Zip: " << Pdata.getZip() << "\n";
        cout << Cdata.getMailingList() << "\n";

        cout << endl << endl;
        cin.ignore(); // discards unread char from cin
    }

    char c;
    cin >> c;

    return 0;
}




How function calls handle scope across javascript "classes"

Context
I have a couple of javascripts that work together to make a game about a space ship.

  • Classes:
  • game.js, which maintains the game loops
  • ship.js, which defines the Ship class and methods

I am new to javascript and welcome logical (even pedantic) explanations. I am trying to understand the language better.

The Game class runs an instance of Phaser.game with Phaser.CANVAS. In the preload() and create() functions of Game, I instantiate the Ship class (ship = new(Ship()); So ship runs as an object in the game.js code. I use keyboard and mouse events to select functions to call. In this case, I am making a call to the Game.nextTurn() function by a mouse-click, which then calls Ship.nextTurn() and runs through the queue of ship.orders.

Details

In the Ship class I have defined a list of orders. It holds the game orders as arrays containing the function call and the args to pass.

this.orders = [[this.recharge,500], [this.reactor,500], [this.attack,200]];

My intention is to run these orders as part of ship.nextTurn by saying:

for (var i in this.orders) {
    this.orders[i][0](this.orders[i][1]);   //execute the orders with their args
}

Failure
However, when I do this, the orders fail because of a loss of scope somehow. Instead of the rechargeShields() function operating math on the this.systems.shields variable, like it does successfully if called directly from Game.function, it throws “this.systems is undefined.”

Questions
Is the correct way to fix this to pass this from the Game class to the Ship class as a way of maintaining scope from the event-handler?

Or did I break some good-coding-practice by calling functions from within an array?

Or is the issue that I defined this.orders = [this.function,args] instead of = [functions, args]?

Is it bad to call "this.function()" from within a method? Is calling "function()" better?

How should I have coded this differently and more elegantly?

Thanks for your time.




How to convert Swift "switch case is ..." block into loop oriented code?

I've got code that looks like this:

class Base {
    func launch(code1: Int, code2: Int) -> Bool { return false }
}

class A: Base {}
class B: Base {}
class C: Base {}

func trynext(obj: Base) -> Base? {
    switch obj {
    case is A: return B()
    case is B: return C()
    default: return nil
    }
}

Basically, I've got a lot (like 20) of subclasses of a common base class and I need to go through them one by one. These subclasses represent parsers and I'm trying them one after another to discover which parser correctly parses some data.

If I fail on a parse, I call a function trynext to return the "next parser" to try. You can imagine that this switch statement can get unyieldly if the constructors take arguments (all subclasses take the same arguments), and the more subclasses there are, etc.

Is there any way I can streamline this code by putting the classes into some sort of array and loop through it somehow? The idea is to reduce the boilerplate so that I end up using a structure like [A, B, C] that implies the subclasses to try and the order to try them in.




How to display the total price from class in driver?

Need to create a pizza parlor using java classes. I have already created a class and driver. Everything is working good, but I don't really understand how to display the total price and all other details of pizza that the user has ordered.

//Pizza class
import javax.swing.JOptionPane;

public class Pizza {

    private String crust;
    private boolean extraCheese;
    private boolean drink;
    private double price;
    private String [] toppings = new String[5];


    public Pizza() {//constructor

        this.crust = "Regular Crust";
        this.extraCheese = false;
        this.drink = false;
        this.price = 6.99;

    }

    public void setCrust(String crust) {//setter

        this.crust = crust;

    }

    public void setExtraCheese(boolean extraCheese) {//setter

        this.extraCheese = extraCheese;

    }

    public void setDrink(boolean drink) {//setter

        this.drink = drink;

    }

    public void setPrice(double price) {//setter

        this.price = price;

    }

    public String getCrust() {//getter

        return this.crust;

    } 

    public boolean getExtraCheese() {//getter

        return this.extraCheese;
    }

    public boolean getDrink () {//getter

        return this.drink;

    }


    public void selectCrust() {

        crust = JOptionPane.showInputDialog(null, "What type of crust do you want? \nOriginal \nThin \nCheese Stuffed \nDeep Dish \nPlease, type a full name of crust.");

    }

    public void addExtraCheese(String decision) {

        if(decision.equalsIgnoreCase("Yes")) {

            extraCheese = true;
            price = price+0.30;
            price = total1;

        }

    }

    public void addDrink (String decision) {

        if(decision.equalsIgnoreCase("Yes")) {

            drink = true;
            price = price+1.39;
        }

    }

    public void addToppings() {

        String [] toppingsList  = {"Pepperoni", "Onions", "Mushrooms", "Pepper", "Sausage"};
        String Answ;
        String Total = "";
        double price  = 0;
        int index = 0;
        do {
            String temp = "";
            toppings[index] = JOptionPane.showInputDialog(null, "Please, select toppings from the list: \nEnter the number \n1) "+ toppingsList[0] +"\n2) "+ toppingsList[1] +"\n3) "+ toppingsList[2] +"\n4) "+toppingsList[3]+"\n5) "+toppingsList[4]);

            if (toppings[index].equals("1")) {
                temp = temp + toppingsList[0] + ", ";
                price = price+0.20;
            }       
            if (toppings[index].equals("2")) {
                temp = temp + toppingsList[1] + ", ";
                price = price+0.20;
            }   
            if (toppings[index].equals("3")) {          
                temp = temp + toppingsList[2] + ", ";
                price = price+0.20;
            }   
            if (toppings[index].equals("4")) {          
                temp = temp + toppingsList[3] + ", ";
                price = price+0.20;
            }
            if (toppings[index].equals("5")) {
                temp = temp + toppingsList[4] + ", ";
                price = price+0.20;
            }
            index++;
            Total = Total+temp; 
            Answ = JOptionPane.showInputDialog(null, "Would you like to add one more topping? \nYes/No");//asks if the user wants to select one more service
            } while (Answ.equalsIgnoreCase("Yes") );

        //JOptionPane.showMessageDialog(null, String.format("Chosen Toppings are: "+Total+" - $%.2f",price));
        public double getPrice() {//getter

        return this.price ;
    }
    }

}

Driver

import javax.swing.JOptionPane;

public class Driver {

    public static void main (String[] args) {

        Pizza NotRegular = new Pizza();


        double price;
        double TotalPrice;
        JOptionPane.showMessageDialog(null, "Welcome to our Pizza Parlor!");
        NotRegular.selectCrust();
        String decision = JOptionPane.showInputDialog(null, "Would you like to add extra cheese?");
        NotRegular.addExtraCheese(decision);
        String decision1 = JOptionPane.showInputDialog(null, "Would you like to add drink?");
        NotRegular.addDrink(decision1);
        NotRegular.addToppings();


    }

}




Timer class in java

How do you create a monthly timer in java within a method without using the abstract class? Need to create it so five seconds is equal to one month! Any help would be greatly appreciated!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

import java.io.Serializable;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
//import javax.swing.Timer;

public class savingsAccount extends Object {

public void monthInterest(){
         int delay = 500;
            ActionListener taskPerformer;
        taskPerformer = new ActionListener(){
            public void actionPerformed(ActionEvent actEvt)
            {
               double workingOut = newBalance/100;
               workingOut = workingOut*3;
               workingOut = workingOut/12;
               newBalance= newBalance + workingOut;

                        }
        };
            new Timer (delay, taskPerformer.start);
    }
}




Getters and Setters Through EventObject - ClassCastException Same Class (Java)

I'm trying to get and set values of a class through an EventObject, but when casting the getSource() to the proper class, I run into a ClassCastException with the same class. How can I get around this while being able to get and set values through the EventObject?

Thank you, Hunter




Setting the value of an enum member of an object in an ArrayList

There are three parts to this. First I have an enum

public enum myType {TYPEA, TYPEB}

Then I have a class with myType as a member

public class myClass{
    myType t;
    int example;
}

Finally I have an ArrayList of that class

ArrayList<myClass> theArray = new ArrayList<myClass>();

I fill the list and then I want to go back and change the value of t of a certain element in theArray, theoretically with something like the following:

theArray.get(i).t = TYPEA;

but this gives me a compiler error: symbol cannot be found.

I've tried searching around for accessing members of objects in ArrayLists and of editing enum values, all to no avail. I'm not really sure where I'm going wrong.




GWT (model) interface/class

I am working on a GWT project and are a bit confused. Its a server/client project. I am handling the json with Autobean. Autobean needs to use interfaces to work. I haven't work so much with interfaces before and need some help. This is how the Autobean code:

interface User {
      int id();
      void setId(int id);
      String getUsername();
      void setUsername(String username);
    }

interface Result{
    List<User> getUsers();
    void setUsers(List<User> users);
}


interface Beanery extends AutoBeanFactory{
      AutoBean<User> makeBean();
      AutoBean<Result> makeBeans();
      }

To convert the json to the a List I do this.

AutoBean<Result> autoBeanCloneAB = AutoBeanCodex.decode(beanFactory, Result.class, "{\"users\": " + json + "}" );
List<User> users = autoBeanCloneAB.as().getUsers();

I am also having a User class, and I am unsure if this is unnecessary or how I should be handling this.

public class User {

private int id;
private String username;


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}


public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}
}

I have in all my earlier projects only been working with model classes and not interfaces. I have tried to read and seem to understand the concept of an interface, but in this case i cannot see any reason to use the User class when I have the User interface. What is the right approach? Is there any purpose of using a the User class, and if yes, please explain.

As usual. All help is appreciated




What is a common way to return the result of method call in Python class?

I have a class in Python which trains a model for the given data:

class Model(object):
    def __init__(self, data):
        self.data = data
        self.result = None

    def train(self):
        ... some codes for training the model ...
        self.result = ...

Once I create a Model object,

myModel = Model(myData)

the model is not trained. Then I can call the train method to initiate the training:

myModel.train()

Then myModel.result will be updated in-place.

Also, I could re-write the train method as:

def train(self):
    ... some code for training the model ...
    result = ...
    # avoid update in-place
    trainedModel = copy.copy(self)
    trainedModel.result = result
    return trainedModel

In this way, by calling myTrainedModel = myModel.train() I have a new object and the state of the original myModel is not changed.

My question is: Which is a more common way to store the returned result from a method in a class?




Unable to access nested property of array of static class

Givens:

  1. The class must be accessible from inside another class that must be static (no choice).
  2. The FOO class must be recursable supporting a nested array of a collection of items given the structure in the example.
  3. FOO must be serializable in full including all nested arrays and subsequent items inclusive to XML (without using fancy tricks -- just straight serialize to xml which seems to support only one class and will auto-find nested classes / structures accordingly)

The problem is I can not do the following as the properties of FOOTabItem are not accessible.

// can not be static
public class TestClass : SomeFancyInheritedObject { 

    // must be static
    public static void Test() {
        FOO.FOOTabItem bar = new FOOTabItem();

        bar.Count = 100;  // This is inaccessible
    }

}

This is the class code I am having trouble making the objects exposed from :

public static class FOO {
    public static int Money { get; set; }

    public static List<FOOTab> Tabs { get; set; }


    public static struct FOOTab {
        public static List<FOOTabItem> Items { get; set; }

        public static FOOTab TabInformation { get; set; }
    }

    public static struct FOOTabItem {
        public ItemInfo Item { get; set; }
        public int Count { get; set; }

    }

    public static FOO() {
        Tabs = new List<FOOTab>();
        Money = 0;
    }

}

I have also tried using nested classes instead of struct in FOO, however this resulted in FOO complaining that I can not use a class as an object parameter which is why I am using struct instead.

There are no syntax errors with this code. I can expose the properties/etc of FOO itself and instantiate new() of the structs, however I can not see the properties of the structs.

I believe this is likely a permissions issue (public / static / internal / etc), but I am unsure what exactly to do to correct this. I have searched SO and there are issues similar in nature however they do not offer any clear insight regarding nested Lists of objects inside static classes and how to properly access them from within other static classes.




how can determine id for last record view to user?

I need to determine last record in oracle that user view and when user login again, next record will be appear..any one have an idea to write code to do that?




Can constructor Initializer fields be called with class objects, c++

I have two classes, one "bank" and one "account". Account's constructor takes an int and a string. Bank is supposed to have two objects of type "account" in it. Is it possible to have the two "account" objects in the fields initializer list be allocated dynamically and not with static values?

Here is the code I have that allocates it statically

    class Bank
{
public:
    Bank():checkings( 500, "C"), saving( 300, "s"){} //predfined int and string

private:
    Account checkings;
    Account saving;

};

Is it possible to do this? I want the constuctor to have its fields allocated dynamically according to user input. I keep getting errors so I am unsure if my syntax is wrong.

    class Bank
{
public:
    Bank():checkings( int val, string s), saving( int val, string s){} //dynamic

private:
    Account checkings;
    Account saving;

};

Also, how do I call this type of constructor in the .cpp file?




Function Pointers in C++ Class Files

I've been trying to work with function pointers for quite a bit now, and to no avail. I've been working with a few friends to create a C++ 11 library to make creating ASCII games easier, and I've personally been working on creating a menu class. The beef of the class is complete, but one issue - I can't get the buttons to call functions. I always get the error:

terminate called after throwing an instance of 'std::bad_function_call'
what():  bad_function_call

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Obviously the error lies somewhere in the pointers, but I can't solve it for the life of me. Thanks for the help in advance.

Menu.h

#ifndef MENU_H
#define MENU_H

using namespace std;

#include <functional>
#include <string>
#include <map>

class Menu {
    public:
        int numberOfOptions;
        map<int, string> options;
        int currentSelection;
        string title;

        Menu();
        Menu(int initialNumberOfOptions, map<int, string> initialOptions, int initialSelection);
        void display();
        void waitForInput();
        void attachOptionAction(int option, void (*function)());

    private:
        map<int, void (*std::function<void()>)> optionActions;

        void executeOptionAction(int option);
};

#endif

Menu.cpp

#include "Menu.h"
#include <windows.h>
#include <iostream>
#include <conio.h>

Menu::Menu(int initialNumberOfOptions, map<int, string> initialOptions, int initialSelection) {
    title = "";
    numberOfOptions = initialNumberOfOptions;
    options = initialOptions;
    currentSelection = initialSelection;
}

void Menu::display() {
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0, 0});
    for(int i = 0; i < 10; i++) {
        cout << "          " << endl;
    }

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0, 0});
    if(title != "") {
        cout << title << endl << endl;  
    }

    for(int i = 0; i < numberOfOptions; i++) {
        if(i == currentSelection - 1) {
            cout << "[ " << options[i] << " ]" << endl;
        } else {
            cout << options[i] << endl;
        }
    }
    waitForInput();
}

void Menu::waitForInput() {
    char input;
    while(!kbhit());
        input = getch();
    if(input == 72 && currentSelection > 1) {
        currentSelection--;
    } else if (input == 80 && currentSelection < numberOfOptions) {
        currentSelection++;
    } else if (input == 13) {
        if(currentSelection == 1) {
            executeOptionAction(1);
        }
        return;
    }

    display();
}

void Menu::attachOptionAction(int option, std::function<void()> function) {
    optionActions[option] = function;
}

void Menu::executeOptionAction(int option) {
    (optionActions[option])();
}

test.cpp

#include "Menu.h"
#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <map>

void test() {
    cout << "Hello, World!";
}

int main() {
    map<int, string> options;
    options[0] = "Play";
    options[1] = "Help";
    options[2] = "Quit";
    Menu menu(3, options, 1);
    menu.title = "ASCII Game Library 2015";
    menu.display();

    void (*actionPointer)() = NULL;
    menu.attachOptionAction(1, (*actionPointer));

    return 0;
}




Using another static member value

There's an issue while using another static member value as key value pairs.

class NumberToWords
{

    public static $baseNumbers = [
        0 => "zero",
        1 => "nje",
        2 => "dy",
        3 => "tre",
        4 => "kater",
        5 => "pese",
        6 => "gjashte",
        7 => "shtate",
        8 => "tete",
        9 => "nente",
        10 => "dhjete",
    ];
}

and I'm trying to use some values from $baseNumbers into another static array, something like this :

public static $endsWith = [
        [10,"mbedhjete" ],
        [20,static::baseNumbers[1]],
    ];

What is the best workaround to this, as I am really trying to keep these arrays static because of the memory usage.




Typescript create a class from json

I have an interface IPost and a class Post, I want to create Post from json data, in Post constructor I get the json response where the interface IPost matches it.

I mean IPost interface is generated by this great tool json2ts

json2ts : generate TypeScript interfaces from JSON

import { IPost, Title, Guid, Content, Excerpt, Embedded, Links } from './Ipost.ts';

export class Post implements IPost {
    Id: number;
    Date: string;
    DateGmt: string;
    Guid: Guid;
    Modified: string;
    ModifiedGmt: string;
    Slug: string;
    Type: string;
    Link: string;
    Title: Title;
    Content: Content;
    Excerpt: Excerpt;
    Author: number;
    FeaturedImage: number;
    CommentStatus: string;
    PingStatus: string;
    Sticky: boolean;
    Format: string;
    Links: Links;
    Embedded: Embedded;

    constructor(json: any) {
        json.subscribe(res => {
            var jsonRes: any = res.json();
            Post = jsonRes;        //something like this
        });
    }
}

Can I assign the class Post to json directly since json is described the same as Post class!

constructor(json: any) {
        json.subscribe(res => {
            this = <IPost> res.json();       //this won't work
        });
    }

Is there any other ways than assigning each property to its peer from json?




JQuery How can I add a class to this?

I need to add a class to this line of code:

$(":text").after("<span>*</span>")

How do I add a class to this?




How to work with php classes and objects to communicate with mysql database - beginner in oop

I started learning resources from the web on object oriented programming not quite long. I have an application am working on that needs that bit of programming ability to protect against sql injections, session hijacking and brute force attacks, thereby, in the process capturing every possible information on who uses or attempted access to the application and where such activity was held. I have almost completed the application now with old fashioned php programming which I learnt on my own too. But the added functionality whereby the administrator of the application would have a tool to check the above information where necessary requires a good touch of OOP.

Here is my class file codes;

 <?php

class Database{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;

private $dbh;
private $error;

private $stmt;


public function __construct()
{
    // Set DSN

    $dsn = 'mysql:host=' . $this->host . ';dbname=' .               $this->dbname;

    // Set options
    $options = array(
    PDO::ATTR_PERSISTENT => true, 
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET utf8");

    try {
    $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    } catch (PDOException $e) {
    $this->error = $e->getMessage();
    }
}

public function query($query)
{
    $this->stmt = $this->dbh->prepare($query);
}

public function bind($param, $value, $type = null)
{
    if (is_null($type)) {
    switch (true) {
    case is_int($value):
    $type = PDO::PARAM_INT;
    break;
    case is_bool($value):
    $type = PDO::PARAM_BOOL;
    break;
    case is_null($value):
    $type = PDO::PARAM_NULL;
    break;
    default:
    $type = PDO::PARAM_STR;
            }
    }
    $this->stmt->bindValue($param, $value, $type);
}

public function execute(){
    return $this->stmt->execute();
}

public function resultset(){
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function single(){
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
}

public function rowCount(){
    return $this->stmt->rowCount();
}

public function lastInsertId(){
    return $this->dbh->lastInsertId();
}

public function beginTransaction(){
    return $this->dbh->beginTransaction();
}

public function endTransaction(){
    return $this->dbh->commit();
}

public function cancelTransaction(){
    return $this->dbh->rollBack();
}

public function debugDumpParams(){
    return $this->stmt->debugDumpParams();
}



}
 ?>

Then I have a test page for the database connection, created the database and attached a username and password to it. Now the details are well entered in the php page that includes the class below like this;

 <?php

// Include database class
include 'database.class.php';
// Define configuration
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "dbname");

// Instantiate database.
$database = new Database();

$database->query("CREATE TABLE mytable (
ID int(11) NOT NULL AUTO_INCREMENT,
FName varchar(50) NOT NULL,
LName varchar(50) NOT NULL,
Age int(11) NOT NULL,
Gender enum('male','female') NOT NULL,
PRIMARY KEY (ID)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ");

$database->query('INSERT INTO mytable (FName, LName, Age, Gender)      VALUES (:fname, :lname, :age, :gender)');

$database->bind(':fname', 'John');
$database->bind(':lname', 'Smith');
$database->bind(':age', '24');
$database->bind(':gender', 'male');

$database->execute();

echo $database->lastInsertId();
?>

But it throws the following error;

Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\folder\folder1\folder2\database.class.php on line 38.

Please, I need to know how I can use classes to perform operations in my database, so far, I conveniently achieve database connection and communication using MySQL_connect($dbserver, $dbroot, $dbpwd), MySQL_select_db($dbname,$query), MySQL_query("Statement"). Please I need a quick solution, as am currently carrying out more study and research on object oriented programming, but my project has to be finished on time. Thanks




Print function in a class not updating when boolean is updated

So I have a program for a class that Im writing that is all done except for the print function. The input function is correct and the boolean value will update in the input function but when i try to transfer to the print function it always prints (-) and if the user enters 'Y' then it is suppose to bypass the (-) and just print out the fraction. If anyone has anyway to get it to work, I feel like ive tried everything.

class fraction

{
    private:
        int numerator;
        int denom;
        bool positive;

    public:
        void inputFrac();
        void printFrac();

        fraction fracMult(fraction& b);
        fraction fracDiv(fraction& b);
        fraction fracAdd(fraction& b);
        fraction fracSub(fraction& b);
};

 void fraction::printFrac()
{
 if (positive=true)
    {
        cout << "-" << numerator << " / " << denom;
    }
    else
    {
        cout << "+" << numerator << " / " << denom;
    }
}
void fraction::inputFrac()
{    
    char tempchar1;
    fraction tempchar;

    cout<<"Please input the numerator ";
    cin>>numerator;
    cout<< "Please input the denominator ";
    cin>>denom;
    cout<<"Is the fraction positive? (Y or N) ";
    cin>>tempchar1;

    if((tempchar1=='Y'))
    {
        positive=true;

    }
    else
    {
        positive=false;
    }
}




Strange class error

I just don't understand why I get this error when I compile this single file main.cpp

#include <iostream>
#include <string>

class Hola{
    private:
        std::string saludo;
    public:
        Hola();
        void salut();
};

Hola::Hola(){}

void Hola::salut(){
    std::cout << "El string es " << saludo << std::endl;
}

int main{
    Hola greet;
    greet.salut();
}

And the compiling error when I type g++ -std=c++11 -o main main.cpp in the console is:

main.cpp:19:7: error: expected primary-expression before ‘greet’
  Hola greet;
       ^
main.cpp:19:7: error: expected ‘}’ before ‘greet’
main.cpp:19:7: error: expected ‘,’ or ‘;’ before ‘greet’
main.cpp:20:2: error: ‘greet’ does not name a type
  greet.salut();
  ^
main.cpp:21:1: error: expected declaration before ‘}’ token
 }
 ^

For whoever that asks, I made this simple program because I didn't understand another one much larger and tried to simplify so I get what's wrong.




Sorting an array of objects in a constructor

I am a bit stuck on this one and would appreciate some feedback. First of all is it even possible to sort a private member array of objects in the constructor? That is what I am trying to do like so (simplified code):

header file:

    class Hand : public Card
    {
      Card array[5]; //5 cards in each hand
     public:
      Hand(const Card& c1, const Card& c2, const Card& c3, const Card& c4, const Card& c5); //constructor prototype
      friend bool alpha(const Card& c1, const Card& c2); //sort the hand in order of value of the cards
};

cpp file:

Hand::Hand(const Card& c1, const Card& c2, const Card& c3, const Card& c4, const Card& c5)
{
  array[0] = c1;
  array[1] = c2;
  array[2] = c3;
  array[3] = c4;
  array[4] = c5;
  std::sort(array, array+5, alpha); //ERRORS RAISED HERE
}

bool alpha(const Card& c1, const Card& c2)
{
  int num1 = c1.getValue();
  int num2 = c2.getValue();
  return (num1 < num2);
}

The error is like so:

error: ‘alpha’ was not declared in this scope
   std::sort(array, array+5, alpha); 




Drop highest and lowest of an array in Java

right now I have a project dealing with fractions. The fractions need to be sorted and the highest and lowest are dropped, and then the middle fractions are added together. I have created the array, and done the sort. I am stuck as to how to drop the highest and lowest. Any help is appreciated, thanks!

public class Tester {

public static void main(String[] args) {
    double[] fractions = {(6/7),(2/4),(3/4),(3/18),(1/8),(10/20),(2/6)};
}
public static void selectionSort (int... arr)
{
    int i = 0, j = 0, smallest = 0;
    int temp = 0;

    for (i = 0;i<arr.length - 1;i++)
    {
        smallest = i;
        for (j = 1; j<arr.length - 1; j++)
        {
            if (arr[j]<arr[smallest])
                smallest = j;
        }
        temp = arr[smallest];
        arr[smallest] = arr[i];
        arr[i] = temp;

    }

    //Drop highest and lowest here
}
}




Read file of Student names and test scores

The goal of the project is to read from a file (info.txt), print the student name, their 3 test scores,and the total of the 3 scores. Additionally I need to include the number of students in the class, the average total score of the class, who got the maximum and minimum scores.

The info.txt file contains information on the students in the following format:

-number of students-
-student name-
-score1-
-score2-
-score3-
-student name-
etc..

The program should look like this when it is complete:

Enter file name: *user input file name*
Name              Score1    Score2    Score3    Total
-----------------------------------------------------
Andy Borders       200       250       400       850
John Smith         120       220       330       670
John Borell        250       250       500      1000
-----------------------------------------------------
Number of students in the class:                   3
Average total score of the class is:             840
John Borell got the maximum score of:           1000
John Smith got the minimum score of:             670

I am able to get all the student scores and the total of their scores to display. My issue currently is with finding the sum of the total scores, as well as finding the maximum and minimum total value and corresponding student name. Currently my sum equation is only returning the total score of the current student in the array.

public class Main {

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter file name: ");
    String fileName = keyboard.nextLine();

    try
    {
        File file = new File(fileName);
        Scanner fileScan = new Scanner(file);
        String numberOfStudents = fileScan.nextLine();              //Set Number of Students
        int numOfStudents = Integer.parseInt(numberOfStudents);     //Set Number of Students to int
        Student [] studentInfo = new Student[numOfStudents];

        //Set Student Name, Score 1, Score 2, Score 3 and send to Student class
        for (int i=0; i<numOfStudents; i++)
        {
            String studentName = fileScan.nextLine();
            String scoreOne = fileScan.nextLine();
            String scoreTwo = fileScan.nextLine();
            String scoreThree = fileScan.nextLine();
            studentInfo[i] = new Student (studentName, Integer.parseInt(scoreOne), Integer.parseInt(scoreTwo), Integer.parseInt(scoreThree));
        }
        fileScan.close();

        for (int i=0; i<numOfStudents; i++)
        {
            studentInfo[i].printname();
            studentInfo[i].printScores();   
        }
    } 
    catch (IOException e) 
    {
        System.out.println(
            "There was a problem reading from " + fileName);
    }
    finally 
    {

    }



}

}


public class Student {
private String studName;
private int score1;
private int score2;
private int score3;
private int total;
private int maximum;
private int minimum;
private int count;
private int sum;


public Student(String studentName, int scoreOne, int scoreTwo, int scoreThree)
{
    this.studName = studentName;
    this.score1 = scoreOne;
    this.score2 = scoreTwo;
    this.score3 = scoreThree;
    this.total = score1 + score2 + score3;
    sum = this.total + sum;
    count++;
}
public String getName()
{
    return studName;
}
public int getScoreOne()
{
    return this.score1;
}
public int getScoreTwo()
{
    return this.score2;
}
public int getScoreThree()
{
    return this.score3;
}
public int getTotal()
{
    total = score1 + score2 + score3;
    return this.total;
}
public void printname()
{
    System.out.print(studName);
}
public void printScores()
{
    System.out.printf("%5d %5d %5d %5d \n", score1,score2,score3, total);
}
public void printMax()
{

}
public void printSum()
{
    System.out.print(sum);
}
public void printCount()
{
    System.out.print(count);
}
}




C# - Student form, lists and serialization

I need help as soon as possible, I'm trying to create but without success.

Create form that shows "Student Color" in top bar Create Student Class Form should have controls to enter Students 1. Name - textbox 2. LastName - textbox 3. ListofColors

Colors should apear only once and order is important (1.Red, 2.Green, 3. Blue). Result should be Read only control that

will display result of operations

Then DO button tahat will serialize Student object.

ListofColors should not be serialized. When User restarts application last student should automatically appear in text

boxes and result dipslays - last student found

If file doesn't exist, or if there is any other error result displays - last student not found + error_detail




How to combine two methods in Java?

I have a class which reads from a sample of text and give a score to each word depending on the number of times that particular word is being repeated.

public class sum2 extends Activity{

private TextView text;
private TextView text2;
String sample = "(CNN) -- Despite some signs that the economy is on the mend, a lack of confidence from consumers and companies alike may hamper job growth during the next few months, economists say. Unlike this point last year, there are some indicators for optimism about the U.S. economy. The market seems to be on a rebound, with stock prices growing steadily since March. Meanwhile, the U.S. Gross Domestic Product, a broad indicator of the economy's strength, grew during the third quarter. It was the largest such growth since the summer of 2007. However, the unemployment rate is staggering. The national rate hit 10.2 percent last month, the first time it has been double digits in more than 25 years. The jobless rate increased in 29 states and the District of Columbia in October, according to a recent Labor Department survey. Thirteen states reported an unemployment rate above the current national rate. Track unemployment numbers by state and industry";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text2);
    text = (TextView)findViewById(R.id.news);
    text2 = (TextView)findViewById(R.id.occurence);


        String[] keys = sample.split(" ");
        String[] uniqueKeys;
        int count = 0;
        uniqueKeys = getUniqueKeys(keys);

        for(String key: uniqueKeys)
        {
            if(null == key)
            {
                break;
            }           
            for(String s : keys)
            {
                if(key.equals(s))
                {
                    count++;
                }               
            }


            //for testing purposes
            if(count >1 ){
                text2.append("Count of ["+key+"] is : "+count);

            }
            count=0;
        }       

}


    private static String[] getUniqueKeys(String[] keys)
    {
        String[] uniqueKeys = new String[keys.length];

        uniqueKeys[0] = keys[0];
        int uniqueKeyIndex = 1;
        boolean keyAlreadyExists = false;

        for(int i=1; i<keys.length ; i++)
        {
            for(int j=0; j<=uniqueKeyIndex; j++)
            {
                if(keys[i].equals(uniqueKeys[j]))
                {
                    keyAlreadyExists = true;
                }
            }           

            if(!keyAlreadyExists)
            {
                uniqueKeys[uniqueKeyIndex] = keys[i];
                uniqueKeyIndex++;               
            }
            keyAlreadyExists = false;
        }       
        return uniqueKeys;
    }

}

This class works perfectly by giving me results of number of repeated words in the text sample.

Then I wrote another class which reads from a text file and store each sentence in the text file in an array.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sum3);
    BufferedReader reader = null;

    try {
         reader = new BufferedReader(
                    new InputStreamReader(getAssets().open("inputNews.txt")));

         String line;



         List<String> sentence = new ArrayList<String>();
            while ((line = reader.readLine()) != null) {               
                sentence.add(line.split("\\.\\?\\!\\r\\n\\t+")[0] + " ");
                //adds functionality

            }
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //log the exception
                }


}
    //TextView output= (TextView) findViewById(R.id.summtext3);
    //output.setText((CharSequence) text);

}


}

I am planning to combine these two classes so the program can read from a text file that is being saved in the work space and identify sentences with repeated words and give it a score. Then the sentences with scores more than 1 will be displayed on the screen. What would be the best way to achieve this?




Python Qt4 classes & QTGui Windows part 2 (HashSplat)

I modifyed your code Python Qt4 classes & QTGui Windows, adding two more choises after pizza selection: pizza shape (tonda or rettangolare) and the qty. The ingredients qty for pizza tonda should be multiplied x1 while for pizza rettangolare should be multiplied x1.5. And finally they should be multiplied x qty. I also added the two classes: tonda and rettangolare were I defined the multiplier. For quantity I also added a combobox but I think its not correct. Could you please help me once again? Thanks

import sys
from PyQt4 import QtGui, QtCore

class Pizza(object):
    '''Create a pizza'''

    def __init__(self):
        self.farina=0
        self.acqua=0
        self.lievito=0
        self.sale=0
        self.olio=0
        self.semola=0
        self.strutto=0
        self.manitoba=0
        self.moltiplicatore=0

        self.set_default_ingredients()
    # end Constructor

    @classmethod
    def default_ingredients(cls):
        '''Return the default ingredients for a pizza.'''
        return {'farina':0, 'acqua':0, 'lievito':0, 'sale':0, 'moltiplicatore':1}

    def set_default_ingredients(self):
        '''Set the default ingredients.'''
        self.farina=0
        self.acqua=0
        self.lievito=0
        self.sale=0
        self.olio=0
        self.semola=0
        self.strutto=0
        self.manitoba=0
        self.moltiplicatore=1
    # end set_default_ingredients

    def uscita(self):
        '''End of program.'''
        sys.exit(app.exec_())
    # end class Pizza

class Romana(Pizza):
    '''Create a special Romana Pizza.'''

    @classmethod
    def default_ingredients(cls):
        '''Return the default ingredients for a Romana Pizza.'''
        return {'farina':80, 'semola':20, 'acqua':57, 'lievito':0.171, 'sale':2.85, 'olio':2.85}

    def set_default_ingredients(self):
        '''Set the default ingredients for a Romana Pizza.'''
        self.farina=80
        self.semola=20
        self.acqua=57
        self.lievito=0.171
        self.sale=2.85
        self.olio=2.85

class Napoletana(Pizza):
    '''Create a special Napoletana Pizza.'''

    @classmethod
    def default_ingredients(cls):
        '''Return the default ingredients for a Romana Pizza.'''
        return {'farina':72, 'manitoba':48, 'acqua':72, 'lievito':0.216, 'sale':3.6, 'strutto':7.2}

    def set_default_ingredients(self):
        '''Set the default ingredients for a Romana Pizza.'''
        self.farina=72
        self.manitoba=48
        self.acqua=72
        self.lievito=0.216
        self.sale=3.6
        self.strutto=7.2

class Tonda(Pizza):

    @classmethod
    def default_ingredients(cls):
        '''Return the default moltiplicatore for Tonda Pizza.'''
        return {'moltiplicatore':2}

    def set_default_moltiplicatore(self):
        '''Set the default moltiplicatore for Tonda Pizza.'''
        self.moltiplicatore=2

class Rettangolare(Pizza):

    @classmethod
    def default_ingredients(cls):
        '''Return the default moltiplicatore for Teglia Pizza.'''
        return {'moltiplicatore':3}

    def set_default_moltiplicatore(self):
        '''Set the default moltiplicatore for Teglia Pizza.'''
        self.moltiplicatore=3


class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super().__init__()

        self.main_widg = QtGui.QWidget()
        self.main_layout = QtGui.QFormLayout()
        self.main_widg.setLayout(self.main_layout)
        self.setCentralWidget(self.main_widg)
        self.resize(550, 250)
        self.setWindowTitle("CALCOLATORE DOSI IMPASTO PER PIZZA ROMANA O NAPOLETANA")
        self.setWindowIcon(QtGui.QIcon('pizza.jpg'))

        self.current_pizza = Pizza()
        self.current_teglia = Tonda()

        '''Select type of Pizza'''
        self.pizza_type = QtGui.QComboBox()
        self.pizza_type.addItems(['Pizza', 'Romana', 'Napoletana'])
        self.pizza_type.currentIndexChanged.connect(self.select_pizza)

        '''Select baking tin: Tonda 30cm or Rettangolare 40x35cm'''
        self.teglia_type = QtGui.QComboBox()
        self.teglia_type.addItems(['Tonda 30cm', 'Rettangolare 40x35cm'])
        self.teglia_type.currentIndexChanged.connect(self.select_teglia)

        '''Select quantity of Pizza to preparare'''
        self.qta_type = QtGui.QComboBox()
        self.qta_type.addItems(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
        self.qta_type.currentIndexChanged.connect(self.select_qta)

        # Ingredients
        self.farina = QtGui.QLineEdit('0')
        self.farina.textChanged.connect(self.set_farina)
        self.acqua = QtGui.QLineEdit('0')
        self.acqua.textChanged.connect(self.set_acqua)
        self.lievito = QtGui.QLineEdit('0')
        self.lievito.textChanged.connect(self.set_lievito)
        self.sale = QtGui.QLineEdit('0')
        self.sale.textChanged.connect(self.set_sale)
        self.olio = QtGui.QLineEdit('0')
        self.olio.textChanged.connect(self.set_olio)
        self.semola = QtGui.QLineEdit('0')
        self.semola.textChanged.connect(self.set_semola)
        self.strutto = QtGui.QLineEdit('0')
        self.strutto.textChanged.connect(self.set_strutto)
        self.manitoba = QtGui.QLineEdit('0')
        self.manitoba.textChanged.connect(self.set_manitoba)
        self.moltiplicatore = QtGui.QLineEdit('0')
        self.moltiplicatore.textChanged.connect(self.set_moltiplicatore)

        # Actions
        self.quit_btn = QtGui.QPushButton("Uscita")
        self.quit_btn.clicked.connect(self.uscita)

        # Layout
        self.main_layout.addRow('Seleziona tipo Pizza', self.pizza_type)
        self.main_layout.addRow('Seleziona tipo Teglia', self.teglia_type)
        self.main_layout.addRow('Seleziona Quantità\n\n\n', self.qta_type)
        self.main_layout.addRow('Farina (W240)', self.farina)
        self.main_layout.addRow('Manitoba', self.manitoba)
        self.main_layout.addRow('Semola rimacinata grano duro', self.semola)
        self.main_layout.addRow('Acqua', self.acqua)
        self.main_layout.addRow('Lievito di Birra', self.lievito)
        self.main_layout.addRow('Olio', self.olio)        
        self.main_layout.addRow('Strutto', self.strutto)

        self.main_layout.addRow(self.quit_btn)
    # end __init__

    def select_pizza(self, idx):
        if self.pizza_type.currentText() == 'Pizza':
            self.current_pizza = Pizza()
        elif self.pizza_type.currentText() == 'Romana':
            self.current_pizza = Romana()
        else:
            self.current_pizza = Napoletana()
        self.set_values()
    # end select_pizza

    def select_teglia(self, idx):
        if self.teglia_type.currentText() == 'Tonda 30cm':
            self.current_teglia = Tonda()
        else:
            self.current_teglia = Rettangolare()
        self.set_values()
    # end select_teglia

    def select_qta(self, idx):
        pass
        #self.qta_type

    def set_values(self):
        '''Set the values from the current pizza.'''            
        self.farina.setText(str(self.current_teglia.moltiplicatore))
        self.acqua.setText(str(self.current_teglia.moltiplicatore))
        self.lievito.setText(str(self.current_teglia.moltiplicatore))
        self.sale.setText(str(self.current_teglia.moltiplicatore))
        self.olio.setText(str(self.current_teglia.moltiplicatore))
        self.semola.setText(str(self.current_teglia.moltiplicatore))
        self.strutto.setText(str(self.current_teglia.moltiplicatore))
        self.manitoba.setText(str(self.current_teglia.moltiplicatore))

    def set_farina(self, val):
        self.current_pizza.farina = val
    def set_acqua(self, val):
        self.current_pizza.acqua = val
    def set_lievito(self, val):
        self.current_pizza.lievito = val
    def set_sale(self, val):
        self.current_pizza.sale = val
    def set_olio(self, val):
        self.current_pizza.olio = val
    def set_semola(self, val):
        self.current_pizza.semola = val
    def set_strutto(self, val):
        self.current_pizza.strutto = val
    def set_manitoba(self, val):
        self.current_pizza.manitoba = val
    def set_moltiplicatore(self, val):
        self.current_teglia.moltiplicatore = val

    def uscita(self):
        self.current_pizza.uscita()
# end class MainWindow

app=QtGui.QApplication(sys.argv)
main=MainWindow()
main.show()
sys.exit(app.exec_())




Should I put these functions in a standalone .h file?

I have a project which includes 2 files: main.cc and header1.h. While main.cc instantiates a class "className" and calls the member functions of it, the header file includes definition of the class.

main.cc:

#include <header1.h>
int main(){
    className classobject();
    classobject.function1();
    ...
    }
}

header1.h:

class className{
   public:
   className();
   void function1();
   ...
}

double className::function1(){
    double function2(){
    ...
    }
}

With this, I met an error which says:"a function definition should not be placed before '{' token.

So I decided to put the definition of function2 outside of the class, and put it in a standalone .h file. In that way, my project would include 3 files, namely: main.cc, head1.h and function2.h file:

main.cc:

#include <head1.h>
int main(){
...
}

head1.h:

#include <function2.h>
class className{
...
}

function2.h:

double function2(){
...
}

Although function2 can also be defined as the class member function so that it can be moved out of function1 while inside the class, I want to know whether the above mentioned treatment is leagal. Besides, does the creation of header files have some implicit rules established by usage (common treatment)?

Could anyone give some comments? Thanks in advance.




Xml class as Object C# [duplicate]

This question already has an answer here:

is it possible to use a class created by xsd.exe or by paste to XML as class (VS13), as a normal object? The situation is this, I have a WebService(WS) that receives an Xml and returns an answer (captain obvious). The xsd as 2000+ lines, so I would like to be able to work with this class that was created and when I wanted to send the info I would serialize it again and send it.

The problem is that when I do the class foo = new class() it's empty/null, no error is given except the NullReferenceException. For what I can understand the problem should be coming from the constructor. The empty constructor is created but as no parameters.

So my question is how can I use the class as a normal one, because 2000+ lines file as a lot of attributes that I would like to avoid to be rewritten. What kind of constructor do I have to write or method to generate\create the object.




why i should use classes in python or need to use the classes. anyone has best topic on python please help me

why i should use classes in python or need to use the classes. anyone has best topic on python please help me




Get class context from another class in android?

I want to get this Code from another class that i named Class2 into my main class named Drawings:

final LinearLayout lm = (LinearLayout) findViewById(R.id.Liner);
final ArrayList<String> Teams = new ArrayList<String>();

                TextView[] myTextViews = new TextView[2];
                final TextView tv1 = new TextView(this);
                tv1.setText(Teams.get(0) + " vs " + Teams.get(1));
                myTextViews[0] = tv1;
                lm.addView(tv1);

is there anyone to Help me that how can i get Class2 with that code and use into my main class?




Rewrite Product List Related class (1.9)

I'm struggling with the following thing. Because I would like to write my own kind of filter for Related Products, I will have to rewrite the class "Mage_Catalog_Block_Product_List_Related". While there has been proven the class I had to rewrite is being called, I cannot seem to edit anything inside the protected function "_prepareData". It isn't being called.

The situation currently: I have a class named "My_Module_Block_Catalog_Product_List_Related" which is extending the class "Mage_Catalog_Block_Product_List_Related". I have copied the protected function "_prepareData()" from the original class (app/code/core/Mage/Catalog/Block/Product/List/Related.php). But this function is not being called. If I test my class (if it is being called) by adding the following line of code:

public function __construct() {
    $this->_prepareData();
}

and I add an echo to the protected function "_prepareData()" I can see my text is being echo'd correctly. However, the rest of the protected function "_prepareData()" is being ignored. Also, if I remove the construct, the text will not be echo'd anymore.

I would like to show you my class and the original class.

My class

class My_Module_Block_Catalog_Product_List_Related extends Mage_Catalog_Block_Product_List_Related {

    protected $_itemCollection;


    protected function _prepareData()
    {
        echo 'Test';
        $product = Mage::registry('product');
        /* @var $product Mage_Catalog_Model_Product */

        $this->_itemCollection = $product->getRelatedProductCollection()
            ->addAttributeToSelect('required_options')
            ->setPositionOrder()
            ->addStoreFilter()
        ;


        if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
            Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
                Mage::getSingleton('checkout/session')->getQuoteId()
            );
            $this->_addProductAttributesAndPrices($this->_itemCollection);
        }
//        Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_itemCollection);
        //Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);
//NOTICE THE COMMENTED LINE ABOVE

        $this->_itemCollection->load();

        foreach ($this->_itemCollection as $product) {
            $product->setDoNotUseCategoryId(true);
        }

        return $this;
    }
}

The class I am extending

class Mage_Catalog_Block_Product_List_Related extends Mage_Catalog_Block_Product_Abstract
{
    /**
     * Default MAP renderer type
     *
     * @var string
     */
    protected $_mapRenderer = 'msrp_noform';

    protected $_itemCollection;

    protected function _prepareData()
    {
        $product = Mage::registry('product');
        /* @var $product Mage_Catalog_Model_Product */

        $this->_itemCollection = $product->getRelatedProductCollection()
            ->addAttributeToSelect('required_options')
            ->setPositionOrder()
            ->addStoreFilter()
        ;

        if (Mage::helper('catalog')->isModuleEnabled('Mage_Checkout')) {
            Mage::getResourceSingleton('checkout/cart')->addExcludeProductFilter($this->_itemCollection,
                Mage::getSingleton('checkout/session')->getQuoteId()
            );
            $this->_addProductAttributesAndPrices($this->_itemCollection);
        }
//        Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_itemCollection);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($this->_itemCollection);

        $this->_itemCollection->load();

        foreach ($this->_itemCollection as $product) {
            $product->setDoNotUseCategoryId(true);
        }

        return $this;
    }

    protected function _beforeToHtml()
    {
        $this->_prepareData();
        return parent::_beforeToHtml();
    }

    public function getItems()
    {
        return $this->_itemCollection;
    }

    /**
     * Get tags array for saving cache
     *
     * @return array
     */
    public function getCacheTags()
    {
        return array_merge(parent::getCacheTags(), $this->getItemsTags($this->getItems()));
    }
}

I hope someone is able to help. Thanks!




Is there a way to assert that an element does not have a class?

I want to create a selector that will check that a specific element does not have a class at all.

I have this selector (Groovy) ->

selector = $('span', text: 'Walrus').parent().children("h5", class: notContains("disabled"))

This won't work because It's expecting the element to have a class, and for the class to not be 'disabled'.

Not looking for workaround answers, just curious if there's any way to do this in any language.




dimanche 29 novembre 2015

python, modifying classes instanses

I have a small class:

import pickle
import shelve

class Base:

    def __init__(self, userid, username, pic_list=[]):
        self.userid=userid
        self.pic_list=pic_list
        self.username_list=[username]
        self.username=self.username_list[-1]

    def pic_add(self, pic):
        self.pic_list.append(pic)

if __name__ == '__main__':

    path="D:/"

    db = shelve.open(path+'test_base')

    db['111']=Base('111','111name',[4,5,6])
    db['111'].pic_add('123dsf')

    print (sorted(db['111'].pic_list))

    db.close()

I want to append '123dsf' to pic_list of class instanse "111". But the result I get is:

[4, 5, 6]
[Finished in 0.3s]

I want to receive [4, 5, 6, 123dsf]. What am I doing wrong?

Thanx.




Goto statement in class file for loop of java

I was analysing the jar file, i see one line in class as below:

for (Iterator i = val.getparts(); i.hasNext(); goto 135)

whats the goto statement is?

can we write go to in for loop?

what does this mean?




TypeError: 'str' object is not callable ... in OOP

So Im just learning how to integrate two classes in one call and I keep getting the error on the print statement: TypeError: 'str' object is not callable. Do I need to create a str contructor? Or do I need to intergrate the two classes into one?

class Election:

    def __init__(self, place, ballot):
        self.place=place
        self.ballot=ballot

    def place(self):
        return self.place

    def getBallot(self):
        return self.ballot

    def getContest(self,number):
        if self.ballot[number]:
            return self.ballot[number]
        else:
            return False

    def size(self):
        return len(self.ballot)

    def addContest(self,Contest):
        self.ballot=self.ballot.append(Contest)
        return self.ballot.get(Contest)

class Contest:

    def __init__(self, position, cands):
        self.position = position
        self.cands = {"Jones":0,"Smith":0}

    def getPosition(self):
        return str(self.position)

    def getCandidates(self):
        return str(self.cands)

    def getTally(self,candidate):
        return self.cands[candidate]

    def addTally(self,candidate,n_votes):
        self.cands[candidate]=self.cands[candidate]+n_votes
def main():
    elect = Election('TestTown', [
        Contest('Senator', ['Jones', 'Smith']),
        Contest('Mayor', ['Anderson', 'Green'])])

    print(elect.place())
    elect.getContest(1)# --> <Election object at 0x7f4b359cf5d0>
    elect.getContest(1).getTally('Anderson')# --> 0

main()




Passing an object as parameter to a method (Java)

Main File

My class

The problem I am encountering is that when I attempt to compile all my program it tells me it cant find all the variables in line 17 of my main file.

I must pass the object to the printmovieinfo method.




Error while overloading <<. What am I doing wrong here?

I am learning C++ and I am working on overloading <<. I am using the below code to print the time from class. It seems to be working with friend function but when I use without friend, it seems to be causing the error "No match for operator<<". What am I doing wrong here? Below is my code:

#include <iostream>

using namespace std;

class Time
{
private:
    int hour;
    int minute;
    int second;

public:
    Time(int hh, int mm, int ss)
    {
        second = ss%60;
        mm +=ss/60;

        minute = mm%60;
        hh +=mm/60;

        hour = hh;
    }

    ostream& operator<<(ostream &out);  //overloading << function declaration
};

ostream& Time::operator <<(ostream &out) // overloading << function definition
{
    out << "Time - " << hour << ":" << minute << ":" << second;

    return out;
}

int main()
{
    using namespace std;

    Time tm(10,36,60);
    cout << tm;

    return 0;
}




pythonic class instance attribute calculated from other attributes

I have a class instance with attributes that are calculated from other attributes. The attributes will change throughout the life of the instance. All attributes are not necessarily defined when the object is initialized.

This is a simple example, the calculations have numerous input variables ("a" below) and calculations ("b" & "c").

a = something
b = function of a (a+5)
c = function of a and b (a*b)

I've tried numerous implementations. Here is a decent one to communicate my intention.

 class CalcAttr(object):

    def __init__(self):
        self._a = None
        self._b = None
        self._c = None

    @property
    def a(self):
        return self._a
    @a.setter
    def a(self,value):
        self._a = value

    @property
    def b(self):
        self.calc_b()
        return self._b

    @property
    def c(self):
        self.calc_c()
        return self._c


    def calc_b(self):
        self._b = self._a + 5

    def calc_c(self):
        self._c = self._a * self._b

def test():
    abc = CalcAttr()
    a = 5
    return abc.c

Note: t.c works if I first call t.b first.

> >>> t=abc.test()
> >>> t.c Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "abc.py", line 22, in c
>     self.calc_c()   File "abc.py", line 29, in calc_c
>     self._c = int(self._a) * int(self._b) TypeError: int() argument must be a string or a number, not 'NoneType'
> >>> t.b 10
> >>> t.c 50
> >>>

Keep in mind most of the real calculations are dependent on multiple attribures (5-10 input variables & as many calculated ones).

My next iteration will include a "calculate_model" function that will populate all calculated attributes after checking that all inputs are defined. Maybe that will be the pyhonic answer?

Thanks!




Class Forward Declaration C++

I was following a tutorial on the Observer Pattern and I came across the following problem.

Namely, I have the following base classes:

class Subject;
class Observer;

Next, I want to define two more classes

class StockGrabber: public Subject {
    //...
    //the constructor involves a StockObserver object
    StockGrabber(StockObserver so){....};

}
class StockObserver: public Observer {
    //...
    StockObserver(StockGrabber sg) {....};
}

Is there any way I could use forward declaration so that StockGrabber would know that StockObserver exists? Given their interdependence, I couldn't just swap the positions of the two classes.

How should I go about solving this issue? (the original tutorial was written in Java, but I'm trying to implement it in C++) Thank you!




Apply CSS to nested HTML code

So, I have this code in "index.html" file:

<div id="Vsebina">
<div class="Slika"></div>
<div id="Prvi" class="Vrh">
<h2>Odstavek 1</h2>
<p><span class="Lorem">Lorem ipsum</span> dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis .</p>
</div>

I have a stylesheet linked to this html document and I am wondering how I can change the text inside class "Lorem". I have tried typing in my CSS file:

#Vsebina #Drugi .Vrh .Lorem{
    text-transformation: uppercase;
}

Nothing happens. If anyone can help me I would be very grateful, thanks.




Does "python closure" apply to function object?

I have 2 py files in the same folder (IDE Pycharm) :

module1.py contains:

def test_func():
    return "test_func"

class test_class(object):
    def __init__(self):
        self._test = test_func()

driver.py contains:

from module1 import test_class
obj = test_class()
print obj._test

I was expecting the the driver.py to fail with as the class instantiation requires the test_func() to be in scope. to my surprise it didn't fail. I am not sure why (in fact there are a few posts in SO asking about how to make function globally available to be used inside of class). is there such thing as "closure" on function object?

Thanks Casbby




C++ unresolved external symbol

So I am making a dynamic array from an input file using pointers. The function below is called when the user enters an index value. It is supposed to find the value in the dynamic array based on the index the user enters. However every time I attempt to run the program on visual studio 2013, I keep getting an unresolved external error. I did some research using google, since I have dealt with unresolved externals before. However, I am a rather new programmer and I suspect it may have something to do with my function headers or class definitions since one of my errors said this..

Error   1   error LNK2019: unresolved external symbol "public: __thiscall collection::collection(void)" (??0collection@@QAE@XZ) referenced in function "public: __thiscall derivedcollection::derivedcollection(void)" (??0derivedcollection@@QAE@XZ)   C:\Users\Nathan Drieling\Documents\Visual Studio 2013\Projects\Program4-NathanDrieling-w853922\Program4-NathanDrieling-w853922\derivedcollection.obj

I am also getting this error about an unresolved external...

Error   2   error LNK1120: 1 unresolved externals   C:\Users\Nathan Drieling\Documents\Visual Studio 2013\Projects\Program4-NathanDrieling-w853922\Debug\Program4-NathanDrieling-w853922.exe    1

Now here is my code starting with the collection header:

#ifndef Collection_H
#define Collection_H
class collection{
public:
    collection(); // default constructor
    virtual void add(int value) = 0; //adds the value to the array
    virtual void remove(int index) = 0; //removes and item from the appropriate index location
    virtual void print() = 0; //prints item of the array comma seperated. 
    virtual int get(int index) = 0; //gets item at a particular index.
    virtual int sum() = 0; //gets the sum of the array
    virtual int size() = 0; //gets the size of the array
};
#endif

Now here is the derived function header derivedcollection and cpp:

  #include "Collection.h"
    #ifndef derivedcollection_H
    #define derivedcollection_H
    class derivedcollection: public collection{
    public:
        derivedcollection(); // default constructor
        virtual void add(int value); //adds the value to the array
        virtual void remove(int index); //removes and item from the appropriate index location
        virtual void print(); //prints item of the array comma seperated. 
        virtual int get(int index); //gets item at a particular index.
        virtual int sum(); //gets the sum of the array
        virtual int size(); //gets the size of the array
    };
    #endif
#include "derivedcollection.h"
#include "Collection.h"
#include <fstream>
#include <iostream>
using namespace std;
derivedcollection::derivedcollection()
{
    // default constructor
};
void derivedcollection::add(int value){
    //adds the value to the array
    int *pointer; 
    pointer = new int[value];
    delete pointer;
};
void derivedcollection::remove(int index){
    //removes an item from the appropriate index location
    int *length = 0;
    for (int i = index; i < index; i++)
    {
        index = index + 1;
        length[index - 1];
        delete length;
    }
};
void derivedcollection::print(){
    //prints item of the array comma seperated.
    int item = 0;
    fstream indata;
    indata.open("data4.txt");
    do {
        indata >> item;
        cout << item << " , ";
    } while (true);
};
int derivedcollection::get(int index)
{
    //gets item at a particular index. returns an int variable
    int *indexpointer;
    int item = 0;
    indexpointer = new int[item];
    int counter = 0;
    fstream indata;
    indata.open("data4.txt");
    for (int i = 0; i < index; i++)
    {
        indata >> indexpointer[item];
        counter++;
        if (counter = index){
            cout << "the item at the index entered is " << item;
        }
        else
            cout << "error";
    }
    return item;
};
int derivedcollection::sum(){
    //gets the sum of the array. returns an int variable
    int item = 0;
    int sum = 0;
    fstream indata;
    indata.open("data4.txt");
    do {
        indata >> item; 
        sum += item;
        cout << sum;
    } while (true);
    return sum;
};
int derivedcollection::size(){
    //gets the size of the array. returns an int variable
    int item = 0;
    int size = 0;
    fstream indata;
    indata.open("data4.txt");
    do {
        indata >> item;
        size += size + 1;
        cout << size;
    } while (true);
    return size;
};

I know for a fact that the error is not coming from my main. So what could be causing this error? I also know this may be considered a duplicate but I would still appreciate any help. Thanks.




How do I get private data from the member functions? c++

I am doing the Big c++ 2nd edition questions and I am on classes, I am stuck on a question. Basically I have to classes one called "person" and one called "Pemployee", I need to write the member functions of "Pemployee".

They gave me the declarations I need to implement the definitions.

What I don't get how to do is write call name, since it needs to call the private variable "person_data" which is a person object, I cannot access the string name directly but the member function of "person" has a "get_name" function which returns void, I dont understand how to get a string returned if I cannot return from the other definition.

Here are the two classes.

class Person
{
public:
    Person();
    Person(string pname, int page);
    void get_name() const;
    void get_age() const; //returns void
private:
    string name;
    int age; // 0 if unknown
};

class PEmployee
{
public:
    PEmployee();
    PEmployee(string employee_name, double initial_salary);
    void set_salary(double new_salary);
    double get_salary() const;
    string get_name() const; //assuming I need to call person get_name
private:
    Person person_data;
    double salary;
};

So once again, how do I call the "Pemployee" get_name to return the string name of the person_data private variable




Read file of Student names and test scores, multiple outputs [duplicate]

This question already has an answer here:

The goal of the project is to read from a file (info.txt), print the student name, their 3 test scores,and the total of the 3 scores. Additionally I need to include the number of students in the class, the average total score of the class, who got the maximum and minimum scores.

The info.txt file contains information on the students in the following format:

  • number of students-
  • student name-
  • score1-
  • score2-
  • score3-
  • student name-

etc..

The program should look like this when it is complete:

Enter file name: user input file name

Name Score1 Score2 Score3 Total

Andy Borders 200 250 400 850

John Smith 120 220 330 670

John Borell 250 250 500 1000

Number of students in the class: 3

Average total score of the class is: 840

John Borell got the maximum score of: 1000

John Smith got the minimum score of: 670

My main issue is when i try to print the studentInfo array, the output comes out as:

Student@33909752

Student@55f96302

Student@3d4eac69

I would like to know how to fix this issue, the rest I feel confident enough to attempt on my own.

    public class Main {

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter file name: ");
    String fileName = keyboard.nextLine();

    try
    {
        File file = new File(fileName);
        Scanner fileScan = new Scanner(file);
        String numberOfStudents = fileScan.nextLine();              //Set Number of Students
        int numOfStudents = Integer.parseInt(numberOfStudents);     //Set Number of Students to int
        Student [] studentInfo = new Student[numOfStudents];

        //Set Student Name, Score 1, Score 2, Score 3 and send to Student class
        for (int i=0; i<numOfStudents; i++)
        {
            String studentName = fileScan.nextLine();
            String scoreOne = fileScan.nextLine();
            String scoreTwo = fileScan.nextLine();
            String scoreThree = fileScan.nextLine();
            studentInfo[i] = new Student (studentName, Integer.parseInt(scoreOne), Integer.parseInt(scoreTwo), Integer.parseInt(scoreThree));
        }
        fileScan.close();

        for (int i=0; i<numOfStudents; i++)
        {
            System.out.println(studentInfo[i]);
        }
    } 
    catch (IOException e) 
    {
        System.out.println(
            "There was a problem reading from " + fileName);
    }
    finally 
    {

    }
}




    public class Student {
private String studName;
private int score1;
private int score2;
private int score3;
private int total;
private String maximum;
private String minimum;


public Student(String studentName, int scoreOne, int scoreTwo, int scoreThree)
{
    this.studName = studentName;
    this.score1 = scoreOne;
    this.score2 = scoreTwo;
    this.score3 = scoreThree;
}
public String getName()
{
    return studName;
}
public int getScoreOne()
{
    return this.score1;
}
public int getScoreTwo()
{
    return this.score2;
}
public int getScoreThree()
{
    return this.score3;
}
public void printname()
{
    System.out.println(studName);
}
}




How to Dynamically create a CSS class using AngularJS

I have an Angular JS web site where I am using data from an API that I want to use to dynamically create a CSS class. This CSS class will then format other data from the API being displayed in an Angular JS page.

For example, is there a way for Angular JS $scope data to be created in the Controller while processing the API data and then on the corresponding .html view, use this $scope data to dynamically create a CSS class ... By the way, $scope data cannot be used inside the HTML 'STYLE' tag, because the bracket characters ('{' and '}') are treated as 'STYLE' characters, so it does not allow '{{' and '}}' to expand the value of a $scope variable.




get strings from other classes java

Just need someone to quickly show me how I can get the macAddress in the Address class to generate in the Network device class, thanks.

Address class

public class Address {

public static void main(String args[]){
Random rand = new Random();

    String result1 = String.format("%x",(int)(Math.random()*100));
    String result2 = String.format("%x",(int)(Math.random()*100));
    String result3 = String.format("%x",(int)(Math.random()*100));
    String result4 = String.format("%x",(int)(Math.random()*100));
    String result5 = String.format("%x",(int)(Math.random()*100));
    String result6 = String.format("%x",(int)(Math.random()*100));

String macAddress = (result1 + ":" + result2 + ":" + result3 + ":" + result4 + ":" + result5 + ":" + result6);
}
}

NetworkDevice class

public class NetworkDevice {
//get it to generate a new address from address class and print it out


public static void main (String args[]){
    Address thisAddress = new Address();
    System.out.println(thisAddress);

}
}




Writing a Tweet Class in Python

I need some help in how to write this class for an assignment, specifically on how to write the get_age method. Here are the instructions:

Requirements Tweet Class Write a class named Tweet and save it as a file named Tweet.py. The Tweet class
should have the following data attributes: author To store the name of whoever is making the tweet. __text To store the tweet itself. __age To store the time when the tweet was created. The Tweet class should also have the following methods: __init This method should take two parameters, the author and text of the tweet.
It should create __author
and __text based on those parameters
and it should create __age based on the current time.

get_author Returns the value of the __author field. get_text Returns the value of the __text field. get_age This method calculates the difference between the current time and the value of the __age field. It should return a string based on the age of the tweet.

For example, this method should return the following:

30s if the tweet was posted 30 seconds ago 15m if the tweet was posted 15 minutes ago 1h if the tweet was posted 1 hour, 10 minutes, and 42 seconds ago * Note that the string returned from __get_age is only concerned with the largest unit
of time. If the tweet is 0 to 59 seconds old, the value returned from __get_age will
end with an “s” for “seconds”. If the tweet is some number of minutes old, it will end with an “m” and ignore the seconds. Likewise, if the tweet is 1 or more hours old, it
will ignore both the minutes and seconds. To work with time, you’ll need to use Python’s time module. The documentation for that module is available here: http://ift.tt/Y4w3lh




Call requires permission which may be rejected by user error

enter image description here

how can i handle this error? I'm triying to get location every 10 seconds, it get a location first but it does not refresh it it always same location.




Call derived class method when upcasted [duplicate]

This question already has an answer here:

Right now I have a hierarchy as follows (-> means parent of )

LSystem -> DLSystem -> Tree -> MonopodialTree
                            -> TernaryTree

And I have a function substitute which is defined in LSystem as follows and given a minimal implementation that LSystem, DLSystem and Tree use.

virtual void substitute(Symbol s, std::vector<Symbol> &string);

Next, MonopodialTree and TernaryTree override the definition of substitute.

The problem arises because I want to have a std::vector<Tree> (with both Monopodial and Ternary) and iterate through it calling substitute for each one of them.

However, they both call LSystem's substitute function instead of their own substitute function, what am I missing?




Making a fraction from two arrays in Java

Right now I am working on a project that will add fractions. I have two arrays, one for the numerator and one for the denominator. How would I use those two arrays to form a fraction? I have tried making a new method and dividing the two arrays and that did not work. Any help is appreciated, thanks! This is my code:

import java.util.Scanner;

public class Fraction {
private int numerator;
private int denominator;
private double ratio_value;

private void setNumerator()
{
    numerator = 1;
}

private void setDenominator()
{
    denominator = 1;
}

private void setRatio_Value()
{
    ratio_value = 1.0;
}

public void getNumerator()
{
Scanner k = new Scanner (System.in);
int numer [] = new int [7];

for (int i = 0; i<numer.length;i++)
{
    System.out.println("Enter the numerator of 7 fractions: ");
    numer[i] = k.nextInt();
}

}

public void getDenominator()
{
    Scanner k = new Scanner (System.in);
    int denom [] = new int [7];

    for (int i = 0; i<denom.length;i++)
    {
        System.out.println("Enter the denominmator of 7 fractions: ");
        denom[i] = k.nextInt();
    }
}

}




Nested class, implemented interface object

I want to create object KalkulatorI.AccumulatorI in JUnit test case. When I create Kalkulator.Accumulator it's ok (Kalkulator.Accumulator t2 = new Kalkulator().new Accumulator()). How can I create such a interface object? I tried:

KalkulatorI.AccumulatorI t = new KalkulatorI.AccumulatorI();

or

KalkulatorI.AccumulatorI t = new KalkulatorI().new AccumulatorI();

but it doesn't work.

AccumulatorI.java

public interface AccumulatorI {
    public int getValue();
    public void setValue(int acc);
}

KalkulatorI.java

public interface KalkulatorI {
    public void setAccumulatorA(AccumulatorI a);
    public void setAccumulatorB(AccumulatorI a);
}

Kalkulator.java

public class Kalkulator implements KalkulatorI {

    private AccumulatorI AA;
    private AccumulatorI BB;

    class Accumulator implements AccumulatorI{
        private int acc;

        public int getValue(){
            int res = this.acc;
            return res;
        }

        public void setValue(int acc){
            this.acc=acc;
        }
    }

    public void setAccumulatorA(AccumulatorI a){
        this.AA=a;
    }
    public void setAccumulatorB(AccumulatorI a){
        this.BB=a;
    }
}




Is there any way in java to limit a pakage's visibility to only some other pakage

I have 2 pakages > work and utils, utils I use for stuff that I need to do in classes in work, Classes and methods of work are the ones I want to make available to users who will run this jar, but I dont want them to access the classes and methods of util. If I make them public, users will be able to see all the methods in util, otherwise I wont be able to use them in 'work'. If I make them in a single package there will be too many classes in one package , so if there's a work around please help. I saw similar questions here as well but I didn't find any answers except to document this to client was the best I could find. Or if someone can suggest a better design for this.




Why do global variable get initialized by class in another source file?

For example, I have 2 sources with a class and a static function in each. Both classes, functions and global variables has same names: (I added functions only for comparision..)

//A.cpp
#include <stdio.h>

static bool FooFunc() { printf("Hello from function in A!\n"); return true; }

class FooClass
{
public:
    FooClass() { printf("Hello from class in A!\n\n"); }
};

static bool fooFunc = FooFunc();
static FooClass fooClass;

and

//B.cpp
#include <stdio.h>

static bool FooFunc() { printf("Hello from function in B!\n"); return true; }

class FooClass
{
public:
    FooClass() { printf("Hello from class in B!\n\n"); }
};

static bool fooFunc = FooFunc();
static FooClass fooClass;

Result:

Hello from function in A!
Hello from class in A!

Hello from function in B!
Hello from class in A!

Is class in 'B.cpp' gets ignored somehow? If so, shouldn't compiler give me some error or warning? I tried 'g++' and 'clang' compilers, same behavior.




C# How to list all classes in the System namespace [duplicate]

This question already has an answer here:

The list is on MSDN, which is what I was looking for.

How do I list the classes of a namespace programmatically?

This seems to be a duplicate of this thread, however the following code yields no result:

using System;
using System.Linq;
using System.Reflection;

namespace ListClassesInNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            string @namespace = "System";

            var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsClass && t.Namespace == @namespace
                    select t;
            q.ToList().ForEach(t => Console.WriteLine(t.Name));
            Console.ReadLine();
        }
    }
}

This code yields no result:

var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"System")).ToList();




How do you transfer a variable defined in the main method of one class to another?

I have seen this done in many programs but I cant seem to follow the programming logic.

Lets say you have a simple class, ClassB. And in ClassB's main method you define an integer variable:

public class B {
    public static void main(String[] args) {
        int stuff = 333;
    }
}

How can you transfer the variable to a different class, say ClassA, to be used.

public class A {
    public static void main(String[] args) {    
        System.out.println(stuff);
    }
}

Can someone please explain this to me in simple terms. I've been trying to learn this for 2 hours and cant wrap my head around it.