lundi 31 août 2015

why extend's class insert before inheritance chain when use extend?

When i use B extend A ,A is the first in B's single instance's inheritance chain . Where is B ? Why A is the first ?

module A

end

class B
  extend A

  class << self 
    p self ##<Class:B>   
    p self.ancestors #[A, Class, Module, Object, Kernel, BasicObject]
  end  
end




Checking validity of input - Setter function

This is an exercise for a university project, currently studying object oriented programming, I am rather new at this.

I have a class Publication with the properties Headline and Text. This is the code for the class (the header file)

#include <iostream>
#include <string>

using namespace std;
using std::string;

class publication
{
    private:
        string headline,text;
    public:
        publication(); //constructor

        void set_headline(string const new_headline);
        void set_text(string const new_text);

        string get_headline();
        string get_text();

        void print();
}

And this is the implementation (.cpp file)

#include <iostream>
#include <string>
#include "publication.h"

using namespace std;
using std::string;

publication::publication()
{
    publication.headline="";
    publication.text="";
}

void publication::set_headline(string const new_headline)
{
    publication.headline=new_headline; //any input is valid
}

void publication::set_text(string const new_text)
{
    publication.text=new_text; //any input is valid
}

string publication::get_headline()
{
    return publication.headline;
}

string publication::get_text()
{
    return publication.text;
}

I don't see any issues so far, please correct me if I'm wrong.

Here is my problem:

I need to define a new class called Article. An Article is a type of Publication, as such it inherits from it, but it also has a unique field of its own called Author.

Here is the code for Article class (header file)

#include <iostream>
#include <string>
#include "publication.h"

using namespace std;
using std::string;

class article: public publication
{
    private:
        string author;
    public:
        article();

        void set_author(string const new_author);

        string get_author();
}

And this is the implementation (.cpp file)

#include <iostream>
#include <string>
#include "article.h"

using namespace std;
using std::string;

article::article()
{
    article.author="";
    article.set_headline("");
    article.set_text("");
}

void article::set_author(string const new_author)
{
    article.author=new_author;
}

string article::get_author()
{
    return article.author;
}

Here is my issue:

In the set_author method I want to check that the input is valid. As far as I know, there is no person named 123 or a person named Bob%^!@. Is there a way to check if a string contains characters that aren't letters?




Instance variable gets modified automatically

I made a new class that represents one position in the game of Tic Tac Toe. Basically what I'm trying to do is make a tree of all possibilities of game positions where each node is a Position object and find the best move for the player using minimax algorithm. The minimax algorithm isn't shown below as the Position class is not working as required.

The Position class has a generate_children method that makes a list of Position objects that can be reached from the current position. Executing the program we get the output that after each iteration the pos_matrix of the current Position object is changing which is undesirable. I have not touched the pos_matrix of the current Position object in the loop and play_move makes a copy of the matrix to avoid messing it up. Still the pos_matrix is changing each iteration.

What is happening? How do I debug it?

Tried: moved play_move out of class, didn't work.

Note: A 0 in the pos_matrix represents empty square while 1 represent "X" and -1 represents "O".
Also kiska_chance means "whose chance". :P

class Position:
    def __init__(self, parent_):
        self.parent = parent_
        self.children = []
        self.best_move = []
        self.pos_matrix = []
        self.last_move = []

    def set_pos_matrix(self, pos_matrix_):
        self.pos_matrix = list(pos_matrix_)
        # Avoiding copying problems by creating copy of list

    def set_last_move(self, last_move_):
        self.last_move = list(last_move_)
        # Avoiding copying problems by creating copy of list

    def play_move(self, move, kiska_chance):
        m2 = list(self.pos_matrix)
        x, y = move
        m2[x][y] = kiska_chance

        return m2

    def generate_children(self, kiska_chance):
        children_ = []
        for move in self.get_possible_moves():
            # Passing a Position object into the possible moves with
            # parent as self.
            pos_temp = Position(self)
            pos_temp.set_pos_matrix(self.play_move(move, kiska_chance))
            pos_temp.set_last_move(move)

            print self.pos_matrix

            children_.append(pos_temp)
        self.children = children_

        return children_

    def get_possible_moves(self):
        dem_moves = []
        for i in xrange(3):
            for j in xrange(3):
                if self.pos_matrix[i][j]==0:
                    dem_moves.append([i, j])
        return dem_moves


pos = Position(None)
pos.set_pos_matrix([[0, 0, 0],
                    [0, 0, 0],
                    [0, 0, 0]])
pos.generate_children(1)




PHP; OOP Class variable

class.sqlsrv.php

class SQLSRV {

    var $SERVERNAME   = _SERVERNAME_;
    var $DATABASENAME = _DATABASENAME_;
    var $USERNAME     = _USERNAME_;
    var $PASSWORD     = _PASSWORD_;
    var $CONNECTED;
    var $DATABASESTATE;

    function __construct()
    {
        # code...
    }

    function connect()
    {
        $CONNECTIONINFO     = array(
                                    'Database'                  => $this->DATABASENAME,
                                    'UID'                       => $this->USERNAME,
                                    'PWD'                       => $this->PASSWORD,
                                    "MultipleActiveResultSets"  => true,
                                    "CharacterSet"              => 'UTF-8'
                              );
        $this->CONNECTED = sqlsrv_connect( $this->SERVERNAME, $CONNECTIONINFO) or $this->_error();
    }
}

mainfile.php

require_once('includes/class/class.sqlsrv.in.php');
$db = new SQLSRV();

index.php

require_once('content.php');

content.php

<?php
   $res['sectionlist'] = $db->query("SELECT * FROM Section");
   while ($arr['sectionlist'] = $db->fetch($res['sectionlist'])) {
?>
<tr>
   <td>
      <?php echo $arr['sectionlist']['Name'];?>
   </td>
   <td>
      <span class="label label-default"> pending </span>
   </td>
   <td>
      <a href="javascript:;" class="btn btn-xs default blue-stripe"> detail </a>
      <a href="javascript:;" class="btn btn-xs default red-stripe"> delete </a>
   </td>
</tr>
<?php
}
?>

but when i run this code it show error

Notice: Undefined variable: db in C:\xampp\htdocs\MA\plugins\admin\content.php on line 2

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\MA\plugins\admin\content.php on line 2

thnaks you a lot for help

but it work if im post " $db = new SQLSRV(); " before " $res['sectionlist'] = $db->query("SELECT * FROM Section"); "




Beginner looking for advice regarding the calling of a member function using objects and pointers to objects

I'm fairly new with C++ and am having issues figuring how to properly call the member function using each of the objects of a class we are working on. The question is given to us as a separate function with the actual class (SuperClass) being hidden. The function is as follows:

void UseingObjects( SuperClass& super_class_1, SuperClass* super_class_2, SuperClass** super_class_3) {

}

I need to call the hidden member function SuperMethod using each of the objects (super_class_1, super_class_2, and super_class_3) as well as set the member variable "Super_Member" to the value of 35 in each instance.

I realize that pointers are being used in the parameters and that is what is throwing me off because we have only just started on classes and have yet to dive deep into pointers. Any help on where to get started is greatly appreciated! Thank you!




Access variables from other classes

I would like to know if there is a way to access variables from an abstract class within another class. Here is my abstract class:

public abstract class ParsResults {

    public String Name;

    public String type;

}

Then I have another class that needs these variables. Im just not sure how to approach it. Thanks in advance.




Facebook SDK and Facebook API Classes

I started using FaceBook SDK 4.6, i have to make some requests against the graph api, However i don't see any custom wrapper class for JSON objects in Facebook SDK. I mean lets suppose i retrieve a bench of users photos, is there any FaceBook class (in the SDK) i can map my results to ? or do i have to access the dictionary to get my stuff.

I checked again and again Facebook docs and i don't see anything regarding my issue http://ift.tt/1NTKVK2

Thank you for your help




No suitable method found for println... Java

I am trying to test my arrays that I stored in variables by displaying the first int/double/string stored under a method called displayMessage. However for some reason whenever I make the method I get the error, No suitable method found for println..., for my Println statement. Any and all help would be fantastic! thanks in advance, below is the code.

public class InventoryClass {
    private int[] itemNumber = {1,2,3,4,5,6,7,8,9,10};
    private String[] productName={"CD1","CD2","CD3","CD4","CD5","CD6","CD7","CD8","CD9","CD10"};
    private int[] unitsInStock={2,14,22,11,5,20,7,9,14,31};
    private double[] productPrice={4.99, 9.99, 4.99, 9.99, 7.99, 7.99, 14.50, 9.99, 9.99, 4.99};




    public void displayMessage(){
        System.out.println(itemNumber[1], productName[1], unitsInStock[1], productPrice[1]);}




Pool within a Class in Python

hope you are doing great :-)

I would like to use Pool within a class, but there seems to be a problem. My code is long, I created a small-demo variant to illustrated the problem. It would be great if you can give me a variant of the code below that works.

Thanks for helping.

from multiprocessing import Pool

class SeriesInstance(object):
def __init__(self):
    self.numbers = [1,2,3]
def F(self, x):
    return x * x
def run(self):
    p = Pool()
    print p.map(self.F, self.numbers)


ins = SeriesInstance()
ins.run()




Silly errors (beginner)

I have a first activity ("Home"), with two buttons: one is called About and leads to activity About and the second is named List and leads to the activity List.

Manifest.xml should be fine, but I get a load of tiny petty errors I can't fix up by myself, regrettably.

Home.class is the following ublic class Home extends AppCompatActivity {

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

    Button AboutButton = (Button)findViewById(R.id.About);

    AboutButton.setOnClickListener(new View.OnClickListener()){

        @Override
                public void onClick(View view); {
            Intent openAbout = new Intent(Home.this, About.class);
            startActivity(openAbout);
        }
    }

    Button ListButton = (Button)findViewById(R.id.List);

    ListButton.setOnClickListener(new View.onClickListener());{

        @Override
                public void onClick(View view); {
            Intent openList = new Intent(Home.this, List.class);
            startActivity(openList);
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

while About.class is like this

public class About extends AppCompatActivity {

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

    Button ReturnButton = (Button)findViewById(R.id.Return);

    ReturnButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent returnhome = new Intent(About.this, Home.class);
            startActivity(returnhome);

        }


        public void onClick(View view); {
            Intent returnhome = new Intent(About.this, Home.class);
            startActivity(returnhome);
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_about, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

and List is like this:

public class List extends AppCompatActivity {

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

    Button ReturnButton = (Button)findViewById(R.id.Return);

    ReturnButton.setOnClickListener(new View.OnClickListener()){

        @Override
        public void onClick(View view)   {
            Intent returnhome = new Intent(About.this, Home.class);
            startActivity(returnhome);
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_list, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

I get lot of red light bulbs, saying, for instance that ")" or ";" is expected or (worse) onClickListener cannot be resolved

Last but not least: I copied this code online and I was wondering why after "View" there is a "view"; what does it mean?

Many thanks in advance




How do I make a character creator that can create variations of the same character? (see post)

This is my first question BTW. So I have been having this problem with a program in Python, I am making a Character class that is able to make characters with different stats, abilities, etc. The class works perfectly fine, but the problem is; I don't know how to make variations of a character. For example,

class Char:
    def __init__(self, HP, attack):
        self.HP = HP
        self.att = attack

Tom = Char(5, 7)
Bill = Char(6, 6)

player1 = Tom
player2 = Tom

print player1.HP, player2.HP
#prints out 5, 5
player1.HP = 3

print player1.HP, player2.HP
#prints out 3, 3

If I could make variations of a character, it would print out 3, 5 on the last part. I figure this can be fixed with another class or a function, but I don't know how. Help?




Public properties in a class

I have two public properties in a class. The business requirement is one property to be exactly the copy of the other one.

How can I have one of the properties to point to the other one? I want ProductNumebr to be the same as SKU.

private string _sku;
public string Sku
{
            get
            {
                return _sku;
            }
            set
            {
                this._sku = value;
            }
}

private string _productNumber;    
public string ProductNumber 
{
             get
             {
                return _sku ?? string.Empty;
             }
             set
             {
                 this._productNumber = Sku;
             }
  }




adding a class to a text_field_tag

I am trying to give a class to my text_field_tag

I have this

<%= text_field_tag :login_aei, class: 'form-control' %>

but it keeps generating this :

<input type="text" name="login_aei" id="login_aei" value="{:class=>&quot;form-control&quot;}">

What am I doing wrong ?




Debugging push function from stack class I wrote in c++

void Stack:: Push ( const int *ele1) {
    if(Is_Full())  {
        cout<<"StackOverflow";
        exit(1);
    }
    else 
        a[++top] = *ele1;
    } 
}

and in the main function I write

if( ch == 1) {
     cout<<"Enter element";
     int ele; cin>>ele;
     s.Push(&ele);
}

But whenever I try to push elements onto the stack, it crashes. What could I be doing wrong? The function prototype and other code seems to be fine.


Here's the WHOLE program:

#include<conio.h>
#include<iostream>
#include<stdlib.h>
#include<stdbool.h>
using namespace std;


class Stack {
    static const int Default_size = 100;
private:
    int a[100];
    int ele;
    int max_size;
    int top;

public:

    Stack(int k){
        int top = -1;
        int max_size = k;
    }

~Stack(){ delete [] a; }

public:
void Push(const int ele1);
void Pop();
bool Is_Full();
bool Is_empty();
void Display();
};

void Stack:: Push ( const int ele1) {
    if(Is_Full())  
        cout<<"StackOverflow";
    else 
        a[++top] = ele1;
}






void Stack::Pop () {
    if(Is_empty()) 
    cout<<"Stack empty";
else    
    top--;
}

bool Stack:: Is_Full() {
    if(top == max_size)
    return true;
    else
    return false;
}

bool Stack:: Is_empty() {
    if( top == -1)
    return true;
    else
    return false;
}

void Stack :: Display () {
     for(int i = 0 ; i< top; i++)
     cout<<a[i];
}


int main() {
Stack s(5);
cout<<"1 to push, 2 to pop, 3 to display, 4 to exit";
int ch;
cin>>ch;
 while(ch != 4) {
    if( ch == 1) {
     cout<<"Enter element";
     int ele; cin>>ele;
     s.Push(ele);
    }
    else if( ch ==2) {
    s.Pop();
    }
    else if(ch == 3) {
    s.Display();
    }
    else 
    exit(0);
    cout<<"Enter ch";
    cin>>ch;
}

return 0;
}       




iOS Swift: does not save pList with class

I try to save my own class "Solutions" in a pList. It contains an array of another class "Solution".

let dict: NSMutableDictionary = ["XInitializerItem": Solution() ]
// saving values
dict.setObject(solutions, forKey: "best")

// writing back
dict.writeToFile(path, atomically: false)

But file is not written. I think it depends on the class. With simple datatypes like String or Int is works. What is missing?




Weird NullPointerException in Constructor

I have this class that is supposed to parse an XML file and get information from it and have the information there as properties of the class. The properties are declared outside the constructor and the assigned inside of it so that the argument can be used in it. When I run the program it gives me a NullPointerException on the line where the first property is assigned. What I would like to know is why it is giving me that exception and I would also like to know what the best way is to go about fixing it. All help is appreciated and here is the code for the class:

class Stock{

public double bid;
public double ask;
public int volume;
public double peratio;

public String name;
public String symbol;

public Stock(Quote stockQuote){

    bid = Double.parseDouble(stockQuote.quote.split("<Bid>|</Bid>")[1]);

    ask = Double.parseDouble(stockQuote.quote.split("<Ask>|</Ask>")[1]);

    volume = Integer.parseInt(stockQuote.quote.split("<Volume>|</Volume>")[1]);

    peratio = Double.parseDouble(stockQuote.quote.split("<PERatio></PERatio>")[1]);

    name = stockQuote.quote.split("<Name></Name>")[1];

    symbol = stockQuote.quote.split("<Symbol></Symbol>")[1];

}

}




Why do we need to use association in class diagrams?

In my application, I have been working with class diagrams. Basically, I have drawn class diagrams for the business logic. Hibernate is used as data access layer. In most of the exmples of class diagrams, I've noticed that association is considered in class diagrams.

I don't see any particular reason to use association in class digarms, because we can't implement it on class. Can anybody explain why we need association with an example?




AS3 - Communicating between timers and loops

I have two classes, one with a loop and one with a timer and I am trying to send data from the timer to the loop.

Here is the relevant part of Main.as:

var zero:int = 0;
var shoot:Shooting = new Shooting(zero); //send zero to class Shooting
while (shoot.finished == 0)  
{    
  move.data; //here data to move an object, rest is irrelevant...
}  

Relevant from class Shooting.as:

public class Shooting extends Sprite
{
private var twenty:int;
private var remove:int;
public  var _isPassed:int = 0;
private var thedata:int;
public var finished:int = 0;

    public function Shooting(data:int):void
    {
    thedata = data; // store the zero
    var updateTimer:Timer;
    updateTimer = new Timer(1, 30); 
    updateTimer.addEventListener(TimerEvent.TIMER, Fire);
    updateTimer.start();    
    }

        public function Fire(e:TimerEvent):void                                                         
        {
        for(var i:int=thedata; i >= 0; i--){ // data is bigger or = to 0 so keep going
        if (_isPassed == 29)
        {       
        finished = 1;
        _isPassed = 0; 
        //do more stuff and break
        break; 
        }           
           // it will go here if it's not the 29 time and do +1 to ispassed.
            _isPassed += 1; 
            var atwenty:int = 20;
            twenty = atwenty;


            break;
        }   
}

So, in Main.class there's a "while" that checks if finished == 0(by default it is), if so it will move an object. In Shooting.as, there's a timer going on 30 times and in the 29th time it is supposed to stop itself(which it does), and change the var finished to 1. problem is, while does not detect that "1" and it keeps moving that object and my flash crashes. I am looking for a better way to communicate between timers and classes, and also figure out what I did wrong.

Thank you.




The "wrong" package specification is required to call a subroutine

I would like to ask you for advice on writing a Perl module. We have three files.

(1) main.pl : uses my_function()

#!/usr/bin/perl 
use strict;
use warnings;
use MyClass;
require "./subroutines.pl";

my $instance = MyClass->new({});
$instance->my_method("a");

MyClass::my_function("b"); # This works.
my_function("c"); # Undefined subroutine &main::my_function called

exit;

(2) MyClass.pm : defines MyClass class. my_method() uses my_function() which is defined in "subroutines.pl".

package MyClass;
use strict;
use warnings;
require "./subroutines.pl";

sub new {
  my $class = shift;
  my $self = shift;
  return bless $self, $class;
}

sub my_method{
  my $self = shift;
  my $text = shift;
  my_function($text);
}

1;

(3) subroutines.pl : defines my_function().

use strict;
use warnings;

sub my_function {
  print "[$_[0]] My function is working!\n";
}

1;

The problem is that my_function() is not working in main.pl, even though the source code has require "./subroutines.pl", while MyClass::my_function() works.

[a] My function is working!
[b] My function is working!
Undefined subroutine &main::my_function called at main.pl line 11.

Because my_function() is useful for me, I want to use it in both main.pl and MyClass.pm, but the subroutine is so general that it is quite strange to define it as a method in MyClass.pm. But it is also strange (to me) that we have to write MyClass:: before my_function(), because the subroutine does not depend on MyClass.

My question is: is it possible to modify the above codes so that my_function() works in main.pl without adding MyClass:: before the function call?




Access a class' private members?

So I have parent class A. Classes B and C inherit from A, however they do not relate to each other. Classes B and C both define their own private members. How can class C access class Bs private members, without inheriting from it ?




When we declare a class without extending any class , does it have parent class?

When we declare a class without extending any class , does it have parent class in java?




use the updating String data in other class

I need help regarding using an updating String data in one class to other class. In this case, the String data I am going to use is in the class below call rxtx.java (I've added comment in the code where the data are needed to be used in othe class):

/**
 * Handle an event on the serial port. Read the data and print it.
 */
public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {

            String inputLine=input.readLine();
            String[] parts = inputLine.split(",");
            String part1 = parts[0]; 
            String part2 = parts[1];
            String part3 = parts[2];
            String part4 = parts[3];
            String d1= part1;
            part12User.usePart1Part2(part1,part2,part3,part4); // where i need to use all the string data here( from part1 to part4)


        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

  • note that the String data are updating constantly, below is the method( other class, not rxtx.java) for the "usePart1Part2(part1,part2,part3,part4)":

    public class usedata {
    Connection connection=null;
    
    
        public void usePart1Part2(String part1, String part2, String part3, String part4)
    {
        Date curDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
        String DateToStr = format.format(curDate);
    
        System.out.println(d1);
    
       connection= SQliteConnectionClass.dbconnector();
       try {
    
       String value1 = part1;   
       String value2 = part2;   
       String value3 = part3;   
       String value4 = part4;  GenerateSummonPDF.java
       String Timestramp = DateToStr;
       String query ="insert into CarRegDatabase (Reg, Speed, Serial, CC, TimeStramps) values (?,?,?,?,?)";
       PreparedStatement pst= connection.prepareStatement(query);
       pst.setString(1, value1);
       pst.setString(2, value2);
       pst.setString(3, value3);
       pst.setString(4, value4);
       pst.setString(5, Timestramp);
       pst.execute();
       pst.close();
    
    

I need to use the constantly update string data for the email body below which is the EmailClient.java:

public void createEmailMessage() throws AddressException,       //generate email.
MessagingException {
    String[] toEmails = { "********@gmail.com" };
    String emailSubject = "Speed Violation Summon Issued";
    String emailBody = "'" + "+" + "+" +"+"+"'"; // here is where the string data need to be placed


    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    for (int i = 0; i < toEmails.length; i++) {
        emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
    }

    emailMessage.setSubject(emailSubject);
    emailMessage.setText(emailBody);
    //emailMessage.setContent(emailBody, "text/html");//for a html email
    //emailMessage.setText(emailBody);// for a text email

    }

The questions is how to use the constantly update string data in other class? i search over the internet and found that got this term "observable object". If it is true regarding the term, how do i actually apply ? Hope that I can find ways and solution to this. thanks in advance.




Why is the compiler showing compilation error?

The following program shows compilation error. But when I uncomment the global namespace scope initialization of x the error is gone. But the text C++ How to Program says that if we do not provide a default constructor, the implicit constructor will intilialize the static variables of primitive types to their default values e.g int to 0. Then why is the compiler showing the error: undefined reference to `SampleClass::x'. The code is

#include<iostream>
using namespace std;

class SampleClass{
    private:
        static int x;
        int y;

    public:

        static int getX(){
            return x;
        }


        static void setX(int xd){
            x = xd;
        }

};

//int SampleClass::x= 2;


int main(){
    SampleClass sample;
    sample.setX(2);
    cout << sample.getX() << endl;

}




Need to use the string from other class

I faced a problem by using some of the String in class1 in class2. class 1 in this case is stated in the code below which is usedata.java

import java.sql.*;
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;


public class usedata {
Connection connection=null;

public void usePart1Part2(String part1, String part2, String part3, String part4)
{
    Date curDate = new Date();
    SimpleDateFormat format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
            String DateToStr = format.format(curDate);

   connection= SQliteConnectionClass.dbconnector();
   try {

       String value1 = part1;   //
       String value2 = part2;   //
       String value3 = part3;   //
       String value4 = part4;   // data need to be used in GenerateSummonPDF.java
       String Timestramp = DateToStr;

the value1 to value4 are needed to used in other class which is Generate SummonPDF as below

public class GenerateSummonPDF {

public static void main(String[] args)
   {
      Document document = new Document();
      try
      {
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
         document.open();
         document.add(new Paragraph("the data(value1 to value4 need to print it out here"));  //here is where i need the data
         document.close();
         writer.close();
      } catch (DocumentException e)
      {
         e.printStackTrace();
      } catch (FileNotFoundException e)
      {
         e.printStackTrace();
      }
   }

}

all help are much appreciated. thanks in advance




Python: Printing a variable delcared in __init__.py after importing a class

This could be a duplicate, because I do not know how to search this problem better, but here it goes.

I have a file called main.py and next to it I got a folder called mymodule with __init__.py and myclass.py files inside.

In my main.py want to import mymodule, but that is not all; I have a variable called, say, version = '1.0' inside __init__.py, which I would like to print from main.py after importing mymodule.

The way I think __init__.py works is that when I import mymodule, __init__.py gets "ran" first? So I want to test this "theory" my putting a variable inside __init__.py and printing it after importing mymodule.

mymodule has just a simple class declared in it:

class MyClassWithCtor:

    def __init__(self, number1, number2):
        self.number1 = number1;
        self.number2 = number2;
        self.multi = self.__multiply()

    def __multiply(self):
        return self.number1 * self.number2

I just use it to print out the multi variable after instantiating the class, so I know it works and all.

So in conclusion:

  • I want to normally import a module which consist of a single class
  • But when importing that module, I have a variable called version in my __init__.py which I want to print from main.py after the import.



Array of classes, subclasses of specific class

I have got an array of Classes, declared as follows:

Class<?>[] serviceStack = {GetPlanningData.class, GetTimeTable.class, GetDataToSync.class, GetData.class};

Classes GetPlanningData, GetTimeTable, GetDataToSync and GetData are all subclasses of IntentService.

Can I declare an array of subclasses of IntentService? I tried:

Class<? extends IntentService>[] serviceStack;

and

Class<IntentService>[] serviceStack;

but the first one is a "Generic array creation", as Android Studio says, and the second one permits only to create {IntentService.class, IntentService.class, ...} and no subclasses are allowed.




Does Java support dispatching to specific implementations based on types of multiple objects like Lisp does?

Reading myself into Lisp, currently on this page (http://landoflisp.com), I found the following statement on the second last paragraph on the page that shows when clicking the link CLOS GUILD:

The important thing to note about the example is that in order to figure out which mix method to call in a given situation, the CLOS needs to take into account both of the objects passed into the method. It is dispatching to a specific implementation of the method based on the types of multiple objects. This is a feature that is not available in traditional object-oriented languages, such as Java or C++.

Here is the example Lisp-code:

(defclass color () ())
(defclass red (color) ())
(defclass blue (color) ())
(defclass yellow (color) ())

(defmethod mix ((c1 color) (c2 color))
    "I don't know what color that makes")

(defmethod mix ((c1 blue) (c2 yellow))
    "you made green!")

(defmethod mix ((c1 yellow) (c2 red))
    "you made orange!")

No I think that the last sentence is wrong. I can actually do exactly that with the following Java code:

public class Main {
    public static void main(String[] args) {
        mix(new Red(), new Blue());
        mix(new Yellow(), new Red());
    }

    public static void mix(Color c1, Color c2) {
        System.out.println("I don't know what color that makes");
    }
    public static void mix(Blue c1, Yellow c2) {
        System.out.println("you made green!");
    }
    public static void mix(Yellow c1, Red c2) {
        System.out.println("you made orange!");
    }
}

class Color {}
class Red extends Color {}
class Blue extends Color {}
class Yellow extends Color {}

which gives me the same output, when I run it:

I don't know what color that makes
you made orange!

So my question is: Is this sentence on that page actually wrong and it is possible in Java / C++? If so, maybe it was not possible in an older version of Java? (Although I highly doubt that, since the book is only 5 years old) If not so, what did I forget to consider in my example?




VBA Collection Error "Object doesn 't support this property or method."

I'm trying to pass collections of custom object to custom objects in VBA powerpoint. But I'm having some problems of putting classes into the

It looks like I can't put custom objects in the collection, it gives the error

Private Sub CommandButton1_Click()
    Dim Test As New Collection
    Dim Number_test As New Class1
    Test.Add (Number_test)
    MsgBox (Test.Count)
End Sub

"Object doesn 't support this property or method." Error 438. When I leave out the New before Class1 I get the 91 Error "object variable or with block variable not set"

Private Sub CommandButton1_Click()
    Dim Test As New Collection
    Dim Number_test As Long
    Test.Add (Number_test)
    MsgBox (Test.Count)
End Sub

This perfectly returns a message box with 1 in it.

How can this be, is it true that I cannot pass my 'own' objects into Collections? Is there a workaround.

BTW the code for the class is now simply:

Option Explicit
Private Sub Class_Initialize()
End Sub




Ruby: Assigning an object to a variable

I have a piece of Ruby code I don't understand:

Line = Struct.new(name, "example")  // what happens here?

def foo(lines)
  lines.map { |z|
    Line.new(name, z[:specific])  // equal to 'Struct.new'?
  }
end

Does it mean that Line is an alias for Struct now? Or what else happens here?




dimanche 30 août 2015

Call Java method in current instance of containing object's class

I have a main class as such, "Class A":

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mView = new AppGLSurfaceView(this); <------- I am creating 
    }

    // Log <--------------------------------------- our log function
    public void LogInfo(String message) {
        android.util.Log.i("MyLogTag", "Message:" + message);
    }
}

Class A contains an object of this class:

class AppGLSurfaceView extends GLSurfaceView {
    public AppGLSurfaceView(Context context) {
        super(context);
        mContext = context;
    }

    public boolean onTouchEvent(final MotionEvent event) {
        mContext.LogInfo ("onTouchEvent"); <--------------- FAIL
        return false;
    }

    Context mContext;
}

Off hand, it looks MyActivity is passing a reference of itself to the 2nd class, mView = new AppGLSurfaceView(this) is passing. "this" is the object reference, correct?

I am storing this object reference in class B in a variable via "mContext = context;"

How can I call the LogInfo method?

(I rarely use Java, so if it isn't method but rather a function, please briefly correctly me, I do want to know the Java terminology.)




How to get Model Object using its name from a variable in Laravel 5?

I am trying to get information from a model using its name which is sent as parameter from blade using ajax call.

$.get("{{ url('auditInformation')}}", {modelName: modelName,versions:versions,currentData:currentData[index]});

Now i need to retrieve information using modelName from a model.

So when i tried this:

$auditInfo=Input::all();
    $modelName=$auditInfo['modelName'];
    $values=$modelName::find(1);

I got this response Class 'Designation' not found

But if i use

$modelName=new Designation();
    $values=$modelName::find(1);

then it shows data exactly what i want.

So i understand that this is all about model ( class ) object.

Is there any way to assign object to $modelName using $auditInfo['modelName'] .

Thanks




How can I extend a "normal" class with a static class in Python?

I'm using Python 3 and I'm trying to rewrite a graphics library that I wrote a while ago. Right now, I have a class called Scene which has three methods in addition to its constructor: logic(self), update(self), and render(self).

logic(self) handles the logic of each Scene. It handles all mouse and keyboard input, and figures out whether a button was clicked, et cetera.

update(self) can be thought of as an abstract method. Its contents are simply raise NotImplementedError. update(self) is called a certain number of times each second, and updates whatever is going on in the program, but does not draw anything on the screen. This is the framerate-independent update. If Pong were to be made with this library, the ball's position would be updated in this method.

render(self) actually updates the screen. This way, the speed of the program is not determined by the framerate.

I like my current implementation of Scene. It's really clean right now, and it seems very intuitive. However, I can't get over how to extend Scene. Suppose I want to make a Scene for a basic GUI like a main menu. I want there to be only one main menu Scene, because I don't think it's a good idea to recreate a whole other Scene every time the main menu will be viewed and used.

I started out by extending Scene with a static class, but quickly realized that it's not really possible to do that. Is the current paradigm just to extend Scene with a normal class, and then recreate and destroy it everytime that the subclass must be used? For example, should I just recreate and destroy a hypothetical MainMenu(Scene) object when viewing and leaving it, respectively?




Cannot find cause of LNK 2019 error in my basic code [duplicate]

I am trying to reteach myself on classes and such, but am having a hard time compiling the code. Below are my header, implementation and main codes. When I try to compile, I get:

LNK2019 unresolved external symbol "public: __thiscall artType::artType(void)" (??0artType@@QAE@XZ) referenced in function _main

I realize that this is an over-done question, but I have spent several days trying to get this (retyping it, researching, reading documentation, pulling hair out) and I wish not to spend too much more time on this stupid error.

Thanks in advance for the help,

Nathan

Code: Header (art.h)

#pragma once
class artType
{
public:
    int x;
    int get();
    artType();
};

Implementation file (art.cpp)

#include "art.h"
artType::get()
{
    return x;
}
artType::artType()
{
    x = 2;
}

Main code (Ov1.cpp)

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

int main()
{
    artType a;
    int num = 0;
    num = a.get();
    cout << num << endl;
    return 0;
}




PHP: Get static method reference

I want to get the reference of a static method from another static method in same class, but PHP interprets the two lines (see example code below) always as an access to a constant. Is it not possible to get a reference to static methods in PHP?

class foo
{
    public static function test()
    {
        self::bar();  // calling (not referencing) works
        $bar_reference = self::bar;  // Error: Undefined class constant 'bar'
    }

    public static function bar()
    {
        echo "hello";
    }
}

foo::test();
$bar_reference = foo::bar;  // Error: Undefined class constant

Just to clarify it again: I do NOT want to call the static method - I just want to get a reference to it.




Doubts about top level class acess modifiers in Java

I have some doubts about access modifiers used for top level classes in Java.

1) Can access modifier public or default be used only with top level classes or even with nested classes?

2) Lets say there are two different classes A and B, both in different packages. Then in order to have access (acess to class members) to class A by class B , then both top level class, that is ‘A’ as well as class members should be defined public, right ? If either class or class members are not public then class B will not have access to class A, right ?

Please correct if I'm wrong.




How can I select a paragraph by its attribute?

I'm currently working with the CKEditor and would like to apply custom styles to the text, while the editor is used.

For this to work I need to select all paragraphs by their "class' attribute one by one. Until now I couldn't quite figure out how to this. I know that I somehow need the CKEDITOR.dom.selection class, but I don't know how I can actually use it.




How can I call the class on the same project in eclipse

I am quite new to Java programming. I am facing a problem that is calling another class to function in my main program. I have a class name "rxtx.java" in the same projects. I need to call it to another class "Login.java".below is the code for rxtx.java:

`

 //this is the class i need to call to run
 public class rxtx implements SerialPortEventListener {
SerialPort serialPort;
    /** The port we're normally going to use. */
private static final String PORT_NAMES[] = { 
        "COM4", // Windows

};

/**
* A BufferedReader which will be fed by a InputStreamReader 
* converting the bytes into characters 
* making the displayed results codepage independent
*/

private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
private usedata part12User = new usedata();
public void initialize() {

    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    //First, Find an instance of serial port as set in PORT_NAMES.
    while (portEnum.hasMoreElements()) {
        CommPortIdentifier currPortId = (CommPortIdentifier)`enter code here`  portEnum.nextElement();
        for (String portName : PORT_NAMES) {
            if (currPortId.getName().equals(portName)) {
                portId = currPortId;
                break;
            }
        }
    }
    if (portId == null) {
        System.out.println("Could not find COM port.");
        return;
    }

    try {
        // open serial port, and use class name for the appName.
        serialPort = (SerialPort) portId.open(this.getClass().getName(),
                TIME_OUT);

        // set port parameters
        serialPort.setSerialPortParams(DATA_RATE,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);

        // open the streams
        input = new BufferedReader(new    InputStreamReader(serialPort.getInputStream()));
        output = serialPort.getOutputStream();

        // add event listeners
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}

/**
 * This should be called when you stop using the port.
 * This will prevent port locking on platforms like Linux.
 */
public synchronized void close() {
    if (serialPort != null) {
        serialPort.removeEventListener();
        serialPort.close();
    }
}

/**
 * Handle an event on the serial port. Read the data and print it.
 */
public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {

            String inputLine=input.readLine();
            String[] parts = inputLine.split(",");
            String part1 = parts[0]; 
            String part2 = parts[1];
            String part3 = parts[2];
            //System.out.print(part1);
            //System.out.print(" , ");
            //System.out.println(part2);
            part12User.usePart1Part2(part1,part2,part3);
            //System.out.println(data);

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
}

public static void main(String[] args) throws Exception {
    rxtx main = new rxtx();
    main.initialize();
    Thread t=new Thread() {
        public void run() {
            //the following line will keep this app alive for 1000 seconds,
            //waiting for events to occur and responding to them (printing incoming messages to console).
            try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
        }
    };
    t.start();
    System.out.println("Started");

}

}`

and here is where i need the "rxtx.java" to run in different class call "Login.java".

JButton btnStart = new JButton("Start");
    btnStart.setFont(new Font("Tahoma", Font.BOLD, 13));
    btnStart.setBackground(Color.LIGHT_GRAY);
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
              // Here is where i wan to run the class rxtx.java
        }




Save a class into a binary file - Python

I'm aware that saving a class into a binary file in c++ is possible using:

file.write(Class_variable, size_of_class, amount_of_saves, file_where_to_save)

or something similar, and I wanted to use that in python in order to make it easier to write and read lots of data.

I've tried to do this:

def Save_Game(player, room):
    address = 'Saves/player'

    file = open(address, 'wb')
    file.write(player)

    address = 'Saves/room'

    file = open(address, 'wb')
    file.write(room)

Room and player being class_objects. But it says:

TypeError: must be convertible to a buffer, not PlayerMarty

What can I do?




Disallow subclass to call methods of protected property

I'm developing application using MVC concept and want to restrict the View class from calling methods of model but give it access to model's properties so it can just get data when it needs it. Instead i want to give the Controller class ability to call model's methods(and if possible restrict it from accessing properties cause it really doesn't need to do so).
My question is how do i design classes relationship to achieve that goal or can i just somehow tell php to disallow that class calling methods of another?
Currently relations of my classes look like this:
Controller

class Controller
{
  protected $_model; //has access to model so it can call model's methods to modify it
  protected $_view;

  public function __construct($model, $view)
  {
    $this->_model = $model;
    $this->_view = $view;
  }

}

View

class View
{
  protected $_model; //has access to model so it can get model's properties when needed

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

}

And there are other classes which are inheriting from Controller and View class, like:

class UserController extends Controller
{
  public function modifyData()
  {
    $this->_model->modifyX(1); //this works and it should be working because i need the controller to be able to call model's methods
    $someVar = $this->_model->x; //this works and it should not be working because i don't need the controller to be able to get model's properties
  }
}

and

class UserView extends View
{
  public function getData()
  {
    $this->_model->modifyX(1); //this works and it should not be working because i don't need the view to be able to call model's methods
    $someVar = $this->_model->x; //this works and it should be working because i do need the view to be able to get model's properties
  }
}

So what do you suggest as the best method of achieving this?




Extracting Data From Python Classes

I wrote a program that computes and animates the orbit of pluto, and have begun rewriting it using classes because this seems like a sensible way of introducing more planets into the simulation. i.e have a class that defines the physics, and then feed in specific planet data to get the orbital data.

    class Planet(object):
        m_sun = 1.989*(10**30)
        G = 6.67*(10**-11)
        dt = 1
        coords = []
        def __init__(self, x, y, vx, vy, m):
            self.x = x
            self.y = y
            self.vx = vx
            self.vy = vy
            self.m = m


        def genData(self):
            while self.dt < 100000000:
                r = ((self.x)**2 + (self.y)**2)**0.5
                a = ((self.G*self.m_sun)/r**2)
                ax = -a*((self.x)/r)
                ay = -a*((self.y)/r)
                self.vx = self.vx + ax*self.dt
                self.vy = self.vy + ay*self.dt
                self.x = self.x + self.vx*self.dt
                self.y = self.y + self.vy*self.dt
                coord = (self.x, self.y)
                print coord
                self.coords.append(coord)
                self.dt = self.dt + 1000

pluto = Planet(4495978707000, 0, 0, 4670, 1.305*(10**22))
pluto.genData()

I'm sure it isn't perfect, but it appears to be working (this is the first class i've built on my own). My question is how do I extract the data from 'coords' into a list that I can work with outside of the class.

I want to generate data for each planet, and then use this data to create an animation in Pygame. For example, a list of (x,y) coordinates for pluto, earth, saturn etc. As it stands, it churns out the data, but it doesn't appear to be accessible from outside the class.

I hope my question makes sense.

Thanks!




How do I go about creating a social networking application in Java? [on hold]

I was trying to come up with a social networking application in Java. I have created two classes as of now: Users and Posts. Users contains user_id, user_name, email, password, editprofile(),register(),login(),like(). Posts consists of post_id, content, date,setPost(),getpost(),deletePost(),likeCount()

I am just stuck right now since there are really no tutorial or any sort of help I could get. Also, this is my first time at StackOverflow. Thanks in advance :)




get text from html without id, name or class VB.net

guys i want get text from html and display in textbox.

i want this 100001063622219 to display in textbox.

here is code:

<div class="container" style="max-width: 600px;">

<div id="success-wrap">

    <h1>Success!</h1>

    <p class="lead">
        Your Facebook personal numeric ID is:<br />
    </p>

    <code>100001063622219</code>

    <p>
        <a href="/" class="btn btn-primary">Find another &rarr;</a>
    </p>

</div>




How restrict scala private scope to one object only?

I am trying to specify that val constant is visible only to one object:

object Config {
    private[my.pack.MyObject] val Some = Option("String")
}

// in package my.pack
object MyObject {
    val Other = Config.Some
}

While compiling this I get an error:

[error] C:\path\Config.scala:17: ']' expected but '.' found.
[error]   private[my.pack.MyObject] val Some = Option("String")
[error]              ^

What is wrong? As I read about access qualifiers they can be a class or object, not a package, am I wrong?




samedi 29 août 2015

What happens if a variable does not get a value? [duplicate]

This question already has an answer here:

Hey just wondering since I don't have access to a Java program on a Guest computer. What would happen if a class has two variables, (width and height) and one variable does not get an instance but the other variable does. Would this output to NullPointer? Or would there just be no ouput with no errors?

So this code for example:

class Box{
   public int width, height;
}

So for the instances;

(Anyone saying this a duplicate question, the other question doesn't ask if this turns into error, but instead says what the default value is. I want to know if it turns into an error or just no output.

Box r;
r.height= 5; 

So the width gets no instance; Would this output in error/ or just no output with no errors?




Java Coin Counter Quarters/Dimes/Nickels/Pennies

I've been having trouble with this one program I'm trying to run,

This lab will investigate the problem solving and programming behind such machinery.

You always want to use the fewest coins possible. You should use integer mathematics to solve this problem.

Provide the number of cents through the constructor. Write a method that calculates the number of each type of coin.

tl;dr I need to count coins in a certain amount of cents.

so far, I have this:

public class P4_Icel_Murad_Coins_java{
   private int c;
public P4_Icel_Murad_Coins_java(int coins){
    c = 94;
    int Q_i, D_i, N_i, N_f;
}

public void counter(){
int Q_i = (int)(c % 25);
int Q_f = c - (Q_i * 25);
int D_i = (int)(Q_f % 10);
int D_f = c - (D_i * 10);
int N_i = (int)(D_f % 5);
int N_f = (int)(c - (N_i * 5));

System.out.println("Quarter(s): " + Q_i );
System.out.println("Dime(s): " + D_i);
System.out.println("Nickel(s): " + N_i);
System.out.println("Penny(ies): " + N_f);               

}
}

And my Driver class is

public class Driver_class
{
public static void main(String[] args) {
    P4_Icel_Murad_Coins_java start = new P4_Icel_Murad_Coins_java(94);
    start.counter();
}
}

I am getting really odd numbers that include negatives in the answer, and alot of pennies for some reason. Any help will be appreciated, and thanks in advance.




How do I make my image change to another image on hover

Can anyone help me out ? I'm trying to make my logo to change into another image when on hover.

I've been trying to do a class in my css img:hover with the background-image that I want to change to it. It didn't work




Simple c++ member reference inside method

All I want to do is create a getter for my Rabbit::Color property. I've done quite a bit of research I'd say now. My error reads: 'Rabbit::Color': function call missing argument list; use '&Rabbit::Color' to create a pointer to member This lead to research on pointer to member readings that seemed way too complicated for what I wanted to do. Here's my method:

string Rabbit::getColor() {
string color = this->Color;
//return (color != "") ? color : "color has not been sent";
string test1 = "test";
return color;
}

The error occurs in my cpp file with the method. I'm coming from a c# background so maybe simply accessing a member from inside a method is more complicated than i thought..

Header:

public:
std::string Color();
int Age();
int ChildrenCount();

public:
string getColor();
int getAge();
int getChildrenCount();




How do I edit multiple class names?

My html:

<div class="Month">
        <a class="Jan">Jan</a>
        <a class="Feb">Feb</a>
        <a class="Mar">Mar</a>
        <a class="Apr">Apr</a>
        <a class="May">May</a>
        <a class="Jun">Jun</a>
        <a class="Jul">Jul</a>
        <a class="Aug">Aug</a>
        <a class="Sep">Sep</a>
        <a class="Oct">Oct</a>
        <a class="Nov">Nov</a>
        <a class="Dec">Dec</a>
</div>

My js:

$("#Year2016").click(function() {
    $('.Month a').attr("class", $('.Month a').attr('class') + "2016");
});

my code is changing all the classes to "Jan2016" when I'm trying to just add "2016" to the end of each individual class. I've been messing around with the $.each() function to fix this, but I can't wrap my mind about how to use it correctly.




quick help needed base class undefined

Couldn't find a solution to this anywhere

here is my file layout

SDK.h

#pragma once
#include "Object.h"
#include "Panel.h"

Object.H

#pragma once
#include "SDK.h"

class BaseObject
{
etc...
}

Panel.h

#pragma once
#include "SDK.h"

class Panel : public BaseObject
{
etc...
}

and then the error

Panel.h(5): error C2504: 'BaseObject' : base class undefined

can somebody please tell me how to do it correctly? it's probably a very simple fix :(




Adding lambda methods to class [duplicate]

This question already has an answer here:

I have class A:

class A:
    a = 2
    b = 3
    c = 4

And I added to it methods for getting each member (get_a, get_b, get_c) by

for attrib in ('a', 'b', 'c'):
    f = lambda self: getattr(self, attrib)
    setattr(A, 'get_'+attrib, f)

Surprisingly calling each method on created instance:

a = A()
print(a.get_a())
print(a.get_b())
print(a.get_c())

Results in

4
4
4

Not in as I expected

2
3
4

I figured out that expanding the loop to 3 uses of setattr do the thing, but why? Why rolling up 3 uses of setattr changes anything?




Python3 - Define attribute within class

It's probably a really stupid question, however I don't know how to do this yet and what I tried didn't work.

I need to change the "name" attribute of a button defined in a class.

class Form(npyscreen.Form):
    def create(self):
        self.add(npyscreen.Button, name='Something')

The above works, however when I define the button as a class, I don't know how to define its name:

class button(npyscreen.Button):
    def create(self):
        self.name = "ButtonName"

class Form(npyscreen.Form):
    def create(self):
        self.add(button)

The above doesn't work and I tried a couple of other ways to define the "name" attribute. No luck though.

Help please.




Why ToString using "." operator

Im starting the second course in computer programming and right now I have an intermediate level of C language knowledge, beginner C++ and just have started learning C# language. In C# fundamentals by Bob Tabor he uses the . as class operator eg.

Console.WriteLine(myValue); Console.ReadLine();

Where Console is the class and WriteLine is part of this class. To keep everything organised I was trying understand all the concepts of it but in one moment he converted an integer to string by using function:

myValue.ToString();

And in that point I got lost. Why he uses that logic instead of simple and organised way like:

System.ToString(MyValue);

He hasn't used the value that has to be converted as an argument. That just doesn't make any logic sense.. Am I wrong?




class->methode1()->methode2() what does it mean?

Im introducing myself to QT right now and often comming across calls like class->methode1()->methode2(). What does this mean? methode1() would be a methode of class, but what about methode2() and how does this notation work out?

Can i split this call to class->methode1() and class->methode2() and get the same result?

Is this C++ or QT spezific?




Explicitly access static member variable in static member method - in C++

I know how to access static member variable in static member method - these are two ways I usually use (very simplified):

class S{
    private:
        static const int testValue = 5;
    public:
        static int getTestValue0(){
            return testValue;
        }
        static int getTestValue1(){
            return S::testValue;
        }
};

( working example on : http://ift.tt/1UcOiAH )

My question is: is there any more explicit way how to access static member variable than ClassName::staticMemberVar?

Is there something like self:: in C++ ?

...simply I am looking for something like this for referencing static members.




OnDestroy not working properly UNITY 2D

I am currently having problems with the OnDestroy function. I have 3 Classes, PickUp, AddGold and Player where PickUp and AddGold is component on the same prefab.

When my character collide with a treasure the PickUp script destroys it. The AddGold should then start a function in the Player class.

PickUp:

 void OnTriggerEnter2D(Collider2D other){
     if (other.gameObject.tag=="Player") {
         Destroy (this.gameObject);
     }

AddGold:

 public Player playerScript;
 public int gold;

 void onDestroy(){
     playerScript.addGold (gold);
 }

And Player has this function in it

public void addGold(int gold){

     goldAmount += gold;
 }

Why doesnt this work?




How to add the value of all the objects?

Let's say we have a class SCORE. It has three objects s1,s2 and s3. SCORE has an attribute RUNS. How to add the runs of all the objects ? SCORE has an internal method int TOTALSCORE(). so when that method is called, it should return the total score .

How should i call that method ? Like s1.TOTALSCORE() ? Or any other way?




How to create multiple class with same function

So for some reason, I have to create multiple classes. Just like this code

class Myclass1:
    do_x

class Myclass2:
    do_x

class Myclass3:
    do_x

Currently, I can do that by copying do_x over and over. However it seems not effective. Any better idea?




vendredi 28 août 2015

How can I make a tree Node object display its contents when printed?

This error is occurring when we call the lookup method. Can anyone say how can it be rectified? I am unable to debug it using the available documents online. This is an implementation of a binary tree class. I know it is something related to the equivalence problem.

import deque

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

    def insert(self, data):    
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)  

    def lookup(self, data, parent=None):    
        if self.data == data:
            return self, parent
        if data < self.data:
            if self.left is None:
                return None
            else:
                return self.left.lookup(data, parent=self)
        else:
            if self.right is None:
                return None
            else:
                return self.right.lookup(data, parent=self)

    # aka bfs traversal
    def level_traversal(self):    
        root = self
        dq = deque()
        dq.append(root)
        while dq:
            root = dq.popleft()
            if root.left:
                dq.append(root.left)
            if root.right:
                dq.append(root.right)
            print (root.data)



    def delete(self, data):
        node, parent = self.lookup(data)
        if node.children_count() == 0:
            if parent.left == node:
                parent.left = None
            else:
                parent.right = None
            del node
        elif node.children_count() == 1:
            if node.left:
                n = node.left
            else:
                n = node.right
            if parent:
                if parent.left == node:
                    parent.left = n
                else:
                    parent.right = n
            del node
        else:
            # find the successor
            parent = node
            successor = node.right
            while successor.left:
                parent = successor
                successor = successor.left

            node.data = successor.data
            if parent.left == successor:
                parent.left = successor.right
            else:
                parent.right = successor.right

    def inorder(self):    
        if self.left:
            self.left.inorder()

        print (self.data)

        if self.right:
            self.right.inorder()

    def preorder(self):    
        print (self.data)
        if self.left:
            self.left.preorder()
        if self.right:
            self.right.preorder()

    def postorder(self):    
        if self.left:
            self.left.postorder()
        if self.right:
            self.right.postorder()
        print (self.data)


root = Node(8)
root.insert(3)
root.insert(10)
root.insert(1)
root.insert(6)
root.insert(4)
root.insert(7)
root.insert(14)
root.insert(13)

# look up
print (root.lookup(6))
# level traversal
root.level_traversal()
#mirror image
#root.mirror_image()
#root.delete(3)
#root.level_traversal()

# inorder
#root.inorder()
# pre order
#root.preorder()
# postorder
#root.postorder()
# size
#root.size()
#root.dfs()
#print root.height()




How would I execute a class as non-blocking?

I am creating a proxy that intercepts, decrypts, prints, and sends the packets to its original destination, however, I have a dilemma.. I execute clienttoserver just fine, but I then need to launch servertoclient, but in a non-blocking way. There seems to be no resources, answers, or examples on how to do something like this, and since I can't, the script fails since it needs to receive a client packet, then a server packet, not just server packets as it wants to do.

NOTE: I can NOT use threads, since they need to communicate data, and execute simultaneously.

Code Snippet:

class clienttoserver:
    def __init__(self):
        self.ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.ss.connect(("place.server.end",1234))
        key = "<key>"
        self.cts = rc4.new(key)
        skip = 'a'*len(key)
        self.cts.encrypt(skip)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind(('',1234))
        self.s.listen(500)
        self.client, self.addr = self.s.accept()

    def main(self):
        stcc = servertoclient()
        stcc.main(self.ss)
        while True:
            pack = self.client.recv(1500)
            decpack = self.cts.decrypt(pack[7:])
            print "Packet from Client"
            msgid = struct.unpack(">H",decpack[0:2])
            print "Msg ID: ",msgid
            print "Payload Len: ",decpack[2:4].encode("hex")
            print "Payload: ",decpack[7:]
            print ""
            self.ss.send(pack)


class servertoclient:
    def __init__(self):
        key = "<key>"
        self.stc = rc4.new(key)
        skip = 'a'*len(key)
        self.stc.encrypt(skip)

    def main(self, ss):
        while True:
            pack = ss.recv(1500)
            decpack = self.stc.decrypt(pack[7:])
            print "Packet from Server:"
            msgid = struct.unpack(">H",decpack[0:2])
            print "Msg ID: ",msgid
            print "Payload Len: ",decpack[2:5].encode("hex")
            print "Payload: ",decpack[7:]
            print ""
            self.client.send(pack)

--And my launch script;

import proxy
stpr = proxy.clienttoserver()
stpr.main()




C# Class Copies

I am have a Class.cs that is supposed to run some sockets/buffers, etc. Mainly some networking. Problem is, this Class can only handle 1 client per time. For example if I created a new Class2.cs with the same exact content and called my functions everything will be fine. My question is, how can I do this without actually creating the same class with different names. Like an array of classes but I tried making an array of classes and I faced a problem. The objects in the array are all being used once I use the first element in the array. I need to have each element separately and not affected by the connected sockets in each class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SilkroadSecurityApi;
using System.Net.Sockets;
using System.Threading;

namespace FayBotFinal
{
    public class Connect
    {
        static Security gw_security;
        public static Security ag_security;
        static TransferBuffer gw_recv_buffer;
        static TransferBuffer ag_recv_buffer;
        static List<Packet> ag_packets;
        static List<Packet> gw_packets;
        static List<Packet> gwtmp_packets;
        static List<Packet> agtmp_packets;
        static Socket gw_socket;
        static Socket ag_socket;
        static uint version;
        static uint locale = UInt32.Parse("22");
        static Thread gwloop;
        static Thread agloop;
        public string id, pw, charname;
        static uint loginID;
        public static int ind;
        public int indd;

        public void gwStart(string IP, string Port, string _id, string _pw, string _charname, uint ver)
        {
            ind = indd;
            id = _id;
            pw = _pw;
            charname = _charname;
            version = ver;
            gwloop = new Thread(Gateway_Support_thread);
            gw_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            gw_socket.Connect(IP, Int32.Parse(Port));
            gwloop.Start();
            gw_socket.Blocking = false;
            gw_socket.NoDelay = true;
        }

        public void Gateway_Support_thread()
        {
            SocketError err;
            gw_security= new Security();
            gw_packets = new List<Packet>();
            gw_recv_buffer = new TransferBuffer(4096, 0, 0);
            while (true)
            {
                gw_recv_buffer.Size = gw_socket.Receive(gw_recv_buffer.Buffer, 0, gw_recv_buffer.Buffer.Length, SocketFlags.None, out err);
                if (err != SocketError.Success)
                {
                    if (err != SocketError.WouldBlock)
                    {
                        break;
                    }
                }
                else
                {
                    if (gw_recv_buffer.Size > 0)
                    {
                        gw_security.Recv(gw_recv_buffer);
                    }
                    else
                    {
                        break;
                    }
                }
                 gwtmp_packets = gw_security.TransferIncoming();
                if (gwtmp_packets != null)
                {
                    gw_packets.AddRange(gwtmp_packets);
                }

                if (gw_packets.Count > 0)
                {
                    foreach (Packet packet in gw_packets)
                    {
                        byte[] packet_bytes = packet.GetBytes();
                        Log("[S->C][{0:X4}][{1} bytes]{2}{3}{4}{5}{6}", packet.Opcode, packet_bytes.Length, packet.Encrypted ? "[Encrypted]" : "", packet.Massive ? "[Massive]" : "", Environment.NewLine, Utility.HexDump(packet_bytes), Environment.NewLine);
                        if (packet.Opcode == 0x5000 || packet.Opcode == 0x9000)
                        {
                            continue;
                        }
                        if (packet.Opcode == 0x2001)
                        {
                            if (packet.ReadAscii() == "GatewayServer")
                            {
                                Globals.Server = Globals.ServerEnum.Gateway_Support;
                                Packet response = new Packet(0x6100, true, false);
                                response.WriteUInt8(locale);
                                response.WriteAscii("SR_Client");
                                response.WriteUInt32(version);
                                gw_security.Send(response);
                            }
                        }
                        else if (packet.Opcode == 0xA100)
                        {
                            byte result = packet.ReadUInt8();
                            if (result == 1)
                            {
                                Packet response = new Packet(0x6101, true);
                                gw_security.Send(response);
                                Packet login = new Packet(0x6102);
                                login.WriteUInt8(22);
                                login.WriteAscii(id);
                                login.WriteAscii(pw);
                                login.WriteUInt16(64);
                                SendToServer(login);
                            }
                            else
                            {
                                return;
                            }
                        }
                        else if (packet.Opcode == 0xA102)
                        {
                            if (packet.ReadUInt8() == 1)
                            {
                                uint LoginID = packet.ReadUInt32();
                                string ip = packet.ReadAscii();
                                ushort port = packet.ReadUInt16();
                                agStart(ip, port.ToString(), LoginID, id, pw);
                                break;

                            }
                        }
                        else if (packet.Opcode == 0x2322) // Send Captcha
                        {
                            Packet p = new Packet(0x6323);
                            p.WriteAscii("");
                            SendToServer(p);

                        }
                    }
                    gw_packets.Clear();
                }
                List<KeyValuePair<TransferBuffer, Packet>> tmp_buffers = gw_security.TransferOutgoing();
                if (tmp_buffers != null)
                {
                    foreach (var kvp in tmp_buffers)
                    {
                        TransferBuffer buffer = kvp.Key;
                        Packet packet = kvp.Value;
                        //err = SocketError.Success;
                        while (buffer.Offset != buffer.Size)
                        {

                            int sent = gw_socket.Send(buffer.Buffer, buffer.Offset, buffer.Size - buffer.Offset, SocketFlags.None, out err);
                            if (err != SocketError.Success)
                            {
                                if (err != SocketError.WouldBlock)
                                {
                                    break;
                                }
                            }

                            buffer.Offset += sent;
                            Thread.Sleep(1);
                        }
                        if (err != SocketError.Success)
                        {
                            break;
                        }

                        byte[] packet_bytes = packet.GetBytes();
                        Log("[C->S][{0:X4}][{1} bytes]{2}{3}{4}{5}{6}", packet.Opcode, packet_bytes.Length, packet.Encrypted ? "[Encrypted]" : "", packet.Massive ? "[Massive]" : "", Environment.NewLine, Utility.HexDump(packet_bytes), Environment.NewLine);
                    }

                    if (err != SocketError.Success)
                    {
                        break;
                    }
                }
                Thread.Sleep(1);
            }
        }

        public void agStart(string IP, string Port, uint _loginID, string _username, string _password)
        {
            loginID = _loginID;
            id = _username;
            pw = _password;

            ag_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ag_socket.Connect(IP, Int32.Parse(Port));

            ag_socket.Blocking = false;
            ag_socket.NoDelay = true;
            agloop = new Thread(Agent_thread);
            agloop.Start();
        }


        public static void OnTimed(object e)
        {
            Packet life = new Packet(0x2002);
            ag_security.Send(life);

        }

        public void Agent_thread()
        {
            SocketError err;
            ag_security = new Security();
            ag_recv_buffer = new TransferBuffer(4096, 0, 0);
            ag_packets = new List<Packet>();
            while (true)
            {
                // Pass to agSecurity
                ag_recv_buffer.Size = ag_socket.Receive(ag_recv_buffer.Buffer, 0, ag_recv_buffer.Buffer.Length, SocketFlags.None, out err);
                if (err != SocketError.Success)
                {
                    if (err != SocketError.WouldBlock)
                    {
                        Globals.g_LogManager.WriteRow(LogLevel.Error,"Error: Receive returned error code {0}.", err.ToString());
                        break;
                    }
                }
                else
                {
                    if (ag_recv_buffer.Size > 0)
                    {
                        ag_security.Recv(ag_recv_buffer);
                    }
                    else
                    {
                        Globals.g_LogManager.WriteRow(LogLevel.Warning ,"{0} has disconnected.",charname);
                        //Globals.g_LogManager.WriteRow(LogLevel.Warning, "Reconnecting.......");
                        //DoPacket.LoadSupport(); ->Reconnect here
                        break;
                    }
                }


                // Packet Queue
                agtmp_packets = ag_security.TransferIncoming();
                if (agtmp_packets != null)
                {
                    ag_packets.AddRange(agtmp_packets);
                }

                if (ag_packets.Count > 0)
                {
                    foreach (Packet packet in ag_packets)
                    {
                        byte[] packet_bytes = packet.GetBytes();

                        // Debug
                        Log("[S->C][{0:X4}][{1} bytes]{2}{3}{4}{5}{6}", packet.Opcode, packet_bytes.Length, packet.Encrypted ? "[Encrypted]" : "", packet.Massive ? "[Massive]" : "", Environment.NewLine, Utility.HexDump(packet_bytes), Environment.NewLine);
                        if (packet.Opcode == 0x5000 || packet.Opcode == 0x9000)
                        {
                            continue;
                        }
                        // Identify
                        if (packet.Opcode == 0x2001)
                        {
                            if (packet.ReadAscii() == "GatewayServer")
                            {
                                Globals.Server = Globals.ServerEnum.Gateway_Support;
                                Packet response = new Packet(0x6100, true, false);
                                response.WriteUInt8(locale);
                                response.WriteAscii("SR_Client");
                                response.WriteUInt32(version);
                                ag_security.Send(response);
                            }
                            else
                            {
                                Globals.Server = Globals.ServerEnum.Agent_Support;
                                Packet p = new Packet(0x6103);
                                p.WriteUInt32(loginID);
                                p.WriteAscii(id);
                                p.WriteAscii(pw);
                                p.WriteUInt8(22);
                                p.WriteUInt32(0);
                                p.WriteUInt16(0);
                                ag_security.Send(p);
                            }
                        }
                        else if (packet.Opcode == 0xA103)
                        {
                            if (packet.ReadUInt8() == 1)
                            {
                                Packet response = new Packet(0x7007);
                                response.WriteUInt8(2);
                                ag_security.Send(response);
                            }
                        }
                        else if (packet.Opcode == 0xB007)
                        {

                            Packet p = new Packet(0x7001);
                            p.WriteAscii(charname);
                            Send(p);
                            Timer timer = new Timer(new TimerCallback(OnTimed), null, 0, 5000);

                        }
                        else if (packet.Opcode == 0x3020)
                        {
                            Packet p = new Packet(0x3012);
                            Send(p);
                        }
                        else if (packet.Opcode == 0x34B5)
                        {
                            Packet p = new Packet(0x34b6);
                            Send(p);
                        }
                        else if (packet.Opcode == 0x3013)
                        {
                            Globals.g_LogManager.WriteRow(LogLevel.Notify, "{0} has spawned.",charname);
                            Globals.Characters[1] = 1;
                        }



                        else if (packet.Opcode == 0x3026)
                        {
                            //CHAT HANDLE
                        }
                    }
                    ag_packets.Clear();
                }

                // Check to see if we have any packets to send
                List<KeyValuePair<TransferBuffer, Packet>> tmp_buffers = ag_security.TransferOutgoing();
                if (tmp_buffers != null)
                {
                    foreach (var kvp in tmp_buffers)
                    {
                        TransferBuffer buffer = kvp.Key;
                        Packet packet = kvp.Value;

                        err = SocketError.Success;

                        // Since TCP is a stream protocol, we have to support partial sends. To do this, we
                        // will just loop until we send all the data or an exception is generated.

                        while (buffer.Offset != buffer.Size)
                        {

                            int sent = ag_socket.Send(buffer.Buffer, buffer.Offset, buffer.Size - buffer.Offset, SocketFlags.None, out err);
                            if (err != SocketError.Success)
                            {
                                if (err != SocketError.WouldBlock)
                                {
                                    Globals.g_LogManager.WriteRow(LogLevel.Error, "Error: Send returned error code {0}.", err.ToString());
                                    break;
                                }
                            }


                            buffer.Offset += sent;
                            Thread.Sleep(1);
                        }

                        // We need to check for an error to break out of the foreach loop
                        if (err != SocketError.Success)
                        {
                            break;
                        }

                        byte[] packet_bytes = packet.GetBytes();


                        // Debug (logical packet)
                        //Console.WriteLine("*** Logical ***");
                        Log("[C->S][{0:X4}][{1} bytes]{2}{3}{4}{5}{6}", packet.Opcode, packet_bytes.Length, packet.Encrypted ? "[Encrypted]" : "", packet.Massive ? "[Massive]" : "", Environment.NewLine, Utility.HexDump(packet_bytes), Environment.NewLine);


                        // If we should be ping'ing, we can reset the ping timer 
                    }

                    // We need to check for an error to break out of the main loop
                    if (err != SocketError.Success) break;
                }

                Thread.Sleep(1);
            }
        }

        public void Log(string msg, params object[] values)
        {
            msg = string.Format(msg, values);
            //Globals.MainWindow.n_Support.AppendText(msg + "\n");
        }

        public void SendToServer(Packet packet)
        {
            gw_security.Send(packet);
        }

        public static void Send(Packet packet)
        {
            try { ag_security.Send(packet); }
            catch { }
        }

    }
}




Java: print a value from another class

I have another class in my program called "time". I need to know how to use the toString() in my main program that will display the time startTime variable and the time endTime variable

package concertapp;



public class Concert 
{

    public String name;
    public Time startTime;
    public Time endTime;

    public Concert (String n,Time start,Time end)//Time end))
    {
        name=n;
        startTime=start;
        endTime=end;

    }
    @Override
  public String toString()
    {
        return String.format("%d:%02d:%02d ",startTime,endTime);
                //how do i make this work using my time class, 
                //and being able to print the toString() in main class??

    }


}




I don't know my operators definitions give me an error in my C++ program [duplicate]

This question already has an answer here:

Hello I'm trying to do a programm to work with vectors 3D, so I started with the basic function of add to vectors, so I'm trying to implement a class and then use it for miy porpouse. The following is what I had done, but when I compiled I got some errors. So could you tell me what is wrong with my code.

Thanks and best regards

class Vector3
{
 protected:
    float x, y, z;

 public:
    Vector3();
    Vector3(float, float, float);
    Vector3& operator +(Vector3,Vector3) const;
};

Vector3::Vector3(){
    x=0;
    y=0;
    z=0;
}

Vector3::Vector3(float X, float Y, float Z){
    x=X;
    y=Y;
    z=Z;
}

Vector3& Vector3::operator +(Vector3 v1,Vector3 v2) {
  Vector3 result;
  result.x= v1.x+v2.x;
  result.y= v1.y+v2.y;
  result.z= v1.z+v2.z;
  return result;
};




C# It is possible to forbit childclass to define a class?

Hello I am working with unity 3D making my own networking with lidgren.

I had this problem one time too when I made a custom gui for me but was not big problem. A small warning to other developer was little help.

But this time I need better solution.

Lets say I have a BaseClass and a Child:

public class BaseClass : MonoBehavior {
    void Upate() {
        //my connectionhandler
    }
}

public class Child : BaseClass {

    // forbit it to use define Update
    void Update() {

    }

    // or let him use it but without writing base.Update() it should still use BaseClass Update()

}

As you see in both classes I have void Update(). That problem is if the child uses void Update as well so the base Update does not get called anymore. Is possible to avoid it. Example restrict access to Update Method if base already defined it? Or it is possible to let child use definition of void Update() but baseclass should also be able to use his own Update() (background working :P)

The other developer should not use everytime base.Update(). I am sure they will forget this many times :)




System.String implementation code

I've tried to ask this question before but I don't think I explained it well enough. I am a beginner and I'm sure this is something I don't know because I'm new. I'm using the Trim() method of the System.String class as an example.

Question: If you use the Trim() method in C# for example on the end of a string, and hit F12 on it to bring you to it's definition at the bottom of the System.String class, where is the actual code that removes all leading and trailing occurences of a set of characters. Does Microsoft hide this for many of there built in types on purpose because we don't need to know the implementation details?

If so, when we define base classes or whatever, are we able to hide the implementation details too?

It's totally possible I'm wrong or missing something. Thanks




JS instance name as a parameter

Is there a way to call a function which will call a class constructor, giving it the arguments, especially the instance name, provided in the call ?

In other words, is there a way to have this working :

//call #1
            instantiationOfSomething("circle", 2, 8, 87);

//call #2
            instantiationOfSomething("ellipse", 2, 85, 87);

    //somewhere else, the function...

            function instantiationOfSomething(instanceName, param1, param2, param3) {

                    instanceName = new mySomethingClass({
                        ...
                    });         
            }




Initializing an AnyObject property in a Swift class?

Ok so I am trying to create a class that creates bullet points in the Swift programming language. However I am having trouble figuring out how to initialize the style of the bullet point.

After initializing a bullet point object I want to be able to select whether the style of the bullet point will be an imported image in which case that property will conform to a UIImageView or (on default) the style of the bullet point will become an auto-incrementing number value and conform to a UILabel.

For example, I want the structure of the class to look something like this:

class bullet {

    var bulletStyle: AnyObject

    init() {
        bulletStyle = UILabel()
    }

    init(styleImage style:UIImageView) {
        bulletStyle = style
    }
} 

However after testing the class, bulletStyle is still taking on the type AnyObject after initializing the class both ways. So how can I set bulletStyle to either a UILabel object or a UIImageView object on initialization?




MouseListener dont work with JPanel and JFrame

MouseListener don't work with JPanel. I dont understand this. Help me please!

All classes:

    package kro.circle.main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;

import kro.circle.paint.Painter;


public class Circle extends JPanel implements ActionListener {
    public static double speed=1000;
    static Timer t = new Timer((int)(1000/speed), new Circle());
    static KeyListener keyListener;
    public static boolean isPause=false;
    public static int i=0;
    public static void main(String[] args) {

        MainFrame.createWindow(400,600,"Circle",4);
        Painter.paint();
        t.start();


    }
    public void actionPerformed(ActionEvent arg0) {
        Painter.paint();

    }

}

Second:

package kro.circle.main;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.BufferedWriter;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainFrame{

    public static BufferedImage buffer;
    public static int bufferData[];
    public static BufferStrategy bufferStrategy;
    public static Graphics bufferGraphics;
    public static JFrame window;
    public static int width, height;
    public static boolean isPause=false;
    public static Canvas canvas;

    public static double alfa;


    public static void createWindow(int _width, int _height, String title, int numBuffers) {
        JFrame window = new JFrame();
        window.setTitle(title);

        canvas = new Canvas();
        canvas.setPreferredSize(new Dimension(_width, _height));

        canvas.setFocusable(false);



        window.getContentPane().add(new Panel());
        window.getContentPane().add(canvas);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);



        buffer = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB);
        bufferData = ((DataBufferInt) buffer.getRaster().getDataBuffer()).getData();
        bufferGraphics = buffer.getGraphics();


canvas.createBufferStrategy(numBuffers);

        bufferStrategy = canvas.getBufferStrategy();


        width=_width;
        height=_height;
        new MainFrame();
    }



}

3 class:

package kro.circle.main;

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

public class Panel extends JPanel{

    public Panel() {
        setLayout(new BorderLayout());
        add(MainFrame.canvas);
        MainFrame.canvas.setBounds(0, 0, MainFrame.width, MainFrame.height);
        addKeyListener(new Keyboard());
        addMouseListener(new MouseList());
        setFocusable(true);
    }

    public class Keyboard extends KeyAdapter {
        public void keyPressed(KeyEvent key) {
            System.out.println(1);

        }
        public void keyReleased(KeyEvent key) {
            System.out.println(2);
        }
    }

    public class MouseList extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            System.out.println(1);
        }
        public void mouseClicked(MouseEvent e) {
            System.out.println(1);
        }
    }





}

Last:

package kro.circle.paint;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import kro.circle.main.MainFrame;

public class Painter {
    public static void paint() {
        ((Graphics2D) MainFrame.bufferGraphics).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        MainFrame.bufferGraphics.setColor(new Color(0,255,0));;
        MainFrame.bufferGraphics.fillRect(0,0,MainFrame.width,MainFrame.height);
        MainFrame.bufferStrategy.getDrawGraphics().drawImage(MainFrame.buffer,0,0,null);
        MainFrame.bufferStrategy.show();
    }
}

KeyListener is working correctly, but mouseListener don't work. I tried many versions. I am waiting for the help! Thanks! (not english)