vendredi 30 septembre 2016

how to make a copy of connected or related list of objects and classes?

I work on a public transportation network (railways) I create a list of station, then a list of nodes, every node represent a station with a specified time , and finally I create the trains the problem is :

I load all the stations first, I need to link the stations with nodes, and I need to link the trains in network with the nodes ..... after many iterations and reductions I want to load everything again from the beginning ..... If I copied 'network', 'nodes' and 'stations' the copies aren't related to each other ... so it won't works because they are not connected

'Defining all stations
            For n = 0 To s.st.Rows.Count - 1
                Dim new_st As New station
                new_st.name = s.st.Rows(n)(1)
                new_st.id = s.st.Rows(n)(2)
                If IsDBNull(s.st.Rows(n)(3)) = False Then
                    new_st.x = s.st.Rows(n)(3)
                    new_st.str = s.st.Rows(n)(4)
                    If IsDBNull(new_st.x) = False Then new_st.main = True
                End If
                stations.Add(new_st)
            Next

    'Defining all nodes 
    For Each sh In s.Tables
        If sh IsNot s.st Then
            Dim i = 2
            Do While True
                i += 1
                If i = sh.Columns.Count Then Exit Do
                Dim j = 1
                Do While True
                    If j = sh.rows.count - 1 Then : Exit Do
                    ElseIf IsDBNull(sh.rows(j + 1)(i)) Then : Exit Do
                    End If
                    j += 1
                    Do Until sh.rows(j)(i) <> -1
                        j += 1
                    Loop
                    Dim no As New node
                    Dim id = sh.Rows(j)(2)
                    Dim st = stations.Findstation_byid(id)
                    Dim t = sh.Rows(j)(i)
                    Dim id_t = id & t
                    If nodes.findnode(id_t) Is Nothing Then
                        no.stat = st
                        no.t = t
                        no.id_t = id & t
                        nodes.Add(no)
                    End If
                Loop
            Loop
        End If
    Next

    'Defining all trains 
    For Each sh In s.Tables
        If sh IsNot s.st Then
            Dim i = 2
            Do While True
                i += 1
                If i = sh.Columns.Count Then Exit Do
                Dim new_t As New train
                Dim new_li As New List(Of node)
                new_t.id = "train" & sh.Rows(1)(i)
                Dim j = 1
                Do While True
                    If j = sh.rows.count - 1 Then : Exit Do
                    ElseIf IsDBNull(sh.rows(j + 1)(i)) Then : Exit Do
                    End If
                    j += 1
                    Do Until sh.rows(j)(i) <> -1
                        j += 1
                    Loop
                    Dim id_t = sh.Rows(j)(2) & sh.Rows(j)(i)
                    Dim no As node
                    no = nodes.findnode(id_t)
                    no.adj.Add(new_t)
                    new_li.Add(no)
                Loop
                network.Add(new_t, new_li)
            Loop
        End If
    Next




Assign Global Variable Inside Class From Class Variable

I have a question about classes in Python. I have create a class that looks something like this:

class Model(Object):

__table__ = 'table_name'

def func():

def func2():

The table name is a global variable that the functions feed off of. I am trying to add old data so I would like to change the table name depending on if I am filling in from old information, so this is what I tried.

class Model(Object):

def __init__(self, backfill = False):
     self.backfill = backfill

if self.backfill:
     __table__ = 'table_name'
else:
     __table__ = 'table_name2'

def func():

def func2():

The final call would be something like this:

if backfill: model = Model(True).func() else: model = Model.func()

Then I realized this wouldn't work because I cannot call self.backfill from outside the class definitions. I even tried creating a definition and calling that inside the class but that did not work either.

My question is:

  1. Is there a way to initialize the global variable inside the class from the class variables? Or is there a better way to do this in general?



What does it mean that a scope is determined statically and used dynamically?

This is an excerpt of Python docs for Classes I'm struggling to understand:

A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.

Although scopes are determined statically, they are used dynamically.

I didn't quite comprehend what the author meant by a scope from this definition, what's a textual region of a program, and what it means that scopes are statically determined and dynamically used. I have an intuitive understanding of a scope, but would love to fully appreciate the docs definition. If someone would be so kind as to elaborate what author had in mind it would be greatly appreciated.




Expression must have a class type(working with linked lists)

Have problems with this snippet of code. I keep getting error "expression must have a class type" on the third line.

if (users.find("I")!=string::npos)
        {
            int spot = atoi((users[3]).c_str());
            string pot = string(users.substr(2));
            stringstream spot(pot);
            string data;
            cin>>data;
            list.insertAfter(list.getNode(spot),data);
        }




How can I call multiple functions from multiple classes that are unknown?

Not sure if the title is entirely accurate. What I am trying to do is create a database of classes to store multiple variables that can be printed out at a later date. What I am having trouble with is calling the functions in all of the classes, as I need a way to have an infinite number of classes but also be able to call them all. At the moment I am using a dictionary to store the variables but it does not appear to be working properly

The code that calls the function (currently doesn't work):

elif option == "3":
        if entries > 0:
            min_entries = entries/entries
        else:
            print ("Nothing is in the database!")
            skip = True
        while min_entries != entries and skip != True:
            v = vehicles (car_lot[min_entries])
            v.print_full()
            min_entries += 1
    elif option == "4":
        exit()

When I run the program, however all I get is this:Database initialised Make: Model: Year: 0 Price new: 0 No price has been calculated Mileage: 0 so I believe that the call is not working the way I want it to.

Core file: http://ift.tt/2dg541m Class file: http://ift.tt/2dFNIcr

If I have left any details then just tell me.




Matlab class constructor without initializing properties

Similar to C++ where we can define a constructor without initialization, can we do it in Matlab classdef? I tried but it complains that "Test is already defined", meaning I can't define two functions with the same name.

classdef Test
    properties
        id;
    end
    methods
        %constructor without initialization
        function obj = Test
        end

        %constructor with initialization
        function obj = Test(x)
            obj.id = x;
            end
        end

end




ReflectionException in Container.php line 741: Class App\Http\Controllers\Backend/ItemsController does not exist

i constantly get this error after i created the update/edit function, route and layout. After some research i tried:

namespace App\Http\Controllers\Backend\ItemsController; 

but still nothing.

Controller:

<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Models\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Laracasts\Flash\Flash;



class ItemsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $items = Item::orderBy('id', 'ASC')->paginate(5);

        return view('backend.item.list')->with("items", $items);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('backend.item.form');
    }


    public function store(Request $request)
    {
        // mejora:
        // $item = new Item($request->all());
        $item = new Item;
        $item->name = $request->get('name');
        $item->pompadour = $request->get('pompadour');
        $item->description = $request->get('description');
        $item->outstanding_image = '';
        $item->save();

        Flash::success("Se ha agregado un nuevo item " . $item->name . " con exito");

        return redirect()->route('item.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $item = Item::find($id);

        //return view('items.show')->withItem->($item);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
         $item = Item::find($id);
         return view('items.edit')->with('item', $item);
    }

    public function destroy($id)
    {
        // delete
        $item = Item::find($id);
        $item->delete();

        Flash::error("El item " . $item->name . " ha sido eliminado correctamente");

        return redirect()->route('item.index');
    }

    public function update(Request $request, $id)
    {
        $item = Item::find($id);
        $item->name = $request->name;
        $item->pompadour = $request->pompadour;
        $item->description = $request->description;
        $item->save();

        Flash::info("El item " . $item->name . " ha sido editado correctamente");

        return redirect()->route('item.index');

    }
}

Routes ( this are the only one that do not work, i also have the destroy route, store and create):

Route::get('item/{id}/edit', ['as' => 'items.edit', 'uses' => 'Backend/ItemsController@edit']);
Route::put('item/{id}', ['as' => 'items.update', 'uses' => 'Backend/ItemsController@update']);

While my form action look like:

<form action="" method="PUT" class="form-horizontal">

Thanks for taking the time reviewing my code.




Sort of multiple inheritance?

I have the following class structure (Blah === ExtBlah):

Base
 +--[ ExtBase ]    --???-- [ ExtBlah ] --- .. more scripts ...
 +--[ Blah ]
        +---[ Script1 ]
        +---[ Script2 ]
        +---[ ....... ]
        +---[ ScriptN ]     

Now I need to write more Scripts which need to extend Blah, but Blah has to extend "ExtBase", instead of "Base" for the new script cases.

I still have to have Blah the way it is because the Scripts1-N have to be dependent on "Base", not on "ExtBase".

Also I don't want to create a copy of Blah i.e. ExtBlah, because that mean duplication of code and will be harder and messier to support.

Any ideas ?




How to properly use pointers with class functions

What is the proper way to implement this class function when using pointers

f3 =  f1->add(new Fraction(1,8));

Everything else in the class is running correctly.

#include <iostream>
using namespace std;

//members of a class default to private
class Fraction
{
private:
    int numerator;
    int denominator;

public:
    Fraction();
    Fraction(int,int);
    ~Fraction();
    Fraction* add(Fraction &f);
    void setFraction(int, int);
    int getNumerator();
    int getDenominator();
    };
Fraction::Fraction()
{
    numerator = 0;
    denominator = 0;
}
Fraction::Fraction(int num, int den)
{
    this->numerator = num;
    this ->denominator = den;
}
Fraction::~Fraction()
{
}
void Fraction::setFraction(int num, int den)
{
    numerator = num;
    denominator = den;
}
int Fraction::getNumerator()
{
    return numerator;
}
int Fraction::getDenominator()
{
    return denominator;
}
Fraction* Fraction::add(Fraction &f)
{
    int num = f.numerator * this->denominator;
    num += this->numerator *f.denominator;
    int den = this->denominator * f.denominator;
    return new Fraction(num,den);
}

int main() {
    Fraction* f1 = new Fraction(5,8);
    Fraction* f2 = new Fraction(1,8);
    cout << f1->getNumerator() << "/" << f1->getDenominator() <<endl;
    Fraction* f3 = new Fraction();
    f3 =  f1->add(new Fraction(1,8));
    return 0;
}




Class vs instance initialization in Python

I am a bit puzzled why when initializing an instance of a class in Python, I cannot use class attributes. Here is the example:

class TestClass:
... shared_list = ['a', 'b', 'c']
... def __init__(self):
...     self.length = len(shared_list)

Now

>>> TestClass.shared_list
['a', 'b', 'c']

So the list exists before any instance of the class appears, but

>>> tc = TestClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: global name 'shared_list' is not defined

Am I missing something simple?




Java Classes Object orientated programming

This is my code :

package myapplication;

/** * * @author w1547901 */

public class MyApplication {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here






    Person d = new Person("");


    d.displayName();

    d.setSurname("");
    System.out.println(d.getSurname());
    d.setAge(23);
    System.out.println(d.getAge()+ "\n");


     Person e = new Person("John");
    e.displayName();
    e.setSurname("Smith");
    System.out.println(e.getSurname());
    e.setAge(30);
    System.out.println(e.getAge()+ "\n");

     Person f = new Person("John");
    f.displayName();
    f.setSurname("Terry");
    System.out.println(f.getSurname());
    f.setAge(29);
    System.out.println(f.getAge());

}

}

and this is my person class which is separate from the code above

public class Person {

private String name;
private String surname;
private int age;

public Person(String n ) {



    name = n;

}

public void displayName() {
    System.out.println(name);
}

public void setSurname(String s) {
    surname = s;
}

public String getSurname() {
    return surname;
}

public void setAge(int num) {
    age = num;
}

public int getAge() {
    return age;
}

}

and what I want is that how can I put my own first name,last name and age using java scanner input




Declaring a class template as a friend of a class template in C++

I'm trying to declare a class template as a friend of another class template, so the private members in one class can be accessed by the other. For example I have two classes as the following:

A.h
template <typename T>
class A {
    private:
       T content;
}

and

B.h
#include "A.h"
template <typename T>
class B {
    public:
        void add(T);

    private:
        A<T>* ptr;
}

Now, I want to make class B< T> a friend of class A< T>, so I can have access to class A< T>'s content through class B< T>'s function add. So, I added a few lines to A.h:

A.h
template <typename T> class B;
template <typename T> 
class A {
    friend class B<T>;
    ...

I'm using Visual Studio and the above code would give me "unresolved external symbol..." error (Error code LNK2019). I have tried other variations but I just couldn't get the code to compile. Please help me out. Thank you.




How should the methods in a Helper class be declared in Java [duplicate]

This question already has an answer here:

I created a java class called Helper and I put on it different functions that could be used in different classes such as log(), checkRequestFormat(), isAuthentificated()... Will it make sense to declare this class as public final and the functions as public static final and call them this way Helper.log(), without creating an instance of the class or shall I just use it as a public class and public method and functions, in this way

Helper helper = new Helper;
helper.log();




Python: Modifying a class' list for specific objects

So I have a list of objects in which I have a list. The list has common strings and is supposed to have some specific strings for every object depending on another variable.

class test: 
   strings = []
   name = None

Then I'm creating a list of objects

objects = []
i = 0
while i < 2 :
   o = test()
   o.name = "Object " + str(i)
   objects.append(o)
   i += 1

Then I'm adding general strings for both objects in the list

test.strings.append("String 1")
test.strings.append("String 1")

What I need is for each object to have a specific string after those, so I tried

test.append("testing")
for element in objects :
   print element.strings[ len(element.strings) - 1 ]
   element.strings[ len(element.strings) - 1 ] = element.name
   print element.strings[ len(element.strings) - 1 ]

The output I'm getting is

testing
Object 0
Object 0
Object 1

And when I try to access element.strings where that string is it always is the last modification.

I tried appending individually, also, instead of doing the test.append before the for, but it added elements to every object. Is there a way to do what I'm trying to do?




Know if a class was added (was added with javascript)

i am programming a web and i need to know when a Class was added. I am using a Javascript plugin and the plugin add a css Class in then deletes it and add it in other div (gallery). I need to know in every moment in wich 'div' is this class.

Here you have an example of what I want to do

$('div').click(function() {
    $(this).toggleClass('red');
});

if ($('div').hasClass("red")) {
  $("div").addClass('border');
}
.box {
    width: 250px;
    height: 100px;
    border: 1px #000 solid;
}

.red {
    background: red;
}
.border {
  border: 6px #000 solid;
}
<script src="http://ift.tt/1oMJErh"></script>
<div class='box'></div>

As you see in this example i want to add the class 'border' only when the class 'red' was added, can not do it together with the class 'red' because as i say in the real page i am using a Javascript plugin.

Thanks!




how to get the class name of a statics method belongs to it

class test:
    @staticmethod
    def somefunc():
        pass

a = test.somefunc

if I print a, it gives

<function __main__.somefunc>

where I can not tell which class it belongs to?




Pointer objects, cant break out of input loop

My program reads input from the user and sets a target and then reads more input from the user. It then compares the numbers entered after the target is initialized and incriments greater_than, less_than, and equal. I am confused on why my program will not break out of the loop when I enter the 'ctrl+d' command for no more input. This is a representative example of a test question for my midterm so I am not allowed to change main(); or in list.h and no I am not violating any of my teachers cheating policies because I am not turning in this work I am using solutions given as means of study.

Here is my code thank you in advance.

main.cpp

#include <iostream>
using namespace std;
#include "list.h"

int main()
{
    List list;
    int value;
    int target;

    // first number read is the target
    cin >> target;

    while (cin >> value)
    {
      list.insert(value);
    }

    // initialized to 100 to make sure List::compare() initializes them correctly
    int less_than = 100;
    int equal = 100;
    int greater_than = 100;
    list.compare(target, less_than, equal, greater_than);

    cout << "target = " << target << endl;
    cout << "less_than = " << less_than << endl;
    cout << "equal = " << equal << endl;
    cout << "greater_than = " << greater_than << endl;
}

list.h

// Linked-List of Integers

#ifndef LIST_H
#define LIST_H

class List
{
    public:
        List();
        ~List();
        void insert(int value); // insert at beginning of list
        void print(); // print all values in the list
        void compare(int target, int &less_than, int &equal, int &greater_than);

    private:
        class Node
        {
            public:
                Node(int value, Node *next)
                {m_value = value; m_next = next;}
                int m_value;
                Node *m_next;
        };
        Node *m_front;
};

#endif

list.cpp

#include <iostream>
using namespace std;
#include "list.h"

List::List()
{
    m_front = NULL;
}

// delete all Nodes in the list
// since they are dynamically allocated using new, they won't go away
// automatically when the list is deleted
// Rule of thumb: destructor deletes all memory created by member functions
List::~List()
{
    while (m_front)
    {
        Node *tmp = m_front;
        m_front = m_front->m_next;
        delete tmp;
    }
}

// always insert at the front of the list
// Note: this works even in the SPECIAL CASE that the list is empty
void List::insert(int value)
{
    m_front = new Node(value, m_front);
}

// iterate through all the Nodes in the list and print each Node
void List::print()
{
    for (Node *ptr = m_front; ptr; ptr = ptr->m_next)
    {
        cout << ptr->m_value << endl; 
    }
}

void List::compare(int target, int &less_than, int &equal, int &greater_than)
{

  less_than = 0;
  equal = 0;
  greater_than = 0;
  int targ;
  targ = target;


  Node *ptr = m_front;
  while(ptr != NULL){

if(ptr ->m_value == targ){

  equal++;
}
else if (ptr -> m_value > targ){

  greater_than++;
}
else if (ptr -> m_value <targ){
  less_than++;
}
  }
  ptr = ptr -> m_next;
}




MatLab: how to define (not constant) properties that depend on other properties?

In the following class

classdef ClassCar
  properties (Constant)
    % Car phyisical properties
    m = 1630;         % [kg]
    R_rim = 14*.0254; % [m]
    e_tire = .175*.55; % [m]
    R_e = ClassCar.R_rim + ClassCar.e_tire;                   % <= HERE

    % Car transmission properties
    gearRatios = [3.154 1.925 1.281 .951 .756];
    finalDrive = 3.05; %Rapport de differentiel
    overallRatios = ClassCar.gearRatios * ClassCar.finalDrive;% <= HERE
  end
end

I want to have composed properties which depend on other properties (as a shortcut). I.e. to retrieve from an instanciated object (car = ClassCar)

car.R_e

or

car.overallRatios

The problem is R_e is a function of R_rim and e_tire. With (Constant) properties, it works, but the problem is I want those properties not constant, and simply removing the keyword causes problems.

Then I tried to do it with help of methods

classdef ClassCar
  properties
    % Car phyisical properties
    m = 1630;         % [kg]
    R_rim = 14*.0254; % [m]
    e_tire = .175*.55; % [m]

    % Car transmission properties
    gearRatios = [3.154 1.925 1.281 .951 .756];
    finalDrive = 3.05; %Rapport de differentiel
  end
  methods (Static)
    function value = R_e()
        value = R_rim + e_tire;                       % <= HERE
    end
    function value = overallRatios()
        value = gearRatios * finalDrive;
    end
  end
end 

But even with keyword (Static) for method, I get error message "Undefined function or variable 'R_rim'." I tried typing self.R_rim, ClassCar.R_rim, in vain.

How to achieve that? Is this the best way to do ? If so, how to access the object's properties (sthg like self.value)?

Thanks.




C# error while calling class

I learned basic and now I want to learn OOP in C# I have this code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace uceni_cs
{
    class Zdravic
    {
        public void pozdrav()
        {
            Console.WriteLine("Ahoj světe ! ");
        }
    }

}

But when I try to call it using this code

namespace uceni_cs
{
    class Zdravic
    {
        public void pozdrav()
        {
            Console.WriteLine("Ahoj světe ! ");
        }
    }
    Zdravic trida = new Zdravic();
}

In code Zdravic trida = new Zdravic(); is error. A namespace cannot directly contain members such as fields or methods. What I am doing wrong ? I just want to call the class. Thanks




PHP restrict abstract class`s protected properties/methods after inxeritance

If I have abstract class then it's properties/methods must be protected or public in order the child class to be able to direct access the parent's properties/methods. Now if the case is that I have inherited abstract class with protected properties and want to restrict in the child class the same propertis to private and after next inheritence to not be able to direct access them - how to do it in PHP?




Using member variables in static function

I am having some issues with using a member variable within static function. I am trying to code a ramp up signal for stepper motor, that has to run on a arduino uno. The timer1 library available from arduino (link), which interfaces with the timer1. The static function is a callback function which has to called everytime an interrupt occurs. When an interrrupt occurs, should the period time of the next pwm signal be decreased, and the amount it is decreased by is calculated within the interrupt/callback, and how I calulated is currently the problem.

The way i calulate is

uint32_t new_period = sqrt(2*n/4.8);
current_period -= new_period;

In which n should be increased for each completed period. I keep track of by having it as a member variable inside of the class,

But that will not work, as the callback is a static function, and the variable is a member of the class.

I guess I could make it as a different design pattern - singleton, But there should be a different way to do the same thing, I would not like to use singleton in case of i would have to use multiple motors

Here is the .cpp

#include "stepper_motor.h"

int step_count = 0;
stepper_motor::stepper_motor()
{
  //pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(en_pin, OUTPUT);
  alive_bool = true;
  position_bool = false;
  step_count = 0;
  period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

}

static void stepper_motor::callback()
{
  if (step_count < 240)
  {
    uint32_t new_period = sqrt(2 * step_count / 4.8);
    period -= new_period; 
  }
  else
  {
    return;
  }
}


void stepper_motor::step_pwm()
{

  digitalWrite(en_pin, HIGH);

  delay(0.005);

  digitalWrite(dir_pin, HIGH);
  //LOW  - Move towards the sensor
  //HIGH -  Move away from the sensor

  delay(0.005);

  int timestep = 0;

  timer1.initialize(period);
  timer1.attachInterrupt(callback);
}

and the .h file

#ifndef stepper_motor_h
#define stepper_motor_h

#include "Arduino.h"
#include <TimerOne.h>

#define step_pin  13
#define dir_pin   12
#define en_pin    11
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void step_pwm();
    static void callback();
    TimerOne timer1;
  private:
    uint32_t period;
    bool alive_bool;    
    //int step_count;
    bool position_bool;
};


#endif




Create a php class from multiple files

I would like to forge a class, from functions inside different php files. Something like this would be possible?

The goal is to create a modular class, which then can be used to upgrade the admin surface of an existing system.




i want to insert a SOS functionality in my android app. But i dont knowthe classes use

When i press my power button 5 times it will place a call to my immediate contact saved in either the Sqlite or my database. I don't know the classes used in it.




Which class properties must be defined as private/protected/public in top of class?

Each and every class property must be defined as public/protected/private in top of class, or just properties that may cause E_NOTICE should be defined there?




jeudi 29 septembre 2016

Values variables inside "this" class differ when created and during OnPress

I am using a custom class to visualize DesignCards that are shown inside a dropdown menu after a button is pressed. The values are correct when these Cards are displayer, which I am sure of since they show the right image. However, after I call the "OnSelected" function trough the default "OnPress" event from Unity's Button component, it shows me in the log that it will always use the default values of this class (CardType being "Powersupply" and PartType being "A").

DesignCard Class:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;

public class DesignCard : MonoBehaviour {

    public enum CardType { Powersupply, Sensor, Weapon, Module}
    CardType cardType = CardType.Powersupply;

    public enum PartType { A, B, C, D, E}
    PartType partType = PartType.A;

    private int inStock;
    private Transform MasterObject, contentList;
    private Sprite sprite;

    void Start ()
    {
        MasterObject = GameObject.Find("Master").transform;
    }

    public DesignCard (CardType mCardType, PartType mPartType, int mInStock)
    {
        cardType = mCardType;
        partType = mPartType;
        inStock = mInStock;
    }

    public void CreateCard(Transform mContentList)
    {
        Debug.Log("Created card with type: " + this.GetType().ToString() + " and model: " + this.GetModel().ToString());
        contentList = mContentList;
        GameObject go = (GameObject)Instantiate(Resources.Load("TowerDesignScene/Card"), contentList);
        go.transform.localScale = new Vector3(1, 1, 1);
        sprite = GetImage(this);
        go.GetComponent<Image>().sprite = sprite;
    }

    public CardType GetType()
    {
        return (cardType);
    }

    public PartType GetModel()
    {
        return (partType);
    }

    public Sprite GetSprite()
    {
        return (sprite);
    }

    public void AddToStock()
    {
        inStock++;
    }

    public int GetStock()
    {
        return (inStock);
    }

    public void OnSelected ()
    {
        Debug.Log("Pressed on card with type: " + this.GetType().ToString() + " and model: " + this.GetModel().ToString());
        MasterObject.GetComponent<TowerDesignMasterScript>().SetCard(this);
    }

    private Sprite GetImage(DesignCard mCard)
    {
        DesignCard.CardType cardType = mCard.GetType();
        DesignCard.PartType partType = mCard.GetModel();
        sprite = null;
        string imagePath = "TowerDesignScene/DesignCards/";
        if (cardType == DesignCard.CardType.Module) imagePath += "Module/";
        else if (cardType == DesignCard.CardType.Powersupply) imagePath += "Powersupply/";
        else if (cardType == DesignCard.CardType.Sensor) imagePath += "Sensor/";
        else if (cardType == DesignCard.CardType.Weapon) imagePath += "Weapon/";
        if (partType == DesignCard.PartType.A) imagePath += "Type A";
        else if (partType == DesignCard.PartType.B) imagePath += "Type B";
        else if (partType == DesignCard.PartType.C) imagePath += "Type C";
        else if (partType == DesignCard.PartType.D) imagePath += "Type D";
        else if (partType == DesignCard.PartType.E) imagePath += "Type E";

        sprite = Resources.Load<Sprite>(imagePath);
        return sprite;
    }

}

Log when pressing each of the 5 buttons in the same order they are created: (cleaned up the unneccesary lines)

Created card with type: Powersupply and model: A 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: B 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: C 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: D 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Created card with type: Powersupply and model: E 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 35)

Pressed on card with type: Powersupply and model: A 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A 
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

Pressed on card with type: Powersupply and model: A
(Filename: Assets/Tower Design/Scripts/DesignCard.cs Line: 70)

I'm pretty sure this isn't some sort of bug, but I'm running out of ideas of where the source of my issue may be.

Thanks.




Am I misunderstanding how pointers work?

I have a class Matrix and another class Camera that I want to utilize the Matrix in. My Matrix class looks like this:

class Matrix {
    public:
        Matrix4f() {
            this->setMatrix(EMPTY);
        }

        Matrix4f(Matrix4f &m2) {
            this->setMatrix(m2.matrix);
        }

        Matrix4f& Matrix4f::identity() {
           Matrix4f& identity = Matrix4f() ;
           identity.setMatrix(IDENTITY);
           return identity;
        }

        void setMatrix(float f[4][4]) {
            for (int r = 0; r < 4; r++) {
                 for (int c = 0; c < 4; c++) {
                      this->matrix[r][c] = f[r][c];
                 }
            }
        }

        Matrix4f& operator=(const Matrix4f &m2) {
             this->setMatrix(m2.matrix);
        }
    private:
        float matrix[4][4];
        static float EMPTY[4][4] = // initialize an empty array (all zeros);
        static float IDENTIY[4][4] = // initialize a identity (array)
}

And I have this in my camera class:

class Camera {
    public:
        Camera() {
            this->calculateProjection();
        }

        Matrix4f* getProjection() {
            return this->projection;
        }
    private:
        Matrix4f* projection;

        Matrix4f* calculateProjection() {
             this->projection = &Matrix4f::identity();
             // modify this->projection...

             return this->projection;
        }
  }

When I try to create a Camera instance and then get its projection I get something that looks like a corrupted object (the matrix is filled entirely to large negative numbers).

I am really confused what is causing my code to misbehave like this.
I am fairly certain it deals with a reference being automatically deleted by the compiler, and I think it deals with the identity matrix but it doesn't really make sense.

Shouldn't the identity matrix be copied into the projection matrix, so it wouldn't even matter if the identity matrix gets garbage collected?

I found that I can actually make this code work by either making the identity matrix create a new Matrix4f() and returning that OR making getProjection() return the calculateProjection().
Problem is, I really don't want to do either of those.
I don't want Identity to construct a new Matrix4f because then I have to deal with destroying it, and I don't want getProjection() to call calculateProjection() because that method is expensive,
and should really only be called once as the Projection matrix never changes.




how to access variable from another class in python

I would like to access variable lotId & qty_selected in class 'InputDialog' and to be use in class 'Mainwindow'. I did tried to find a solution in net but unable to solve it until now. can anyone show how to make it?

Here is my current code:

from __future__ import division
from skimage.measure import compare_ssim as ssim
import matplotlib.pyplot as plt
import numpy as np
import sys
import os, glob
import cv2
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from inputdialog import Ui_inputDialog
from mainwindow import Ui_mainWindow
from tkinter import messagebox

class MainWindow(QtGui.QMainWindow, Ui_mainWindow):

  def __init__(self, class_input):
    QtGui.QMainWindow.__init__(self)
    Ui_mainWindow.__init__(self)
    Ui_inputDialog.__init__(self)
    self.setupUi(self)
    self.capture_button.clicked.connect(self.captureImage)
    self.display_button.clicked.connect(self.displayImage)
    self.deviceBox.activated.connect(self.selectDeviceCombo)
    self.startInspectionBtn.clicked.connect(self.enterLotID)
    self.display_button.clicked.connect(self.displayResults)
    #self.viewResultBtn.clicked.connect(self.viewResults)
    self.window2 = None


  def enterLotID(self): # Dialog box will ask user to enter lot ID and wafer qty
    if self.window2 is None:
        self.window2 = InputDialog(self)
    self.window2.isModal()
    self.window2.show()

# Program need to be loop through a image file in directory
  def displayImage(self, ):
    os.chdir('c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId )
    for lotId in glob.glob('*.jpeg'):
        print(lotId)

    sample_label = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 6.jpg' # Sample image must read from current folder lot ID running the inspection
    self.sample_label.setScaledContents(True)
    self.sample_label.setPixmap(QtGui.QPixmap(sample_label))

  def selectDeviceCombo(self):
    self.var_Selected = self.deviceBox.currentText()
    #print('The user selected value now is:')
    print('Device = ' + self.var_Selected)

    if self.var_Selected.lower() == 'xf35':
      print("Great! Device Id is - " + self.var_Selected + '!')
      source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 4.jpg'
      self.source_label.setScaledContents(True)
      self.source_label.setPixmap(QtGui.QPixmap(source_label))
    elif self.var_Selected.lower() == 'xf38':
      print("Great! Device Id is - " + self.var_Selected + '!')
      source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 5.jpg'
      self.source_label.setScaledContents(True)
      self.source_label.setPixmap(QtGui.QPixmap(source_label))
    elif self.var_Selected.lower() == 'x38c':
      print("Great! Device Id is - " + self.var_Selected + '!')
      source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
      self.source_label.setScaledContents(True)
      self.source_label.setPixmap(QtGui.QPixmap(source_label))
    else:
      print("Pls select device id. It's compulsory field!")


  def captureImage(self):  # Capture image and display on 'Sample' column under Inspection

    cam = cv2.VideoCapture(0)

    i = 1
    while i < int(input(qty_selected)):
        ret, frame = cam.read()
        cv2.imshow('Please review an image', frame)

        if not ret:
            break
        k = cv2.waitKey(0)

        if k%256 == 27:
        # ESC pressed
         print("Escape hit, closing...")
         break
        if k % 256 == 32:
            # SPACE pressed
            img_name = "_{}.jpeg".format(i)
            #print (img_name)
            cv2.imwrite(img_name, frame)
            #cv2.imwrite(os.path.join(dirname, img_name), frame)
            print("{}".format(img_name))
            i += 1

    cam.release()
    cv2.destroyAllWindows()

  def displayResults(self): #Display image of wafer at 'Result' tab. Simultaneously with 'Inspect'
    label_vid01 = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
    self.label_vid01.setScaledContents(True)
    self.label_vid01.setPixmap(QtGui.QPixmap(label_vid01))


# A new class for user input dialog to enter lot information

class InputDialog (QtGui.QDialog, Ui_inputDialog):

  def __init__(self, parent, lotid):
    QtGui.QWidget.__init__(self, parent)
    self.setupUi(self)
    self.okButton.clicked.connect(self.addLotId)
    self.okButton.clicked.connect(self.selectWaferQty)

  def addLotId(self):
    lotId = str(self.strLotId.toPlainText())
    self.strLotId.setText(lotId)
    print(lotId)

    path = 'c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId
    if not os.path.exists(path):
            os.makedirs(path)

    else:
        messagebox.showwarning('Error','Please enter required information')
        QtGui.QMessageBox.show(self)


  # User require to select wafer quantity upon enter the lot ID
  def selectWaferQty(self):
    qty_selected = self.waferQty.currentText()
    #print ('The user selected value now is:')
    print ('Wafer Qty = ' + qty_selected)

    #if self.qty_selected() == '1':
    #  print('Great! Wafer Qty is - ' + self.qty_selected + '!')

    #else:
    #  print ('Pls select wafer quantity!')

if __name__ == '__main__':
   app = QtGui.QApplication(sys.argv)
   Window = MainWindow()
   Window.show()
   sys.exit()




Using foreach loop with methods in another class (Java)

I have a program that creates a couple objects and adds each one to an ArrayList, then is supposed to loop over each object in the ArrayList and use a getter from another class within the project to display information on each object. I can't get the objects in my foreach loop to use any of the methods in my other class. Here is my main, including the trouble loop at the bottom:

import java.util.ArrayList;

public class ITECCourseManager {

    public static void main(String[] args) {

        ArrayList ITECCourse = new ArrayList();

        ITECCourse infotech = new ITECCourse("Info Tech Concepts", 1100, 5, "T3050");
        infotech.addStudent("Max");
        infotech.addStudent("Nancy");
        infotech.addStudent("Orson");
        ITECCourse.add(infotech);

        ITECCourse java = new ITECCourse("Java Programming", 2545, 3, "T3010");
        java.addStudent("Alyssa");
        java.addStudent("Hillary");
        ITECCourse.add(java);

        for (Object course : ITECCourse) {
            System.out.println("Name: " + course.getName());
        }
    }
}

And here is the other class in my project with the method I need to use:

public class ITECCourse {

    public String name;
    public int code;
    public ArrayList<String> students;
    public int maxStudents;
    public String room;

    ITECCourse(String courseName, int courseCode, int courseMaxStudents, String roomNum) {

        name = courseName;
        code = courseCode;
        maxStudents = courseMaxStudents;
        students = new ArrayList<String>();
        room = roomNum;
    }

    public String getName() {
        return name;
    }

If I replace course.getName() with java.getName(), the code works. I'm confused why I can't use a foreach loop across the ArrayList to use the getter for each object, when I am able to call the object and use the method directly from the same place in the code.




PHP Use static variable in other variable in class

I have a minor problem with using a global variable class for my PHP app. I really want to use this method of storing variables because I know I'll be changing file names and folder structures as time goes on.

I want to use the variable public $rootin the variables under it, that aren't in a method.

Like this:

public $root = "/rootfolder/";
public $something = $root . "path/";

But I keep getting this error:

Fatal error: Constant expression contains invalid operations in C:_server\htdocs\p\chestools\core\php\global.php on line 26

Here's my full page:

class gvars {

  public static $debug_mode = true;

  /*
  * Tab Title Control
  * n\a
  */
  public static $tab_after                = " | Chestools";
  public static $tab_name_enable          = true;

  /*
  * Dialouge Control
  * utils.dialouges.php
  */
  public static $dia_show_fatal = true;
  public static $dia_enabled = true;

  /*
  * Page Paths
  * n\a
  */
  public static $root                     = "/p/chestools/";
  public static $path_home                = "Home";
  public static $path_contactus           = "Contactus";
  public static $path_login               = "Login";
  public static $path_signup              = "Signup";
  //General Pages
  public static $path_help                = "Help";
  public static $path_profile             = "Profile";
  //Student Pages
  public static $path_select_cat          = "Catagorys";
  //Teacher Pages
  public static $path_view_student        = "View";
  public static $path_create              = "Create";
  //Catagorys
  public static $path_cat_math            = "c/math/";
  public static $path_cat_life_sci        = "c/life-science/";
  public static $path_cat_int_sci         = "c/interactive-science/";
  public static $path_cat_earth_sci       = "c/earth-science/";
  //Security
  public static $path_sec_finish          = "security/Finish";
  public static $path_sec_change_password = "security/ChangePassword";
  public static $path_sec_change_email    = "security/ChangeEmail";
  public static $path_sec_checkpoint      = "security/Checkpoint";

  /*
  * System Paths
  * n\a
  */
  public static $head_css                 = "core/css/chestools.css";
  public static $head_js_app              = "core/js/app.js";

  /*
  * Footer Resource Paths
  * n\a
  */
  public static $path_dwa                 = "about/district-wide-accounts/";
  public static $path_isa                 = "about/independent-school-          accounts/";
  public static $path_support             = "support/";
  public static $path_pp                  = "Privacy";
  public static $path_tos                 = "Terms";

}




Swift & Cordova Inheritance Two Class

Now days, I want to create Swift Cordova plugin.

I have a One object.c Library. (.h, .m file)

Then I Want to make a swift class for cordova plugin.

it must inherit by CDVPlugin. but when swift class inherit by CDVPlugin,

then i can't inherit My object.c Library.

Because of, Multiple inheritance is not supported in swift.

How Can I Do?

Cordova Plugin is here

http://ift.tt/2cF7QOJ

http://ift.tt/2dhUKoI

My Object.c Library is here

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "Commucation.h"
#import "MBProgressHUD.h"

@protocol BodySDKDelegate
- (void) Evt_StatusLog:(NSString*)log Status:(LogStatus)status;
- (void) Evt_DetailLog:(NSString*)log Status:(LogStatus)status;
- (void) Evt_Connect;
- (void) Evt_DisConnect;
- (void) Evt_StopScan;
- (void) Evt_BLEUpdateState:(Boolean)isPaired;
- (void) Evt_SendFrame:(NSData*) data;
@end

@interface BLEController : UIViewController <CBCentralManagerDelegate,      UARTPeripheralDelegate>
{
     Boolean SDK_bDisconnect; // disconnect flag
     Boolean SDK_bReceviedAK;
}

@property CBPeripheral*         SDK_discovered_peripheral;
@property UARTPeripheral*       SDK_currentPeripheral;
@property ConnectionState       SDK_state;
@property CBCentralManager*     SDK_cm;
@property id<BodySDKDelegate> SDK_delegate;

- (void) SDK_StopScan;
- (void) SDK_ScanDevice:    (Boolean)init;
- (void) SDK_InitVariable:  (double)_height Weight:(double)_weight Age:    (int)_age Gender:(NSString*)_Gender delegate:(id<BodySDKDelegate>) delegate;
- (void) SDK_fncSendCommand:(unsigned char)cmd1 cmd2:(unsigned char)cmd2 data:(NSData *)data;
- (void) SDK_SetDeviceName: (NSString*) Name;
- (void) SDK_RemoveDevice;
-(Boolean) SDK_CheckPreviousDevice;

@end




Reference imported class from within imported class

For a chess board, imagine there's a Board class, with a squares attribute, which is an array of Square instances. The file structure is that there is main.py, board.py, square.py, and an empty __init__.py (I have to say I don't fully understand the purpose of the latter... but apparently that's the way to do things). These are all in the same directory. (I've not done anything in Python involving multiple files before.)

In main.py I want to instantiate a Board object. Here's the contents of main.py:

from board import Board
from square import Square

board = Board()

here's square.py:

class Square:
    def __init__(self):
        pass
        #this class doesn't do anything yet

and here's board.py:

class Board:
    row_count = 8
    column_count = 8

    def __init__(self):
        self.squares = self.generate_squares()

    def generate_squares(self):
        squares = {}
        for i in range(0, self.row_count * self.column_count):
            squares[i] = Square()
        return squares

However, when I run main.py I get told that there's an error on the squares[i] = Square() line; namely that NameError: global name 'Square' is not defined.

I've tried changing it to squares[i] = square.Square() but that yields the same error.

If I remove the import statements and just copy the class definitions into main.py then the instantiation works fine, so that pinpoints the issue down to being related to the import statements themselves.




Python won't print the from a function in a class

Title pretty much says it all. I am trying to print from a function in a class but Python doesn't print it. It doesn't crash, either. I am using the line

elif option == ("4"): #Print database
    v.print_full()

in line 50 of core.py to call the def print_full(self): in line 75 of my class vehicle.py

Core.py pastebin: http://ift.tt/2cP0KG5

vehicle.py pastebin: http://ift.tt/2dqeuo2




Having problems initializing an object in c++ - Linux

Not sure what I'm doing wrong, was hoping someone can point me in the right direction. I created a customer class but I cannot initialize it.

customer.h

#ifndef CUSTOMER_H
#define CUSTOMER_H

#include "defs.h"
#include <string>
using namespace std;

class Customer
{
  public:
    Customer(string fName, string lName);
    string       getFirstName();
    string     getLastName();
    int        getCustID();
    int        getNumAccounts();

  protected:
    string     firstName;
    string     lastName;
    int        custID;
    int        numAccounts;

};

#endif

customer.cc

#include "defs.h"
#include "Customer.h"


int Customer::nextCustID = 9001;

void Customer(){
    //nothing;
}

void Customer::Customer(int test, int tes2)
{
    custID = 100;
    firstName = "George";
    lastName = "sadfsad";
    numAccounts = 0;
}


void Customer::Customer(string fName, string lName)
{
  custID  = nextCustID++;
  string firstName = fName;
  string lastName = lName;
  numAccounts  = 0;
}

int      Customer::getCustID()  { return custID;  }
string     Customer::getFirstName()     { return firstName;     }
string     Customer::getLastName()     { return lastName;     }
int      Customer::getNumAccounts()  { return custID;  }

I am trying to initialize the customer with

Customer test("Billy", "Bob");

But then I get the error when I try to initialize

BankControl.cc:(.text+0xaf): undefined reference to `Customer::Customer(std::string, std::string)'
collect2: error: ld returned 1 exit status

I can't figure out what I'm doing wrong, if anyone has some input, that would be great. Thanks a lot in advance.




Cannot get variable passed into one specific class, instance member cannot be used on type error

Working on a project where one Storyboard view requires two classes, a normal UIViewController class and an IAxisValueFormatter class that works with the iOS-Charts library to label one axis with string values. These classes in relevant part and in their original (before troubleshooting) form are shown:

import Foundation
import Charts

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter{

    var dates: [String]!

    public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return dates[Int(value)]
    }
}

class SessionRevew: UIViewController {

    @IBOutlet weak var HBCController: HorizontalBarChartView!
    var dates: [String]!

The problem is that I have been unable to pass any values into the IAxisValueFormatter class. Passing values from the previous view controller to the SessionRevew class is painless and continues to work.

The following code from another view controller successfully passes the dates array to the UIViewController class SessionRevew:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "ReviewData") {
        let datespass = segue.destination as! SessionRevew
        datespass.dates = dates
    }
}

However as soon as code is added to pass the same variable to the other class:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "ReviewData") {
        let datespass1 = segue.destination as! BarChartFormatter
        let datespass = segue.destination as! SessionRevew
        datespass1.dates = dates
        datespass.dates = dates
    }
}

The code becomes in operable, as the activation of the segue triggers this error: EXC_BAD_INSTRUCTION error

Which occurs at the line: let datespass1 = segue.destination as! BarChartFormatter If anyone can help me understand why this is failing and how to pass the array to that class, this is the ideal answer. That said, the following represents some efforts to sidestep this error by sharing the variable from the SessionRevew class to the other class. We first created a secondary variable in the other class, which resulted in this:

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter{

    var BCFdates = SessionRevew.dates

    public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return BCFdates[Int(value)]
    }
}

That code will not compile because of the error "Instance member 'dates' cannot be used on type SessionRevew", which occurs on the line:

var BCFdates = SessionRevew.dates

We tried nesting the above class inside of the SessionRevew class, which yielded the exact same error. In trying to resolve this error, we found the solution shown here: http://ift.tt/2cOCm7s, and attempted to implement it like so:

import Foundation
import Charts

class SessionRevew: UIViewController {

    @IBOutlet weak var HBCController: HorizontalBarChartView!

    var dates: [String]!

    @objc(BarChartFormatter)
    public class BarChartFormatter: NSObject, IAxisValueFormatter{

        var BCFdates: [String] {
            get {
                return {
                    SessionRevew.dates
                    }
                }
        }

        public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
            return BCFdates[Int(value)]
        }
    }
}

Unfortunately, the error remains exactly the same ("Instance member 'dates' cannot be used on type SessionRevew") and the code does not compile. Un-nesting the class gives:

import Foundation
import Charts

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter{

    var BCFdates: [String] {
        get {
            return {
                SessionRevew.dates
            }
        }
    }

    public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        return BCFdates[Int(value)]
    }
}

class SessionRevew: UIViewController {

    @IBOutlet weak var HBCController: HorizontalBarChartView!
    var dates: [String]!
}

This code also generates the error code: "Instance member 'dates' cannot be used on type SessionRevew". Then tried to define the BCFdates variable as a read only computed property in accordance with this solution to a similar problem: http://ift.tt/2dpDID0

var BCFdates: [String] {
    return SessionRevew{dates}
}

But the compile error remained. Any solutions or explanations that get this code working would be greatly appreciated. As mentioned before, it would be ideal if we could just pass the array right to the BarChartFormatter class and forget the sharing between class issue.




C# new array. Class with constructor

I am working in Unity but I guess the same applies to C# in general.

this is a class I made:

    public class KeyboardInput
    {
        private string name;
        private KeyCode btn;

        public KeyboardInput(string buttonName, KeyCode button)
        {
            name = buttonName;
            btn = button;
        }
    }

When I create an instance of the class, if I don't specify the values required by the constructor, I will get an error.

Now I want to create an array of the class and I want to specify the values, but how ?

This seems to be working fine without specifying the values

    public class InputController
    {
        private KeyboardInput[] defaultKeyBinding = new KeyboardInput[4];

        public InputController()
        {
            for (int i = 0; i < defaultKeyBinding.Length; i++)
            {
                //Something inside here
            }
        }
    }

I can tweak the code to be able to set the values inside the for loop, but I am very curious to know if there is a way!




Get the full name of a nested class

Given a nested class B:

class A:
    class B:
        def __init__(self):
            pass

ab = A.B()

How can I get the full name of the class for ab? I'd expect a result like A.B.




Collision Game Errors and Timers

In my game I have two problems. First I am getting some errors that I have no idea how to resolve. Secondly my goal for this project is to add a ball every 30 seconds the player survives. However I have tried several methods in doing so (timers and for loops). However these methods have resulted in graphics not appearing but the rest of the functions working (an invisible ball). If anyone could help me fix these issues it would be much appreciated.

import java.awt.*;
import java.lang.*;
import java.awt.event.KeyEvent;
import java.util.Formatter;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Polygon;
import java.awt.geom.Area;
public class  Man  implements KeyListener {

private static final int BOX_WIDTH = 640;
private static final int BOX_HEIGHT = 480;
private float ballSpeedX3 = 7;
private float ballSpeedY3 = 7;
private double ball3Radius = 20;
private double ball3X = 320 ;
private double ball3Y = 120 ;
private float ballSpeedX4 = -10;
private float ballSpeedY4 = 10;
private double ball4Radius = 15;
private double ball4X = 600 ;
private double ball4Y = 300 ;
private float ballSpeedX = 0;
private float ballSpeedY = 0;
private double ballRadius = 20;
private double ballX = 120;
private double ballY = 140;
private float ballSpeed1X = 10;
private float ballSpeed1Y = -10;
private double ballRadius1 = 20;
private double ball1X = 320;
private double ball1Y = 340;
private float ballSpeed2X = -3;
private float ballSpeed2Y = -3;
private double ballRadius2 = 50;
private double ball2X = 50;
private double ball2Y = 400;

private static final int UPDATE_RATE = 30;

public Man() {
    this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
    Thread gameThread = new Thread() {
        public void run() {
while(true){             

              if ( Math.sqrt(    (Math.pow((ballX- ball1X), 2))    +    Math.pow((ballY-ball1Y), 2)) <= (ballRadius1 + ballRadius)) {
    System.exit(0);}
              if ( Math.sqrt(    (Math.pow((ball4X- ballX), 2))    +    Math.pow((ball4Y-ballY), 2)) <= (ball4Radius + ballRadius)) {
                    System.exit(0);}
              if ( Math.sqrt(    (Math.pow((ball2X- ballX), 2))    +    Math.pow((ball2Y-ballY), 2)) <= (ballRadius2 + ballRadius)) {
                System.exit(0);}        

                  ball4X += ballSpeedX4;
                  ball4Y += ballSpeedY4;
                  if (ball4X - ball4Radius < 0) {
                      ballSpeedX4 = -ballSpeedX4;
                      ball4X = ball4Radius;
                  } else if (ball4X + ball4Radius > BOX_WIDTH) {
                      ballSpeedX4 = -ballSpeedX4;
                      ball4X = BOX_WIDTH - ball4Radius;
                  }
                  if (ball4Y - ball4Radius < 0) {
                      ballSpeedY4 = -ballSpeedY4;
                      ball4Y = ball4Radius;
                  } else if (ball4Y + ball4Radius > BOX_HEIGHT) {
                      ballSpeedY4 = -ballSpeedY4;
                      ball4Y = BOX_HEIGHT - ball4Radius;
                  }

              if ( Math.sqrt(    (Math.pow((ball3X- ballX), 2))    +           Math.pow((ball3Y-ballY), 2)) <= (ball3Radius + ballRadius)) {
                System.exit(0);}


                ball3X += ballSpeedX3;
                ball3Y += ballSpeedY3;
                if (ball3X - ball3Radius < 0) {
                    ballSpeedX3 = -ballSpeedX3;
                    ball3X = ball3Radius;
                } else if (ball3X + ball3Radius > BOX_WIDTH) {
                    ballSpeedX3 = -ballSpeedX3;
                    ball3X = BOX_WIDTH - ball3Radius;
                }
                if (ball3Y - ball3Radius < 0) {
                    ballSpeedY3 = -ballSpeedY3;
                    ball3Y = ball3Radius;
                } else if (ball3Y + ball3Radius > BOX_HEIGHT) {
                    ballSpeedY3 = -ballSpeedY3;
                    ball3Y = BOX_HEIGHT - ball3Radius;
                }

                ballX += ballSpeedX;

                ballY += ballSpeedY;


                if (ballX - ballRadius < 0) {

                    ballX = ballRadius;
                } else if (ballX + ballRadius > BOX_WIDTH) {

                    ballX = BOX_WIDTH - ballRadius;
                }

                if (ballY - ballRadius < 0) {

                    ballY = ballRadius;
                } else if (ballY + ballRadius > BOX_HEIGHT) {

                    ballY = BOX_HEIGHT - ballRadius;
                }

                ball1X += ballSpeed1X;
                ball1Y += ballSpeed1Y;
                if (ball1X - ballRadius1 < 0) {
                    ballSpeed1X = -ballSpeed1X;
                    ball1X = ballRadius1;
                } else if (ball1X + ballRadius1 > BOX_WIDTH) {
                    ballSpeed1X = -ballSpeed1X;
                    ball1X = BOX_WIDTH - ballRadius1;
                }

                if (ball1Y - ballRadius1 < 0) {
                    ballSpeed1Y = -ballSpeed1Y;
                    ball1Y = ballRadius1;
                } else if (ball1Y + ballRadius1 > BOX_HEIGHT) {
                    ballSpeed1Y = -ballSpeed1Y;
                    ball1Y = BOX_HEIGHT - ballRadius1;
                }
                ball2X += ballSpeed2X;
                ball2Y += ballSpeed2Y;
                if (ball2X - ballRadius2 < 0) {
                    ballSpeed2X = -ballSpeed2X;
                    ball2X = ballRadius2;
                } else if (ball2X + ballRadius2 > BOX_WIDTH) {
                    ballSpeed2X = -ballSpeed2X;
                    ball2X = BOX_WIDTH - ballRadius2;
                }

                if (ball2Y - ballRadius2 < 0) {
                    ballSpeed2Y = -ballSpeed2Y;
                    ball2Y = ballRadius2;
                } else if (ball2Y + ballRadius2 > BOX_HEIGHT) {
                    ballSpeed2Y = -ballSpeed2Y;
                    ball2Y = BOX_HEIGHT - ballRadius2;
                }

                repaint();
                try {
                    Thread.sleep(1000 / UPDATE_RATE);

                } catch (InterruptedException ex) { }
            }
        }  
    };
    gameThread.start();

}
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);
    g.setColor(Color.BLUE);
    g.fillOval((int) (ballX - ballRadius), (int) (ballY - ballRadius),
               (int)(2 * ballRadius), (int)(2 * ballRadius));
    g.setColor(Color.RED);
    g.fillOval((int) (ball1X - ballRadius1), (int) (ball1Y - ballRadius1),
               (int)(2 * ballRadius1), (int)(2 * ballRadius1));    
    g.setColor(Color.PINK);
    g.fillOval((int) (ball2X - ballRadius2), (int) (ball2Y - ballRadius2),
               (int)(2 * ballRadius2), (int)(2 * ballRadius2));   
           g.setColor(Color.GREEN);
    g.fillOval((int) (ball3X - ball3Radius), (int) (ball3Y - ball3Radius),
                           (int)(2 * ball3Radius), (int)(2 * ball3Radius));
    g.setColor(Color.YELLOW);
    g.fillOval((int) (ball4X - ball4Radius), (int) (ball4Y - ball4Radius),
                           (int)(2 * ball4Radius), (int)(2 * ball4Radius));


}

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
        ballSpeedX = 5;
    }
    else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
        ballSpeedX = -5;
    }
    else if (e.getKeyCode() == KeyEvent.VK_UP ) {
        ballSpeedY = -5;
    }
    else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
        ballSpeedY = 5;
    }
}

public void keyReleased(KeyEvent e) {
     if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
         ballSpeedX = 0;
     }
     else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
         ballSpeedX = 0;
     }
     else if (e.getKeyCode() == KeyEvent.VK_UP ) {
         ballSpeedY = 0;
     }
     else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
         ballSpeedY = 0;

     }  
}
public void keyTyped(KeyEvent e) { }

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame("Collision");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Man man = new Man();
            frame.setContentPane(man);
            frame.pack();
            frame.addKeyListener(man);
            frame.setVisible(true);
        }
    });
}
}




__del__ does not work if the instance is recorded in a class dictionnary

I want to register every instances on my class in a dictionary, keys are one of the parameter.

This seems to work, but the __del__ function fails. Here is the code :

class Test(object):
    instances = {}

    def __init__(self, id):
        self.id = id

    def launch(self):
        print("launch")
        Test.instances[self.id] = self

    def __del__(self):
        print("del")
        del Test.instances[self.id]

And here are the different outputs I get:

>>> a = Test(25)
>>> del a
del
>>> a = Test(25)
>>> a.launch()
launch
>>> del a
>>> 

I don't understand why this is happening, does someone has a suggestion?




can subclass initialize superclass variable

i have an activity say A that is extended by many other activities , i have a variable in activity A which is used by all other sub activities(classes) extending it. I want to know if i can set a value for that variable from a sub-activity such that the change will reflect in all the other subclasses extending Activity A. i know its a basic question ,i am new to this any help is appreciated.

eg:
Activity A has
public String global = "ABC"

Activity B extent A
display(global); ---> ABC

Activity C extent A
display(global); ---> ABC

Activity D extent A
display(global); ---> ABC  

now how can i change global in Activity D such that Activity B and C should also be affected.




C# Using data from another class in a class

First time posting a question because up untill now I've always found the answer I'm looking for here so bear with me. :)

On to the problem, I'm testing an interface I'm making in a console application to use in a game. I got an interface for a character, also made a class for it. In my main code I can succesfully call my "sCharacterName" from my class(Character1Class).

In my (SwordClass) I have a void for equiping the weapon and i want it to show like this: "(sCharacterName) equiped (sWeaponName)." But whenever I try it shows up as a blank space instead of the name. This is part of my code:

namespace ConsoleInterfaceTest
{
    class Program
    {
        public interface ICharacters
        {
            // The name of the character
            string sCharacterName { get; set; }
        }

        public interface IWeapon
        {
            // The name of the weapon
            string sWeaponName { get; set; }

            void Equip();
        }

        public class Character1Class : ICharacters
        {
            // The name of the character
            public string sCharacterName { get; set; }

            public Character1Class(string v)
            {
                sCharacterName = ("ZeeAars");
            }
        }

        public class SwordClass : IWeapon, Characters.ICharacters
        {
            // The name of the weapon
            public string sWeaponName { get; set; }

            public string sCharacterName { get; set; }

            public SwordClass(string sName)
            {
                sWeaponName = sName;
            }

            public void Equip()
            {
                Console.WriteLine(sCharacterName + " equiped " + sWeaponName + ".");
            }
        }

        public static void Main (string[] args)
        {
            Characters.Character1Class character1 = new Characters.Character1Class("");
            character1.CharacterDamage(50);


            Weapons.SwordClass sword = new Weapons.SwordClass("TestSword");
            sword.Equip ();

            Console.ReadKey();
        }
    }
}

Thanks in advance, really been scratching my head for a couple days with this problem :D




in Python Class object, how to auto update attributes when you change only one entry of a list

I have seen this answer for a very similar question:

http://ift.tt/2duk8eb

I will paste the code here:

class SomeClass(object):
    def __init__(self, n):
        self.list = range(0, n)

    @property
    def list(self):
        return self._list
    @list.setter
    def list(self, val):
        self._list = val
        self._listsquare = [x**2 for x in self._list ]

    @property
    def listsquare(self):
        return self._listsquare
    @listsquare.setter
    def listsquare(self, val):
        self.list = [int(pow(x, 0.5)) for x in val]

>>> c = SomeClass(5)
>>> c.listsquare
[0, 1, 4, 9, 16]
>>> c.list
[0, 1, 2, 3, 4]
>>> c.list = range(0,6)
>>> c.list
[0, 1, 2, 3, 4, 5]
>>> c.listsquare
[0, 1, 4, 9, 16, 25]
>>> c.listsquare = [x**2 for x in range(0,10)]
>>> c.list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In this code, when I update the list using:

>>> c.list = [1, 2, 3, 4]

c.listsquare will be updated accordingly:

>>> c.listsquare
[1, 4, 9, 16]

But when I try:

>>> c.list[0] = 5
>>> c.list
[5, 2, 3, 4]

Listsquares is not updated:

>>> c.listsquare
[1, 4, 9, 16]

How can I make listsquare auto update when I change only one item inside the list?




Moodle - Override function from lib.php in theme or Plugin

I'm trying to reduce core patches in a moodle-instance. There where a lot of renderer-related patches, that I could move to the theme.

Now, I am stuck with functions in e.g. lib/datalib.php.

Is it possible to override core functions beside output renderers in moodle 2.6 on plugin or theme base? If so, how can on do?




how to get datas from mainwindow to other class/namespace

is it possible to get the data from WPF mainwindow's listbox and then access it from a class/namespace? or put the codes into other class and then access it by functions in the mainwindow? how? i have no idea, tried to watch some videos but they use atleast 2 different forms, with many classes or modules.




Stub dependent objects

Suppose that we have an object that has a vertical dependency from another

class Ship
  def initializer
    ...
  end

  def launch
    ShipLauncher.new(self, platform: platform)
  end
end


class ShipLauncher
  def initializer(ship, platform:)
  ...
  end
end

And we want to test it:

it do
  allow(ShipLauncher).to receive(:new)

  ship = Ship.new
  ship.launch

  expect(ShipLauncher).to have_received(:new).with(ship, platform: 'x')
end 

Until now all seems good, but if we change the ShipLauncher class like this

 class ShipLauncher
  def initializer(ship, platform_number:)
  ...
  end
end

The test will pass when it shouldn't because the ShipLauncher class expects another parameter. What I'm doing wrong? I must test it with an integration test? What happen if the ShipLauncher class hides a big complexity? I have to stub all its dependencies?




Programming: Classes VS Functions

Talking in general, (not referring to a particular programming language) is there one thing in the world that can be accomplished with classes only that functions cannot?

If the response is "no" What is the point in using classes instead functions in programming?

It seems to me that using classes code is more complex... but might be that I'm talking as newbie/profane...




Getters and setters on Java

Very brief question.

 

If I do a class: Circle.java, for example. I declare as attribute Radius, and as getter and setter: getRadius() and setRadius(float R).

 

Now, if a do a method on Circle.java, public float areaCircle(), do I need to use getRadius() or can I just use radius.




In object oriented php class , what is meant by $this->name = $name?

class User {

  public $name;

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

  public function sayHi() {
    echo "Hi, I am $this->name!";
  }
}

Can someone explain to me word by word, what is meant by $this->name=$name? I keep thinking like, $this goes into(hence the -> sign) name which is (hence the = sign) $name defined beforehand. Also I dont see the need of that function?

Could just go like this :

class User {

  public $name;

  public function sayHi() {
    echo "Hi, I am $name!";
  }
}

I'm out of idea thinking about this .. thanks in advance.




Method and class on Java

So, I'm writing a Java program that has some classes in it. I have one class that is Rectangle.java and the other Circle.java. On Rectangle.java I'm doing a method to compare the area of the rectangle and the circle. It's called public boolean compare(Circle C).

When I call the method on Principal.java I declare Rectangle R = new Rectangle(), Circle C = new Circle(), and then R.compare(C).

My question is, inside of public boolean compare(Circle C) do I need to call another time Rectangle R = new Rectangle() to compare R.areaRectangle() with C.areaCircle(), or there is another way to do it?

Thanks in advance




How to use child class to change parents property

I'm trying to change a property in my parent class with my child class but I'm not getting the result I'm expecting. I've done some research (like Change parent variable from child class), but I can't seem to find the problem.

class A {
    public $msg;

    public function __construct() {
        $this->msg = 'foo';
    }

    public function setMessage($string) {
        $this->msg = $string;
    }

    public function getMessage() {
        var_dump($this->msg); // For demo purposes
    }

    public function triggerB() {
        $b = new B;
    }
}
class B extends A {
    public function __construct() {
        parent::setMessage('bar');
    }
}

$a = new A;
$a->getMessage();
$a->triggerB();
$a->getMessage();

The output I get is "foo" twice and I expect it to be "foo" "bar".

Could anyone explain me what i'm doing wrong and how I can fix this?




PHP class in WordPress: assign value using get_option()

The below is a dependency of another script, and in its current form it works just fine. It's just some info needed to authenticate an API call.

<?php
class getStuff {
    public $subdomain = 'somedomain';
    public $key = '123-456-789';
}
?>

However, the values are static. I want to use get_option() to make these values easily changeable from wp-admin. So I figured that this would make sense...

<?php
class getStuff {
    public $subdomain = get_option( 'option_subdomain' );
    public $key = get_option( 'option_key' );
}
?>

Of course, it won't work. I've read and tried a lot of examples on constructors they seem to be addressing different problems. I'm not exactly sure what to look for...

BTW, there is nothing wrong with the way information is stored in options.php - it's working just fine.




Assign a BigInteger to a normal integer

For example, I can do this :

uint64_t a = 100;
BigInteger b = a;

But I can't do this :

BigInteger a = 100;
uint64_t b = a;

Is there any way? Thanks.




Cannot access aspose.barcode license

I'm making a barcode recognition in java and I already have an aspose.total license. When I try to call com.aspose.barcode.License, it seems that its not working. It throws an error message saying that I'm still using an evaluation version. Now, I'm asking for your suggestions/comments about this. I'm having this wild thought in mind that maybe my problem is in my aspose license file path.




Misunderstanding in use of class variables from a header file

struct TodoItem
{
    std::string todo;
};

const int MAX_STACK_SIZE = 5;

class TodoStackArray
{
  public:
    TodoStackArray();  //confusion here<---
    bool isEmpty();  
    bool isFull();  
    void push(std::string todoItem);  
    void pop();  
    TodoItem* peek();  

    /* for grading purposes we need these following methods */  
    int getStackTop()    { return stackTop; }  
    TodoItem** getStack() { return stack; }   

  private:  
    int stackTop;  
    TodoItem* stack[MAX_STACK_SIZE];  
};  

Above, is some declarations and a class from a header file for a current assignment. Our duty was to implement a stack program using this header file. However, I am a little confused as to the purpose of the "TodoStackArray()" in the Header File. Is this supposed to be a base constructor? Am I supposed to use it for anything??

I understand that this is somewhat situation specific but given that stack Arrays are STL I figured you might all be able to provide some insight. Thanks!

In case you want to see what I did with this header file...

TodoStackArray::TodoStackArray() //This, unsurprisingly, produces an error.
    {
        stackTop = -1;
        stack[stackTop];
    }

    bool TodoStackArray::isEmpty()
    {
        return (stackTop == -1);
    }

    TodoItem* TodoStackArray::peek()
    {
        if(stackTop ==-1)
        {   
            cout<< "Stack empty, cannot peak."<<endl;
        }
        else
        {
            return(stack[stackTop]);
        }
    }
    bool TodoStackArray::isFull()
    {
        return(stackTop == 4);
    }

    void TodoStackArray::push(std::string todoItem)
    {
            if(stackTop >= 5)
            {
                cout<<"Stack full, cannot add new todo item."<<endl;
            }
            else
            {
                stack[stackTop++];
                stack[stackTop]->todo = todoItem;
            }
    }

    void TodoStackArray::pop()
    {
        if(stackTop == -1)
        {
            cout<<"Stack empty, cannot pop an item."<<endl;
        }
        else
        {
            stackTop--;
        }
    }

Also, to be clear, we were not provided driver software. They will be assessing from their own stuff so we have to write our own driver software to test our functions. Hence the lack of any Main implementation.




Add current date and PC username when a class is created in Visual Studio

Is it possible to add creation date and username when a *.cs file is created in Visual Studio like IntelliJ IDEA do?

For example:

//Created by Tamerlan, 9.28.2016 11:00  <- add this line automatically
public class MyNewClass
{
}




mercredi 28 septembre 2016

Java - Deferent between declare class and class object (class vs class)

Please see below code and say me what is deferent.

public class c1
{
  //....
}

Class c2 = obj.getClass();

Object o1 = new c1();
Object o2 = new c2();  //  <<-----  here 

Whats wrong end line ???

How i can to create a object of c2 ????




Java- Print the source code of imported class

Is there any way to view the source code of the imported class? For example

import java.io.Reader;
public class Helper {
    public static void main(String args[]){
        // print source code of java.io.Reader
    }
}

How can I print the source code of java.io.Reader in my class?




Shadowing Precedence Ordering for an outer variable vs an inherited variable

If I have an inner class that is in the context of an outer class that defines some field "foo", and that inner class inherits from another class that also has a "foo" field, which foo is visible within the inner class?




Convert Class Object to String

I have an assignment for a class that requires me to convert a class object, clock_time, to a string using two required, instructor-defined empty functions: to_string() and an overloaded << operator. I am not able to get it to work and I am unsure why.

string to_string(clock_time c)
{
    ostringstream ss;
    ss << c;
    return ss.str();
}

ostream& operator<<(ostream &out, clock_time c)
{
    out << to_string(c);
    return out;
}




Classes and 2 Dimension Arrays

The code I am working with is below. I feel like this should be simple, but I'm having an incredibly hard time focusing this week and need some help.

I'm not able to properly set the values for pt.x or pt.y in the nested for loops. IDEA is telling me that the symbol can't be resolved. The class is identified from another java file in the package that only identifies that class. it is as follows:

public class pointClass {
    class point{
        int x;
        int y;
        int z;
    }
}

(Adding text to demonstrate these are 2 separate files)

This is for a class assignment, but I'm not sharing the whole assignment, just what I need help with. I'm trying to learn, not have things done for me.

public class main {
    public static void main (String args[]){

        ArrayList<pointClass.point> pointlist =  new ArrayList<>();

        //Creating map
        int row = 40;
        int col = 40;
        int [][] bigarray = new int [row] [col];

        //iterating through map
        for (int i = 0; i < row; i++;){
            for (int j=0; j< col; j++){
                pointClass pt = new pointClass.point;
                pt.x = row;
                pt.y = col;
                pt.z = ;//RNG HERE//

            }
        }

How do I need to more properly identify these class attributes? For context,this code cretes a 40x40 array and will assign a random value to each number. Another code stanza will be added to print the 2D array.




undefined reference to `class::class() error [duplicate]

I have looked at other similar questions but I did not really understand the answers very well. I am getting this error:

In function main': C:/Users/Danny/ClionProjects/LinkedList/main.cpp:9: undefined reference tolinkList::linkList()' collect2.exe: error: ld returned 1 exit status

linkList.cpp:

#include <iostream>
#include <cstdlib>
#include "linkList.h"

using namespace std;

linkList::linkList()
{
    head = NULL;
    follow = NULL;
    trail = NULL;
}

void linkList::addNode(int dataAdd) 
{
    nodePtr n = new node; 
    n->next = NULL;
    n->data = dataAdd;

    if (head != NULL)
    {
        follow = head;
        while (follow->next != NULL)
        {
            follow = follow->next;
        }
    }
    else
    {
        head = n;
    }

}

void linkList::deleteNode(int nodeDel)
{
    nodePtr delPtr = NULL;
    follow = head;
    trail = head;

    while(follow != NULL)
    {
        trail = follow;
        follow = follow->next;
        if (follow->data == nodeDel)
        {
            delPtr = follow;
            follow = follow->next;
            trail->next = follow;
            delete delPtr;
        }
        if(follow == NULL)
        {
            cout << delPtr << " was not in list\n";
            delete delPtr; // since we did not use delPtr we want to delete it to make sure it doesnt take up memory
        }

    }

}

void linkList::printList()
{
    follow = head;
    while(follow != NULL)
    {
        cout << follow->data << endl;
        follow = follow->next;
    }


}

LinkList.h:

struct node {
    int data;
    node* next;
};

typedef struct node* nodePtr; 


class linkList
{ // the linkList will be composed of nodes

private:
    nodePtr head;
    nodePtr follow;
    nodePtr trail;

public:
    linkList();
    void addNode(int dataAdd);
    void deleteNode(int dataDel);
    void printList();
};

main.cpp:

#include <cstdlib>
#include "linkList.h"


using namespace std;

int main() {

    linkList myList;


    return 0;
}

I understand it has something to do with the way my files are linked, when I change #include linkList.h to #include linkList.cpp in my main file it works fine why is this? I have another similar program that is a binary search tree that works perfectly and has basically the same type of set up. So my question is how do I fix it? why is it happening?




Iterate through java classes and call main?

I'm importing a package of java classes and I want to call the main method of each one.

Basically my question is, how can I shorten this?

import somePackage.*;

A1.main(args);
A2.main(args);
A3.main(args);
// so on...

Is there a way to store them and iterate through them?




TypeError: argument of type 'class_object' is not iterable - python

I am having an issue iterating through a class that I stored into a list. This class has two variables and that is it.

I am getting the error: TypeError: argument of type 'FileClass' is not iterable, where FileClass is my class.

Here is the code:

        for i, address in enumerate(filePaths):
                fp = filePaths[i]
                if fp.path in address:

I am basically trying to store the class in a list, iterate through it, and assign each class object in the list to a variable and access that objects attributes to see if it is in address.

Let me know if you can spot the issue!

Thanks!




TYpescript : Static methods on Function as class

I have a fn that inherit an existing fn ( take Angular1 $q for example )

//$q original behavior
var defer = $q.defer();
defer.promise.then(function(result){})
//or
$q( (resolve, reject) => {
   //promise execution here
}).then(function(result){});

If I want to decorate it, I would do :

var Qdecorator = function($delegate) {

     var Q = function(resolver:any): any {
       //do some extra stuff here
       return $delegate.apply($delegate, arguments);
     }

     //Assign the static methods here: 

     Q.defer = function() {
        //do some stuff 
        return $delegate.defer.apply($delegate, []);
     }
     //same goes for race, when, resole reject and so on
     return Q;
}

Problem is that typescript complains about Property defer, race, when, resolve, etc... does not exist on type '(resolver: any) => any'

I tried to use the IQService, and IPromise with no luck, btu I'd like to raise a more global question :

How do I define late static methods on function() that return an object without using new




React `context` always empty object

I'm trying to set a context in my React App, but somehow i can't acces context from childrens. This is the parent class:

import React from 'react'
import MenuBar from './MenuBar.js'

export default class App extends React.Component {

  static childContextTypes = {
    prop:    React.PropTypes.bool
  };

  getChildContext(){
    return {
      prop: true
    }
  }

  render() {
    return (
      <div>
        <MenuBar />
      </div>  
    )
  }

}

And here is my children class:

import React, { Component } from 'react';

export default class MenuBar extends Component {

  constructor(props, context){
    super(props,context)
    console.log(this.context)
    console.log(context)
  }

  render() {
    console.log(this.context)
    return (
      <div>MenuBar</div>
    );
  }
}

All the console.log's return an empty object, what am i doing wrong?




Secure execution by Java Class Loader

I'm not so good in English and I'm trying to understand a Java book. Here a concept I have not undertook. Could you make it more clear ? Thanks

'The Java Class loader, to safeguard a secure execution, can assign different portions of memory to locally versus remotely obtained classes '




How to store the current login time of a user to database through

I want to store the current time of the system at the time of the user gets login.

public string getlgn(string userNametime, string passWordtime)
{
    var myUser = entity.MVCUsers.FirstOrDefault(m => m.Username == userNametime && m.Password == passWordtime);
    //string s= lastweblogin(userNametime, passWordtime);

    // Get previous login
    var prevLogin = myUser.Lastlogintime;

    // Update with current login
    string currentime = DateTime.Now.ToString();
    prevLogin = currentime;
    MVCUser tbluser = new MVCUser();
    entity.MVCUsers.Add(tbluser);

    //entity.SaveChanges();
    var userlogindate = myUser.UserID.ToString();
    return (userlogindate);
}




python: Threading classes from main_window class

I'm trying to create a game using Tkinter that can run functions from multiple class objects simultaneously using threads. In the MainWindow class, I have "player" and "player2" assigned to the "Player" class.

In the "Player" class, have a function called "move" that simply moves the canvas object.

When the right button is press , "player" starts moving.However, as soon as the left button is pressed, it seems that "player" is stopped in replacement for "player2".

Is there anyway to fix this?

from tkinter import *
from threading import Thread
import time


class MainWindow(Frame):
    def __init__(self , parent):
        self.backround = '#%02x%02x%02x' % (180, 180, 180)
        self.main_width = 1905
        self.main_height = 1002

        Frame.__init__(self , parent , bg = self.backround)
        self.pack(fill=BOTH, expand=1)
        self.parent = parent
        self.parent.geometry('1905x1002+0+0')
        self.main_canvas = Canvas(self , width = self.main_width , height =       
        self.main_height , bg = 'white')
        self.main_canvas.pack()

        self.Keyboard_Events = Thread(target = self.keyboard_events)
        self.Keyboard_Events.start()

players

        self.player = Player(self.main_canvas , [125 , 125] , self) #(canvas , coords)
        self.player2 = Player(self.main_canvas , [200 , 100] , self) #(canvas , coords)

callbacks

    def keyboard_events(self):
        def callback_mouse_primary(event):
            self.player.move(0.01)
        def callback_mouse_secondary(event):
            self.player2.move(0.01)

        root.bind('<Button-1>' , callback_mouse_primary)
        root.bind('<Button-3>' , callback_mouse_secondary)

player class

class Player(Thread):
    def __init__(self , canvas , coords , parent):
        Thread.__init__(self)
        self.setDaemon(True)
        self.canvas = canvas
        self.coords = coords
        self.player_object = self.canvas.create_rectangle(self.coords[0]-25 , self.coords[1]-25 , self.coords[0]+25 , self.coords[1]+25)

    def move(self , Time):

        for y in range(100):
            self.canvas.coords(self.player_object , self.coords[0]-25 , self.coords[1]-25 , self.coords[0]+25 , self.coords[1]+25)
            self.coords[0] += 0.1
            self.coords[1] += 0.1
            self.canvas.update()
            time.sleep(Time)

    def Print_info (self):
        print (self.coords)

if __name__ == '__main__':
    root = Tk()
    main = MainWindow(root)
    root.mainloop()

Just to make it clear. Player objects are created within the MainWindow class and functions within those players are run within the MainWindow class. Is there anyway to thread those player objects to run independently?




Second level looping over dictionaries in Python

In building a class with an out line like below I would like the behaviour of the for loops to, if done once: just give the keys as normal an then move on to the next line of code. But if a second loop is set up inside the first loop it would give the keys on the first loop and then ea value in the sequences in the second loop. The problem I can't figure out is how to set up this under iter.

class MyClass():
    def __init__(self):
        self.cont1 = [1,2,3,4]
        self.cont2 = ('a','b','c')

def __iter__(self):
    pass # ???????

Something like this:

dct = dict(container1=[5,6,7,8], container2=('a','b','c')

if one loop is used:

   for ea in dct:
        print(ea)
print("Howdy")

'containter1'
'containter2'
Howdy

If a nest loop is used:

for ea in dct:
    print(ea)
    for i in dct.get(ea):
        print(i)

'container1'
5
6
...
'container2'
a
b
c




Customize class loading - Java

I am working in an Eclipse based RCP application, where my custom app is deployed as a plugin. I want to customize the Login window for this application, I just know the class of the original Login dialog, but do not have control to customize it.

I want to know whether custom class loading can be an option here, to tell JVM to load my custom login dialog class(which may be a subclass of the original login dialog class) instead of the original class. The application does provide login API to be used by custom applications, so that I will be able to establish the Application session once my custom login window is loaded.

Thanks in Advance. I am able to see in questions related to class loaders that people generally don't like the idea of custom class loading.




is there a plugin in Eclipse that facilitate the drawing of memory models for a class in Java?

I am new to java and learning how to draw memory models with primitive data, I was wondering if a there is an Eclipse Plugins that can facilitate this process like the one used to create UML diagram in BlueJ.




Python Method can pass Class Parameter?

In c#, Method can pass Class Parameter Like this

Public void Method1(Class1 input)
{}

but in python, is this possible to pass class for method parameter?




Error while get array from class

I need help... i don't know how to get my function work. All in one big

the function:

function calc_distance_by_pids($iPid1, $iPid2) {
$aReturn = array('sl' => 0, 'ml' => 0);
    if($iPid1 != $iPid2) {
        $aCoords1 = planet::get_coords_by_pid($iPid1);
        $aCoords2 = planet::get_coords_by_pid($iPid2);
        $aReturn['sl'] = $this::calc_distance_by_coords($aCoords1,$aCoords2);
    if($aCoords1['sys_id'] != $aCoords2['sys_id']) {
        $aSysCoords1 = map::get_systemcoord_by_num($aCoords1['sys_id']);
        $aSysCoords2 = map::get_systemcoord_by_num($aCoords2['sys_id']);
        $aReturn['ml'] = $this::calc_distance_by_coords($aSysCoords1, $aSysCoords2);
    }
}
return $aReturn;
}


function calc_distance_by_coords($aCoords1, $aCoords2, $sX = 'pos_x', $sY = 'pos_y') {
return sqrt(pow($aCoords1[$sX] - $aCoords2[$sX], 2) + pow($aCoords1[$sY] - $aCoords2[$sY], 2));
}

the class:

class planet {
public static function get_coords_by_pid($iPid) {
    switch($iPid) {
        case 1:
            return array('sys_id' => 4,'pos_x' => 231,'pos_y' => 113);
        break;
        case 2:
            return array('sys_id' => 51,'pos_x' => 123,'pos_y' => 241);
        break;
    }
}
}


calc_distance_by_pids($iPid1, $iPid2);

I got the errorcode:

Notice: Undefined variable: iPid1 in F:\Portable\xampp\htdocs\trans\index.php on line 343

Notice: Undefined variable: iPid2 in F:\Portable\xampp\htdocs\trans\index.php on line 343

But... why?




Creating SKU Codes Using PHP

I wanted to apologise off the bat for asking a question with very little prior information to go on, but im at a loss as to how to even start.

I need to create a list of SKUs based on a preset grouping of SKUs that already exists its like a combination table, or iteration table.

However doing this manually is a ridiculous task and I could find no Javascript site that would allow me to do it as required.

Using PHP Classes i thought it would be a much more efficient way to achieve the goal.

AIM: The target item will consist of 5 or so TYPES of items. For each TYPE there is approximately 15-20 exact codes it could consist of.

For example TYPE 1 could be Apple, Pear, Orange, Pineapple. Etc. TYPE 2 could be Red,Green,Blue,Black. Etc

I need to be able to input a list of Variants for each TYPE and have it concatenate the Variants in every possible iteration of an item that could exist.

I am aware this would create 10s of thousands of (in this case) SKUs.

The problem i encounter is when creating the iterations the types always duplicate. Furthermore there are exceptions to this rule, for example Variant Apple could never be with Variant Black. So those types would never be found in the same concatenated code.

Im sure that for someone out their this is really very simple basic grouping and class configuration. So I very much appreciate any help that anyone might have for this.

Many Thanks - Lewis