mardi 30 juin 2015

access static method of class within a namespace

I have a nam.hpp which defines a namespace and that namespace contain one testclass. I have another header sum.hpp that include nam.hpp. i want to call the func() from sum.hpp. how to do so..??

nam.hpp

#include <iostream>
using namespace std;
// first name space
namespace first_space{

Class test
{
public:
inline static int func(){
  //cout << "Inside first_space" << endl;
 return 2;
}
}
}

sum.hpp

#include <cstring>
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>
#include <stdio.h>
#include <assert.h>
#include "nam.hpp"

using namespace std;
using namespace first_space:;

static inline int process(int a,int b)
{
     return a+b+first_space::test::func();
}




What is the use of Byte code in java

I am a little bit confused... I know that classes are loaded by the class loader only when they are needed,that is when we are trying to use static variables or when we are creating instance of that class.Thus if we have for e.g. 3 classes in our program and we are going to use only one,then only that particular class will be loaded and rest are not,but when we run the java compiler,it will create 3 .class files,I know these 3 .class files are byte code files,but then what is this byte code and what is the difference between loading a class and generating bytecode of a class?Where is the use of this byte code?If we are not going to use a particular class,then what is the need of generating a bytecode for that class?




How do start running a class through a sperate class

Hello i am trying to make a program that solves algebraic problems and i have run into an issue. the issue is is that i can't run a class a through a different class here is my code

package practice;
import java.util.Scanner;
public class Algeabram8 extends Nexttimesandsuch {
public static void main(String[] args) {
     Scanner scan = new Scanner(System.in);
    System.out.println("Amount of X's on left side:");
        int xsOnleftside = scan.nextInt(); 
    System.out.println("Amount of -X's on left side:");
        int negXsOnleftside = scan.nextInt();
    System.out.println("Is there a second variable? Y or N");
    String SecondVariableYorNleft = scan.next();
if (SecondVariableYorNleft.equalsIgnoreCase("Y")){
    System.out.println("Amount of Y's on left side:");
        int ysOnleftside = scan.nextInt();
    System.out.println("Amount of -Y's on left side:");
        int negysOnleftside = scan.nextInt();
    }
    System.out.println("Amount of X's on right side:");
        int xsOnrightside = scan.nextInt(); 
    System.out.println("Amount of -X's on right side:");
        int negXsOnrightside = scan.nextInt();
    System.out.println("is there a second variable on the right side? Y or N");
        String SecondVariableYorNright = scan.next();
if (SecondVariableYorNright.equalsIgnoreCase("Y")){
    System.out.println("Amount of Y's on right side:");
        int ysOnrightside = scan.nextInt();
    System.out.println("Amount of -Y's on right side:");
        int negysOnrightside = scan.nextInt();
    }
    System.out.println("Sum of all positve numbers on left side:");
        double allpositivenumberscombinedleftside = scan.nextDouble();
    System.out.println("Sum of all negative numbers on left side(Do it in a positive fashion ex. -5 = 5 (0 if none)):");
        double allnegativenumberscombinedleftside = scan.nextDouble();
    System.out.println("Sum of all positve numbers on right side:");
        double allpositivenumberscombinedrightside = scan.nextDouble();
    System.out.println("Sum of all negative numbers on right side(Do it in a positive fashion ex. -5 = 5 (0 if none)):");
        double allnegativenumberscombinedrightside = scan.nextDouble();

    System.out.println("input +,*,-,/ variables for left side? Y or N");
    String yOrN = scan.next();
    String timesandothers = scan.next(); 
    if (yOrN.equalsIgnoreCase("Y")){
    }
}

}

This is the code i want to run with the one above

package practice;
import java.util.Scanner;
public class Nexttimesandsuch {

public static void main(String[] args) {
        int x = 1;
        int add;
        int multiply;
        int divide;
        int subtract;
    Scanner scan = new Scanner(System.in);
        System.out.println("How many +,*,-,/ are there");
            int amountOfSlots = scan.nextInt();
    while(x <= amountOfSlots){
        System.out.println("What is it that you want to put on slot " + x + "(+,*,-,/):");
            String Whatdoyouwant = scan.next();
        if(Whatdoyouwant.equals("*"))
            multiply = 1; int multiplyslot = x;
            if(Whatdoyouwant.equals("+"))
                add = 1; int addslot = x;
                if(Whatdoyouwant.equals("-"))
                    subtract = 1; int subtractslot = x;
                    if(Whatdoyouwant.equals("/"))
                        divide = 1; int divideslot = x;
                        x++;
        }

    }

}

I have tried many things but i cant figure it out P.S please don't insult me for my bad naming of variables i'm just screwing around




Execute class code once C++

I am trying to use sdl as a window manager for openGL. I looked into using Windows native API, but looked to confusing.

With that being said, I have a class Window which I would like to wrap all the SDL stuff in for my windows management right now. Figure it will let me swap out windows management later if I find I do not want to use SDL.

I am guessing that a lot of openGL initialization code only needs to be run one time.

    if(SDL_Init(SDL_INIT_EVERYTHING) < 0 ) { 
        exit(0x1);
    }

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE,           8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,         8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,          8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,         8);

    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,        16);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,       32);

    SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,     8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE,   8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE,    8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE,   8);

    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);

Then in the class constructor I can create the window with

Window::Window(int winW, int winH) {

    if((Surf_Display = SDL_SetVideoMode(winW,winH,32, SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL | SDL_RESIZABLE )) == NULL) {
        exit(2);
    }

    glClearColor(0, 0, 0, 0);
    glClearDepth(1.0f);

    glViewport(0, 0, winW, winH);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, winW, winH, 0, 1, -1);

    glMatrixMode(GL_MODELVIEW);
    glEnable (GL_BLEND); 

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glLoadIdentity();


}

I'm just not sure how to go about doing this. If I put the code before I define the class in the header, does this achieve the desired result?

;init code
;class window { };




how can I broadcast an object of a class from a service to an activity?

I have a userObject Class(made it parcelable for following implementation) and I wrote the below code in my service. Just want to know, is there any other efficient/easy way then Android Parcelable in which I need not to make my class Parcelable?

  public  final static String PAR_KEY = "par_key";
userObject currentUser = new userObject(uid,uname,role,status,avatarUrl,profileUrl);
                                Intent Connect = new Intent("onChatConnect");//add action
                                Bundle mBundle = new Bundle();
                                mBundle.putParcelable(PAR_KEY, currentUser);
                                Connect.putExtras(mBundle);
                                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(Connect); 




Return one of two types of strings

I have a Python function which may return either one of two types of return values, animal or food. Both are string types. Right now, I differentiate between the two by always returning two values, asserting that only of them is True:

def help(x):
    if some_condition(x):
        return 'monkey', None
    elif # ...
        return 'hippo', None
    elif #..
        return None, 'bananas'
    elif # ...
        return None, 'steak'
    # ...



def main():
    animal, food = help('ddd')
    if animal:
        assert(not food)
        # do something useful
        pass
    else:
        assert(food)
        # do something useful
        pass
    return

There must be a better way to handle this. What are the options?




Can .h files have classes and still work in C?

Is it possible for .h files to be used in c even if they have classes? If so, how is this done?


If that is not possible, what is an easy way of converting c++ classes and templates to a c usable format?

Thanks!




Class Design and Collections

If I have a class defined as:

public class Car{
    public int doors {get;set}
    public int wheels {get;set}
    public string make {get;set}
    public string model {get;set}

    public Car(){}
}

And I want to create a collection of this class. In the past I have understand it was acceptable to create a collection class:

public class CarCollection{};

That would return a collection of Cars.

With Generic List now I understand that we should not be creating collection classes, but instead creating generic list of the object inheriting some collection type.

My question is where should this code go, and what definition should the method have? For example should I just add a public method to my car class:

public List<Car> GetAllCars()
{
    ...
}

If so, it seems weird to instantiate a Car Class to get a collection of cars, but I know declaring it as a shared class isn't the right option either. How should we be designing our collections of classes, and where should we be including them?




Javascript: assign onclick inside class

I created a constructor that will handle a custom list control. I created a method in order to allow the user to add elements to the list, and I need to assign event handlers to the click events of the list elements (divs).

A simplified version of the code is here. The list elements are created using the innerHTML property and a string template upon which I substitute specific parts. Later I get the element by it's id and assign it a function in closure:

function prueba(){
    var plantilla = '<div id="«id»">«texto»</div>';

    var f = function(nombre){
        return function(){console.log('mi nombre es ' + nombre)};
    };

    this.agregar = function(id, texto){
        var tmp = plantilla.replace('«id»', id);
        tmp = tmp.replace('«texto»', texto);
        document.body.innerHTML += tmp;

        document.getElementById(id).onclick = f(id);
    };
};

The problem is that, apparently, the event handler is unasigned to previous created divs, so is only retained by the last one, as it can be tested with the following code:

var p = new prueba;

p.agregar('i1', 'texto1');
console.log(document.getElementById('i1').onclick.toString());//shows the function code
p.agregar('i2', 'texto2');
console.log(document.getElementById('i2').onclick.toString());//shows the function code
console.log(document.getElementById('i1').onclick.toString());//returns 'null' error
p.agregar('i3', 'texto3');
console.log(document.getElementById('i3').onclick.toString());//shows the function code
console.log(document.getElementById('i2').onclick.toString());//returns 'null' error

This happens in Iceweasel as well as in Chromium. It does NOT happen when I add 'onclick = f(«id»)' in the template (which I cannot do here because of the assigned function scope), and neither happens if I use document.createElement. What am I doing wrong?




.class == .class vs .class.toString() vs .class.toString()

I was playing around with Classname.class and Classname.class.toString() and found something unusual.

.class seems to equate to .class when run on the same Class. Although .class.toString() does not equate to the .class.toString() on the same class. Why would this be.

Please see my code below

public class HelloWorld{

    public static void main(String []args){
        if(String.class.toString() == String.class.toString())
            System.out.println("toString(): Yes they are the same");
        else
            System.out.println("toString(): They are not the same ?");

        System.out.println("=============================");

        if(String.class == String.class)
            System.out.println(".class: Yes they are the same");
        else
            System.out.println(".class: They are not the same");
    }
}

Output:

sh-4.3# javac HelloWorld.java                                                                                                                            
sh-4.3# java -Xmx128M -Xms16M HelloWorld       

toString(): They are not the same ?                                                                                                                      
=============================                                                                                                                            
.class: Yes they are the same




C++ Use Class as Variable

So I have a class similar to this one:

class CVal {
public:
    void operator=(int n) {
        d = n;
    }
private:
    int d;
};

Now whenever I do something like

CVal c;
switch(c) {...}

I want the CVal::d to be accessed, so how would I do that? I thought of overloading some operator but I can't find anything.




Theano Shared Variables on Python

I am now learning the Theano library, and I am just feeling confused about Theano shared variables. By reading the tutorial, I think I didn't understand its detailed meaning. The following is the definition of the Theano shared variables from the tutorial:

"Variable with Storage that is shared between functions that it appears in. These variables are meant to be created by registered shared constructors."

Also, I am wondering if the Theano shared variables can be a python class data member. For example:

class A(object):   
    data = None
    ...

Can "data" be or initialized as a Theano Shared variable? I really appreciate if anyone could help me.




Adapt abstract class in Codeigniter

I have the following scenario:

Controller:

class Collect extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->library('phirehose');
        $this->load->library('oauthphirehose');
        $this->load->library('ghettoqueuecollector');
    }

    function index() {
        // Start streaming/collecting
    $this->ghettoqueuecollector('datos');
...
}

Class: A)

class Ghettoqueuecollector extends Oauthphirehose {
...
}

B)

abstract class Oauthphirehose extends Phirehose {
...
}

C)

abstract class Phirehose {
...
}

When I try to use the controller gives this error: "Fatal error: Cannot instantiate abstract class Phirehose"

That is lacking adapt? Codeigniter outside these classes work using require. Can I use them in CI? Thanks




Swift - error: 'AnyObject' is not a subtype of 'T'

I'm trying to create an array of objects of ObjApply, every one with the constraint between objType and apply of ObjApplySpecific. So this is what I need to do:

var arr = [ObjApply]()
let test = ObjApplySpecific(objType: NSButton.self, apply: {(a,b) in return})
arr.append(test)

But I have a trouble with the creation of the classes:

class ObjApply{

 private var _objType: AnyObject.Type = NSObject.self
 private var _apply : (AnyObject, Any)->() = {(a,b) ->() in return}

 internal var objType: AnyObject.Type{
    get{
        return _objType
    }
 }
 internal var apply : (AnyObject, Any)->() {
    get{
        return _apply
    }
 }

 init(objType:AnyObject.Type, apply:(AnyObject,Any)->()){
     _objType = objType
     _apply = apply
 }
}

class ObjApplySpecific<T : AnyObject> : ObjApply {

 init(objType: T.Type, apply:(T,Any)->()){

    super.init(objType: objType, apply: apply)             // **** ERROR ****
 }
}

It says:

error:'AnyObject' is not a subtype of 'T' super.init(objType: objType, apply: apply)

But I placed T : AnyObject so I can't understand this error

Thanks in advance




What is the below architecture for?

In the below code, MYClassB inherits from both MYClassA and IMyinterface. But MYClassA already ingerits from IMyinterface.

  1. Does it have any differece to use like MYClassB : MYClassA without IMyinterface?

  2. If 1. has some differences please explain to me. And is there any reason to use this kind of confused classes in the real world?

    interface IMyinterface
    {
        void myfunc();
    }
    
    abstract class MyClassA : IMyinterface
    {
        public virtual void myfunc() 
        {
            Console.WriteLine("myfunc in MYClassA");
        }
    }
    
    class MYClassB : MyClassA, IMyinterface
    {
        public override void myfunc()
        {
            Console.WriteLine("myfunc in MYClassB");
        }
    }
    
    



(UPDATED) Python: Why is it saying my method isn't defined when it clearly is?

class GameMech:
    def __init__(self ,aCharacter):
        print("A battle is starting")
    def getMP(self, aCharacter):
        return aCharacter.mp
    def getHP(aCharacter):
        return aCharacter.hp
    def getAtk(aCharacter):
        return aCharacter.atk
    def getDef(aCharacter):
        return aCharacter.defense
    def usePotion(aCharacter):
        aCharacter.hp += 100
        return aCharacter.hp
    def useSpecial(self, aCharacter, target):
        if aCharacter.mp >= 100:
            target.hp -= 45

    def dead(self, aCharacter):
        return aCharacter.name +" is now dead"
    def attack(self, aCharacter, target):
        if target.hp - (http://ift.tt/1dr1FsI) <= 0:
            dead(target)
        else:
            target.hp - http://ift.tt/1dr1FsI
            print(getHP(target))
    def guard(self, aCharacter):
        print(aCharacter + "was unharmed")
        if aCharacter.hp <= 50:
            retaliation(aCharacter, target)
    def retaliation(self ,aCharacter, target):
        target.hp - (aCharacter.atk/10)
        print(getHP(target))

    def battleMenu(aNumber, self):
        if aNumber == 1:
            attack(aCharacter, target)
        if aNumber == 2:
            guard(aCharacter)
            print(aCharacter + " was unharmed!")
        if aNumber == 3:
            useSpecial(aCharacter, target)
            print(getHP(target))
        if aNumber == 4:
            heal = useItem(aCharacter)
            print(heal)

    def myTurn(self):
        print("ATTACK")
        print("GUARD")
        print("SPECIAL")
        print("ITEM")
        aNumber = int(input("What would you like to do? "))
        battleMenu(aNumber)

    def oppTurn(self):
        print("It is the opponent's turn")
        randomNum = random.randint(1,4)
        battleMenu(randomNum)

a few notes, obviously due to this formatting you can't tell that all my methods are actually under the class, but they are. you can ignore the first few parts, the part im focusing on is battle menu. So i'm creating a little text game as a project for myself, pure leisure nothing academic or for a job. Just a little game for myself to help me jog my memory in regards to python. So that's where the gut of my game is, the character class is an another file and there's nothing important in there just the attributes of character (hp, mp, atk, def) here's the main

import random
import character
import battle



#create a battle menu
#and a character value check menu
#add buttons




def main():
char1 = character.Character("Charlie", 5000, 2000, 1500, 750)
char2 = character.Character("Mark", 2000, 4000, 2000, 900)

newGame = battle.GameMech(char1)
while char1.hp != 0 or char2.hp != 0:
    newGame.myTurn()
    newGame.oppTurn()

main() (not sure why it's not including the definition of my main in the code snippet) Any how I'm getting this error saying "name 'battleMenu' is not defined". Name usually applies to variables correct? But battleMenu is a method is there a reason i'm getting this error?

Traceback (most recent call last):
File "E:\PythonGame\mainGame.py", line 22, in <module>
  main()
File "E:\PythonGame\mainGame.py", line 20, in main
  newGame.myTurn()
File "E:\PythonGame\battle.py", line 55, in myTurn
  battleMenu(self,aNumber)
NameError: name 'battleMenu' is not defined




Call a method of another class

people! I have a method called methtod1 defined as:

Public Sub method1() For Each elem In Me.arrayElemWithLogkNull Console.WriteLine(elem) Next End Sub

This method is in a class called XMLClass. So I have the Main class and, there, I want to call the method1 of XMLClass. How am I supposed to do that? I'm trying with this: XMLClass.method1(), but it throws me an error. I'm a vb.net begginer so, please, be kind! Thank you all!!




Method to require another class, is not getting class

I have lots of methods in a class to create reports using PHPExcel, I have one method to return a new instance of the PHPExcel object like so:

public function run_excel(){

    if(!class_exists(EXTPATH.'PHPExcel/PHPExcel.php')){
        require_once EXTPATH.'PHPExcel/PHPExcel.php';
    }

    return new PHPExcel();
}

I also want to add other PHPExcel functions into the run_excel to make titles and other stuff more dynamic to reduce my code, however I have tried assigning the PHPExcel method to a variable and returning that variable, but this doesn't work...

Example of what I want:

public function setup_phpexcel($title){

    if(!class_exists(EXTPATH.'PHPExcel/PHPExcel.php')){
        require_once EXTPATH.'PHPExcel/PHPExcel.php';
    }

    $objPHPExcel->getActiveSheet()->setTitle($title);

    return new PHPExcel();
}

Thanks




Objective - C Mulitple interface

How can I do the following things in Objective C for interface for same class :

@interface DashControl : UIViewController <WitDelegate> @property(nonatomic, strong) id <WitDelegate> delegate; @end @interface DashControl : DashWidget <ICustomizableIcon, ICustomizableActionText> @end

I would like to have one interface.

Thanks.




Add /Remove class and animate

I will animate a div with a button. => click . move div top. click again move div bottom . If i click irt move to top. but if i click again it do nothing.

here is my script:

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#overlay-tv").animate({top: '0px'}, 4000, 'linear');
        $(this).delay(200).addClass('tv-aktiv');
    });
    $("button.tv-aktiv").click(function(){
        $("#overlay-tv").animate({top: '20px'}, 4000, 'linear');
        $(this).delay(200).removeClass('tv-aktiv');
    });
});
</script>



Can main and constructor be together in a class in Java

Check The below Code

import Shashwat.TestJava;
public class Main extends TestJava{
public static void main(String s[]){
    System.out.println("Inside Orignal \"Main\" Method");
    Main m = new Main();

}

public  void Main(){
    System.out.println("Inside Duplicate Main");
     }
}

Now the point is that when I execute the program, This line runs

System.out.println("Inside Orignal \"Main\" Method");

After which I create a Main class Object using

Main = new Main();

As far as I have seen this should call the constructor which has to be named 'Main' for the Class is named Main. Now This is what it executes to

Inside Orignal "Main" Method

Process finished with exit code 0

But I have created a constructor and it should print text out. So Why is it not printing ? Are Constructors not allowed in a class with a main method ?




using static member variable of a class inside a method of this same class [duplicate]

if I have a static member variable of a class A declared in the file Af.h and I want to use this variable inside a method "met" of this same class inside the file Af.cpp, how do I proceed? here is my files

Af.h

class A
{
  public:
    static std::vector <int> vec;
    void met();
//....
};

Af.cpp

//...
void A::met()
{
// I will use here some int variable i
vec.push_back(i);
//...
}

Unfortunately,this code provides the following compiling error:

undefined reference to A::vec




Class design patterns - best practices

men and women!

My problem is I don't really know what is the best way to design so I defined 2 classes 1'st one is:

class color
{
private $id = NULL; 
private $name = '';
private $rgb = NULL; 
private $cmy = NULL;
private $wavelength = NULL; 
private $frequency = NULL; 

public function __construct($name, $rgb, $cmy, $wavelenght, $frequency)
    {
    setName($name);
    setRGB($rgb);
    setCMY($cmy);
    setWavelength($wavelength);
    setFrequency($frequency);
    }

public function __destruct()
    {

    }

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

public function setRGB($rgb)
    {
    $this->rgb=$rgb;
    }

public function setCMY($cmy)
    {
    $this->cmy=$cmy;
    }

public function setWavelength($wavelength)
    {
    $this->wavelength=$wavelength;
    }

public function setFrequency($frequency)
    {
    $this->frequency=$frequency;
    }

public function getId()
    {
    return $this->id;
    }

public function getName()
    {
    return $this->name;
    }

public function getRGB()
    {
    return $this->rgb;
    }

public function getCMY()
    {
    return $this->cmy;
    }

public function getWavelength()
    {
    return $this->wavelength;
    }

public function getFrequency()
    {
    return $this->frequency;
    }

public function toJSON()
    {
    return "{'id':'".$this->id."', 'name':'".$this->name."', 'rgb':'".$this->rgb."', 'cmy':'".$this->cmy."', 'wavelength':'".$this->wavelength."', 'frequency':'".$this->frequency."'}";
    }

public function toCSV()
    {
    return $this->id . ", " . $this->name . ", " . $this->rgb . ", " . $this->cmy . ", " . $this->wavelength . ", " . $this->frequency;
    }

public function toHTML()
    {
    return "<p>ID: " . $this->id . "</p><p>Name: " . $this->name . "</p><p>RGB: " . $this->rgb . "</p><p>CMY: " . $this->cmy . "</p><p>Wavelength: " . $this->wavelength . "</p><p>Frequency: " . $this->frequency . "</p>";
    }

and 2'nd class looks like

class CRUD_color
{
public function create_color($parameters)
    {
    $color=new color();
    $color->setName($parameter['name']);
    $color->setRGB($parameter['rgb']);
    $color->setCMY($parameter['cmy']);
    $color->setWavelength($parameter['wavelength']);
    $color->setFrequency($parameter['frequency']);

    $entitymanager->persist($color);
    $entitymanager->flush();
    }
public function request_color($parameters)
    {
    $color=$entitymanager->find($parameter['id']);
    echo $color->toJSON($parameter['name']);
    }
public function update_color($parameters)
    {
    $color=$entitymanager->find($parameter['id']);
    $color->setName($parameter['name']);
    $color->setRGB($parameter['rgb']);
    $color->setCMY($parameter['cmy']);
    $color->setWavelength($parameter['wavelength']);
    $color->setFrequency($parameter['frequency']);

    $entitymanager->persist($color);
    $entitymanager->flush();
    }
public function delete_color($parameters)
    {
    $color=$entitymanager->delete($parameter['id']);
    }
}

now my question is if maybe it is better to have only one class color and include the functions from the second class in the 1st one? or let them apart?

why is one better than the other or vice versa? the design pattern is important to me so why choose one over the other..

Is there a problem if lets say we have the function create_color in witch we instantianate the class itself like new color() ????




PHP : "Fatal error: Using $this when not in object context in"

I want to create a class for a license manager , however , I have to use another class to do what I need is to create a new connection to the database in the __construct class .

When I try to use a function , getAll in this case , I have a PHP error that appears on the screen :

Fatal error: Using $ this WHEN NOT in object context in [...] line 112 .

Here is my class :

class cLicences {

    // Contient les valeurs à afficher
    protected $iLicID                = null;
    protected $sLicProduct           = null;
    protected $sLicDesc              = null;
    protected $sLicKey               = null;
    protected $iLicDateAdded         = null;
    protected $iLicDateEdited        = null;
    protected $iLicUserAdded         = null;
    protected $iLicUserEdited        = null;

    // Connexion à la base de données
    private $oLicMySQL               = null;

    // Contient les noms des champs dans la db
    private static $sFieldID         = 'id_licence';
    private static $sFieldProduct    = 'lic_product';
    private static $sFieldDesc       = 'lic_desc';
    private static $sFieldKey        = 'lic_key';
    private static $sFieldDateAdded  = 'lic_date_added';
    private static $sFieldDateEdited = 'lic_date_edited';
    private static $sFieldUserAdded  = 'idx_user_added';
    private static $sFieldUserEdited = 'idx_user_edited';

    // Nom de la table
    const TABLENAME = 't_licences';

    /**
     * Initialisation de l'objet
     * @param int $iLicID -> ID de la licence
     */
    public function __construct($iLicID = null) {

        // Si l'ID est un ID (numérique donc)
        if(is_numeric($iLicID)) {

            // Stock la connexion dans la classe
            $this->oLicMySQL = new cMySQLi(DB_USERNAME,DB_PASSWORD,DB_HOSTNAME,DB_HOSTPORT,DB_DATABASE);

            // Initialise l'ID de la classe avec l'ID passé en param
            $this->iLicID = $iLicID;

            // Initialise les variables de la classe selon l'ID
            $this->init();
        }

    }

    /**
     * Détruit la connexion à la db
     */
    public function __destruct() {
        $this->oLicMySQL->fClose();

    }

    /**
     * Retourne la valeur souhaitée selon le nom du champ en param
     * @param string $sName -> Nom du champs
     * @return string
     */
    public function __get($sName) {

        // Retourne la valeur souhaitée
        return $this->$sName;

    }

    /**
     * Initalise les variables de la classe avec les données reçuent selon l'ID
     */
    public function init() {

        // Séléctionne la licence selon ID
        $sReqSltLic = 'SELECT *
                        FROM '.self::TABLENAME.'
                        WHERE '.self::$sFieldID.' = "'.$this->iLicID.'"
                        LIMIT 1';

        // Exécute la requête
        $rLic = $this->oLicMySQL->fQuery($sReqSltLic);

        // Met en forme la ressource SQL
        $aLic = $this->oLicMySQL->fFetch($rLic);

        // Assigne aux variables de la class les données reçuent
        $this->sLicProduct       = $aLic[self::$sFieldProduct];
        $this->sLicDesc          = $aLic[self::$sFieldDesc];
        $this->sLicKey           = $aLic[self::$sFieldKey];
        $this->iLicDateAdded     = $aLic[self::$sFieldDateAdded];
        $this->iLicDateEdited    = $aLic[self::$sFieldDateEdited];
        $this->iLicUserAdded     = $aLic[self::$sFieldUserAdded];
        $this->iLicUserEdited    = $aLic[self::$sFieldUserEdited];

    }

    /**
     * Récupère toutes les licences
     * @param ressource SQL $rData -> & indique l'index mémoire de la variable
     * @param string $sArg -> Argument pour la séléction des licences
     * @return \cLicences
     */
    public function getAll(&$rData,$sArg = null) {
        if(empty($rData)) {
            $sReqSltAll = 'SELECT *
                            FROM '.self::TABLENAME.(!empty($sArg) ? ' '.$sArg : null);

            $rData = $this->oLicMySQL->fQuery($sReqSltAll);
        }

        // On met en forme les données
        $aData = $this->oLicMySQL->fFetch($rData);

        // Si on a des données
        if(!empty($aData)) {

            // Parcours les données
            while($sValue = $aData) {

                // Retourne un nouvel objet licence
                return new cLicences($sValue[self::$sFieldID]);
            }
        }

    }

}

Here is my page:

// Affiche les erreurs
error_reporting(E_ALL);

// Change le dossier courant
chdir('../../../');

// Fichier requis pour traitement
require_once('./configuration/general.conf.php');
require_once(PATH_CONFIGURATION.'user.conf.php');
require_once(PATH_CLASS.'mysqli.class.php');
require_once(PATH_MODULES.'licencesManager/langages/'.SITE_LANG.'.lang.php');
require_once(PATH_MODULES.'licencesManager/classes/licences.class.php');

// Nouvelle connexion à la db
$oMySQL = new cMySQLi(DB_USERNAME,DB_PASSWORD,DB_HOSTNAME,DB_HOSTPORT,DB_DATABASE);

// Initialise la classe licence
$oLicences = new cLicences();

// Récupération de toutes les licences
$sReqSelectLicence = "SELECT id_licence
                        FROM t_licences";

$rLicences = $oMySQL->fQuery($sReqSelectLicence);

// Affiche les infos de la licence
while($oLicence = cLicences::getAll($rLicences)) {
    echo '<tr>
            <td>'.$oLicence->iLicID.'</td>
            <td>'.$oLicence->sLicProduct.'</td>
            <td>
                <button onclick="fShowLicence('.$oLicence->iLicID.')" class="btn btn-xs btn-primary">
                    <i class="fa fa-key hidden-xs"></i> '.$_SESSION['mdlLicShow'].'
                </button>
            </td>
            <td><i class="fa fa-pencil"></i> <i class="fa fa-trash-o"></i></td>
        </tr>';
}

// Ferme la connexion à la base de données
$oMySQL->fClose();

Here is the full error:

Fatal error: Using $this when not in object context in /srv/www/htdocs/dev/php/TEST/DAS/iRat-tools/modules/licencesManager/classes/licences.class.php on line 112

I 'm stuck on this problem for 3 days now. If anyone can help me to find a solution.




Conecpt of Abstract class and interface in php?

I have research about Abstract class and interface in php, and find some best examples but i'm still little confuse and fail several time in interview due to these. So From my experience I think the following is true.

Interface

Interface will have to implemented in classes. For Example,

interface BikeDrive{
public function MotorCycleDriving($FootGear, $RightHandBrake)
}

Abstract class is core functionality, for example every vehicles

Abstract Class Drive(){

}

Please guide me concept




lundi 29 juin 2015

The hierarchy of the type 'GssoSsoWebV2ServiceLocator' is inconsistent?

axis-1.4.jar, axix-ant.jar, i have added these jar file's in eclipse buildpath, i am getting the following error - The hierarchy of the type 'GssoSsoWebV2ServiceLocator' is inconsistent




Trying to understand when i should use id and/or class tag

i'm new to html/css and completed the css/html tutorial on codeacademy. I've reread over everything i've done and have a good knowledge around why everything works the way it does except the class/id tag. If i understand correctly the class tag is useful for when a bunch of elements should all recieve the same styling and id's are useful when you have exactly one element that should receive it's own styling. The thing i don't get is then what is the point of the id tag if i can get the same result using the class tag. For e.g. i have boxes 1,2 and 3 and i want them all to be the color black aka all recieve the same styling i would use the class tag. But i change my mind and now i want box2 to be white so in theory i should change box2 to an id tag so it can receive it's own styling but the thing is i can still use the class tag and get the same result by typing .box2 color:white;

My question is what is the point of the class and id tag if i can do the same thing for both using just the class tag.

Sorry if this is a difficult question to understand. I tried to word it as best as i could.




Create Simple Class with multiple calculating function( )

Trying to run a simple calculation via a function in my class. I simply want to add bill1 + bill2 and print the total amount spent on bills. So (bill1 + bill2 = total). And then print the total amount.

Current error states - "Code after 'return' will never be executed." Now, is my location for my print in the wrong location or did I declare my variables incorrectly? Should I be using vars instead of lets?

What do you recommend for my function in order to calculate and print the result?


class BillsCalculator
{
    let nameOfBill1: String = "Medical"
    let nameOfBill1: String = "Hulu"
    let monthlyBillAmount1: Double = 34.25
    let monthlyBillAmount2: Double = 7.99
    let calculateTotalsPerMonth: Double = 0.0

   //calculateTotalPerMonth ( = monthlyBillAmount_1 + monthlyBillAmount_2 + 3)

    func calculateTotalsPerMonth(monthlyBillAmount: Double, monthlyBillAmount2: Double) -> Double
    {
        //totalBillsPerMonth = add(monthlyBillAmount1 + monthlyBillAmount2)
        return totalBillsPerMonth(monthlyBillAmount1 + monthlyBillAmount2)
*Error        println("You spend \(totalBillsPerMonth)")

    }
}




Python Import class in __init__.py from file in same package

I feel like I should know this, having programmed in Python for as long as I have, but I'm constantly learning new this about the fine lanuaguge. The question I have (which may very well be a duplicate, however I haven't been able to find this same case) is this. I have a file layout like this:

websocket/
    __init__.py
    client.py
    server.py

How can I import classes that are in the file __init__.py from client.py or server.py? Nice and simple :P Thanks in advance!




what happens when I create a object instance of my class

I have two class like this:

class one
{
    public $var1 = 'anythig';
}

class two
{
    public $var2 = 'anythig';
}

I want to know when I create a object instance of these classes what happens? My point is about the values stored in the memory. In reality I have some big class, and my resources are limited. then I want to know, If I put NULL into my class when don't need to it anymore is good ? and help to optimizing ?

I have a switch() to include the desired class. something like this:

switch{
          case "one":
          require_once('classes/one.php');
          break;

          case "two":
          require_once('classes/two.php');
          break;
      }

Every time I only need one class. When I define a new object ($obj = new class) what happens to my class previously defined as object instance? that is remain in memory? and if I put NULL is helpful ? Please guide me ..




java.lang.RuntimeException: Unable to start activity ComponentInfo Error Inflating Class Fragment

Hi I am getting this error in Android Studio: Can anyone help to resolve this error.. I have removed few lines from the code here but all the required stuff is there I am sure... Thanks in advance..


ERROR

Process: stockquote.anirudh.com.stockquote, PID: 6263
    java.lang.RuntimeException: Unable to start activity ComponentInfo{stockquote.anirudh.com.stockquote/stockquote.anirudh.com.stockquote.MainActivity}: android.view.InflateException: Binary XML file line #127: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: android.view.InflateException: Binary XML file line #127: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at stockquote.anirudh.com.stockquote.MainActivity.onCreate(MainActivity.java:46)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.ClassCastException: stockquote.anirudh.com.stockquote.MainActivity@19a16f79 must implement OnFragmentInteractionListener
            at stockquote.anirudh.com.stockquote.NavigationDrawerFragment.onAttach(NavigationDrawerFragment.java:103)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
            at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1206)
            at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2159)
            at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297)
            at android.support.v7.app.ActionBarActivity.onCreateView(ActionBarActivity.java:547)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at stockquote.anirudh.com.stockquote.MainActivity.onCreate(MainActivity.java:46)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)


MAINACTIVITY

public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
public final static String STOCK_SYMBOL = "com.anirudh.stockquote.STOCK";
private SharedPreferences stockSymbolsEntered;
private TableLayout stockTableScrollView;
private EditText stockSymbolEditText;
Button enterStockSymbolButton;
Button deleteStocksButton;
Button updateStocksButton;

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

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
          getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);


    drawerFragment.setup((DrawerLayout)findViewById(R.id.drawer_layout),toolbar);

    stockSymbolsEntered = getSharedPreferences("stockList", MODE_PRIVATE);
    stockTableScrollView = (TableLayout) findViewById(R.id.stockTableScrollView);
    stockSymbolEditText = (EditText) findViewById(R.id.stockSymbolEditText);
    enterStockSymbolButton = (Button) findViewById(R.id.enterStockSymbolButton);
    }
@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_main, 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) {

        Toast.makeText(this, "Application created by Anirudh", Toast.LENGTH_LONG).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}


navigationDrawerFragment.JAVA

package stockquote.anirudh.com.stockquote;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link NavigationDrawerFragment.OnFragmentInteractionListener} interface
  * to handle interaction events.
 * Use the {@link NavigationDrawerFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NavigationDrawerFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;

private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;


// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;


// TODO: Rename and change types and number of parameters
public static NavigationDrawerFragment newInstance(String param1, String param2)            
{
    NavigationDrawerFragment fragment = new NavigationDrawerFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}


public NavigationDrawerFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     mUserLearnedDrawer=Boolean.valueOf(readFromPreference(getActivity(),KEY_USER_LEARNED_DRAWER , "false"));

    if (savedInstanceState!=null)
    {
        mFromSavedInstanceState = true;

    }


    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_navigation_drawer, container,     false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public void setup( DrawerLayout drawerLayout, final Toolbar toolbar) {

    mDrawerLayout = drawerLayout;
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar
            , R.string.drawer_open, R.string.drawer_close) {
        @Override

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            Log.d("VIVZ", "onDrawerOpened");
        }

        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }


    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://ift.tt/NoA2Cz"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}


public static void saveToPreference ( Context context, String preferenceName , String preferenceValue){

    SharedPreferences sharedPreference = context.getSharedPreferences( "PREF_FILE_NAME" , Context.MODE_PRIVATE);
    SharedPreferences.Editor editor= sharedPreference.edit();

    editor.putString(preferenceName , preferenceValue);
    editor.apply();

}

public static String readFromPreference ( Context context, String preferenceName , String defaultValue){

    SharedPreferences sharedPreference = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
   return  sharedPreference.getString(preferenceName,defaultValue);

}

}


fragment_navigation_drawer.xml

    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="stockquote.anirudh.com.stockquote.NavigationDrawerFragment">

<!-- TODO: Update blank fragment layout -->
<TextView

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/hello_blank_fragment" />


activity_main.xml

    <android.support.v4.widget.DrawerLayout     xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
xmlns:app="http://ift.tt/GEGVYd"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start">


<TableLayout
    xmlns:tools="http://ift.tt/LrGmb4"
    android:id="@+id/TableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

       <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">





        </TableRow>

    </TableLayout>

    <fragment
    android:layout_width="280dp"
    android:layout_height="match_parent"
    android:id="@+id/fragment_navigation_drawer"
    android:layout_gravity="start"

    app:layout="@layout/fragment_navigation_drawer"
    android:name="stockquote.anirudh.com.stockquote.NavigationDrawerFragment"
    tools:layout="@layout/fragment_navigation_drawer" />

     </android.support.v4.widget.DrawerLayout>





Invoke unique functions of derived classes from a vector of pointers to base class objects

#include <iostream>
#include <vector>

using namespace std;

class Base
{
public:
    void speak() { cout << "Hello!"; }
};

class Derived1 : public Base
{
public:
    void func1() { cout << "I'm a function!"; }
};

class Derived2 : public Base
{
public:
    void func2() { cout << "I'm also a function!"; }
};

int main()
{
    vector<Base*> v = { new Derived1(), new Derived2(), new Derived1(), new Derived2() //, ...
    };
    // For each Derived1 object invoke func1() and for each Derived2 object invoke func2()
}

Base is not polymorphic (no virtual function). From these conditions how can I be able to invoke func1 for each Derived1 object and func2 for each Derived2 object in v?




why the name of script file and the the name of class should be the same when using __autoload?

I use __autoload. It give me error if the name of script page (script.php) and the name of class into script page be different, why ?!

In fact I want to know __autoload is depends on what ? class name ? script name ? both of them ? I know, both of them. but why ? Is it possible to I define a class disagree with name of script ? when I do that, It give me this error:

Fatal error: Class 'ClassOne' not found in C:\xampp\htdocs\my_mvc\index.php on line 10

I want to my class name and script name be different, Is it possible ?!




Declaring Multiple Object with Different Names

The number of objects that are created differ depending on user input, so how can I declare the following with a for loop in Java?

    MicroStep darkCalibMicro0 = new MicroStep();
    MicroStep darkCalibMicro1 = new MicroStep();
    MicroStep darkCalibMicro2 = new MicroStep();
    MicroStep darkCalibMicro3 = new MicroStep();
    MicroStep darkCalibMicro4 = new MicroStep();
    MicroStep darkCalibMicro5 = new MicroStep();

These can't be hardcoded, they have to be generated based on the size that the user inputs.




What order are methods executed?

So I have this piece of code, the output produced is xycg... but how? Can someone explain in how that is.

public class Sequence {

    Sequence() {
        System.out.print("c");
    } {
        System.out.print("y");
    }
    public static void main(String[] args) {
        new Sequence().go();
    }
    void go() {
        System.out.print("g");
    }
    static {
        System.out.print("x");
    }
}




Change variable type

I'm new in C++ and I'm from Ruby where I can declare a variable and set what I want, for example a class

@variable=MyClass.new

Can do something like that in C++? I have two classes and a global variable declared with the first one set and I want to modify it and set it to the second class, in Ruby I can do something like

@variable=MyClass2.new

My c++ code is like this:

TestClass1 *scene = NULL;
*scene=TestClass1();

And now I try to set it to the second class like I do in Ruby: TestClass2 *newScene=NULL

*newScene=TestClass2()
*scene=*newScene();

error: cannot convert 'TestClass1*' to 'TestClass2*' in assignment

I've search here a lot and in Google but I don't find anything, can someone help me? Thanks you so much




CAKEPHP SELECT OPTION CLASS

Does someone know how to add class to a select option in a view file ?

I have at the moment:

echo $this->Form->input(
                'shelf_id',
                array(
                    'options' => $Shelves,
                    'label'=> 'Etagère :',
                    'default' => $Place['Place']['shelf_id'],
                    'class'=>'form-control')
            );

All my options element are like this :

<option value="1">Element</option>

But I want them to be like this :

<option value="1" class="myClass">Etagere 1</option>

Tks




Show all data with class same as the id clicked on

I have a question about Jquery. I want to show all data with the same class as I clicked on.

i made a list of things I can click on. So when I click it, the right data should be shown. I made this but it's not working.

This is my Jquery code:

$("div span").hide();
$('input[type=checkbox]').on("change", function(e) {

    var id = $(this).attr('id'); 
    if(this.checked){
        alert("checked");
        e.preventDefault();

    }else{
        alert("not checked");
    }


});

http://ift.tt/1U1nCAn




Formatting values in class modules

i have the following code

Dim W As New WordC ' being WordC the name of my clase
W.Revenue=101545

i want to format it as currency but i want it to be done in the class module. how can i do that using properties?

i want something like this code somewhere in the class module

If Revenue > 1000000 Then
    Revenue = Format(Revenue / 1000000, "Currency") & "M"
Else
    Revenue = Format(Revenue / 1000, "Currency") & "k"
End If

the formatted revenue will only be needed in the class module




Handling exceptions in JAVA

I know that if we have a normal code without try and catch statements,then if an exception occurs,then the default exception handler of JVM handles that exception. I have a code...

public class St
{
    public static void main(String args[])
    {
        try
        {
            int y=23/0;
        }
        catch(Exception e)
        {
            System.out.println("Division by zero");
        }
    }
}

As far as I know, in this code exception occurs at line 7,an object of class Exception is thrown and that's why we have taken as argument an object of class Exception in order to catch the exception.Am I right upto now????

But why this code shows a compile time error...

public class St
{
    public static void main(String args[])
    {
        Exception e=new Exception();
        try
        {
            int y=23/0;
        }
        catch(e)
        {
            System.out.println("Division by zero");
        }
    }
}

In this I have created an object reference e of class Exception,and that I have taken as argument in catch.But its not running,giving error at compile time.Can someone explain why???




Create new object of class or use static method?

I have a simple program consisting of 3 classes. GUI, Driver and Main.

Main Class:

public static void main(String[] args){
GUI theGUI = new GUI();
}

GUI Class:

public void makeGUI(){
final GUI guiInstance = new GUI();
//some other code here
}

Instead of creating two objects, can I just make the makeGUI() method static, so I can just avoid creating one unnecessary object? I know for a program of this scale, the performance doesn't really matter, but is it good programming practice to try and avoid unnecessary objects?




How do I initialize a 2D array in a class (c++)?

class ABC {
 char mat[3][3];
 public:
 ABC();
}

if I have the above class how to initialize

mat[3][3]={{'1','2','3'},{'4','5','6'},{'7','8','9'}};

also I'm using turbo c++ (compulsory for a school project).




How do I reach the running instance of my Thread?

Basically, I have a class called Playback which extends a thread. I want to be able to run functions i have defined from this class from my thread object, but when i do they have no affect on the current thread of said object. I can only get my functions to work when called if i was .run() instead of .start() but that causes my GUI to freeze up. Here is my code

Playback function = new Playback(list, progBar, settings);
function.start();
function.terminate();

The above code does not work but the below does

Playback function = new Playback(list, progBar, settings);
function.run()
function.terminate();   

When i use run though it causes my GUI to freeze. How do i call my methods on a already running thread?




can't assign function to call error in manipulating dataframe class

I have a class called BirthInformation which creates a Pandas dataframe of number of births by name.

I then add a column to determine if I have enough datapoints. The column is called EnoughInfo. If there is not enough info, I remove the column. The problem I run into is that I get the error, can't assign function to call. This is where I need some help on best practices.

I can assign the dataframe to a variable, but the problem with this is that I later can't call the method get_male(). Should I assign this to a variable then get rid of the function get_male() by just writing it as a line of code?

MyNewDataframe = MyData.get_dataframe()[MyData.get_dataframe().EnoughInfo == 'yes']

Full Code:

import pandas as pd
class BirthInformation:
    def __init__(self, data, headers):
        self.data = data
        self.headers = headers
        self.dataframe = pd.DataFrame(data=self.data, columns=self.headers)

    def get_dataframe(self):
        return self.dataframe

    def get_male(self):
        return self.dataframe[self.dataframe['Gender'] == 'Male']

data = [['Bob', 968, 'Male'], ['Jessica', 303, 'Female'], ['Mary', 77, 'Female'], ['John', 578, 'Male'], ['Mel', 434, 'Female']]
headers = ['Names', 'Births', 'Gender']
MyData = BirthInformation(data,headers)


MyData.get_dataframe()['EnoughInfo'] = ['no' if x[1] < 400 else 'yes' for x in data]

MyData.get_dataframe() = MyData.get_dataframe()[MyData.get_dataframe().EnoughInfo == 'yes']

print MyData.get_male()




Instance of Anonymous Class in JAVA [duplicate]

This question already has an answer here:

I have read from link:

this

and from other forums that instances of an interface can't be made... But in the above link,we are creating an instance of the interface Test.. In the answers that follows,it is written that it is not the instance of the Test interface,rather it is the instance of the Anonymous class, I am confused,how can that be an instance of an anonymous class?




Accessing variables outside of a class and function [on hold]

I am trying to get the value of a function inside of a class.

classes.php

 class luresClass {

  public function lureSelect() {

   global $lureChoice;
    if ($_POST['airtemp'] == 2 && $_POST['watertemp'] == 5) { 
          $lureChoice = 1;
         }
    else {$lureChoice = 0;}

 }   

}

This is the main file (index.php) that needs to access the value of $lurechoice.

if (isset($_POST['submit'])) {

$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

    $displayLureChoice = new luresClass(); 
    $displayLureChoice->lureSelect();
    $stmt = $conn->prepare("SELECT * FROM ".$tbl."lure WHERE id = ".$lureChoice."");    
    $stmt->execute();

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
          echo "Lure Choice: ".$row['type']. "<br />Color: " .$row['color']. "<br /><br />";
    }
}

The user chooses certain items from a form and it is to return the if/else values.

I have tried making $lurechoice a global variable within the function lureSelect() in the classes.php file but doesn't work. I tried making it a public var in the class but that failed as well.

Thanks for the guidance.




How do I access instance data from a method in python?

So I am trying to create a public method that can be called by class a so that it edits a data item in class b.

class aClass():
    def __init__():
        aVariable = 1

class aNotherClass():
    def aMethod():
        aFunction(5)

def aFunction(aNumber):
    instance1.aVariable = aNumber

instance1 = aClass()
instance2 = aNotherClass()
instance2.aMethod

However, when I call instance1 in aFunction, python tells me it isn't defined. If I want to change aVariable in aClass, what should aFunction() say?




jQuery add numbered class recursively to blocks of divs

I'm dinamically wrapping a fixed number of divs from an array. I need to recursively ad the same class to those groups of divs wrapped toghether:

<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

and this is tghe final result:

<div class="wrapper">
  <div class="item div-01"></div>
  <div class="item div-02"></div>
  <div class="item div-03"></div>
  <div class="item div-04"></div>
</div>
<div class="wrapper">
  <div class="item div-01"></div>
  <div class="item div-02"></div>
  <div class="item div-03"></div>
  <div class="item div-04"></div>
</div>




Passing object(create from dll) to other class file on C# with spel

Can anyone suggest me how to passing class program to another class file? My code: (main form)

private SpelNetLib.Spel m_spel;
Robot robot = new Robot();
private void Prototype_Load(object sender, EventArgs e)
    {
        m_spel = new SpelNetLib.Spel();
        m_spel.Initialize();
        m_spel.Project = "c:\\EPSONRC50\\projects\\TimCS\\TimCS.sprj";
        m_spel.MotorsOn = true;
        m_spel.PowerHigh = true;
        m_spel.Speed(100);
    }
 private void startBt_ButtonClick(object sender, EventArgs e)
    {
       SpelPoint pt = new SpelPoint();
        pt = m_spel.GetPoint("P*");
        pt.X = (float)125.5;   
        robot.goTOPT(pos,10,5,5);
        }

Robot Class

class Robot
public void goToPt(SpelPoint point,int x,int y,int z)
{
 point.X=point.X+x;
 m_spel.Go(point); // Want to use this function direct from class
}
}

Hope someone could help? Thank you.




Q>How to fix "DML currently not allowed" when accessing visualforce page

I edited my class and saved it successfully but when I accessed my page which uses the class, I get an error of

DML currently not allowed An unexpected error has occurred. Your development organization has been notified.

here is my controller

public class DefinitionController {

public DefinitionController() {
        this.DefTable();
}

public void DefTable(){ listplatforms = [select Name,Status__c from Platform__c];

  for(Platform__c idlistplatforms : [select Id from Platform__c]){
    List<Def__c> existplatforms = [select Platform__c from Def__c where Platform__c=:idlistplatforms.Id];

        if(existplatforms.size() > 0)
        {
            idlistplatforms.Status__c = 'Set';
            //update idlistplatforms;
            System.debug('Found'+ idlistplatforms);
        } 
        else 
        {
            idlistplatforms.Status__c = 'Not Set';
            //update idlistplatforms;
            System.debug('Not Found'+ idlistplatforms);
        }
        update idlistplatforms;
  }

}

}

I think the problem is because of the update part. Can someone please edit my code so that I will overcome that error?

Thanks in advance!




dimanche 28 juin 2015

How to make functions interact with class variables between eachother c++

I have been having trouble with a simple program that utilizes seperate file classes (i'm pretty new to them). Could you please help me figure out why it won't display the changed value?

main

 stats startout;

startout.beginning();
startout.start();

header

class stats
{
public:
void start();
void beginning();

//setter
void setHealth(int x){
    health = x;
    }
//getter
int getHealth(){
    return health;
    }
private:

int health;

};

implementation .cpp file

void stats::beginning(){
stats set;

set.setHealth(10);
}

void stats::start(){

stats stat;

cout << "Health: " << stat.getHealth() << endl;
}

It keeps displaying health as 0, which I assume is some sort of default since it is not being set as ten as described in my beginning() function. If anybody knows what the problem is or has suggestions on the best way to handle variables in classes and trading them between functions then please share your wisdom!




How to implement something similar to the @Override java annotation?

With this jdk code in ../java/lang/Override.java,

package java.lang;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)

public @interface Override {
}

having just annotation declaration, java compiler is intelligent enough to detect error(compile time):

The method toString123() of type Example must override or implement a supertype method

in the below problem code.

package annotationtype;

public class Example {

    @Override public String toString() {
       return "Override the toString() of the superclass";
    }

    @Override public String toString123() {
       return "Override the toString123() of the superclass";
    }

    public static void main(String[] args) {

    }


}

Annotation declaration for Override just gets compiled to,

interface java.lang.Override extends java.lang.annotation.Annotation{
}

which is nothing more than an interface.

So,

How does interface java.lang.Override syntax help java compiler to detect above error at compile time?




C++ Pass an object into another object?

I don't know if I've missed something, but I can't seem to figure out how to make this work, and couldn't find the answer online.

Lets say I have a two classes, Class A, and Class B. (stored in separate files)

Class A has a function setName() that sets a variable within a Class A object.

Class B has a function setOtherName() that sets the value of a Class A object's name.

So I set setOtherName() up like so:

void setOtherName(ClassA& cla)
{
*cla.setName("foobar");
}

then my main script looks like so:

Class A burger;
Class B fries;
fries.setOtherName(*burger);

this does not work in my orignal script, I get the following error:

error: no matching function for call to 'ClassB::setOtherName(ClassA*&)

Any help is aprreciated! ( sorry for any confusion )

Actual code: main.cpp:

#include <iostream>
#include "quests.h"
#include "player.h"
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
    quests GameQuests;
    player Player;
    GameQuests.quest1(Player);
    Player.main();

    return 0;
}

quests.cpp:

#include "quests.h"
#include "player.h"
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

void quests::quest1(player& charact){
    cout << "By the way, what was your name?" << endl;
    person1=4;
    system("pause");
    charact->setName();
}




PHP Slim framework instantiating a class

Ok guys, this must be a noob question but I am having trouble understanding this odd behavior of Slim class instantiation. To be very precise:

require 'Slim/Slim.php';
$app = new \Slim\Slim();

I believe everything is straightforward. Except I cannot understand why I have to write this:

$app = new \Slim\Slim();

as opposed to this:

$app = new Slim();

it's the same when I am referring to a function. This works:

  $request = \Slim\Slim::getInstance()->request();

But this doesn't:

  $request = Slim::getInstance()->request();

I believe I have done this quite a few times in the past successfully. It took me like two hours to figure this out. Am I imagining me being able to instantiate classes without including the relative path?




Arrays appended inside function not working in other class

My problem is that I have 4 empty arrays:

var Names:[String] = []
var Amounts:[Int] = []
var Dates:[NSDate] = []
var Images:[UIImage] = []

Inside a class NewPersonViewController.

I also have a function inside NewPersonViewController:

func create(){
   Names.append(nameField.text)
   Amounts.append(amountField.text.toInt()!)
   Dates.append(dateToBePaid.date)
}

I call create() when a button is pressed. The function is just a button action, declared inside NewPersonViewController.

My problem: When I print out the arrays in another class (which is in another file) not including Images, I just get this:

[]
[]
[]

Yup, thats my output. Thank you in advance. Side note: I am new to swift :)




Non-static nested class in java

I expect the output of the below program to be:

Inside Static Block A
Inside A
Inside Constructor B

But the output is:

Inside Static Block A
Inside A
Inside A
Inside A
.
.
.
Inside A(Infinite times)

The code is:

public class First
{
    public static void main(String args[])
    {
        A op=new A();
    }
}
class A
{
    private int a=100;
    private int b;
    A()
    {
        System.out.print("Inside A");
        B obj=new B();
    }
    static
    {
        System.out.print("Inside Static Block A");
    }
    class B
    {
        B()
        {
            System.out.print("Inside Constructor B");
        }
        A o=new A();
    }
}

Can someone please tell me why the output is so?




Is that good to define concreate classes inside abstract class? [java]

I am reading a java code like this below,: It defines concreate classes ClientEntry, ConfirgurationEntry inside abstract class LogEntry.

Is this a good practice? Usually I define them in separate files.

Thanks.

public abstract class LogEntry {

    /**
     * The four allowed {@link LogEntry} types.
     */
    public static enum Type {

        /**
         * {@link LogEntry} with {@code index} = 0, {@code term} = 0.
         */
        SENTINEL,

        /**
         * {@link LogEntry} that stores a noop entry.
         */
        NOOP,

        /**
         * {@link LogEntry} that stores cluster membership information about the Raft cluster.
         */
        CONFIGURATION,

        /**
         * {@link LogEntry} that stores a {@link Command} submitted by a client.
         */
        CLIENT,
    }

    /**
     * Singleton instance of the {@link LogEntry.Type#SENTINEL} log entry.
     */
    public static final LogEntry SENTINEL = new LogEntry(Type.SENTINEL, 0, 0) {

        @Override
        public String toString() {
            return Objects
                    .toStringHelper(this)
                    .add("type", "SENTINEL")
                    .add("index", getIndex())
                    .add("term", getTerm())
                    .toString();
        }
    };

    //----------------------------------------------------------------------------------------------------------------//
    //
    // Base class
    //

    private final Type type;
    private final long index;
    private final long term;

    // keeping this constructor private restricts
    // the number of allowed LogEntry types to those defined in this
    // compilation unit
    // i.e. using 'protected' instead would allow anyone to define additional
    // LogEntry types, which I don't support
    private LogEntry(Type type, long index, long term) {
        checkArgument(index >= 0, "index must be positive:%s", index);
        checkArgument(term >= 0, "term must be positive:%s", term);
        if (index == 0 && term == 0) {
            checkArgument(type == Type.SENTINEL);
        }
        this.type = type;
        this.index = index;
        this.term = term;
    }

    /**
     * Get the type of this log entry.
     *
     * @return {@link LogEntry.Type} of this log entry
     */
    public final Type getType() {
        return type;
    }

    /**
     * Get the log entry's position in the 0-indexed Raft log.
     *
     * @return index >= 0 of this log entry's position in the Raft log
     */
    public long getIndex() {
        return index;
    }

    /**
     * Get the election term in which this log entry was created.
     *
     * @return election term >= 0 in which this log entry was created
     */
    public final long getTerm() {
        return term;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(type, index, term);
    }

    @Override
    public boolean equals(@Nullable Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        LogEntry other = (LogEntry) o;
        return type == other.type && index == other.index && term == other.term;
    }

    //----------------------------------------------------------------------------------------------------------------//
    //
    // Subclasses
    //

    /**
     * {@code LogEntry} that contains a client {@link Command}.
     * <p/>
     * Once this entry is committed
     * the client is notified via {@link io.libraft.RaftListener#applyCommitted(Committed)}
     * that this {@code Command} can be applied locally.
     */
    public static final class ClientEntry extends LogEntry {

        private final Command command;

        /**
         * Constructor.
         *
         * @param index index > 0 of this log entry's position in the log
         * @param term election term > 0 in which this log entry was created
         * @param command instance of {@link Command} to be replicated
         */
        public ClientEntry(long index, long term, Command command) {
            super(Type.CLIENT, index, term);
            this.command = command;
        }

        /**
         * Get the {@link Command} to be replicated.
         *
         * @return instance of {@code Command} to be replicated
         */
        public Command getCommand() {
            return command;
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            if (!super.equals(o)) return false;

            ClientEntry other = (ClientEntry) o;
            return getType() == other.getType()
                    && getIndex() == other.getIndex()
                    && getTerm() == other.getTerm()
                    && command.equals(other.command);
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(getType(), getIndex(), getTerm(), command);
        }

        @Override
        public String toString() {
            return Objects
                    .toStringHelper(this)
                    .add("type", getType())
                    .add("index", getIndex())
                    .add("term", getTerm())
                    .add("command", command)
                    .toString();
        }
    }

    // FIXME (AG): the design of this log entry is incorrect and has to be reworked
    /**
     * {@code LogEntry} that contains the
     * configuration state of the Raft cluster.
     */
    public static final class ConfigurationEntry extends LogEntry {

        private final Set<String> oldConfiguration;
        private final Set<String> newConfiguration;

        /**
         * Constructor.
         *
         * @param index index > 0 of this log entry's position in the log
         * @param term election term > 0 in which this log entry was created
         */
        public ConfigurationEntry(long index, long term, Set<String> oldConfiguration, Set<String> newConfiguration) {
            super(Type.CONFIGURATION, index, term);
            this.oldConfiguration = oldConfiguration;
            this.newConfiguration = newConfiguration;
        }

        public Set<String> getOldConfiguration() {
            return oldConfiguration;
        }

        public Set<String> getNewConfiguration() {
            return newConfiguration;
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            if (!super.equals(o)) return false;

            ConfigurationEntry other = (ConfigurationEntry) o;

            return getType() == other.getType()
                    && getIndex() == other.getIndex()
                    && getTerm() == other.getTerm()
                    && oldConfiguration.equals(other.oldConfiguration)
                    && newConfiguration.equals(other.newConfiguration);
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(getType(), getIndex(), getTerm(), oldConfiguration, newConfiguration);
        }

        @Override
        public String toString() {
            return Objects
                    .toStringHelper(this)
                    .add("type", getType())
                    .add("index", getIndex())
                    .add("term", getTerm())
                    .add("oldConfiguration", oldConfiguration)
                    .add("newConfiguration", newConfiguration)
                    .toString();
        }
    }

    /**
     * noop {@code LogEntry}.
     * <p/>
     * {@code NoopEntry} is for {@link RaftAlgorithm}
     * internal use only. The client <strong>will not</strong>
     * be notified when a {@code NoopEntry} instance
     * is committed.
     */
    public static final class NoopEntry extends LogEntry {

        /**
         * Constructor.
         *
         * @param index index > 0 of this log entry's position in the log
         * @param term election term > 0 in which this log entry was created
         */
        public NoopEntry(long index, long term) {
            super(Type.NOOP, index, term);
        }
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("type", getType())
                .add("index", getIndex())
                .add("term", getTerm())
                .toString();
    }
}




Xcode 6.3 Can't choose class for my ViewControllers

Connections don't work anymore, because apparently there is not a class like that anymore..

Before all my custom VC classes were available here in this list, now I can only see the default ones This is driving me crazy. I have worked with this xcode iOS project for quite some time now, and now suddenly I see that I can't add my custom View Controller classes to the View Controllers in my storyboard anymore... And the outlets from the classes is not available anymore, I get warnings where I connected the outlets to labels and all that in the storyboard, saying that it is not defined in the custom class... Everything worked before... I have tried to restart xcode and the computer and tried to remove the reference to a custom class and add it again, but I was not able to give a View Controller that subclass anyway...

Any idea what happened?? :(

EDIT: Found this in the Build Phases in Copy bundle Resources. I recently changed from deployment target iOS 8.3 to iOS 7.0.. Something to do with this?

How do I fix this?




Python: Why is it saying my method isn't defined when it clearly is?

class GameMech:
def __init__(self ,aCharacter):
    print("A battle is starting")
def getMP(self, aCharacter):
    return aCharacter.mp
def getHP(aCharacter):
    return aCharacter.hp
def getAtk(aCharacter):
    return aCharacter.atk
def getDef(aCharacter):
    return aCharacter.defense
def usePotion(aCharacter):
    aCharacter.hp += 100
    return aCharacter.hp
def useSpecial(self, aCharacter, target):
    if aCharacter.mp >= 100:
        target.hp -= 45

def dead(self, aCharacter):
    return aCharacter.name +" is now dead"
def attack(self, aCharacter, target):
    if target.hp - (http://ift.tt/1dr1FsI) <= 0:
        dead(target)
    else:
        target.hp - http://ift.tt/1dr1FsI
        print(getHP(target))
def guard(self, aCharacter):
    print(aCharacter + "was unharmed")
    if aCharacter.hp <= 50:
        retaliation(aCharacter, target)
def retaliation(self ,aCharacter, target):
    target.hp - (aCharacter.atk/10)
    print(getHP(target))

def battleMenu(aNumber):
    if aNumber == 1:
        attack(aCharacter, target)
    if aNumber == 2:
        guard(aCharacter)
        print(aCharacter + " was unharmed!")
    if aNumber == 3:
        useSpecial(aCharacter, target)
        print(getHP(target))
    if aNumber == 4:
        heal = useItem(aCharacter)
        print(heal)

def myTurn(self):
    print("ATTACK")
    print("GUARD")
    print("SPECIAL")
    print("ITEM")
    aNumber = int(input("What would you like to do? "))
    battleMenu(aNumber)


def oppTurn(self):
    print("It is the opponent's turn")
    randomNum = random.randint(1,4)
    battleMenu(randomNum)

a few notes, obviously due to this formatting you can't tell that all my methods are actually under the class, but they are. you can ignore the first few parts, the part im focusing on is battle menu. So i'm creating a little text game as a project for myself, pure leisure nothing academic or for a job. Just a little game for myself to help me jog my memory in regards to python. So that's where the gut of my game is, the character class is an another file and there's nothing important in there just the attributes of character (hp, mp, atk, def) here's the main

import random
import character
import battle



#create a battle menu
#and a character value check menu
#add buttons




def main():
char1 = character.Character("Charlie", 5000, 2000, 1500, 750)
char2 = character.Character("Mark", 2000, 4000, 2000, 900)

newGame = battle.GameMech(char1)
while char1.hp != 0 or char2.hp != 0:
    newGame.myTurn()
    newGame.oppTurn()

main() (not sure why it's not including the definition of my main in the code snippet) Any how I'm getting this error saying "name 'battleMenu' is not defined". Name usually applies to variables correct? But battleMenu is a method is there a reason i'm getting this error?




Making a class object belong to only one another class object

I just want to know if it is possible to do something like this:

#include "graph.h"
Graph A, B;
Node n;

A.insertNode(n);
A.nodeExists(n); // returns true
B.nodeExists(n); // returns false

Since now I only stored a boolean var inside Node class, which tells me if a Node object has been inserted inside a Graph. But in this way, what happens:

A.nodeExists(n); // returns true
B.nodeExists(n); // returns true

which is incorrect. How can I solve this?




What is the use of Byte code in java

I am a little bit confused... I know that classes are loaded by the class loader only when they are needed,that is when we are trying to use static variables or when we are creating instance of that class.Thus if we have for e.g. 3 classes in our program and we are going to use only one,then only that particular class will be loaded and rest are not,but when we run the java compiler,it will create 3 .class files,I know these 3 .class files are byte code files,but then what is this byte code and what is the difference between loading a class and generating bytecode of a class?Where is the use of this byte code?If we are not going to use a particular class,then what is the need of generating a bytecode for that class?




Java classes reference each other

I have two java class files. Each of them has methods the other one uses.

public class class1{
    class2 c2 = new class2(); 
    m1(){
        c2.ma(); 
        m2();
    }
    m2(){}
}

public class class2{
    class1 c1 = new class1();
    ma(){}
    mb(){
        c1.m2();
    }
}

The lines

class1 c1 = new class1();  

and

class2 c2 = new class2();  

refer to each other causing an infinite loop, resulting in a java.lang.StackOverflowError error.

Is there some way to have the classes refer to each other or do I have no choice but to transfer all of my methods into a single class?




How to execute different classes in one class

I want to create a program that can do all the stuff from another code, depending on user input. Something like this:

import java.util.Scanner;
public class Main_Programm1 {
    public static void main(String args[]) {
        String something = "something";
        String something2 = "something2";
        Scanner userInput = new Scanner(System.in);
        String action = userInput.next();
        if (action.equals(something)) {
            //here i want to execute all the code from class Main_Programm2
        } else if (action.equals(something2)) {
            //here i want to execute all the code from class Main_Programm3 and so on
        }
    }
}

How do i do it?




How to Call a SQLiteOpenHelper Class Having it's name in a String

I have several readable databases in my assets with same structure. the user will select the name of a database and the name of it's SQliteOpenHelper class is passed in a String. I could initiate the class with Class.forname() but I cant cast Class.getMethod("TableA", null) to Cursor. Can anyone help me get cursors while I only have SQLiteOpenHelper Class name?




samedi 27 juin 2015

Ruby Instance Array Is Modified in a Separate Object

Lets say I create an object with an array. I then create another object that takes said array and modifies it within its own scope. If I try to access original array from the first object again, shouldn't I have the unmodified version of the array?

Example code:

class Test
    attr_accessor :g

    def initialize
        @g = [1,2,3]
    end

    def do_stuff
        Test_Two.new(@g).modify
    end

end

class Test_Two
    def initialize(h)
        @h = h
    end

    def modify
        @h[0] +=1
    end

end


t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"

Expected output:

[1,2,3]
[1,2,3]

Actual output:

[1,2,3]
[2,2,3]

Weirdly enough, if I make g an integer, I get what I expect:

class Test
    attr_accessor :g

    def initialize
        @g = 1
    end

    def do_stuff
        Test_Two.new(@g).modify
    end

end

class Test_Two
    def initialize(h)
        @h = h
    end

    def modify
        @h +=1
    end

end


t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"

Output:

1
1




What is the advantage of using annotation type over interface type?

In this example, below annotation type(@interface):

@interface ClassPreamble {
       String author();
       String date();
       int currentRevision() default 1;
       String lastModified() default "N/A";
       String lastModifiedBy() default "N/A";
       // Note use of array
       String[] reviewers();
    }

gets compiled to interface type:

interface annotationtype.ClassPreamble extends java.lang.annotation.Annotation{
    public abstract java.lang.String author();
    public abstract java.lang.String date();
    public abstract int currentRevision();
    public abstract java.lang.String lastModified();
    public abstract java.lang.String lastModifiedBy();
    public abstract java.lang.String[] reviewers();
}

So, the annotation type is getting compiled to interface type, before runtime.

In java, What is the advantage of using annotation type(@interface) over the interface type?




Wordpress oop wpdb in class

I am new in OOP PHP and I am trying to use $wpdb (WORDPRESS) object in some of my custom classes but have no idea how to do it. Every time I try to implement basic operations with $wpdb results in fail. I need some basic stuff like get_results(),.... So how to do something like this:

global $wpdb;

$my_custom_table = $wpdb->prefix . "table_name";

$table_content = $wpdb->get_results("SELECT * FROM ".$my_custom_table);

and put it into my class like this:

Class MyClass{

     public function table_results(){
            //put in here
            return $this->table_content;
     }
}

I need that class in separate file so I could easily call to it.




Collapsing navbar content margin - span class bars

I have been working on this navbar template for a few days. Almost done, but it is not just as I wanted. Navbar is working fine, but how can I overcome spaces on four sides: 3px on the left (most probably 1px border+1px space+1px border) 10px on top, 10 px bottom, 33px on the right. Can you help me overcome them?

Second, Span class bars are not showing, the same code works on another page? What am I missing?

Here is the example of my template:

http://ift.tt/1RHZ6QD




ruby: calling a instance method without using instance

I know in ruby, when we call an instance method, we need to firstly instantiate a class object. But when I see a open sourced code I got confused. The code is like this:

File Message.rb
require 'json'

module Yora
  module Message
    def serialize(msg)
      JSON.generate(msg)
    end

    def deserialize(raw, symbolized_key = true)
      msg = JSON.parse(raw, create_additions: true)
      if symbolized_key
        Hash[msg.map { |k, v| [k.to_sym, v] }]
      else
        msg
      end
    end
  end
end



File. Persistance.rb


require 'fileutils'
require_relative 'message'

module Yora
  module Persistence
    class SimpleFile
      include Message

      def initialize(node_id, node_address)
        @node_id, @node_address = node_id, node_address

        FileUtils.mkdir_p "data/#{node_id}"

        @log_path = "data/#{node_id}/log.txt"
        @metadata_path = "data/#{node_id}/metadata.txt"
        @snapshot_path = "data/#{node_id}/snapshot.txt"
      end

      def read_metadata
        metadata = {
          current_term: 0,
          voted_for: nil,
          cluster: { @node_id => @node_address }
        }
        if File.exist?(@metadata_path)
          metadata = deserialize(File.read(@metadata_path)) #<============
        end

        $stderr.puts "-- metadata = #{metadata}"

        metadata
      end

.....

You can see the line I marked with "<===" It uses deserialize function that been defined in message class. And from message class we can see that method is a instance method, not class method. So why can we call it without instantiating anything like this?

thanks




how to get value from another class in python by hit button

I have some problem, i want get value from database in another class by hit button. I used methode string matching, when user input string and after taht user press button. System will matching what user input to database. what i want now is, i want the output in another form and absoluty in another class. I create some code like this.

class MyFrame(wx.Frame):
  def __init__(self, parent):
    wx.Frame.__init__(self, parent)
    wx.StaticText(self, -1, "Asking", pos=(20, 50))
    self.inpt = wx.TextCtrl(self, -1, pos=(10, 70), size=(250, 20), style= wx.EXPAND)
    wx.StaticText(self, -1, "Link", pos=(20, 135))
    self.opt = wx.ListBox(self, -1, pos=(10, 160), size=(480, 250), style= wx.TE_MULTILINE | wx.BORDER_SUNKEN)

    img = "search.png"
    image1 = wx.Image(img, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
    self.btn1 = wx.BitmapButton(pan1, id=-1, bitmap=image1, pos=(85, 105), size = (image1.GetWidth()+5, image1.GetHeight()+5))

    self.btn1.Bind(wx.EVT_BUTTON, self.OnEnter, self.btn1)

    self.klik = self.opt.Bind(wx.EVT_LISTBOX_DCLICK, self.playVideo)

def playVideo(self, event):
    data = event.GetClientObject()
    link = data[0]
    ex = data[1]

    self.player.Load(link)
    self.pjs.Clear()
    self.pjs.AppendText(ex)

  def OnEnter(self, event):
    self.opt.SetLabel(self.PatMatch())

  def PatMatch(self):
    self.opt.Clear()
    con = lite.connect('media.db')  
    with con:
        cur = con.cursor()
        for row in cur.execute("select * from baru"):
            self.klmt = self.inpt.GetValue()
            if row[1] in self.klmt.lower():
                self.opt.Append(row[2], [row[4], row[3]])

class Kmp(wx.Frame):
  def __init__(self, parent, *args, **kwds):
      kwds["style"] = (wx.DEFAULT_FRAME_STYLE) & ~ (wx.RESIZE_BORDER|wx.RESIZE_BOX)
      wx.Frame.__init__(self,parent,title='Informasi', size=(500, 500), *args, **kwds)

      km2 = wx.StaticText(self, label='Word', pos=(20, 70))
      ttk2 = wx.StaticText(self, label=':', pos=(200,70))
      txt1 = wx.TextCtrl(self, -1, pos=(220, 70), size=(200, 30), style= wx.EXPAND)
      txt1.SetEditable(False)

      km3 = wx.StaticText(self, label='Total word', pos=(20, 110))
      ttk3 = wx.StaticText(self, label=':', pos=(200,110))
      txt2 = wx.TextCtrl(self, -1, pos=(220, 110), size=(200, 30), style= wx.EXPAND)
      txt2.SetEditable(False)

      km4 = wx.StaticText(self, label='POsisition Word', pos=(20,145))
      ttk4 = wx.StaticText(self, label=':', pos=(200,145))
      txt3 = wx.TextCtrl(self, -1, pos=(220, 150), size=(200, 30), style= wx.EXPAND)
      txt3.SetEditable(False)

      btn2 = wx.Button(self, -1, 'Exit', pos=(200, 200))

    def data(self):
        dt = MyFrame(self)
        klm = selt.inpt.GetValue()
        re.findall(r"[\w']+", klm)      

    def compute_prefix(word):
        word_length = len(word)
        prefix = [0] * word_length
        k = 0

        for q in xrange(1, word_length):
            while k > 0 and word[k] != word[q]:
                k = prefix[k - 1]

            if word[k + 1] == word[q]:
                k = k + 1
            prefix[q] = k
        return prefix

    def search(self, string, word):
        word_length = len(word)
        string_length = len(string)
        offsets = []
        if word_length > string_length:
            return offsets

        prefix = compute_prefix(word)
        q = 0
        for index, letter in enumerate(string):
            while q > 0 and word[q] != letter:
                q = prefix[q - 1]
            if word[q] == letter:
                q += 1
            if q == word_length:
                offsets.append(index - word_length + 1)
                q = prefix[q - 1]
        return offsets

    word = ""
    string = "" 

    def pro(self, event):
        pp = MyFrame(self)
        self.opt.SetLabel(self.PatMatch())

my database:

id  word        name_link   explain     link
--- ------      ----------- ---------   --------
1   python      Video1      test        C:\Users\Ihsan\Downloads\Video1.MP4
2   python      Video2      test1       C:\Users\Ihsan\Downloads\Video2.MP4
3   python      Video3      test2       C:\Users\Ihsan\Downloads\Video3.MP4