jeudi 30 juin 2016

How do I use named constructors in C++ using constructor delegates?

Say I have a constructor and a delegated constructor

SomeClass(const std::string&& _name) : obj_needs_construction(100), name(_name) {}
SomeClass(const std::string& _name) : SomeClass(_name) {}

But both are using the same type, I've seen many solutions but they all seem to operate because they make different types but that won't work in my situation. How can I solve this?


Is that possible to get value from List

I have a question for example code below :

  1. player.cs

        using UnityEngine;
        using System.Collections;
        using System.Collections.Generic;
        public class player {
            public List<item> items = new List<item> (); // Here
            public player () {
  2. inventory.cs

        using UnityEngine;
        using System.Collections;
        using System.Collections.Generic;
        using UnityEngine.UI;
        public class inventory : MonoBehaviour {
            public List<GameObject> slotsx = new List<GameObject> ();
            public player Player;
            public GameObject slots;
            itemDatabase database;
            // Use this for initialization
            void Start () {
                int slotAmount = 0;
                database = GameObject.FindGameObjectWithTag ("itemDatabase").GetComponent<itemDatabase> ();
                //Generate the Slot and Slot Name;
                for(int i = 1; i <= 24; i++) {
                    GameObject Slot = (GameObject) Instantiate(slots);
                    Slot.GetComponent<slotScript>().slotNumber = slotAmount;
                    Player = new player();
                    Player.items.Add(new item()); // This Work
                    Player.items[i] = database.items[i];
                    addChilParent (this.gameObject,Slot);
           = "slot-" + i;
  3. slotScript.cs

        using UnityEngine;
        using System.Collections;
        using UnityEngine.UI;
        using UnityEngine.EventSystems;
        using System.Collections.Generic;
        public class slotScript : MonoBehaviour, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler, IDragHandler {
            public item itemx;
            public int slotNumber;
            inventory inventoryx;
            player Player;
            // Use this for initialization
            void Start () {
                inventoryx = GameObject.FindGameObjectWithTag ("inventory").GetComponent<inventory> ();
                itemImage = gameObject.transform.GetChild (0).GetComponent<Image> ();
                amount = gameObject.transform.GetChild (1).GetComponent<Text> ();
                Debug.Log ("ItemName : " + inventoryx.Player.items [1].itemName); // This Work
                Debug.Log ("ItemName : " + Player.items [1].itemName); // Why This Not Work ???

As you can see in file player.cs i have declare a list variable with this code :

        public List<item> items = new List<item> (); // Here

and then in file inventory.cs i have add the items inside the List variable with this code :

            Player = new player();
            Player.items.Add(new item()); // This Work
            Player.items[i] = database.items[i];

Until here this all work.

and in the slotScript.cs file i want to debug.log the list items from player.cs with this code :

        Debug.Log ("ItemName : " + inventoryx.Player.items [1].itemName); // This Work

This is also work, but i try a different and short code with this code :

        Debug.Log ("ItemName : " + Player.items [1].itemName); // Why This Not Work ???

Why thats not work ? Any Idea ?


Wrong class passed into class function

I am writing a program which has a Settings class that manage the settings in the program. There is a SettingDialog function in it that shows up the option window and a lang_register function that does some other things. However, when I call the SettingDialog function in the main window, it says that the class is a ImageMenuItem object and it has no attribute lang_register. But if I manually call the SettingDialog function manually and print its class, it says that it is a Settings class, which is what I expected. Can anyone tell me what's happening? The code is here. The error happens at line 110. Thanks very much.

code example to create a shape with events vba

Could you please help me with a example of class or simple module code that creates a shape with events in vba? basically what i need is to create a button but from zero using a shape but with a click and mouseover envents.

Creating object using user input to store in Java array

My assignment is the following:

"Create a program that keeps track of specific information for Students. The information stored should be the following: First Name, Last Name, Major, GPA, UIN, NetID, Age, Gender, For this simple program we will only need to store 10 students in an array. Your students should be stored in an object called Student. You should be able to add, display and remove Students in the array. You will be submitting 2 files for grading: and"

I'm currently stuck with how to create the student object with all of the separate attributes by using the users input.

My code so far:

 public class StudentData{
            public static void main(String[] args){ 
                //Creating an info class for the student object
                StudentData studentA = new StudentData((strFirstName, strLastName, strMajor, 
                intGPA, intUIN, strNetID, intAge, strGender));​

                String strFirstName;
                String strLastName; 
                String strMajor;
                int intGPA;
                int intUIN;
                String strNetID;
                String strAge;
                String strGender;

                    // Capturing user input into class attributes
                    Scanner input = new Scanner(;
                    System.out.println("Enter First Name");
                    strFirstName = input.nextLine();

                    System.out.println("Enter Last Name");
                    strLastName = input.nextLine();

                    System.out.println("Enter Major");
                    strMajor = input.nextLine();

                    System.out.println("Enter GPA");
                    intGPA = input.nextLine();

                    intUIN = input.nextLine();

                    System.out.println("Enter netID");
                    strNetID = input.nextLine();

                    System.out.println("Enter Age");
                    strAge = input.nextLine();

                    System.out.println("Enter Gender");
                    strGender = input.nextLine();

Translate package+class name to .class filename

I'm writing a program which analyzes .class files. I want to attach package and class name to my output.

My plan is to write a function which takes the package and class name as input and finds the corresponding .class file (so the user doesn't have to enter that as well, and can't get it wrong), where 'find' should be read as 'give me some data I can use as arguments for BCEL's ClassParser constructor' (either a filename, or a name of a zip file and a name within the zip file).

How do I go about that? Does java come with something which does that? I understand name resolution to be done in the context of a CLASSPATH, so the user should probably supply one of those as well; that's fine.

Note: solutions should not execute any code from the .class file. Just the bytes, ma'm ;-)

Translate package+class name to .class filename

I'm writing a program which analyzes .class files. I want to attach package and class name to my output.

My plan is to write a function which takes the package and class name as input and finds the corresponding .class file (so the user doesn't have to enter that as well, and can't get it wrong), where 'find' should be read as 'give me some data I can use as arguments for BCEL's ClassParser constructor' (either a filename, or a name of a zip file and a name within the zip file).

How do I go about that? Does java come with something which does that? I understand name resolution to be done in the context of a CLASSPATH, so the user should probably supply one of those as well; that's fine.

Note: solutions should not execute any code from the .class file. Just the bytes, ma'm ;-)

How to check if a class has any instance in Java?

is there a way to find out if there already exists any instances in Java?

How can I have this function if there is any instance of a certain class, it will return true and return false if not.


Assigning (instead of defining) a __getitem__ magic method breaks indexing

I have a wrapper class similar to this (strongly simplified) example:

class wrap(object):
    def __init__(self):
        self._data = range(10)

    def __getitem__(self, key):
        return self._data.__getitem__(key)

I can use it like this:

w = wrap()
print w[2] # yields "2"

I thought I could optimize and get rid of one function call by changing to this:

class wrap(object):
    def __init__(self):
        self._data = range(10)
        self.__getitem__ = self._data.__getitem__

However, I receive a

TypeError: 'wrap' object does not support indexing

for the print w[2] line with the latter version.

The direct call to the method, i.e., print w.__getitem__(2), works in both cases...

Why does the assignment version not allow indexing?

R loop to change class for many columns in many data frames

I have a list of tables

tablas<-list(ratingsRyUyM1, dfLikedSum,dfNotLikedSum,dfLikedQ, dfNotLikedQ)

And I want to convert 2 columns that I'm going to use in a join to characters. So I wrote:

for (i in tablas){
   for (j in c('movieId', 'userId')){
     i[, j]<-as.character(i[, j])}}

I run that and still get the columns as factors.

I also tried it with a function:

foo<-function(x){for (j in c('movieId', 'userId')){
        x[, j]<-as.character(x[, j])}}

And then:

lapply(tablas, foo)

I get:

> lapply(tablas, foo)





There is a code involves the Delegate Up, I hope I understand it right

Delegation is a new concept for me. To my understanding, it asks someone else to do some job for me. I then, delegate some tasks to him.

class Vehicle {
    var numberOfWheels = 0
    var description: String {
        return "\(numberOfWheels) wheel(s)"

class Bicycle: Vehicle {
    override init() {
        super.init() //# Delegate up
        numberOfWheels = 2

The code super.init() is a delegate up action in class initialization. The subclass initializer calls the initializer of the superclass first. The superclass' default initializer assigning the integer 0 to the variable numberOfWheels. This is Phase one initialization. After that, the overriding action of the subclass' initializer further customizes the variable by numberOfWheels = 2.

Question Is there any incorrectness of my understanding? and I hope the delegate up description I'm used here is correct.

Please correct any error and misunderstandings I have it here. Thanks

PHP, OOP: Why can't the array property of my class use properties & methods as values like an array outside of a class can?

So like the title says, I am having a hard time making an array property of one of my classes have it's values be declared as properties & methods.

I can successfully do this if the array is not a property of a class, but as soon as the array is dropped into a class, the script doesn't like those values, and throws me this error.

Fatal error: Constant expression contains invalid operations in C:\xampp\htdocs_webdev\repos\mcf\static\inc\classes\class.catalogue.php on line 17

I have both classes being included in a different .php called inc.classes.php. That file is then included in each page. Here is some code to better illustrate my issue,

Master Class File: inc.classes.php

// config
require_once('config/config.php'); // config file

// other tools
require_once(ROOT_DIR . 'inc/parsedown/Parsedown.php'); // tool that I am using for parsing .md files

// my classes
require_once(ROOT_DIR . 'inc/classes/class.vendor.php');
require_once(ROOT_DIR . 'inc/classes/class.catalogue.php');

Class A: class.vendor.php

class Vendor
  public $vendor = array(
    'foo' => array(
      'name' => 'Foo Inc.',
      'image' => (VENDOR_IMG . 'foo/foo-logo.png'),
    'bar' => array(
      'name' => 'Bar Co.',
      'image' => (VENDOR_IMG . 'bar/bar-logo.png'),

  public function get($data) {
    if (array_key_exists($data, $this->vendors)) {
      return $this->vendors[$data];
    } else {
      // throw error

  // Class methods...

Class B: class.catalogue.php

class Catalogue
  public $catalogue = array(
    '1' => array(
      $section = $markdown->text(file_get_contents(ROOT_DIR . catalogue/markdown/')),
      $link = 'catalogue/pdf/section1.pdf,
      $pdf = (ROOT_DIR . $link),
      'title' => 'Section One',
      'content' => mdReplace($section, $pdf, $link),
      'theme' => 'purple',
      'vendors' => array(
        1 => $vendor->get('foo'),
        2 => $vendor->get('bar'),
    // '2' ...

  // Class methods...

(mdReplace() is a small function located in a seperate php file called inc.functions.php. It's purpose is to replace a few keywords inside of the .md files that contain the sections' content.)

Apologies in advance if I am just blind as a bat right now and am missing something obvious.

MVC passing array of classes to view

I have a project I am working on in MS VS 2012. I have a class that pulls data down from a database and puts it into an array of classes. That part of the code works seamlessly. The part I am having issue with is getting the data to the view for display. It seems that from the controller you should have the ability to pass classes through but I have not found it.

In the model

    public Guid BoxGUID {get;set;}
    [Required(ErrorMessage="A box number is required")]
    public int BoxID { get; set; }
    public DateTime Date { get; set; }
    [Required(ErrorMessage="Please pick an option")]
    public string BCAppearance { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string BCTrash { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string BCPad { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string BCClean { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string BCStrap { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string BCDoc { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string BCMaint { get; set; }
    public string BCMaintNote { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string UBWrap { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string UBPiece { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string NPSec { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string NPDmg { get; set; }
    [Required(ErrorMessage = "Please pick an option")]
    public string NPHardware { get; set; }
    public string TruckNum { get; set; }
    public string Images { get; set; }
    public int CompletedFlag { get; set; }
    //odd items for manipulating data
    public string curDate { get; set; }
    public string boxGUIDString { get; set; }

int the db code section:

            public BoxInfo[] getBox(int count)
        string query = "select * from Box where CompletedFlag = '0'";
        BoxInfo[] boxInfo = new BoxInfo[count];

        //create boxinfo array
        SqlCommand cmd = new SqlCommand(query, oConn);
        SqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.Read())

            for (int i = 0; i < count; i++)
                boxInfo[i] = new BoxInfo();
               // string test = rdr[0].ToString();
                boxInfo[i].BoxGUID = new Guid(rdr[0].ToString());
                boxInfo[i].BoxID = (int)rdr[1];
                boxInfo[i].Date  = (DateTime)rdr[2];
                boxInfo[i].BCAppearance = rdr[3].ToString();
                boxInfo[i].BCTrash = rdr[4].ToString();
                boxInfo[i].BCPad = rdr[5].ToString();
                boxInfo[i].BCClean = rdr[6].ToString();
                boxInfo[i].BCStrap = rdr[7].ToString();
                boxInfo[i].BCDoc = rdr[8].ToString();
                boxInfo[i].BCMaint = rdr[9].ToString();
                boxInfo[i].BCMaintNote = rdr[10].ToString();
                boxInfo[i].UBWrap = rdr[11].ToString();
                boxInfo[i].UBPiece = rdr[12].ToString();
                boxInfo[i].NPSec = rdr[13].ToString();
                boxInfo[i].NPDmg = rdr[14].ToString();
                boxInfo[i].NPHardware = rdr[15].ToString();
                boxInfo[i].TruckNum = rdr[16].ToString();
                boxInfo[i].Images = rdr[17].ToString();
                boxInfo[i].CompletedFlag = 0;

        return boxInfo;

in the controller

    namespace BoxCheckInApp.Controllers
     public class AddBoxController : Controller
    // GET: /AddBox/
    public CodeDB D = new CodeDB();
    public CodeODB O = new CodeODB();
    public BoxInfo box = new BoxInfo();

    public ActionResult Boxes()
        int count = D.getRows();

        if (count != 0)
            BoxInfo[] myBoxes = new BoxInfo[count];
            myBoxes = D.getBox(count);

            return View();
            String noBoxes = "There are no incomlete boxes to edit";
            return View();

in the controller I need to pass myBoxes to the view. My boxes is a BoxInfo object Array. Each object is one row of the database.

How to access parent class from child class?

I'm trying to automate a form validation and db insertion process. In a particular part, I need to be able to access the parent class from the child class. To be exact, I need to access the parent class to access another child class.

I've tried to replicate the same structure I'm using in the actual code:

class Family {
    public function __construct($members = []) {
        foreach ($members as $member) {
            $this->$member[0] = new Member($member);
class Member {
    public $name;
    public $niisan;
    public function __construct($name = []) {
        $this->name = $name[0];
        if (count($name) > 1) {
    public function get_niisan($member_lookup) {
        $this->niisan = $this->name . " has a niisan named X";

$Winchesters = new Family([
    ["Sam", "Dean"],


object(Family)#1 (2) {
    ["Dean"]    => object(Member)#2 (2) {
        ["name"]    => "Dean"
        ["niisan"]  => NULL
    ["Sam"]     => object(Member)#3 (2) {
        ["name"]    => "Sam"
        ["niisan"]  => "Sam has a niisan named X"

What I want to do is create two subclasses in the main class. Order of the creation of subclasses matters. ["Sam", "Dean"] is dependant on ["Dean"], so ["Dean"] needs to be created first. Some of the properties of ["Dean"] will be used in ["Sam", "Dean"].

In JavaScript, I'd write it like this:

function Family(members) {
    var parent = this;
    for (var i = 0; i < members.length; i++) {
        this[members[i][0]] = new Member(parent, members[i]);

function Member(parent, name) {
    this.parent = parent; = name[0];
    this.niisan = "";
    this.get_niisan = function (lookup) {
        this.niisan = + " has a niisan named " + this.parent[lookup].name;
    if (name.length > 1) {

var Winchesters = new Family([
    ["Sam", "Dean"]

Passing the main object to each sub-object. PHP must have its own way to deal with this. I just don't know it.

Python: init not run when object is created

thing = Thing(arg1, arg2, arg3)

class Thing:
    def __init__(self, args.....):
          print "init start"
          self.logging = {}

          with open(name, 'r') as j_file:
             load and write to self.logging

          print "self.logging is:   ", self.logging

The thing is, nothing got printed, and self.logging apparently doesn't have any of the keys I've inserted.


How to avoid a long chain of getter calls in a swing gui MVC app?

I am student working on a personal java project (read: NOT homework) with a large GUI component and attempting to follow a MVC architecture. I am building up a complicated view using many nested JPanels with various layouts. The actionListeners for buttons in these panels are/will be implemented in a controller class that contains a reference to the model and the view. Each panel only contains a reference to its immediate child panels,so as it stands right now when the controller needs to update something in one of the deeply nested panels, it requires code like this:


which seems less than ideal. Some more pseudoish code of the whole system in question is below. I have omitted simple get methods from the code here, but all of my GUI component classes include get methods that return the reference to the child panels that they directly own.

How can this situation be improved while still obeying MVC?

The controller:

public class Controller implements ActionListener {

    private View view;

    public Controller(View view, Model model){
        this.view = view;
        this.model = model;

    private void updateOrderTable() {

        TableModel tableModel; //= **call model method to query db and generate a TableModel**  
        // This looks bad

The View:

public class View {
    // Setup stuff

    JFrame mainFrame = new JFrame();
    myCardLayoutPanel = new MyCardLayoutPanel ();\
    // add cardLayoutPanel to mainframe

Next layer:

public class MyCardLayoutPanel extends JPanel {

    receptionPanel = new ReceptionPanel();
    dataEntryPanel = new DataEntryPanel();
    // etc

    // Add all the panels to the layout

One more intermediate panel, which I will omit, follows the same pattern...and finally, the JPanel with the table in it.

public class OrderContentsPanel extends JPanel {

    private JTable table;
    private JScrollPane scrollpane;

    public OrderContentsPanel() {
        setLayout(new BorderLayout());
        scrollPane = newJScrollPane(table);
        add("Center", scrollPane) //

    public void updateTable(TableModel tablemodel) {

getting "Undefined variable" Error when getting data from database as LIKE filter [duplicate]

This question already has an answer here:

i have problem getting data from data base , this is my page code:


 * @author AmirMohammad
 * @copyright 2016

    if(isset($_GET['cat']) && ($_GET['cat'] !== null)){        
        $catQuery = mysql_query("SELECT * FROM posts WHERE category LIKE '{$_GET['cat']}'");        
            $catArrays = array();        
        while($catrow = mysql_fetch_array($catQuery)){
            $catArrays[] = $catrow;            
        foreach($catArrays as $cat){            
        $row = new Template("{$tpl_dir}/post.tpl");                            
        foreach ($cat as $key => $value) {
            $row->set($key, $value);
        $catTemp[] = $row;
        $runFunc = Template::merge($catTemp);                                            
} else {
    header('location: /');

the problem is when the category field is multiple (like : cat1,cat2) the page return

this error : Notice: Undefined variable: catTemp in C:\xampp\htdocs\wn-category.php on line 23

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\engine\template.class.php on line 27

and the class file code is :

    class Template {
       protected $file;
        protected $values = array();
        public function __construct($file) {
            $this->file = $file;
        public function set($key, $value) {
            $this->values[$key] = $value;
        public function output() {
            if (!file_exists($this->file)) {
                return "Error loading template file ($this->file).<br />";
            $output = file_get_contents($this->file);

            foreach ($this->values as $key => $value) {
                $tagToReplace = "[@$key]";
                $output = str_replace($tagToReplace, $value, $output);

            return $output;
        static public function merge($templates, $separator = "\n") {
            $output = "";

            foreach ($templates as $template) {
                $content = (get_class($template) !== "Template")
                    ? "Error, incorrect type - expected Template."
                    : $template->output();
                $output .= $content . $separator;

            return $output;
        public function newConnection($table,$name,$w,$wt){            
            $Query = mysql_query("SELECT * FROM {$table} WHERE {$w} = {$wt} ORDER BY id DESC");               
     $Arrays.$name = array();      
     while($row = mysql_fetch_array($Query,MYSQL_ASSOC)){
        $Arrays.$name[] = $row; 


i need your help!!!

how to use class method

im tring to use a method in my main and get "expression must have class type". i cant understan why i cant do such an easy command/ here is my main:

#include "stdafx.h"
#include "movement.h"
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void main()
    movement trackersList();
    int id;
    double a, b;

    cout << "enter tracker number, speed & course" << endl;
    cin >> id >> a >> b;

    trackersList.addRow(id, a, b);

in the class header i have

void addRow(const int& ID, const double& speed, const double& course);

what im missing here> thank you

How do i call a function within my class?

so basically, let's say i have a class like this:

class something:
 def __init__(self):
   '''Some stuff in here'''
 def some_function(self):
   ''' Some more stuff in the function'''
   def function_2(self,x):
     x = x + 10
     return x
   new_x = self.function(10)

but when i run my code, which is of the same format as the above, i get an error saying that there's a missing argument in the new_x = self.function(10)

So i tried removing the self, but that doesnt work either. So how do i use a function, in a function, in a class?

How can I create a c++ class diagram generator on ubuntu? [on hold]

On ubuntu, I want to create a diagram showing the relations between the classes. Is there any way I can automatically do this?

how to use vector and struct members in method

im new in c++ (and not to old in programming...) and i have problem with handling vectors and strucs in class. basically i have a vector and a array of pointers to struct members in the class and i want work on the in my methos but im doing something worng/

here is my movement.h

#pragma once
using namespace std;
class movement
    static const int MAX_ROW_PER_TRACKER = 100;
    static const int MIN_TO_START_CALC = 30;
    static const int MAX_TRACKERS = 20;

    struct tracker
        int id;
        double a[MAX_ROW_PER_TRACKER];
        double b[MAX_ROW_PER_TRACKER];
        double c;
    vector<int> trackersOrder[MAX_TRACKERS] = {};
    tracker* trackersArr[MAX_TRACKERS];

    void addRow(int a, int b, int c);

and my movement.cpp

#include "stdafx.h"
#include "movement.h"
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;


void movement::addRow(int id, int a, int b)
    int index;
    vector<int>::iterator searchID = find(trackersOrder.begin(), trackersOrder.end(), ID);
    if (searchID == trackersOrder.end())
        vector<int>::iterator freeLocation = find(trackersOrder.begin(), trackersOrder.end(), 0); 
        index = freeLocation - trackersOrder.begin();
        trackersOrder.insert(trackersOrder.begin + index, id);
        structArr[index] = new tracker;
        structArr[index]->id = id;
        structArr[index]->a[0] = a;
        structArr[index]->b[0] = b;
        structArr[index]->c = 0;



so when i send to method "addRow" id, and b i want to first check if i allready have this id in my vector (the vector just give me the index for the structs array) and if not then if put the id in the first empty place in the vector and on the structs array/ but from some reasin its look to me that the methid dont reconized the vector and the structs. can you help me understand why? p.s - i can bet that i have more mistakes in my code, its my firs try with pointers and ect. (im comming from the good life in Matlab) so i will be happy to learn on them also thank you very much!

Is that Possible To Add List

I have a simple questions.

I have two file script :

  1. Player.cs

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    public class player {
        public List<item> itemx = new List<item> (); // Here
  2. File Inventory.cs

            using UnityEngine;
            using System.Collections;
            using System.Collections.Generic;
            using UnityEngine.UI;
            public class inventory : MonoBehaviour {
                public player playerx;
                itemDatabase database;
                // Use this for initialization
                void Start () {
                    database = GameObject.FindGameObjectWithTag ("itemDatabase").GetComponent<itemDatabase> ();
                    //Generate the Slot and Slot Name;
                    for(int i = 1; i <= 24; i++) {
                        playerx.itemx.Add(new item()); // Here
                        playerx.itemx[i] = database.items[i]; // And Here

As you can see in player.cs file i have declare a list variable :

public List<item> itemx = new List<item> (); // Here

and in Inventory.cs file i want to add the value using :

playerx.itemx.Add(new item()); And Here

is that possible to save the value variable to player.cs file ?


Where is the Order and Export tab in Android Studio 2.x?

After updating Android Studio 2.1.2 apps running on my local device now fatal errors with "java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{today.trsc.songs/today.trsc.songs.MainActivity}: java.lang.ClassNotFoundException: Didn't find class". But the MainActivity is there in the IDE. Others with this problem suggested updating java libraries in "Order and Export" but that's an Eclipse feature; where is that in Android Studio 2.x? There is no "Properties" choice when right-clicking on Project.

Initialize two Python classes with same arguments, get different results

Objective: understand strange behavior regarding two classes initialized with identical arguments, and producing different results.


My project involves a Raspberry Pi 3 communicating with various sensors on an Arduino MEGA via serial (through the USB port) communication. The communication protocol is simple.

The Raspberry Pi sends two bytes:

  1. The address of the sensor (e.g. '\x04')
  2. A second empty byte that can contain additional commands (e.g. '\x00')

The MEGA waits for two bytes, and then replys with the requested information based on a large case/switch tree.

I have encapsulated the code for handling various sensors withing Python classes. The one that is giving me trouble is the Encoder() class. Here is a minimal example:

import serial

class Encoder(object):
    def __init__(self, hex_name):
        self.hex_name = hex_name

    def value(self):
        temp = hex_name + '\x00'
        return int(arduino.readline())

    if __name__ == '__main__':
        arduino = serial.Serial('/dev/ttyACMO', 115200)

        encoder_one = Encoder('\x03')
        encoder_two = Encoder('\x04')

        print encoder_one.value()
        print encoder_two.value()


I get nonsensical values from the encoders. Particularly concerning is that when I initialize both encoder with the same hex_name (i.e. '\x04'), I get different values from encoder_one.value() and encoder_two.value().


  1. Something about the class structure is wrong.

I had this working alright before I encapsulated it in a class. I wondered if I was assigning encoder_one and encoder_two to the same object or something silly like that.

I added a line just before return in value() that would print the hex_name (i.e. print self.hex_name). When I set both encoders to '\x04' I get the same non-alphanumeric character printed. When I set one encoder to '\x03' and the other to '\x04' I get two different non-alphanumeric characters--one being the character from the previous test.

  1. Frame-shift in the communication.

The MEGA is expecting two bytes. It waits for two bytes, sends the requested information, then clears the buffer. Is is possible that storing the hex values as string in my Python program, a extra byte is getting added when it performs arduino.write(). Something like a \n or other non-printable character.


I've put about three hours into this bug, and I think solving it requires some information about how classes work that I do not understand.

Python class variable getting overwritten by local variable even after implementing setter and getter functions

I have a sample payload as follows:


The logic of my code is to replace every value from the key value pairs in the above sample payload with ">qqqq, but one at a time. Below is my code. Please note that I have omitted the functions which were irrelevant to this question.

Also note that execution starts by calling loadRequest()

class XSSChecker(object):

    def setPayload(self,payload):

    def getPayload(self):
        """Note that the below print statement is added to show that
        self.payload is getting changed with each call to
        self.getPayload() in loop in iterator()"""
        print self.payload
        return self.payload

    def loadRequest(self):
        #have omitted the code to open the sample payload file
        for line in samplePayloadFile: 
            if (re.match(r'[{}]',line)):

    def iterator(self,localpayload):
        for i in localpayload:
            if isinstance(localpayload[i],dict):
                for j in localpayload[i]:

    def iterator1(self,localpayload,key):
        return localpayload

I have never used self.payload directly in my code except in the getter and setter functions. Still as I run this program, I get the following output:

{'existingGroupIds': [], 'existingUserIds': [], 'role': {'assetPermissions': [], 'name': 'a', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': [], 'existingUserIds': [], 'role': {'assetPermissions': [], 'name': 'a', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': [], 'role': {'assetPermissions': [], 'name': 'a', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': [], 'name': 'a', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': [], 'name': 'a', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': '">qqqq', 'name': 'a', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': '">qqqq', 'name': '">qqqq', 'clientId': 100, 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': '">qqqq', 'name': '">qqqq', 'clientId': '">qqqq', 'description': 'b'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': '">qqqq', 'name': '">qqqq', 'clientId': '">qqqq', 'description': '">qqqq'}, 'removedGroupIds': [], 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

{'existingGroupIds': '">qqqq', 'existingUserIds': '">qqqq', 'role': {'assetPermissions': '">qqqq', 'name': '">qqqq', 'clientId': '">qqqq', 'description': '">qqqq'}, 'removedGroupIds': '">qqqq', 'removedUserIds': [], 'addedGroupIds': [], 'addedUserIds': []}

..... and so on

The print statement for the above output is present in my getPayload function, which means what it should always print original sample payload. But instead, the loop in iterator function is overwritting the self.payload value even without directly accessing it, which I am not able to understand how. I am new to Python and with the concept of class in Python and I am unable to understand this.

Prepopulating instances in code for classes (Python)

I am trying to make it so that when I can run a function which would populate a class with a couple of instances which are written in the code.

class Pets(object):

  def __init__(self, name, scientific_name, feet_number, type)
    super(Pets,self).__init__() = name
    self.scientific_name = scientific_name
    self.feet_number = feet_number
    self.type = type

This is the point where I get stuck. I want to make a function which has a list of instances (Ex. a dog, a cat, a horse...) so that when the function is run those instances can already be accessed from the class.

How do I initialize the instance using only coding? Do I make an instance through a dictionary, or a list or do I just use a return method in a function?

Javascript event listener called with class method

So I have following code:

class SquareBlock {
    this.startPosition = rand(1, boardHeight - 3);
    this.block = [{x: 1, y: this.startPosition}];
    this.block.push({x: 1, y: this.startPosition + 1});
    this.block.push({x: 2, y: this.startPosition});
    this.block.push({x: 2, y: this.startPosition + 1});

    document.addEventListener('keydown', () => {return this.move();}, true);

    for(var n in this.block){
        fields[getFieldId(this.block[n].x, this.block[n].y)].hasBlock = true;
        pointColor(this.block[n].x, this.block[n].y, 'blue');


    for(var n in this.block){
        fields[getFieldId(this.block[n].x, this.block[n].y)].hasBlock = false;
        pointColor(this.block[n].x, this.block[n].y, 'transparent');
    for(var n in this.block){
        this.block[n].x += 1;
    for(var n in this.block){
        fields[getFieldId(this.block[n].x, this.block[n].y)].hasBlock = true;
        pointColor(this.block[n].x, this.block[n].y, 'blue');

    if(this.isSettledValidate() != 'stop'){
        setTimeout(() => {this.start()}, 100);

    if(this.block[2].x == boardWidth - 2 || this.block[3].x == boardWidth - 2){
        return 'stop';
    if(fields[getFieldId(this.block[2].x + 1, this.block[2].y)].hasBlock == true){
        return 'stop';
    if(fields[getFieldId(this.block[3].x + 1, this.block[3].y)].hasBlock == true){
        return 'stop';

        case 37:
        for(var n in this.block){
            if(this.block[n].y - 1 != 0){
                this.block[n].y -= 1;
        case 39:
        for(var n in this.block){
            if(this.block[n].y + 1 != boardHeight - 1){
                this.block[n].y += 1;


And I have problem with document.addEventListener in constructor. What I want to achieve is to move SquareBlock one space left or right with move() class method. When I use code "document.addEventListener('keydown', move, true)" square won't move because "this" in move function points at "document" object. When I tried to fix this with arrow function (as in code above), "this" correctly points at square object but then it won't move either because square object doesn't have "which" property and I can't use it to scan keycodes. Forgive me if it's dumb question with simple solution but I'm novice programmer. I've read related topic about this in event handlers but I couldn't find an ansewr there.

Eclipse Open Declaration opens class files instead of java

I have a multimodule Maven project in my eclipse, with around 40 projects. Navigation among classes was working fine within the same project and within different projects. However, this has stopped working and I don't know why. Now, Open Declaration is always opening the generated class files, under Maven dependencies, instead of the java ones, even to the java class that is right below the current one. All projects have the Maven's Workspace resolution enabled. Also, I still can open the java file with CTRL+SHIFT+T.

I've been googling and stackoverflowing, but the answers I found didn't help much

Any ideas? Thanks in advance

Instantiate a simple class.....?

I'm new to python, i just have some experience with java, where i do understand how to use classes and instantiate them. But i cant get it to work in python -.-

This is my code:

#! /usr/bin/python
#coding: utf8
import os,getpass

class RdpSession:

      serveraddress = ''
      username = ''
      password = ''
      domain = ''

      def __init__(self,serveraddress,username,password,domain):
           self.serveraddress = serveraddress
           self.username = username
           self.password = password
           self.domain = domain

      def main():
           s = 'terminal'
           u = 'username'
           p = 'password'
           d = 'domain'
           rdp = RdpSession(s,u,p,d)


How I understand, classes in python work:

I write a class with class ClassName Then I can assign some class variables like serveraddress,username,....

Then I write the init method, that gets called when I instantiate the Class. Is this already wrong?

And in my main method I can instantiate the Class with variable=ClassName(parameters from init)

Serialization: Dynamic class names

I have already tried various possibilites but maybe I am just to tired to see the solution -.-

I have an xml structure like this:


As you see there is variable number of surgeries. I have a class "surgery" containing the xml elements.

class Surgery
        public string date { get; set; }

        public string description { get; set; }

        public string ops301 { get; set; }

        public Surgery()

and a class diagnosis creating the structure by adding the surgery class to the constructor.


class Diagnosis
        public Surgery surgery

        public Diagnosis(Surgery Surgery)
            surgery = Surgery;

I need to be able to serialize the classname of the surgery dynamically by adding a number before serialization happens.

does anybody know a way to achieve that?

any help is really appreciated :)

Kind regards sandro

Python Class : passing self.var as default function argument?

Can you please tell me why this won't work ? While assigning num1 = self.var1 in function fiz, python says unresolved reference. why is that ?

class foo:
    def __init__(self):
        self.var1 = "xyz"

    def fiz (self, num1 = self.var1):

mercredi 29 juin 2016

Can I refer to a subclass in another subclass?

This is a somewhat general question.

If I am creating a class with functions in it can i refer to another function in that class?

For ex does this work:

class pythonExcelFunctions():

    def getSheetNumber(self, fileName, sheetName):

        workbook = xlrd.open_workbook(fileName, on_demand=True)

        for index, sheet in enumerate(workbook.sheet_names()):
            if sheet == sheetName:
                return index

    def createSheet(self, fileName, sheetName):

        rb = xlrd.open_workbook(fileName, formatting_info=True, on_demand=True)

        wb = xl_copy(rb)

        Sheet1 = wb.add_sheet(getSheetNumber(fileName, sheetName)

When to extend a class vs interfacing in PHP?

Say I'm creating a chest with a lock...


  class Lock
    public $locked = false;
    function lock()
      $this->lock = true;
    function unlock()
      $this->lock = false;

  class Chest extends Lock

  $myChest = new Chest;

Using Interfaces:

  interface Lock
    protected $locked;
    function lock();
    function unlock();
  trait LockTrait
    protected $locked = false;
    function lock()
      $this->lock = true;
    function unlock()
      $this->lock = false;
  class Chest implements Lock
    use LockTraits;
  $myChest = new Chest;

Using Class-Based Dependency Injection:

  class Lock
    public $locked = false;
    function lock()
      $this->lock = true;
    function unlock()
      $this->lock = false;

  class Chest
    protected $lock;
    function __construct($lock)
      $this->lock = $lock;

  $myChest = new Chest(new Lock);

There are differences in both implementation, and characteristics of the resulting object. Extending and using interfaces will result in Chest objects which have the properties and methods of the Lock class. Injecting a new instance of the Lock class into the constructor of the Chest class will result in a property of the Chest class being a lock.

It seems to me that the best way to create my Chest object is to inject a Lock instance into the Chest constructor. This leads me to a second question though. Where would I use interfaces and extensions?

The answer to that question seems to be, "When I have multiple classes that share similar characteristics!" I would then is the "is a" principle to abstract traits.

However, when should I extend, and when should I use interfaces? I can use many interfaces while I can only extend one class. Why ever extend? Why not just use interfaces?

Instantiated object variable visibility

This seems to be a simple problem to state, but I am unable to understand what the solution is. I have a screen class where the objects are basically x and y coordinates, font color, etc. All is working well, I can instantiate and use these objects.

Sometimes I need to change the color of the string that is being written to the screen. This is more of a "system call" that once done, sets all strings written after that. So each time I write to the screen, I am forced to first "set the text color". Or do I? I have a method, setValue: objA->setValue("1234", RED);

When the method gets this call, it will set the color of the screen write. Let's say objA just set the color RED. If another object needs to write to the screen, and it's the same color, I don't want to write that to the screen again as to reduce the number of writes to the screen. So, based on the last object's color, I want to update the screen text color (or not) In C, this of course would be the most evil static global. How can I do something similar in C++?


c++ how to access private class members and functions in program

How would I edit my code to allow for private class members, yet use the data from those private class members in my program? If I change the class members to private, the program does not function correctly. Other than that, everything in the program is working with them set to public.

code snippets:

#include <iostream>
#include <iomanip>

using namespace std;    

class allData {

public: char selection; 
    double r; 
    double centimeter; 
    double value; 
    double ConvertC (double value);
    double ConvertR (double value);
    double valueF (double value); 
    char selectionF (char selection); 

} allData;

int main() {

cout << "Enter C for converting your Feet to Centimeters.\n"
        "Enter R for converting your Inches to Centimeters.\n";

cin >> allData.selection; 

cout << "\nYou selected to convert to: " <<   
allData.selectionF(allData.selection) << ".\n\n"; 

cout << "Enter your starting value to two decimal places, and press 

cin >> allData.value; 

cout << "\nYou entered a starting value of: " << 
allData.valueF(allData.value) << ".\n\n"; 

//switch to decide which conversion function to use from the structure

switch (allData.selectionF(allData.selection)) {

    case 'c': { allData.ConvertC(allData.value);  
        cout << "Your Feet converted to Centimeters is: " << 
        allData.ConvertC(allData.value) << "\n\n"; 

    case 'C': { allData.ConvertC(allData.value);  
        cout << "Your Feet converted to Centimeters is: " << 
        allData.ConvertC(allData.value) << "\n\n"; 
    case 'r': { allData.ConvertR(allData.value);  
        cout << "Your Inches converted to Centimeters is: " << 
        allData.ConvertR(allData.value) << "\n\n"; 

    case 'R': { allData.ConvertR(allData.value);  
        cout << "Your Inches converted to Centimeters is: " << 
        allData.ConvertR(allData.value) << "\n\n"; 
   default: {cout << "You entered an invalid selection for your conversion"   

return 0; 


//Function definitions
double allData::ConvertC (double value) {
    centimeter = value * 30.48;
    return centimeter; 

double allData::ConvertR (double value) {
    r = value * 2.54; 
    return r; 
double allData::valueF (double value) {
    return value; 

char allData::selectionF (char selection) {
    return selection; 

//End of program.

How can I use another class in my PHP 5.6 __autoload() declaration?

I have a messageService class that I'm instantiating like this:

$messageService = new messageService();


I want to use the $messageService object in my __autoload method which looks like this:

function __autoload($className) {
    $fileName = "./classes/" . $className . ".class.php";
    $messageService->logNotice("Loaded File: " . $filename);


When I run the code I'm getting:

Notice: Undefined variable: messageService iin /var/www/html/beta.gmtools/api/index.php on line 17

Fatal error: Call to a member function logNotice() on null in /var/www/html/beta.gmtools/api/index.php on line 17

Which I'm assuming is because $messageService isn't in scope?

How can I resolve this?

Binary search tree, trying to implement a delete-node method, not understand basics

Been sitting with this for a while, if anyone of you got a clue, please help out. I have a binary search tree class done, and I wanna implement a remove function, after looking it up, I found one and I've tried to understand it, but I've realized that I simply cant. The code is looking like this:

class Treenode:
    def __init__(self,data,left=None,right=None):

    def __str__(self):
        return str(

    def delete(self):
        if self.left == self.right==None:
            return None
        if self.left==None:
            return self.right
        if self.right==None:
            return self.left
        if grandchild:
            while grandchild.right:
                child = grandchild
                grandchild = child.right
            child.right = grandchild.left
            self.left = child.left
        return self

class Bintree:
    def __init__(self):
        self.root = None

    def put(self,data):
        if self.root == None:
            self.root = Treenode(data)
        p = self.root
        while True:
            if data <
                if p.left == None:
                    p.left = Treenode(data)
                    p = p.left
            elif data >
                if p.right == None:
                    p.right = Treenode(data)
                    p = p.right
            elif data ==
                return False

    def exists(self, data):
        return finns(self.root, data)

    def isempty(self):
        return self.root == None

    def height(self):
        def hp(tree):
            if tree is None:
                return 0
                return 1 + max(hp(tree.left), hp(tree.right))
        return hp(self.root)

    def printTree(self):

    def remove(self, data):
        if self.root and == data:  #self.root kanske inte behövs, undersök
            self.root = self.root.delete()
            parent = self.root
            while parent:
                if data <
                    child = parent.left
                    if child and data:
                        parent.left = child.delete()
                    parent = child
                    child = parent.right
                    if child and == data:
                        parent.right = child.delete()
                    parent = child

def skriv(tree):
    if tree == None:

def finns(roten, key):
    if roten == None:
        return False
    if key ==
        return True
    elif key <
        return finns(roten.left, key)
        return finns(roten.right, key)

I'm creating my binary search with this code:

from labb8test import Bintree

tree = Bintree()    

My problem is the delete-method under the Treenode class. Im trying to draw it on a paper, can someone please explain, how does the while-loop work? the grandchild.right, is that neccesary code since I have already defined them above... Thankful for any help at this point!

Enum Members conflict with class names

I recently produced a wierd set of errors when working on a little project. This was basically the code that caused it:

#include <memory>

enum derivedtype {B, C};

//abstract class
class A{};

class B : public A
class C : public A

int main()
    std::unique_ptr<A> myb(new B);
    std::unique_ptr<A> myc(new C);

Which produces this compiler error:

enumclasserror.cpp: In function ‘int main()’:
  enumclasserror.cpp:15:30: error: ‘B’ does not name a type
  std::unique_ptr<A> myb(new B);
  enumclasserror.cpp:16:30: error: ‘C’ does not name a type
  std::unique_ptr<A> myc(new C);

The fix was adding the class keyword after the new:

std::unique_ptr<A> myb(new class B);

Now the enum was included in the headerfile of the abstact class in the original code(which made it even harder to spot), but nevermind that; I could have never imagined that the members of an enum can cause the creation of an instance to fail. It literally took me hours to find that bug. Can anyone explain to me why that happens? Does new make any sense with enums?

Thanks in advance!

Adding controls to a new class

I have declared a class called SubjectRow, each instance of which has its own controls inherited from System.Windows.Forms.Control:

public class SubjectRow : Control
        static int counter = 0;
        public ComboBox subjectBox = new ComboBox();
        public Label maxBox = new Label();
        public TextBox nBox = new TextBox();
        public TextBox aBox = new TextBox();
        public TextBox mBox = new TextBox();
        public TextBox eBox = new TextBox();
        public TextBox cBox = new TextBox();

        public SubjectRow()
            subjectBox.Location = new Point(100, 300);

In my SubjectRow() method, you can see my attempt to make the ComboBox subjectBox visible on the form using new Point(left, top). However, this does nothing and the form is still blank on runtime.

I am pretty new to C#, but my understanding is that the SubjectRow() method is run whenever a new instance of class SubjectRow is created. So why does this not work? How can I have the subjectBox control appear on the form at a given location?

How do I connect two objects with a method to return a new object

I have 2 class objects A and B. Both contain an attribute called 'prob' (for probabillity). Now I want to write a Method, which connects both objects and creates a new one, with a defined attribute 'prob' with "


Here is my code:

PMF add(PMF pmf){
    for(int i=0; i<x; i++){
        for(int j=0; j<x; j++){

This is in my PMF class. I have defined in my other class (the one with the main method, it is called "Hund" ) some objects:

public class Hund {

public static void main(String[] args){
    PMF A= new PMF(6);
    PMF B= new PMF(6);
    PMF C= new PMF(6);
    A.setProb(1, 1);
    A.setProb(2, 1);
    A.setProb(3, 1);
    A.setProb(4, 1);
    A.setProb(5, 1);
    A.setProb(6, 1);


But now, it shows me an error "C cannot be resolved to a variable". How do I make it return a PMF-Type variable? Variations I tried are e.g.:

PMF add(PMF pmf){
    PMF C= new PMF(x*2);
    for(int i=0; i<x; i++){
        for(int j=0; j<x; j++){
        return C;

But then it shows me the error This method must return a result of type of PMF.

What am I doing wrong? The Method name(type) is given, so I cannot change it into void add(PMF pmf) or smth.

Why is my LINQ query not recognizing members of a generic list?

I am trying to query (via LINQ) a generic list, and it is "acting" as if some of the fields I'm "whereing on" do not exist.

Here is the code:

private decimal GetPriceForMember_Code_Desc_Unit_Week(string member, string itemcode, string desc, string unit, int weeknum)
    Decimal price = 0.00M;
    if (unit == CRAFTWORKS_SC)
        price = craftworksWeek1PVDSubsetList.Select(x => x.Price)
            .Where(x => x.ShortName.Equals(member))
            .Where(x => x.Description.Equals(desc))
            .Where(x => x.WeekNum.Equals(weeknum))
            .Where(x => x.ItemCode.Equals(itemcode));
    //else if (unit == CHOPHOUSE) TODO: Finish
    return price;

It fails with, "'string' does not contain a definition for 'ShortName' and no extension method 'ShortName' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)"

There's apparently something wrong with my LINQ syntax, but I don't know what. The generic list in the code is defined and declared like so:

public class PriceVarianceSubsetData
    public String ShortName { get; set; }
    public String ItemCode { get; set; }
    public String Description { get; set; } //<= need this, too?
    public String Price { get; set; }
    public int WeekNum { get; set; }
. . .
List<PriceVarianceSubsetData> craftworksWeek1PVDSubsetList = null;

Why does it have no qualms about "Price" yet complains about "ShortName"? They are both members of the class "PriceVarianceSubsetData"

Does Javac ignore defined generics of methods in a parameterized class's raw instance?

From what I can tell, if there is a parameterized class instance whose generics are left raw, the Java compiler doesn't obey generics rules for any methods in the class.

I have the following example Java code:

import java.util.Arrays;
import java.util.List;

public class GenericsTest
    public static class ParameterizedFoo<T>
        List<String> getList()
            return Arrays.asList("Hello world!");

    public void main(String[] args)
        ParameterizedFoo<Integer> bar = new ParameterizedFoo<>();
        ParameterizedFoo baz = new ParameterizedFoo();

        // works fine, no compiler errors
        String hi1 = bar.getList().get(0);

        // Javac gives "error: incompatible types: Object cannot be converted to String"
        String hi2 = baz.getList().get(0);

Can someone explain what is going on with Javac? I believe that it's a bug, but wanted to post here before submitting to

Self referencing variables passed during the instantiation of a class

I'm not sure if I'm using the correct terminology, but here's my code:

class Candidate(object):
        def __init__(self, party_code, state, age=random.randint(35, 70),
                social_index=(1 if party_code == 'dem' else -1 if party_code == 'rep' else 0),
                econ_index=(-1 if party_code == 'dem' else 1 if party_code == 'rep' else 0)):
            self.state = state
            self.party_code = party_code
            self.age = age
            self.social_index = social_index
            self.econ_index = econ_index

I would like to be able to use party_code to determine what the initial values of social_index and econ_index will be, but this isn't allowed with the way I currently have it set up. Is there an alternative way to dynamically set keyword variable on creation of this class?

Swift nstimer accessing function other class

Having trouble running the function in a different class as a selector for NStimer.

   class VariClass
  func updateUILoop()
    {print("updating UI")}

In the app delegate I have

let values = VariClass()

In the appdelegate I have.

let timer = NSTimer(fireDate: NSDate(), interval: 5, target: self, selector: #selector(values.updateUILoop), userInfo: nil, repeats: true)

The function works perfectly if I run it manually.


I want to put panels side by side with bootstrap

I fetch some info from the database with a while loop to output panels side by side with boostrap.

This is the code:


    $sql = "SELECT * FROM items ORDER BY `id`"; 

    $res = mysqli_query($conn,$sql);

    $x = 4;

    while($page = mysqli_fetch_assoc($res)){ 
        echo "<div class='col-lg-$x col-md-5'>
                 <div id='posts' class='transitions-enabled masonry'>".
                   "<div class='box panel panel-default masonry-brick' style='position: absolute; top: 0px; left: 0px;'' target='_blank>".
                      "<a href=''><img src=''></a>". 
                         "<h2 class='box_text_hover'>". $page["name"]"."</h2>".(float)$page["price"]." ". 
                          "<a href='item.php?id=".$page["id"]."'>See more!</a>".

But the output is always looks like this:

enter image description here

I am creating a GUI for a school assignment and am getting some funky errors. Any help would be appreciated [on hold]

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import javax.swing.SwingUtilities;

public class LivingExpensesCalculator extends JFrame

 public static void main(String[] args){
 LivingExpensesCalculator livingExpenses = new LivingExpensesCalculator();

//Provided info and calculated info panels
private JPanel providedInfoPanel;
private JPanel buttonPanel;
private JPanel calculatedInfoPanel;

//Labels for the Living Expenses Calculator fields
private JLabel rentalMortgageLabel;
private JLabel insuranceLabel;
private JLabel billsForUtilitiesLabel;
private JLabel fuelLabel;
private JLabel transportationTicketsLabel;
private JLabel parkingLabel;
private JLabel groceriesLabel;
private JLabel clothingLabel;
private JLabel personalCareLabel;
private JLabel medicationLabel;
private JLabel dinningOutLabel;
private JLabel vacationLabel;
private JLabel grossYearlyAmountLabel;
private JLabel taxAmountLabel;
private JLabel budgetLabel;
private JLabel calculatedInfoPanelLabel;

//Text Fields for the Living Expenses Calculator entry
private JTextField rentalMortgageTextField;
private JTextField insuranceTextField;
private JTextField billsForUtilitiesTextField;
private JTextField fuelTextField;
private JTextField transportationTicketsTextField;
private JTextField parkingTextField;
private JTextField groceriesTextField;
private JTextField clothingTextField;
private JTextField personalCareTextField;
private JTextField medicationTextField;
private JTextField dinningOutTextField;
private JTextField vacationTextField;
private JTextField grossYearlyAmountTextField;
private JTextField taxAmountTextField;
private JTextField budgetTextField;
private JTextField calculatedInforPanelTextField;

private JButton resetButton;
private JButton calcButton;

public LivingExpensesCalculator()
// Call the JFrame constructor & set title
super("Living Expenses Calculator");

// a reference to the default toolkit
Toolkit mytoolkit = Toolkit.getDefaultToolkit();
//get screen size
Dimension screenDimension = mytoolkit.getScreenSize();
int width = screenDimension.width;
int height = screenDimension.height;

Compiler isn't liking that I'm calling methods here, do not know why

// Set size
setSize(width/4, height/2);

// Specify an action for the close button

// Create a BorderLayout manager for the content pane
setLayout(new BorderLayout());

// Make window centered

// Build the providedInfo and calculatedInfo Panel

// Add the panels to the frame's content pane
add(providedInfoPanel, BorderLayout.CENTER);
add(calculatedInfoPanel, BorderLayout.SOUTH);

// Pack the contents of the window and display it

//The buildProvidedInfoPanel method adds the labels and text fields to the 

private void buildProvidedInfoPanel()
    //Create the labels for providedInfo fields
    rentalMortgageLabel = new JLabel("Yearly rent or mortgage cost: ");
    insuranceLabel = new JLabel("Insurance costs: ");
    billsForUtilitiesLabel = new JLabel("Cost for utility bills: ");
    fuelLabel = new JLabel("Fuel costs: ");
    transportationTicketsLabel = new JLabel("Transportation tickets costs: ");
    parkingLabel = new JLabel("Parking costs: ");
    groceriesLabel = new JLabel("Grocery costs: ");
    clothingLabel = new JLabel("Clothing costs: ");
    personalCareLabel = new JLabel("Personal care costs: ");
    medicationLabel = new JLabel("Medication costs: ");
    dinningOutLabel = new JLabel("Dinning out costs: ");
    vacationLabel = new JLabel("Vacation costs: ");
    grossYearlyAmountLabel = new JLabel("Gross amount earned per year: ");
    taxAmountLabel = new JLabel("% applied to gross income as deduction: "); 
    budgetLabel = new JLabel("Budget for expenses and payments: ");

    // Create text boxes
    rentalMortgageTextField = new JTextField(7);
    insuranceTextField = new JTextField(7);
    billsForUtilitiesTextField = new JTextField(7);
    fuelTextField = new JTextField(7);
    transportationTicketsTextField = new JTextField(7);
    parkingTextField = new JTextField(7);
    groceriesTextField = new JTextField(7);
    clothingTextField = new JTextField(7);
    personalCareTextField = new JTextField(7);
    medicationTextField = new JTextField(7);
    dinningOutTextField = new JTextField(7);
    vacationTextField = new JTextField(7);
    grossYearlyAmountTextField = new JTextField(7);
    taxAmountTextField = new JTextField(7);
    budgetTextField = new JTextField(7);

    // Create a panel to hold labels and text fields
    providedInfoPanel = new JPanel();

    // Create GridLayout manager with 10 rows and 2 columns
    providedInfoPanel.setLayout(new GridLayout(10, 2));

    // Add the labels and text fields to this panel

    // Add an empty border for spacing
    providedInfoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 1, 10));

// buildButtonPanel creates and adds the reset and calculate buttons to
// the providedInfoPanel as its own panel
private void buildButtonPanel()
    // Create the calcButton
    calcButton = new JButton("Calculate");

    // Register an event listener for the caclButton
    calcButton.addActionListener(new CalcButtonListener());

    // Create the resetButton
    resetButton = new JButton("Reset");

    // Register an event listener for the resetButton
    resetButton.addActionListener(new ResetButtonListener());

    // Create the buttons panels
    buttonPanel = new JPanel();

    // Create BorderLayout manager
    buttonPanel.setLayout(new BorderLayout(5, 5));

    // Add the two buttons to buttonPanel
     buttonPanel.add(resetButton, BorderLayout.WEST);
     buttonPanel.add(calcButton, BorderLayout.CENTER);

     //Add empty border for spacing
     buttonPanel.setBorder(BorderFactory.createEmptyBorder(1, 10, 10, 10));

// Private inner class that handles the events when the user clicks the 
// Calculate button
private class CalcButtonListener implements ActionListener
    // Variables used in calculations
    String input; 
    double rentalMortgage;
    double insurance;
    double billsForUtilities;
    double fuel;
    double transportationTickets;
    double parking;
    double groceries;
    double clothing;
    double personalCare;
    double medication;
    double dinningOut;
    double vacation;
    double grossYearlyAmount;
    double taxAmount;
    double budget;

This is underlined, I do not understand why

    public void actionPerformed(ActionEvent e)
        // Variables for calculated items
        double netIncomeYearly;
        double netIncomeMonthly;
        double totalExpenses;
        String highestMonth;
        String lowestMonth;
        double savingsLeft;
        double housingExpensesMonthly;
        double housingExpensesYearly;
        double transportationExpensesMonthly;
        double transportationExpensesYearly;
        double livingExpensesYearly;
        double livingExpensesMonthly;
        double lifeStyleExpensesMonthly;
        double lifeStyleExpensesYearly;
        boolean overBudget;
        boolean underBudget;

        // Create DecimalFormat object to formate the totals as dollar amounts
        DecimalFormat dollar = new DecimalFormat("$#,##0.00#");

    // Get Input Data the user entered in the TextFields
    private void getData()
        rentalMortgage = Double.parseDouble(rentalMortgageTextField.getText());
        insurance = Double.parseDouble(insuranceTextField.getText());
        billsForUtilities = Double.parseDouble(billsForUtilitiesTextField.getText());
        fuel = Double.parseDouble(fuelTextField.getText());
        transportationTickets = Double.parseDouble(transportationTicketsTextField.getText());
        parking = Double.parseDouble(parkingTextField.getText());
        groceries = Double.parseDouble(groceriesTextField.getText());
        clothing = Double.parseDouble(clothingTextField.getText());
        personalCare = Double.parseDouble(personalCareTextField.getText());
        medication = Double.parseDouble(medicationTextField.getText());
        dinningOut = Double.parseDouble(dinningOutTextField.getText());
        vacation = Double.parseDouble(vacationTextField.getText());
        grossYearlyAmount = Double.parseDouble(grossYearlyAmountTextField.getText());
        taxAmount = Double.parseDouble(taxAmountTextField.getText());
        budget = Double.parseDouble(budgetTextField.getText());

    // Determine the values and print them
    private void dertermineCalculations(double netIncomeYearly, 
            double netIncomeMonthly, double totalExpenses, String highestMonth, 
            String lowestMonth, double savingsLeft, 
            double housingExpensesMonthly, double housingExpensesYearly, 
            double transportationExpensesMonthly, 
            double transportationExpensesYearly, double livingExpensesYearly, 
            double livingExpensesMonthly, double lifeStyleExpensesMonthly, 
            double lifeStyleExpensesYearly, boolean underBudget, 
            boolean overBudget)
    netIncomeYearly = grossYearlyAmount * (1 - (taxAmount / 100)); 
    netIncomeMonthly = netIncomeYearly / 12;
    totalExpenses = ((rentalMortgage * 12) + (insurance * 12) + 
            (billsForUtilities * 12) + (fuel * 12) + (transportationTickets * 12)
            + (parking * 12 ) + (groceries * 12) + (clothing * 12) + 
            (personalCare * 12) + (medication * 12) + (dinningOut * 12) + 
            (vacation * 12));
    highestMonth = "February";
    lowestMonth = "July";
    savingsLeft = netIncomeYearly - totalExpenses;
    housingExpensesMonthly = rentalMortgage + insurance + billsForUtilities;
    housingExpensesYearly = ((rentalMortgage * 12) + (insurance * 12) + 
            (billsForUtilities * 12));
    transportationExpensesMonthly = fuel + transportationTickets + parking;
    transportationExpensesYearly = (fuel * 12) + (transportationTickets * 12)
            + (parking * 12 );
    livingExpensesYearly = groceries + clothing + personalCare + medication;
    livingExpensesMonthly = (groceries * 12) + (clothing * 12) + 
            (personalCare * 12) + (medication * 12);
    lifeStyleExpensesMonthly = dinningOut + vacation;
    lifeStyleExpensesYearly = (dinningOut * 12) + (vacation * 12);
    if (savingsLeft > 0)
        underBudget = true; overBudget = false;
    else if (savingsLeft < 0)
        underBudget = false; overBudget = true;
        underBudget = false; overBudget = false;

I am getting an error here, do not understand why since I imported javax.swing.JOptionPane

    //Display the calculated message box
    JOptionPane.showMessageDialog(null, "Net income yearly: " + netIncomeYearly
    + "\n" + "Net income monthly: " + netIncomeMonthly + "\n" + "Total expenses: "
    + totalExpenses + "\n" + "Highest Month: " + highestMonth + "\n" + 
    "Lowest month" + lowestMonth + "\n" + "Savings left: " + savingsLeft + "\n"
    + "Housing expenses monthly: " + housingExpensesMonthly + "\n" + 
    "Housing expenses yearly: " + housingExpensesYearly + "\n" + 
    "Transportation expenses yearly: " + transportationExpensesYearly + "\n" +
    "Transportation expenses monthly: " + transportationExpensesMonthly + "\n" +
    "Living expenses yearly: " + livingExpensesYearly + "\n" + 
    "Living expenses monthly: " + livingExpensesMonthly + "\n" +
    "Life Style expenses yearly: " + lifeStyleExpensesYearly + "\n" + 
    "Life Style expenses monthly: " + lifeStyleExpensesMonthly + "\n" + 
    "Under budget: " + String.parseString(underBudget) + "\n" + "Over budget: "
    + String.parseString(overBudget) + "\n"); 

private class ResetButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)


Any help would be very much appreciated, I am sorry if the errors are silly. I am new to this and am very confused. Thanks in advance!

How to call a function from class when clicking on PHP Button? [duplicate]

This question already has an answer here:


I have a PHP Class like this:

class DiffFunctions {
    function showMessage($msg){
        echo "<script type='text/javascript'>alert('$msg')</script>";

and I have tried this code in PHP Page:

include_once './Classes/DiffFunctions.php';
$myFuns2 = new DiffFunctions();
<button id="sendMsg" type="submit" onclick="$myFuns2->showMessage('You have clicked the button')">Click Here To Show The Message</button>

But It did not work!

Add/Remove/Toggle Classes - good/bad practice?

I'm relatively new to the world of JavaScript, and have a question for you. I'm doing a simple JavaScript game, and I have several of these type of things to change, add, and remove classes when a button is clicked on. Now my question is, is this type of thing considered bad practice to have all of these listed like this? Is there a better way? Or is this totally fine?

$('#topsbtn').click(function () {

EDIT: The top ones toggle the option, and the following are to make sure the other options are turned off when this button is clicked.

Thanks in advance!

VB.Net - Using a subclass in a class

Trying to convert some VBA code to VB.Net and getting hung up on some class issues. I have a main class: clsComputer. It has a subclass: clsHardDrive. Since a computer can have more than 1 hard drive, it's Get and Set properties look like this in clsComputer:

Private pHardDrive(8) As clsHardDrive

Public Property Get HardDrive(index As Integer) As clsHardDrive
    If pHardDrive(index) Is Nothing Then Set pHardDrive(index) = New clsHardDrive
    Set HardDrive = pHardDrive(index)
End Property
Public Property Set HardDrive(index As Integer, value As clsHardDrive)
    pHardDrive(index) = value
End Property

This allows me to do something like this in code:

objComp.HardDrive(0).Size = "500"
objComp.HardDrive(1).Size = "1000"

However, I don't know how to convert this to VB.Net. I tried this:

Property HardDrive As HDD
    Get (ByVal index As Integer)
        Return pHardDrive(index)
    End Get
    Set (ByVal index As Integer, value As HDD)          
        pHardDrive(index) = value
    End Set
End Property

But it gives a compile error: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'. (BC30124)

Searching that error isn't very helpful: To correct this error make sure you include both a Get procedure and a Set procedure between the Property statement and the End Property statement. I have both Get and Set, and I think they are properly terminated. I've also searched for examples on using one class within another, but I didn't find anything useful.

How do I get the same functionality in VB.Net that I have in VBA? EG, how do I create the instances of HardDrive so that one computer object can have many hard drive objects?

Using resulting lcmm model to make predictions for new individuals

I've applied lcmm (in R) to a large dataset of individuals for which I have a response measure at multiple time points and several covariates (which were included in the model). 1. How can I use the resulting model to predict/assign a new individual to one of the resulting classes? i.e given an lcmm model and a new individual, can I predict which class he is likely to belong to? I cannot find the R function for this. 2. Can this be done if for the new individual only the covariates are known (when no response measure data is available)?


custom text processor metaclass not returning all modifications to string

I'm writing a text processor for different fields, the fields are somewhat similar to what you would see in Django's model fields. Meaning textfields etc.

I have a text processor metaclass, a base text processor, and further processors that inherit from this base processor for further extensions. e.g. - I have a Title field which would require further custom processing.

However, for the Title field it only seems to process the first filter(s) that are from the BaseTextProcessor's __call__ method. Although, if I add print statements, all filters are called and the string is modified it's just not returning the further modifications to the string for some reason.

I left out the metaclass for the BaseField as it's redundant here, but included the BaseField etc to show the inheritance schema.

Here's a minimal example demonstrating the issue:

 class TextProcessorMeta(type):

    def __prepare(name, bases, **kwargs):

        return collections.OrderedDict()

    def __new__(meta, name, bases, dct, **kwargs):

        instance = super().__new__(meta, name, bases, dict(dct))
        instance._filters = [
            v for v in dct.values() if hasattr(v, '_filter')]
        return instance

class BaseTextProcessor(metaclass=TextProcessorMeta):

    def __call__(self, string):

        _string = string
        for _filter in self._filters:
            _string = _filter(self, _string)
            print(_string, "after filter", _filter)
        return _string

def textfilter(func):
    func._filter = True
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

class TextProcessor(BaseTextProcessor):

    def correct_spaces(self, string):

        return " ".join(string.split())

class TitleProcessor(TextProcessor):

    def capitalize(self, string):

        return string.capitalize()


class BaseField(Field, metaclass=_FieldMeta):


class TextField(BaseField):

    textprocessor = TextProcessor()

    def __init__(self, text, maxlen):

        self.__text = self.textprocessor(text)

    def __str__(self):

        return self.__text

class Title(TextField):

    titleprocessor = TitleProcessor()

    def __init__(self, title, maxlen=140):

        super().__init__(title, maxlen)
        self.__title = self.titleprocessor(self._TextField__text)

Now, if I do the following:

 print(TextField('a sentence with        way too many spaces.'))

I get:

 a sentence with way too many spaces.

Now, if I tried to use the Title field for an extra filter (say capitalization here):

 print(Title('a capitalized    title with too many.'))

I still get back:

 a captialized title with too many

Instead of:

 A ...

How to cast class object to interface

I have an interface Home and a class HomeClass implements Home .

How can i cast object of HomeClass into Home ?

swift2 custom segue display name

Using IOS 9 and Swift2.2

I want to change the name displayed in story board by Capitalising each word

If i declare class as "DismissBack", in story board it shows as "dismiss back"

Instead i want to make it show as "Dismiss Back" by Capitalising each word

How do i change that name in the code while declaring the custom class

class DismissBack: UIStoryboardSegue
    override func perform()
        /* CodTdo */

I tried

 UIStoryboardSegue.title = "Dismiss Back" = "Dismiss Back"

Trying to build an Array with Data from different Classes

I'm building an app with different, selectable tabs that change color when selected. Each button has a different Image so i created a new class each time. I want my code to input a string value into a common array for each tab that is selected.

here is my code:

import UIKit

var interestsArray:[AnyObject] = []

class Bar: UIButton {

let checkedImage1 = UIImage(named: "BarsTabHighlight")
let unCheckedImage1 = UIImage(named: "BarsTab")

//bool propety
@IBInspectable var isChecked:Bool = false{

override func awakeFromNib() {
    self.addTarget(self, action: #selector(Bar.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)

func updateImage() {
    if isChecked == true{
        self.setImage(checkedImage1, forState: .Normal)
        self.setImage(unCheckedImage1, forState: .Normal)


func buttonClicked(sender:UIButton) {
    if(sender == self){
        isChecked = !isChecked

        if (isChecked == !isChecked) {
            interestsArray[1] = "Golf"}



I do this several times with a tab for each button (if someone could explain how to loop it that would be tremendous also!!!) with the array index number changing for each one so at the end i can output an array with all of the selected interests. Can someone please explain the easiest way to do this?

Inheritance wrong call of constrostructors

I'm implemeting this diamond inheritance:

class Object {
    int id; string name;
    Object(int i, string n){name = n; id = i;};

class Button: virtual public Object {
    string type1;
    int x_coord, y_coord;
    Button(int i, string n, string ty, int x, int y):Object(i, n){
          type = ty;
          x_coord = x;
          y_coord = y;};

class Action: virtual public Object {
    string type2;
    Action(int i, string n, string t):Object(i, n){ type2 = t;};

class ActionButton: public Button, public Action{
    bool active;
    ActionButton():Buton(), Action(){};
    ActionButton(int i, string n, string t1, int x, int y, string t2, bool a):
    Button(i, n, t1, x, y), Action(i, n, t2) {active = a;};

Everything works fine about the first three classes, but when i try to create an object of the type ActionButton, instead of calling the constructor with the parameters i wrote it is calling the default one from the class Object. So every ButtonAction object has name an empty string and id a random value. What's wrong with my code and how can i make it work properly?

Cannot create new instance of class for BaseAdapter

I have two Classes, a Person Class that creates a new instance of a person, and a Stopwatch Class that Creates a new instance of a stopwatch (it takes in variables Button,Button,TextView, and Person).

in my Main function, i have two edit Text Boxes, a Button, and then a listview. What I'm trying to do is fill in EditText's with First and Last name, then click save. When saved I want to save that data to that particular instance of my person. Then use that person to update the text of the Button within the stopwatch instance. Each stopwatch instance should have a different person instance assigned to it so that each stopwatch has a different name. As of right now, my onclick listener for the save button is not doing anything and I don't know why. Right now i have the getCount hardcoded to one until i am able to assign just one person to a stopwatch.

Sorry if This is a stupid question, I'm new to Java

Main Function:

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {

    final EditText firstName = (EditText)findViewById(;
    final EditText lastName = (EditText)findViewById(;
    ListView listView = (ListView)findViewById(;
    final Button save =  (Button)findViewById(;

    BaseAdapter myAdapter = new BaseAdapter() {
        public int getCount() {
            return 1;

        public Object getItem(int position) {
            return null;

        public long getItemId(int position) {
            return 0;

        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.stopwatchview,parent,false);

            final TextView Screen = (TextView) convertView.findViewById(;
            final Button start = (Button) convertView.findViewById(;
            Button reset = (Button) convertView.findViewById(;
            final Person person = new Person();
            final Stopwatch stopwatch = new Stopwatch(Screen,start,reset,person);;
            Button save = (Button) findViewById(;
            final EditText first = (EditText) findViewById(;
            final EditText last = (EditText) findViewById(;

            assert save != null;
            save.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    person.setName(first.getText().toString(), last.getText().toString());

            start.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (stopwatch.isTicking()) {
                    } else {

            reset.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
            return convertView;

Stopwatch Class:

import android.os.Handler;
import android.os.SystemClock;
import android.widget.Button;
import android.widget.TextView;

public class Stopwatch {
    TextView text;
    Button start;
    Button reset;
    Person person;

public Stopwatch(TextView t, Button Start, Button Reset, Person p){
    text = t;
    start = Start;
    reset = Reset;
    person = p;


long starttime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedtime = 0L;
int t = 1;
int secs = 0;
int mins = 0;
int milliseconds = 0;
Handler handler = new Handler();
Runnable callback;

public void start(){
    callback = updateTimer();
    starttime = SystemClock.uptimeMillis();
    handler.postDelayed(callback, 0);
    t = 0;

public void stop(){
    timeSwapBuff += timeInMilliseconds;
    t = 1;

public void reset(){
    starttime = 0L;
    timeInMilliseconds = 0L;
    timeSwapBuff = 0L;
    updatedtime = 0L;
    t = 1;
    secs = 0;
    mins = 0;
    milliseconds = 0;

public boolean isTicking(){
        return true;
    return false;

//Update Timer
private Runnable updateTimer() {
    return new Runnable() {
        public void run() {
            timeInMilliseconds = SystemClock.uptimeMillis() - starttime;
            updatedtime = timeSwapBuff + timeInMilliseconds;
            secs = (int) (updatedtime / 1000);
            mins = secs / 60;
            secs = secs % 60;
            milliseconds = (int) (updatedtime % 1000);
            text.setText("" + mins + ":" + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            handler.postDelayed(this, 0);


Person Class:

public class Person {
String firstName;
String lastName;
String initials;

public Person(){
    firstName = null;
    lastName = null;
    initials = null;

public void setName(String FirstName, String LastName){
    firstName = FirstName;
    lastName = LastName;
    setInitials(FirstName, LastName);

private void setInitials(String firstName, String lastName) {
    String firstLetter = firstName.substring(0,1);
    String lastLetter = lastName.substring(0,1);
    initials = firstLetter.concat(lastLetter);