PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label oop. Show all posts
Showing posts with label oop. Show all posts

Wednesday, December 21, 2022

[FIXED] Why don't associated types for protocols use generic type syntax in Swift?

 December 21, 2022     generics, oop, swift, syntax     No comments   

Issue

I'm confused about the difference between the syntax used for associated types for protocols, on the one hand, and generic types on the other.

In Swift, for example, one can define a generic type using something like

struct Stack<T> {
    var items = [T]()
    mutating func push(item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
}

while one defines a protocol with associated types using something like

protocol Container {
    associatedtype T
    mutating func append(item: T)
    var count: Int { get }
    subscript(i: Int) -> T { get }
}

Why isn't the latter just:

protocol Container<T> {
    mutating func append(item: T)
    var count: Int { get }
    subscript(i: Int) -> T { get }
}

Is there some deep (or perhaps just obvious and lost on me) reason that the language hasn't adopted the latter syntax?


Solution

This has been covered a few times on the devlist. The basic answer is that associated types are more flexible than type parameters. While you have a specific case here of one type parameter, it is quite possible to have several. For instance, Collections have an Element type, but also an Index type and a Generator type. If you specialized them entirely with type parameterization, you'd have to talk about things like Array<String, Int, Generator<String>> or the like. (This would allow me to create arrays that were subscripted by something other than Int, which could be considered a feature, but also adds a lot of complexity.)

It's possible to skip all that (Java does), but then you have fewer ways that you can constrain your types. Java in fact is pretty limited in how it can constrain types. You can't have an arbitrary indexing type on your collections in Java. Scala extends the Java type system with associated types just like Swift. Associated types have been incredibly powerful in Scala. They are also a regular source of confusion and hair-tearing.

Whether this extra power is worth it is a completely different question, and only time will tell. But associated types definitely are more powerful than simple type parameterization.



Answered By - Rob Napier
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, December 14, 2022

[FIXED] How to add a loop inside a variable php

 December 14, 2022     loops, oop, php, syntax     No comments   

Issue

I have to use a foreach loop inside a variable in php but Im not sure of the right syntax. This is what Ive tried but it shows an error(Parse error: syntax error, unexpected 'foreach' (T_FOREACH))

 $doctor = foreach($doctor->find_all() as $d){
      echo '<td>'.$d->getName().'</td>';
      echo '<td>'.$d->getEmail().'</td>';
      echo '<td>'.$d->getPhone().'</td>';
      echo '<td>'.$d->getGender().'</td>';
      echo '<td>'.$d->getSpecialist().'</td>';
      echo '<td><a href="../doctor/updatedoc.php"><i class="fa-solid fa-pen-to-square"></i></a></td>';
      echo  '<td><a href=""><i class="fa-solid fa-trash"></i></a></td>';
    };

Solution

You cannot assign loop on variable or with the echo instead you can direct save the data to variable inside the loop

$doctor = "";
foreach($doctor->find_all() as $d){
      $doctor .='<td>'.$d->getName().'</td>';
      $doctor .='<td>'.$d->getEmail().'</td>';
      $doctor .='<td>'.$d->getPhone().'</td>';
      $doctor .='<td>'.$d->getGender().'</td>';
      $doctor .='<td>'.$d->getSpecialist().'</td>';
      $doctor .='<td><a href="../doctor/updatedoc.php"><i class="fa-solid fa-pen-to-square"></i></a></td>';
      $doctor .='<td><a href=""><i class="fa-solid fa-trash"></i></a></td>';
    }; 


Answered By - Existed Mocha
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 25, 2022

[FIXED] When returning a table get {}

 November 25, 2022     lua, module, oop, return, roblox     No comments   

Issue

I am trying to create a maze generation script using the module listed below. I'm having this strange problem were the grid variable has a value, but when return grid is called, it returns and empty table? Here is the code to the module script.

local ServerStorage = game:GetService("ServerStorage")
local cellTemplate = ServerStorage:WaitForChild("Cell")

local Maze = {}
local cellObject = {}

local grid = {}

Maze.Size = 25

Maze.CellWidth = 9
Maze.CellLength = 9

Maze.Offset = Vector3.new(0,0,0)

function Maze.new(x,z) -- Create a new cell
    local newCell = {}
    
    setmetatable(newCell,{ -- Allows us to create functions for a cell easier
        __index = cellObject
    })
    
    newCell.X = math.clamp(x,1,Maze.Size)
    newCell.Z = math.clamp(z,1,Maze.Size)
    
    newCell.Visited = false
    
    newCell.Model = cellTemplate:Clone()
    newCell.Base = newCell.Model:WaitForChild("Base")
    
    newCell.Model.Name = newCell.Model.Name.. "_".. newCell.X.. "-".. newCell.Z
    
    newCell.Walls = {
        ["Forward"] = newCell.Model:WaitForChild("Forward");
        ["Backward"] = newCell.Model:WaitForChild("Backward");
        ["Left"] = newCell.Model:WaitForChild("Left");
        ["Right"] = newCell.Model:WaitForChild("Right");
    }
    
    if not grid[x] then grid[x] = {} end -- We might not have anything on that x axis yet; inserts it into the table
    
    grid[x][z] = newCell
    
    print(grid)
    
    return newCell
end

function Maze.RenderAll() -- Render every cell; exists for more readibility
    for _,cellRow in pairs(grid) do -- Loop through every cell row
        for _,cell in pairs(cellRow) do -- Loop through every cell in the row
            cell:Render() -- Render the cell
        end
    end
end

function Maze.Grid() -- Allows other scripts to get the grid but not modify it
    return grid
end

function Maze.FilterUnvisited(cells) -- Takes in a table and returns one with only the cells in the table that are unvisited
    local unvisited = {}
    
    for _,cell in pairs(cells) do -- Loop through every cell in the table passed
        if not cell.Visitied then -- The cell hasn't been visited
            table.insert(unvisited,cell)
        end
    end
    
    return unvisited
end

function Maze.GetCell(x,z)
    local cell
    
    if grid[x] and grid[x][z] then
        cell = grid[x][z]
    else
        cell = nil
    end
    
    return cell
end

function cellObject:Render() -- Render the cell
    self.Model:SetPrimaryPartCFrame(CFrame.new(Vector3.new(self.X * Maze.CellLength,0,self.Z * Maze.CellWidth) + Maze.Offset)) -- Move the cell to the correct position
    
    if self.Visited then -- We have gone through the cell
        self.Model.PrimaryPart.Color3 = Color3.new(0,1,0) -- Show that the cell has been visited; used for debugging
    end
    
    self.Model.Parent = workspace
end

function cellObject:Neighbours() -- Returns the cell's neigbours
    local neighbours = {}
    
    -- Order: Right Left Up Down
    
    if grid[self.X + 1] and grid[self.X + 1][self.Z] then -- A cell with +1 X exists
        table.insert(neighbours,grid[self.X + 1][self.Z])
    end
    
    if grid[self.X - 1] and grid[self.X - 1][self.Z] then -- A cell with -1 X exists
        table.insert(neighbours,grid[self.X - 1][self.Z])
    end
    
    if grid[self.X][self.Z + 1] then -- A cell with +1 Z exists
        table.insert(neighbours,grid[self.X][self.Z + 1])
    end

    if grid[self.X][self.Z - 1] then -- A cell with -1 Z exists
        table.insert(neighbours,grid[self.X][self.Z - 1])
    end
    
    return neighbours
end

function cellObject:RandomNeighbour()
    local neighbours = self:Neighbours() -- Gets the neigbours of the current cell
    
    if #neighbours > 0 then
        return neighbours[math.random(1,#neighbours)] -- Returns a random neigbour
    else
        return nil
    end
end

function cellObject:WallArray() -- Returns an array of the walls instead of a table
    local wallArray = {}
    
    wallArray[1] = self.Walls.Forward
    wallArray[2] = self.Walls.Right
    wallArray[3] = self.Walls.Left
    wallArray[4] = self.Walls.Backward
    
    return wallArray
end

function cellObject:Join(cell) -- Joins 2 cells together
    local wallPosition = self.Base.Position:Lerp(cell.Base.Position,.5) -- This will return the position of the wall (excluding the Y)
    
    local cell1Array = self:WallArray()
    local cell2Array = cell:WallArray()
    
    for wallIndex,wall in pairs(cell1Array) do
        if wall.Position.X == wallPosition.X and wall.Position.Z == wallPosition.Z then -- Its the right wall
            wall.Transparency = 1
            wall.CanCollide = false
            
            cell2Array[4 - (wallIndex - 1)].Transparency = 1
            cell2Array[4 - (wallIndex - 1)].CanCollide = false
            
            break -- We don't need to loop anymore, since we've already removed the walls
        end
    end
end

function cellObject:Unjoin(cell) -- Unjoins 2 cells
    local wallPosition = self.Base.Position:Lerp(cell.Base.Position,.5) -- This will return the position of the wall (excluding the Y)
    
    local cell1Array = self:WallArray()
    local cell2Array = cell:WallArray()
    
    for wallIndex,wall in pairs(cell1Array) do
        if wall.Position.X == wallPosition.X and wall.Position.Z == wallPosition.Z then -- Its the right wall
            wall.Transparency = 0
            wall.CanCollide = true
            
            cell2Array[4 - (wallIndex - 1)].Transparency = 0
            cell2Array[4 - (wallIndex - 1)].CanCollide = true
            
            break -- We don't need to loop anymore, since we've already added the walls
        end
    end
end

return Maze

Below is the piece of code I'm having diffuculty with.

function Maze.Grid() -- Allows other scripts to get the grid but not modify it
    return grid
end

I have tested printing the grid variable and it's not {} but when I call the function in the script below, I always get {}! I have no idea why this is. Is this a bug in roblox or am I being stupid?

local ServerScriptService = game:GetService("ServerScriptService")
local Maze = require(ServerScriptService:WaitForChild("Maze"))

local latestX = 0
local latestZ = 0

function CreatePath(cell)
    local nextCell = cell:RandomNextCell(false)
    
    if nextCell then -- We have a cell next to the current one
        print("Joining cells:",cell,nextCell)
        
        cell:Join(nextCell)
        cell.Visited = true
        
        cell:Render()
        
        wait(.01)
        CreatePath(nextCell)
    else -- It must be the end of the maze
        print("Path generated!")
        print("Maze end: ".. cell.Model.Name)
        
        cell.Base.Color = Color3.new(1,0,0)
    end
end

function GenerateMaze()
    local cell = Maze.new(latestX + 1,latestZ + 1) -- Create a new cell
    
    cell:Render() -- Render it
    
    print("Created cell")
    
    latestZ += 1
    
    if latestZ > Maze.Size then -- It has exceeded the max size, move on to a new row
        latestX += 1
        latestZ = 0
    end
    
    if #Maze.Grid() < Maze.Size ^ 2 then
        wait(.01)
        GenerateMaze()
    else
        print("Grid completed, generating path...")
        
        CreatePath(Maze.GetCell(1,1))
    end
end

GenerateMaze()

Solution

You are returning a cached value, or well i don't find out other reason.

You may do (and it's not editable):

function Maze.Grid(i, l)
    local passed = 1
    local response = {}
    for index, v in pairs(grid) do
        response[index] = i and passed >= i and l and passed <= l and v or not (i or l) and v
        -- basically get more than `i` if it, and minor than `l` if it passed
        i = i + 1
    end
    return response
end

It should work, I don't tested it sorry.



Answered By - Corotyest
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, November 20, 2022

[FIXED] How can I move chinese characters in a string to the end of string?

 November 20, 2022     oop, php, preg-replace     No comments   

Issue

I have a string like this now: I want to do the following in PHP:

$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';

I want to move all Chinese characters to the end of the string, and also reversing their current order. Accordingly, Removing the duplicate English words and Return the modified string


Solution

Here you go! Check the comments in the code:

<?php

$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';

// split by a space into an array
$explosion = explode(' ', $string);

$normalWords = [];
$chineseWords = [];

// loop through the array
foreach ($explosion as $debris) {

   // if not normal alphabet characters
   if (!preg_match('#[a-zA-Z]+#', $debris) && !in_array($debris, $chineseWords)) {
       // add to chinese words array if not already in the array
      $chineseWords[] = $debris;
   } elseif (preg_match('#[a-zA-Z]+#', $debris) && !in_array($debris, $normalWords)) {
        // add to normal words array if not already in the array
       $normalWords[] = $debris;
   }
}

// reverse the chinese characters like you wanted
$chineseWords = array_reverse($chineseWords);

// Piece it all back together
$string = implode(' ', $normalWords) . ' ' . implode(' ', $chineseWords);

// and output
echo $string;  // Testing giving dancing passing 吃 跑步 制图 喝

See it here! https://3v4l.org/FWQWG



Answered By - delboy1978uk
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 14, 2022

[FIXED] How can I call class methods dynamically?

 November 14, 2022     abstract-class, error-handling, methods, oop, typescript     No comments   

Issue

I am trying to make an abstract class with method callAction which calls methods of class dynamically.

I have tried to write this but I am getting error.

abstract export class BaseContoller {
    public callAction(method: keyof typeof this, parameters: any[]) {
        this[method](parameters);
    }
}

Error - This expression is not callable. Type 'unknown' has no call signatures.ts(2349)

Is there another way to achive this?


Solution

Your class can have value as well as function properties together, so to make sure your property is a function type, you can use typeof x === "function".

That can help to check method's type with the call signature before method execution.

class BaseContoller {
    public callAction(method: keyof typeof this, parameters: any[]) {
      const property = this[method]
      if(typeof property === "function") {
        property(parameters);
      }
    }

    public testFunction() {}
}

Playground



Answered By - Nick Vu
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 26, 2022

[FIXED] How to delete a specific value from a doubly linked list?

 October 26, 2022     c++, doubly-linked-list, function-definition, linked-list, oop     No comments   

Issue

I was given a task with a DOUBLY linked list to delete a specific number from the list. My code is giving an Access Violation error. Even after multiple dry runs, I can't figure out what is wrong. The task basically is to create a search function which finds a specific number in the linked list, and a deletion function which deletes that specific link.

node* search(int val){
    node* cur=head;
    while(cur!=NULL){
        if(cur->data==val){
            cout<<"value found "<<val<<endl;
            return cur;
        }
        cur=cur->next;
    }
    cout<<"value not exist"<<endl;
    return NULL;
}

bool delspval(int val){
    node*temp=0;
    if(search(val)==NULL){
        return 0;
    }
    else{
        temp=search(val);
        temp->prev->next=temp->next;
        delete temp;
        temp=0;
        cout<<"specific value "<<val<<" deleted"<<endl;
        return 1;
    }
}

In the above given code, the line temp->prev->next=temp->next; is giving the error. I'm pretty much a beginner at linked lists, so any help would be appreciated.

minimal working code:

#include<iostream>
using namespace std;
class dll{
    struct node{
        int data;
        node *next,*prev;
    };
    node *head;
public:
    dll(){
        head=NULL;
    }
    void inatst(int val){
        node *temp=new node;
        temp->data=val;
        temp->next=head;
        head=temp;
    }
    node* search(int val){
        node* cur=head;
        while(cur!=NULL){
            if(cur->data==val){
                cout<<"value found "<<val<<endl;
                return cur;
            }
            cur=cur->next;
        }
        cout<<"value not exist"<<endl;
                    return NULL;
    }
    bool delspval(int val){
        node*temp=0;
        if(search(val)==NULL){
            return 0;
        }
        else{
            temp=search(val);
            temp->prev->next=temp->next;
            delete temp;
            temp=0;
            cout<<"specific value "<<val<<" deleted"<<endl;
            return 1;
                }
            }
    void display(){
        node*cur=head;
        while(cur!=NULL){
            cout<<cur->data<<" ";
            cur=cur->next;
        }
        cout<<endl;
    }
    ~dll(){
        while(head!=NULL){
            node*cur=head;
            head=cur->next;
            delete cur;
            cur=head;
        }
    }
};
void main(){
    dll l1;
    l1.inatst(1);
    l1.inatst(2);
    l1.inatst(3);
    l1.inatst(4);
    l1.inatst(5);
    l1.inatst(6);
    l1.display();
    l1.delspval(3);
    system("pause");
}

Solution

For starters, the search() function is being called twice within the delspval() function:

if(search(val)==NULL){

and

temp=search(val);

that makes the delspval() function less efficient.

This statement:

temp->next->prev=temp->next;

does not make sense.

The delspval() function can be defined in the following way. I suppose that the class contains only one pointer to the head node. If the class contains also a pointer to the tail node, then the function below must be modified.

bool delspval( int val )
{
    node *temp = search( val );
    bool success = temp != nullptr;

    if ( success )
    {
        if ( temp->next != nullptr )
        {
            temp->next->prev = temp->prev;
        }
        // If the class has a pointer to the tail node
        //   then uncomment the else part  
        /*
        else
        {
            tail = temp->prev;
        }
        */

        if ( temp->prev != nullptr )
        {
            temp->prev->next = temp->next;
        }
        else
        {
            head = temp->next;
        }

        delete temp;
    }

    return success;
}


Answered By - Vlad from Moscow
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] when to use interface and when not?

 October 26, 2022     class, interface, oop     No comments   

Issue

I completely understand that we use interface's as contract to tell developers what are the functions to implement. But is this going to be at all cases "Meaning do we have to implement an interface for each class". lets say we have only one class going to implement an interface. do we define an interface for for that class specifically. and when not to use interfaces.

My understanding is that we use interface when we would like to enforce developers to implement a set of must have functions. lets say we have a server class. then we must do interface because we always need for instance two functions one to turn the server on ServerOn(); and one to turn the server off ServerOff();


Solution

The use of interface comes into play where you want common behavioural functions to be used at all time. Let’s say you are building an application that deals with different type of server’s and in the future you might add other types of servers. Then in this case you will always have functions to turn on server’s and turn off server’s. Use interface to add these required functions ServerOn();, ServerOff(). then each time you add a new server new type you implement the Interface IServer which then requires these function. The idea here is to apply abstractions where low level classes depends on abstractions.

The other main usage of interface that some programming languages or almost all allow the concept of polymorphism through interfaces. Meaning that all classes implements the interface called IServer for instance can be declared as IServer sqlServer; IServer orcaleServer; this helps in using DI and Unit testing. Ex: Look at the following constructor Public Server(IServer server){//rest of code}; you see we created a constructor that can take for instance OrcaleServer, SQLServer where these are classes that do implement the interface.



Answered By - Mohamed
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why the Class Adapter Design Pattern Can't Use an Interface Instead of Multiple Inheritance?

 October 26, 2022     design-patterns, java, oop     No comments   

Issue

I've recently learned the Class Adapter pattern. In order to implement it, the language used must support multiple inheritance since the adapter class must inherit two classes, the Target, and the Adaptee. So in a language like Java, it could not be done.

But why couldn't it use an interface Target instead of a class Target? More inline with the Object Adapter pattern as well. Just switching from object composition (Adapter having the Adaptee) to single inheritance (Adapter inheriting the Adaptee). By using an interface, I don't see the design difference, and as a result, the pattern can be used in Java.

Link to object adapter and class adapter class diagram


Solution

But why couldn't it use an interface Target instead of a class Target?

you can use interface. But then you will have duplication of code, but multiple inheritance removes duplication of code.

Let me show an example.

Our abstractions:

public interface IDuck
{
    void Quack();
}

public interface ITurkey
{
    void Gobble();
}

And concrete implementations:

public class Duck : IDuck
{
    public void Quack()
    {
        Console.WriteLine("Quack");
    }
}

public class Turkey : ITurkey
{
    public void Gobble()
    {
        Console.WriteLine("Gobble");
    }
}

And class adapter would look like this:

public class ClassAdapter : IDuck, ITurkey
{
    public void Gobble()
    {
        // duplication of code
        Console.WriteLine("Gobble");
    }

    public void Quack()
    {
        Gobble();
    }
}

The above ClassAdapter has duplications of code. Sure we can extract this code and provide it through composition or inject Duck and Turkey. However, it brings additional dependencies and some complexity. So it is better to use object adapter pattern. Your code will be simpler. Simple code is almost always the best choice.



Answered By - StepUp
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Get Specific Variables from One Class to Another?

 October 26, 2022     class, oop, python, variables     No comments   

Issue

I am currently in the processing of self making an inventory system, and am trying to better organize my code in specific classes and methods. Currently, I am trying to organize a class that does user input, sends that input to another class to use.

Here is my relevant code:

class user_interaction(object):

    def __init__(self):
        self.name = self.ask()
        self.options = self.ask_options()
        self.add_item_num = None
        self.add_item_price = None
        self.add_item_quant = None
        self.add_item_name = None

    def ask(self):
        while 1:
            name = input("What is your name?\n")
            if name == "":
                print("Ha! You have to enter a name!")
            else:
                print("Welcome to the Shepherdstown Bake Shop " + name)
                return name
            
        
                
    def ask_options(self):
        while 1:
            option = input('''What would you like to do? \n1. Add a Item: \n2. Delete a Item:\n3. Edit an Item: \n4. View Inventory \n5. End Program\n''')
            if option == '1':       
                print("Welcome to the adding process " + self.name)
                ????
                break

     def enter_data(message, typ):
            while True:
                try:
                    v = typ(input(message))
                except ValueError:
                    print(f"Thats not an {typ}!")
                    continue
                else:
                    break
            return v

   def add_item_interaction(self):
            self.add_item_num = enter_data("What is the items #?\n", int)
            self.add_item_price = enter_data("What is the items price?\n", float)
            self.add_item_quant = enter_data("What is the items quantity?\n", int)

            while True:
                self.add_name = enter_data("What is the items name?\n", str)
                if name == "":
                    print("Ha! You have to enter a name!")
                    continue
                break

and my other class

class DataBase_Management(object):
    
    def __init__(self):
        self.result = []


    def make_dict_items(self):
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                if row:
                    row[0] = int(row[0])
                    row[1] = float(row[1])
                    row[2] = int(row[2])
                    pairs = zip(labels, row)
                    self.result.append(dict(pairs))
    
    def add_item(self):
        #Make Entries the variables in new_row???
        new_row = [item_num, price, quant, name]
        with open("Items2.csv", "a+") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())
           print("Item Added! Check Inventory Again to see!")

How would I make it so the entries gotten in class User_interaction, in the method add_item_interaction, are sent to the add_item method in the DataBase_Management class? For example, I am trying to make it where self.add_item_num = item_num in the add_item method in the database management class?


Solution

It sounds like the User_Interaction class should have its own Database_Management instance and use it when necessary:

class User_Interaction:

    def __init__(self):
        self.database = DataBase_Management()
        ...

   def add_item_interaction(self):
            add_item_num = self.enter_data("What is the items #?\n", int)
            add_item_price = self.enter_data("What is the items price?\n", float)
            add_item_quant = self.enter_data("What is the items quantity?\n", int)

            while True:
                add_name = self.enter_data("What is the items name?\n", str)
                if add_name == "":
                    print("Ha! You have to enter a name!")
                    continue
                break
            self.database.add_item(add_item_num, add_item_price, add_item_quant, add_name)
    ...

class DataBase_Management:    
    def __init__(self):
        self.result = []

    
    def add_item(self, item_num, price, quant, name):
        ...


Answered By - quamrana
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Call/Run Specific Methods within my Main Loop?

 October 26, 2022     class, loops, methods, oop, python     No comments   

Issue

I am currently in the process of making an inventory system, and am working on my main loop. Currently I am trying to make it in the main loop, that when a user inputs 1, it sends them through the process of adding a new item.

I have the following relevant code:

import csv
class user_interaction(object):

    def __init__(self):
        self.name = self.ask()
        self.options = self.ask_options()
        self.database = DataBase_Management()
        
    def ask(self):
        while True:
            name = input("What is your name?\n")
            if name == "":
                print("Ha! You have to enter a name!")
            else:
                print("Welcome to the Shepherdstown Bake Shop " + name)
                return name
            
        
                
    def ask_options(self):
        while True:
            option = input('''What would you like to do? \n1. Add a Item: \n2. Delete a Item:\n3. Edit an Item: \n4. View Inventory \n5. End Program\n''')
            if option == '1':       
                print("Welcome to the adding process " + self.name)
                items = DataBase_Management()
                items.make_dict_items()
                self.add_item_interaction()
                #add_item_interaction()
                #items.add_item()
                break

   def enter_data(selfmessage, typ):
            while True:
                try:
                    v = typ(input(message))
                except ValueError:
                    print(f"Thats not an {typ}!")
                    continue
                else:
                    break
            return v

     def add_item_interaction(self):
            add_item_num = enter_data("What is the items #?\n", int)
            add_item_price = enter_data("What is the items price?\n", float)
            add_item_quant = enter_data("What is the items quantity?\n", int)

            while True:
                add_name = self.enter_data("What is the items name?\n", str)
                if name == "":
                    print("Ha! You have to enter a name!")
                    continue
                break
            self.database.add_item(add_item_num, add_item_price, add_item_quant, add_name)

as well as the other class:

class DataBase_Management(object):
    
    def __init__(self):
        self.result = []


    def make_dict_items(self):
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                if row:
                    row[0] = int(row[0])
                    row[1] = float(row[1])
                    row[2] = int(row[2])
                    pairs = zip(labels, row)
                    self.result.append(dict(pairs))


    def add_item(self, item_num, price, quant, name):
        new_row = [item_num, price, quant, name]
        with open("Items2.csv", "a+") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())
           print("Item Added! Check Inventory Again to see!")


if __name__ == "__main__":
    obj = user_interaction() 
    while True:
        obj.ask_options() 

I was wondering how I can implement it into my ask_options main loop, that if a user inputs 1, it sends them to add_item_interaction and enter_data in the first class, and then adds the new items to the database as is done by add_item in the second class? The comments in the ask_options method were my attempts/thoughts at doing so.

EDIT: Added some suggested code, and seem to now get error:

Traceback (most recent call last):
  
 line 209, in <module>
    obj = user_interaction()
  
line 7, in __init__
    self.options = self.ask_options()
  
 
line 28, in ask_options
    self.add_item_interaction()

AttributeError: 'user_interaction' object has no attribute 'add_item_interaction'

Solution

This code should be the next step forward:

import csv
class User_Interaction:

    def __init__(self, name):
        self.name = name
        self.database = DataBase_Management()
        self.database.make_dict_items()
    
    @staticmethod
    def ask():
        while True:
            name = input("What is your name?\n")
            if name == "":
                print("Ha! You have to enter a name!")
            else:
                print("Welcome to the Shepherdstown Bake Shop " + name)
                return name
                
    def ask_options(self):
        option = input('''What would you like to do? \n1. Add a Item: \n2. Delete a Item:\n3. Edit an Item: \n4. View Inventory \n5. End Program\n''')
        if option == '1':       
            print("Welcome to the adding process " + self.name)
            self.add_item_interaction()
        elif option == '2':
            ...

    @staticmethod
    def enter_data(message, typ):
            while True:
                try:
                    v = typ(input(message))
                except ValueError:
                    print(f"Thats not an {typ}!")
                    continue
                else:
                    break
            return v

     def add_item_interaction(self):
            add_item_num = self.enter_data("What is the items #?\n", int)
            add_item_price = self.enter_data("What is the items price?\n", float)
            add_item_quant = self.enter_data("What is the items quantity?\n", int)

            while True:
                add_name = self.enter_data("What is the items name?\n", str)
                if add_name == "":
                    print("Ha! You have to enter a name!")
                    continue
                break
            self.database.add_item(add_item_num, add_item_price, add_item_quant, add_name)

Note the changes to the __init__() method and how some other methods are marked @staticmethod since those never need access to self.

Also ask_options() doesn't need its own while loop since that is already included below.

Also I've added an elif/... in ask_options() as a placeholder for all the other options that need implementing and is not real code.

class DataBase_Management:
    def __init__(self):
        self.result = []

    def make_dict_items(self):
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                if row:
                    row[0] = int(row[0])
                    row[1] = float(row[1])
                    row[2] = int(row[2])
                    pairs = zip(labels, row)
                    self.result.append(dict(pairs))

    def add_item(self, item_num, price, quant, name):
        new_row = [item_num, price, quant, name]
        with open("Items2.csv", "a+") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())
           print("Item Added! Check Inventory Again to see!")

if __name__ == "__main__":
    name = User_Interaction.ask()
    obj = User_Interaction(name) 
    while True:
        obj.ask_options()

Note that some variables can just be local to methods and don't need to be members. (eg. You don't need self.add_item_name)

Note that the __init__() method only really initialises members that it needs control over. (Yes, it is debateable whether ask() should be called outside as I have done or whether it should be called inside as you did)

Note that there are some formatting issues with your posted code. You should be using an IDE that would immediately highlight such things so that we never see them in code posted here.

Note that classes can be declared: class Foo: (No brackets nor the need to derive from object)

Also note that, as I've said previously, you should not use stackoverflow and your personal software development environment. You are asking questions and stitching together a program from the answers in a cargo cult style that will lead to much confusion and less than optimal learning.



Answered By - quamrana
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I "reset" the size of a Window on Tkinter when using Notebook?

 October 26, 2022     oop, python, tkinter, user-interface     No comments   

Issue

I know this has been asked before but none of the solutions that I've seen so far seem to work.

So here's the exact case: I'm building an app that has 3 different tabs (using ttk.Notebook). The initial contents of the 3 tabs is different: the second is the smallest and the third is he biggest.

Now here comes the issue (I'm using grid, btw): when I change from the first to the second, there is an extra empty space (because the content of the first Tab is a little bigger than the one of the second, and the same happens when I go from the third to the second/first, so after using the third tab and changing to another one, the size stays as if I still was in the third.

I add some of the code that I'm using, but since I'm not sure what is going wrong, I'll let you ask for whatever extra code you might need to help me find the solution.

# Tk modules
import tkinter as tk
from tkinter import ttk

# # define main()
def main():
    app = App()
    MainWindow(app)
    app.mainloop()


# Frame for data input
class RegisterChooseType(ttk.Frame):
    def __init__(self, container):
        # Inheritance
        super().__init__(container)
        self.container = container

        # Var for selection
        self.selected_value = tk.IntVar()

        # Options
        self.options = {"padx": 10, "pady": 10}

        # Doc types
        self.doc_types = ("Incoming Bill", "Outgoing Bill", "Contract", "Other")

        # Labels
        self.barcode_label = ttk.Label(self, text="Barcode:").grid(
            row=0, column=0, sticky="EW", **self.options
        )

        self.doc_type_label = ttk.Label(self, text="Document type:").grid(
            row=0, column=2, sticky=tk.W, **self.options
        )

        # Entries
        self.barcode_entry = ttk.Entry(self)
        self.barcode_entry.grid(row=0, column=1, sticky="EW", **self.options)

        self.grid()

    def submit(self):
        self.current_dict["func"](self, self.current_frame)


class DeleteTab(ttk.Frame):
    def __init__(self, container):
        # Inheritance
        super().__init__(container)

        # self.columnconfigure(0, weight=1)
        # self.columnconfigure(1, weight=1)

        self.options = {"padx": 10, "pady": 10}

        ## Type Barcode
        # Label
        self.barcode_label = ttk.Label(self, text="Barcode:").grid(
            row=0, column=0, sticky="EW", **self.options
        )
        # Entries
        self.barcode_entry = ttk.Entry(self)
        self.barcode_entry.grid(row=0, column=1, sticky="EW", **self.options)

        # self.pack(fill="x")
        self.grid(sticky="W")


class ViewTab(ttk.Frame):
    def __init__(self, container):
        # Inheritance
        super().__init__(container)
        self.container = container

        self.options = {"padx": 10, "pady": 10}

        # Doc types
        self.doc_types = ("Incoming Bill", "Outgoing Bill", "Contract", "Other")

        ## Type Barcode
        # Labels
        # Barcode
        self.barcode_label = ttk.Label(self, text="Barcode:")
        self.barcode_label.grid(row=0, column=0, sticky="EW", **self.options)

        # Document type
        self.doc_type_label = ttk.Label(self, text="Document Type:")
        self.doc_type_label.grid(row=0, column=2, sticky="EW", **self.options)

        # Entries
        # Barcode
        self.barcode_entry = ttk.Entry(self)
        self.barcode_entry.grid(row=0, column=1, sticky="EW", **self.options)

        # Document type
        self.doc_type_comb = ttk.Combobox(self)
        self.doc_type_comb["state"] = "readonly"  # Doesn't allow new entries
        self.doc_type_comb["values"] = self.doc_types
        self.doc_type_comb.grid(
            row=0, column=3, columnspan=3, sticky=tk.EW, **self.options
        )

        ## View Button
        self.viewSubmitButton = ttk.Button(
            self, text="View", command=lambda: print("View")
        )
        self.viewSubmitButton.grid(
            column=4,
            row=self.grid_size()[0],
            sticky="EW",
            **self.options,
        )

        # New LabelFrame
        self.deliver_view_LabelFrame = ttk.LabelFrame(self)
        self.deliver_view_LabelFrame["text"] = "View Document"
        self.deliver_view_LabelFrame.grid(
            row=1,
            columnspan=self.grid_size()[0],
            column=0,
            sticky="ew",
            padx=10,
            pady=10,
        )
        # Inside LabelFrame

        ##TreeView
        self.dataDisplay = ttk.Treeview(self.deliver_view_LabelFrame, show="")
        self.dataDisplay.pack(fill="x", **self.options)

        self.grid(sticky="ews")


# Create window
class MainWindow:
    def __init__(self, container):
        self.container = container

        ## Create Parent
        self.tab_parent = ttk.Notebook()
        self.tab_parent.enable_traversal()

        # Create tab frames
        self.tab_register = ttk.Frame(self.tab_parent)
        self.tab_view = ttk.Frame(self.tab_parent)
        self.tab_delete = ttk.Frame(self.tab_parent)

        # Adding the tabs to the main object (self.tab_parent)
        self.tab_parent.add(self.tab_register, text="Register Documents")
        self.tab_parent.add(self.tab_delete, text="Delete Documents")
        self.tab_parent.add(self.tab_view, text="View Documents")

        # Create empt variables
        self.current_tab = None
        self.last_tab = None

        # Focus on barcode
        # self.register.barcode_entry.focus()

        self.tab_parent.bind("<<NotebookTabChanged>>", self.on_tab_change)

        # Pack notebook
        # self.tab_parent.pack(expand=True, fill="x", side="left")
        self.tab_parent.grid(sticky="e")

    ## Triggers when changing tabs
    def on_tab_change(self, event):
        if self.current_tab != None:
            self.current_tab.destroy()

        # Get the current tab name
        selected = event.widget.tab("current")["text"]

        # Create frame depending on Tab chosen
        if selected == "Register Documents":
            self.current_tab = RegisterChooseType(self.tab_register)
            self.clean_tabs()
            self.last_tab = self.current_tab

        elif selected == "Delete Documents":
            self.current_tab = DeleteTab(self.tab_delete)
            self.clean_tabs()
            self.last_tab = self.current_tab

        elif selected == "View Documents":
            self.current_tab = ViewTab(self.tab_view)
            self.clean_tabs()
            self.last_tab = self.current_tab

        self.current_tab.barcode_entry.focus()

    def clean_tabs(self):
        if self.last_tab != None:
            # for widget in self.last_tab.winfo_children():
            #     # for widget in self.last_tab.grid_slaves():
            #     widget.destroy()
            self.last_tab.destroy()

            # ## INTERESTING
            # self.last_tab.blank = ttk.Label(self.last_tab, text="1")
            # self.last_tab.blank.grid()
            # print(self.last_tab.grid_slaves()[0].cget("text"))
            # self.container.geometry("1x1")
            self.tab_parent.update()
            # self.container.update()
        # self.container.geometry("")
        # self.container.update()


# Creatig App
class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.geometry("")
        self.title("iMPETU Document Handling v.0.1.0a")
        self.resizable(0, 0)


if __name__ == "__main__":
    main()

I tried deleting one by one the widgets of the current tab before changing to another one, also doing the same AFTER changing to the new tab (that's why I have 2 variables for current and last tab), I also tried leaving an empty tag (supposedly 0 pixels) but that would push all the contents down.

I tried withdraw, deiconify just out of curiosity, I also tried using self.container.update() to update the main window, also tried changing the geometry to "1x1" in the clean_tabs function and then changing again to "" at the end of the on_tab_change and see if that would maybe force it to resize but none of that worked.


Solution

You can resize all the frames (parents of instances of RegisterChooseType, DeleteTab and ViewTab) to size 1x1 at the beginning of clean_tabs():

def clean_tabs(self):
    for tab in self.tab_parent.tabs():
        # tab is the name of the frame
        # so get the widget using .nametowidget()
        # then call .config(width=1, height=1) to resize the frame to size 1x1
        self.tab_parent.nametowidget(tab).config(width=1, height=1)
    ...


Answered By - acw1668
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why a function with protected modifier can be overridden and accessible every where?

 October 26, 2022     access-modifiers, c#, d, oop     No comments   

Issue

I'm C# programmer new to D language. I'm a bit to confused with OOP in D programming language.

Assuming that I have the following class:

public class A {
   protected void foo() {
      writefln("A.foo() called.");
   }
};

public class B : A {
   public override void foo() {
      writefln("B.foo() called.");
   }
};

The protected modifier means that I can access the .foo() method just on inherited class,so why this D program compiles normally?

Here is the equivalent to C#.NET:

using System;

public class A {
   protected virtual void foo() {
      Console.WriteLine("a.foo() called.");
   }
};

public class B : A {
   public override void foo() {
      Console.WriteLine("b.foo() called.");
   }
};

public class MainClass  {
   public static void Main(string[] args) {
      A a = new A();
      B b = new B();    
      a.foo();
      b.foo();
   }
};

It don't compiles and given the following error message(as I expected):

test.cs(10,30): error CS0507: B.foo()': cannot change access modifiers when overridingprotected' inherited member `A.foo()'

Can someone explain this D behavior? Thanks in advance.


Solution

There's no purpose in preventing the override. The derived class could implement a trivial forwarding function that allows access. Consider:

public class A {
    protected virtual void foo() {
        writefln("A.foo() called.");
    }
};

public class B : A {
   protected override void foo() { // OK
       writefln("B.foo() called.");
   }
   public void call_foo() {
       foo(); // But I allowed public access anyway!
   }
};

Thus, even though I didn't redefine the access level of foo, I still allowed public access to it and there's nothing you can do about it. Allowing the redefinition is just simpler.



Answered By - Puppy
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to restrict access to the most direct base class, while still exposing the base-base classes?

 October 26, 2022     c++, inheritance, oop, qt     No comments   

Issue

I have a class hierarchy similar to this:

class Widget {
    // a lot of virtual members
};

class Button : public Widget {
    // new stuff + overrides
};

class MySuperButton : public Button {
    // ...
};

And I would like to hide the fact that MySuperButton inherit from Button, but not from Widget. Basically making the inheritance from Button private while keeping all its base classes public.

Why?

I have a complicated widget build on Button, which needs to maintain some invariant with its button state. Exposing it has a Button might allow something to modify the button directly breaking these invariants.

Example:

MySuperButton button;
button.setText("Click me!") // calls Button::setText
// Oh no, MySuperButton set some special text which has now been overriden =(

What doesn't work

  • Making MySuperButton inherit from Button privately also hides Widget, preventing me from doing Widget things with my button.

  • Using access specifiers does not prevent MySuperButton to be converted into a Button. So void doButtonStuff(Button& b); will accept a MySuperButton& just fine.

  • Using compositon forces me to reimplement a bunch of stuff that Button already reinmplements, just to forward it which is a PITA. Especially since the actual hierarchy is rather deep and these are big classes.

  • Virtual inheritance doesn't seem to work as the base isn't visible (not sure why that would be a problem though). See Godbolt

I can not modify the Button or Widget classes as they are from an external library (Qt in this case). Also the actual code is somewhat more complicated, the provided hierarchy is for illustration.

Is there any way to do this, or do I need to accept that my widget can be broken if I am not careful ?


Solution

What you are asking is not really possible.

A possible Qt-specific solution is the following:

class MySuperButton : public Widget {
public:
    MySuperButton () {
        QVBoxLayout *layout = new QVBoxLayout;
        layout->addWidget(button = new Button());
        setLayout(layout);
    }

private:
    Button *button;
}


Answered By - m7913d
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When should one use interfaces?

 October 26, 2022     interface, oop     No comments   

Issue

I know that an interface does not have a body, just a method definition. But when should I use interfaces? If I provide someone a set of interfaces with no body, why would they feel a need to write the function body? Would they be better off writing their own abstract class with abstract methods in it?

The way I understand interfaces is that they could be useful when you are a part of a team. Suppose Team A writes some code for something and they wanted to see if a call to a method getRecords() is done or not. This will help Team B to write the body of the interface provided to them and Team B has to keep the method name similar so that code of Team A runs.

As far as I can tell, interfaces don't appear to be useful for individual developers.

Maybe interfaces have more use when you are making something like API?


Solution

In languages such as Java and C# interfaces provide a means for a class to be have in a polymorphic manner. That is to say a class can satisfy more than one contract - it can behave as multiple different types, a class of one type can be substituted for another. In other languages this can also be provided by multiple inheritance, but there are various disadvantages to this approach. However, having a class behave as more than one type is not the most common motivation for using interfaces.

By programming to interfaces instead of classes you can also decouple your program from specific implementations. This makes it much easier to substitute one class implementation for another. This is particularly useful when writing unit tests where you may wish to swap some heavyweight class implementation with a lightweight mock object. If your program only expects an interface type, and both the heavyweight object and mock object implement said interface, then they are very easy to substitute.

Also, consider a simple Java example where I say have a program that displays pages of data on the screen. Initially I want it to get the data from a database or XML files. If I write my program so that it uses interfaces I can define an interface like so:

public interface PageDatasource {
    public List<Page> getPages();
}

And use it like so:

PageDatasource datasource = // insert concrete PageDatasource implementation here
List<Pages> pages = datasource.getPages();
display(pages);

I can then write separate database and XML implementations that adhere to this interface:

public class DatabasePageDatasource implements PageDatasource {
    public List<Page> getPages() {
        // Database specific code
    }
}

public class XmlPageDatasource implements PageDatasource {
    public List<Page> getPages() {
        // XML specific code
    }
}

Because I used an interface I can now use either implementation - Database or XML - interchangeably without having to change the parts of my program that ask for the page data. The XML and Database implementations likely do completely different things but all my program cares about is that the object supplying the page data implements the PageDatasource interface.



Answered By - teabot
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to insert an element at some specific position in the list using classes?

 October 26, 2022     c++, oop     No comments   

Issue

#include<iostream>
using namespace std;
template<typename T>
class List
{
public:
    T *values;
    int capacity;
    int counter;
public:
    List()
    {
        values = NULL;
        capacity = 0;
        counter = 0;
    }
    List(int cap)
    {
        capacity = cap;
        values = new T[cap];
        counter = 0;
    }
    bool insert(T item)
    {
        if (isFull() == false)
        {
            values[counter] = item;
            counter++;
            return true;
        }
        return false;
    }
    bool insertAt(T item, int index)
    {
        
        if (isFull() == false && index < counter)
        {
            capacity++;
            for (int i = capacity; i > index; i--)
                values[i] = values[i - 1];
            
            values[index] = item;
            
            return true;
        }
        return false;
    }
    bool isFull()
    {
        if (counter == capacity)
        {
            return true;
        }
        return false;
    }
    void print()
    {
        for (int i = 0; i < capacity; i++)
        {
            cout << values[i] << " ";
        }
    }
    
};
int main()
{
    List<int> obj1(5);
    obj1.insert(1); //0
    obj1.insert(2); //1
    obj1.insert(3); //2
    obj1.insert(4); //3
    
    obj1.insertAt(3, 1);
    obj1.values[1];
    obj1.print();
    
}

Kindly look into this program I have to insert an element at given position. But when I run this program I am getting garbage at the end element of an array. Kindly check and let me know where is the problem? Please check the insertAt function I think this function has some logical error. I have added the main function when I call print function it give garbage at the last index


Solution

bool insertAt(T item, int index)
    {
        
    
        if (!isFull() && index < counter)
        {
            for (int i = counter; i > index; i--) {
                values[i] = values[i - 1];
            }
            values[index] = item;
            counter++;
            return true;
        }
        return false;
    }

void print()
    {
        for (int i = 0; i < counter; i++)
        {
            cout << values[i] << " ";
        }
    }

I have corrected these two function. Try these functions instead of the one you implemented



Answered By - Mudassir Waheed
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is different between $this-> and parent:: in OOP PHP?

 October 26, 2022     inheritance, oop, php, super     No comments   

Issue

I code something like this to give you an example

This is using "$this->"

<?php
class A{
    public function example(){
        echo "A";
    }
}

class B extends A{
    public function example2(){
        $this->example();
    }
}

$b = new B();

echo $b->example2();
?>

and This is using parent::

<?php
class A{
    public function example(){
        echo "A";
    }
}

class B extends A{
    public function example2(){
        parent::example();
    }
}

$b = new B();

echo $b->example2();
?>

What is different between $this-> and parent:: in OOP PHP?


Solution

The difference is that you can access a function of a base class and not of the currient implementation.

class A {
    public function example() {
        echo "A";
    }

    public function foo() {
        $this->example();
    }
}

class B extends A {
    public function example() {
        echo "B";
    }

    public function bar() {
        parent::example();
    }
}

And here some tests:

$a=new A();
$a->example(); // echos A
$a->foo();     // echos A

$b=new B();
$b->example(); // echos B
$b->foo();     // echos B
$b->bar();     // echos A


Answered By - rekire
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why the parent's method should be called explicitly with the parent's prefix from the child object?

 October 26, 2022     c++, class, hierarchy, oop     No comments   

Issue

see please the code:

#include <iostream>

using namespace std;


class A{
public:
    A() = default;
    
    virtual void foo() = 0;
    
    bool foo(int x)
    {
        cout<<"A::foo(int x)\n";
        return true;
    }
    
     bool func(int x)
    {
        cout<<"A::func(int x)\n";
        return true;
    }
    
};

class B: public A
{
    
    public:
    B() = default;
    
    void foo()
    {
         cout<<"B::foo()\n";
    }
    
};

int main()
{
    B b;

    b.func(0);
    
    //b.foo(0); //it's not compiled
    b.A::foo(0);
    
    return 0;
}

It seems the parent's method should be called explicitly with the parent's prefix from the child object for any reason. b.foo(0) is not compiled but if I add A:: prefix like b.A::foo(0) it works. Why is b.foo(0) not compiled but b.func(0) is?


Solution

It is called 'name hiding'.

You have a function called foo without parameters in your subclass. The compiler will hide any other function with the same name from the superclass, unless you declare it with the using A::foo; directive in the child class.

To my knowledge, this is done to avoid confusion of the function calls. All non-overloaded functions will be inherited automatically.

Your code should work, if you write it like this (untested):

class B: public A
{
    
    public:
    using A::foo;
    B() = default;
    
    void foo()
    {
         cout<<"B::foo()\n";
    }
    
};

Please note that the using syntax will move ALL functions called foo into your subclass, regardless of their prototype.

For further information, see https://www.ibm.com/docs/en/zos/2.3.0?topic=scope-name-hiding-c-only or https://bastian.rieck.me/blog/posts/2016/name_hiding_cxx/



Answered By - Refugnic Eternium
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What are the comments found above methods in a controller?

 October 26, 2022     laravel, oop, php     No comments   

Issue

This may be a silly question, but I'm new to back-end development.

I always see comments like this above various methods:

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

What are these called? Do they even have a name? Does the @return actually do anything, or is it just for reference?

I'm mostly asking because I have a technical interview as a junior Laravel developer coming up this week, and I want to make sure all my code is up to standards for a pair-programming session they said might happen.


Solution

These are called "DocBlocks", or Documentation Block Comments, etc. You can read more about them here:

https://docs.phpdoc.org/guide/getting-started/what-is-a-docblock.html

https://docs.phpdoc.org/guide/guides/docblocks.html

Basically, these are a way to summarize what a Method/Function does, expects as its arguments (if any), and what it returns. IDEs/Code Editors like VSCode, Sublime Text, PHPStorm, etc. can actually read these comments and assist you when using them, providing hints, autocompletion, etc.

Here's a basic example:

<?php

namespace = App\Http\Controllers;

class ExampleController extends Controller {
  /**
   * Method accepts an instance of `MyModel` and returns
   * a View responsible for displaying associated information 
   *
   * @param MyModel $myModel - An instance of `MyModel`
   *
   * @return \Illuminate\Contracts\View\View
   */
  public function myMethod(MyModel $myModel) {
    return view('index', compact('myModel');
  }
}

With this comment in place, my instance of VSCode (or your IDE of choice), should be able to display some information when hovering (or similar):

enter image description here

Additionally, if I go to use this method, I get some help:

enter image description here

As you can see, VSCode now knows what myMethod is, what it expects and returns, how to use it, etc. They aren't strictly required, as some IDEs can auto-detect methods, arguments and returns, but they can help.



Answered By - Tim Lewis
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where to write the common logic in Java Strategy design pattern?

 October 26, 2022     design-patterns, java, oop, software-design, strategy-pattern     No comments   

Issue

This is related to Java Strategy design pattern.

In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.

I have common code logic to be executed for all the strategies which is have implemented using Java Strategy design pattern. Which is the right place to write this common logics(something like validations and other stuffs).

Consider the below code. Here I want to do file validation which is common across any file type . Something like , the file should exist and its size should be greater than zero and file name validation. All these file related common stuff I want to keep in some place. Which could be a right design for this?

//BaseFileParser.java
public abstract class BaseFileParser{
  public abstract void parseFile();
}

//XMLFileParser.java
public class XMLFileParser extends BaseFileParser{
  public void parseFile(){
    //Logic for parsing an XML file goes here
  } 
}

//CSVFileParser.java
public class CSVFileParser extends BaseFileParser{
  public void parseFile(){
    //Logic for parsing a CSV file goes here
  } 
}

//Client.java
public class Client{
  private BaseFileParser baseFileParser;
  public Client(BaseFileParser baseFileParser){
    this.baseFileParser=baseFileParser;
  }  
  public void parseFile(){
    baseFileParser.parseFile();
  } 
  public static void main(String args[]){
    //Lets say the client needs to parse an XML file
    //The file type(XML/CSV) can also be taken as 
    //input from command line args[]
    Client client=new Client(new XMLFileParser());
    client.parseFile();
  }
}

Solution

If you have common behaviour, then abstract class or class is what we can use. So basic idea is to put common logic into some base common strategy class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete strategy.

I am sorry, I am not Java guy, but I've provided comments how it can be implemented in Java. Let me show an example via C#.

This is our abstract class which has common strategy:

public abstract class BaseStrategy
{
    // I am not Java guy, but if I am not mistaken, in Java,
    // if you do not want method to be overriden, you shoud use `final` keyword
    public void CommonBehaviourHere() 
    {  }

    public abstract void 
        UnCommonBehaviourHereShouldBeImplementedBySubclass();

}

And its concrete implementations:

public class StrategyOneSubclass : BaseStrategy // extends in Java
{
    public override void 
        UnCommonBehaviourHereShouldBeImplementedBySubclass()
    {
        throw new NotImplementedException();
    }
}

public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
    public override void 
        UnCommonBehaviourHereShouldBeImplementedBySubclass()
    {
        throw new NotImplementedException();
    }
}

UPDATE:

This is your abstract class:

public abstract class BaseFileParser
{
    // I am not Java guy, but if I am not mistaken, in Java,
    // if you do not want method to be overriden, you shoud use `final` keyword
    public bool IsValid()
    {
        return true;
    }

    public abstract void ParseFile();
}

and its concrete implementations:

public class StrategyOneSubclass : BaseStrategy // extends in Java
{
    public override void ParseFile()
    {
        if (!IsValid())
            return;

        throw new NotImplementedException();
    }
}

public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
    public override void ParseFile()
    {
        if (!IsValid())
            return;

        throw new NotImplementedException();
    }
}


Answered By - StepUp
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What are the differences between struct and class in C++?

 October 26, 2022     c++, c++-faq, class, oop, struct     No comments   

Issue

This question was already asked in the context of C#/.Net.

Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.

I'll start with an obvious difference:

  • If you don't specify public: or private:, members of a struct are public by default; members of a class are private by default.

I'm sure there are other differences to be found in the obscure corners of the C++ specification.


Solution

You forget the tricky 2nd difference between classes and structs.

Quoth the standard (§11.2.2 in C++98 through C++11):

In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):

Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.

Additional difference: the keyword class can be used to declare template parameters, while the struct keyword cannot be so used.



Answered By - Assaf Lavie
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing