jeudi 30 avril 2015

Open another class via button push as a display panel

Basically I'm trying to open my porttest.java class via a button push in my main program.

I thought their might be a way to do it via frame.add(porttest) but that didn't work.

Here is my porttest.java code.

package Random;
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;

import java.awt.BorderLayout;
import java.util.Enumeration;
import java.util.HashMap;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JPanel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JComboBox;


public class porttest {
    private Enumeration ports = null;
    private HashMap portMap = new HashMap();
    private JFrame frame;
    private JPanel panel;
    private JLabel label;
    private JComboBox comboBox;
    public porttest() {
        initialize();
        searchForPorts();
    }
      public void searchForPorts()
        {
            ports = CommPortIdentifier.getPortIdentifiers();

            while (ports.hasMoreElements())
            {
                CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();

                //get only serial ports
                if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
                {
                    comboBox.addItem(curPort.getName());
                    portMap.put(curPort.getName(), curPort);
                }
            }
        }
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        panel = new JPanel();
        panel.setBounds(0, 0, 442, 266);
        panel.setLayout(null);

        label = new JLabel("COM Ports:");
        label.setBounds(10, 130, 82, 14);
        panel.add(label);
        frame.getContentPane().add(panel);

        comboBox = new JComboBox();
        comboBox.setBounds(76, 124, 93, 26);
        panel.add(comboBox);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    porttest window = new porttest();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Do I need to add some code in here to make it work?

all I want it to do is open in the middle of my main program so the user can set some settings then close the program. The only reason I'm doing it this way is because I can't seem to get a JComboBox to work in a Jmenu.

maybe theirs another way to open a dialog box with a JComboBox?

any help would be great.




Rails: Can I create and save an object instance within a class method on a model?

Is it possible and kosher to use a class method on a model to create a new instance of the same model?

The scenario is that I want to interact with an external API, create an instance on the other service, and then once completed successfully store that new object reference in a local model.

So for example I want to call something like this from the controller:

MyModel.interact_with_api_function([variables required])

And have a class method like this on the model:

def interact_with_api([variables required])
  interacts with api, generates object over there, returns result
  This.new(identifier: result, ...).save!
end




Rearranging code using classes?

I'm currently working on a project that was assigned to me and I'm having a bit of trouble trying to find out how I should start. This assignment is to rewrite a program using classes instead of just putting everything into the main program. Here is my code that I created that has to rewritten:

public class Lab14 {
public static void main(String[] args)  {
int Numbook1=0;
int Numbook2=0;
int Numbook3=0;
double priceOfDesignPatterns=32.46;
double priceOfEffectiveJava=35.48;
double priceOfJavaPuzzlers=27.86;
String book1="Design Patterns";
String book2="Effective Java";
String book3="Java Puzzlers";
final double SALES_TAX=.065;
String choice;
int finished=0;


Scanner input=new Scanner(System.in);
System.out.println("Welcome to ECommerce!");
System.out.println("The books we have in stock are: ");
System.out.println(book1+", "+book2+", "+book3);
System.out.println("Please enter the name of the book you wish to purchase.  Press 'q' to quit.");

while (finished==0) 
{
choice=input.nextLine();
    if (choice.equals(book1))   
    {
        System.out.println("How many "+book1+"(s) do you wish to buy?");
        Numbook1=(input.nextInt())+Numbook1;
        System.out.println(Numbook1+" copies of "+book1+" are in your cart.");
        System.out.println("Enter the name of the next book you would like to purchase, or press 'q' to quit.");
    }
    else if (choice.equals(book2))
    {
        System.out.println("How many "+book2+"(s) do you wish to buy?");
        Numbook2=(input.nextInt())+Numbook2;
        System.out.println(Numbook2+" copies of "+book2+" are in your cart.");
        System.out.println("Enter the name of the next book you would like to purchase, or press 'q' to quit.");
    }
    if (choice.equals(book3))
    {
        System.out.println("How many "+book3+"(s) do you wish to buy?");
        Numbook3=(input.nextInt())+Numbook3;
        System.out.println(Numbook3+" copies of "+book3+" are in your cart.");
        System.out.println("Enter the name of the next book you would like to purchase, or press 'q' to quit.");
    }
    if (choice.equals("q"))
    {
        double total=0;
        double totalTax=0;

        total=(Numbook1*priceOfDesignPatterns)+(Numbook2*priceOfEffectiveJava)+(Numbook3*priceOfJavaPuzzlers);
        totalTax=total*SALES_TAX;
        System.out.println("Your cart contains: ");
        System.out.println(Numbook1+" "+book1+"(s), "+Numbook2+" "+book2+"(s), "+Numbook3+" "+book3+"(s).");
        System.out.println("Sales Tax: $"+totalTax);
        System.out.println("Your total cost is: $"+(totalTax+total));
        finished=1;
    }
}
}
}

Now I know that I have to write a couple of classes to construct book1,2,3 and also to set the price and access them later, but I'm just really lost on how to start the process and aggregate everything together. If someone could guide me in the right direction it would be greatly appreciated! Thank you so much.




How to load maven jars at runtime in Java?

I am working on a project in which I need to load maven jars at runtime and call one particular method of a class in runtime as soon as those two projects are loaded up. For example: let's say if I have two maven projects, ProjectA and ProjectB, I need to find a way to load these two projects at runtime and as soon as they gets loaded up, I need to call execute method of those two projects.

ProjectA has a class called TestClassA and it will have a method called execute. It might have other classes as well.

public class TestClassA {

    public String execute(DataEvent event) {
        // dome some stuff

    }
}

ProjectB has a class called TestClassB and it will have same method called execute as well. And it will also have other classes as well in same project.

public class TestClassB {

    public String execute(DataEvent event) {
        // dome some stuff      
    }
}

Question:

What is the best way I can load any maven projects in runtime without restarting/stopping my server and as soon as they are loaded up successfully, it should call execute method of those two projects. I can have n number of maven projects, two maven projects is just an example.

NOTE: It's not require that I need to have execute method in all the maven projects. Any general format by which my main application code knows that after loading maven jars I need to call this overridden method automatically. This example is just to give an idea what I am trying to do.

Has anyone tried to solve this problem before?




How to load maven jars at runtime in Java?

I am working on a project in which I need to load maven jars at runtime and call one particular method of a class in runtime as soon as those two projects are loaded up. For example: let's say if I have two maven projects, ProjectA and ProjectB, I need to find a way to load these two projects at runtime and as soon as they gets loaded up, I need to call execute method of those two projects.

ProjectA has a class called TestClassA and it will have a method called execute. It might have other classes as well.

public class TestClassA {

    public String execute(DataEvent event) {
        // dome some stuff

    }
}

ProjectB has a class called TestClassB and it will have same method called execute as well. And it will also have other classes as well in same project.

public class TestClassB {

    public String execute(DataEvent event) {
        // dome some stuff      
    }
}

Question:

What is the best way I can load any maven projects in runtime without restarting/stopping my server and as soon as they are loaded up successfully, it should call execute method of those two projects. I can have n number of maven projects, two maven projects is just an example.

NOTE: It's not require that I need to have execute method in all the maven projects. Any general format by which my main application code knows that after loading maven jars I need to call this overridden method automatically. This example is just to give an idea what I am trying to do.

Has anyone tried to solve this problem before?




Python: How can I write a iterator that has this property: it must iterate over mutations made to the object while the object is being iterated over

I defined an iterator for a class that produces the init's values in increasing order.

 class Increase:
    def __init__(self,aset):
        self.n = aset
    def __iter__(self):
        for i in self.n:
            yield i

a = {1, 3, 5, 10, 19}
i = iter(Increase(a))
print(next(i)) 
print(next(i))
a.remove(10)
print(next(i))
a.add(25)
print(next(i)) 
print(next(i))

It should print:

1
3
5
19 
25

But I always get:

1
3
5
10
19

The iterator should iterate over mutations made to the object while the object is being iterated over. How should I do?




Why doesn't this class execute properly?

Here is my first class called World

public class World {

    private static char[][] world2D;
    private int characterRow;
    private int characterColumn;


    public World(int width, int height){
        world2D = new char[width][height];
        characterColumn = 0;
        characterRow = 0;

        for(int i = 0; i < world2D.length; i++){
            for(int j = 0; j < world2D[i].length; j++){
                world2D[i][j] = '-';
            }
        }

        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveUp(){
        world2D[characterRow][characterColumn] = '-';
        if (characterRow > 0){
            characterRow -= 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveDown(){
        world2D[characterRow][characterColumn] = '-';
        if (characterRow < world2D.length){
            characterRow += 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveRight(){
        world2D[characterRow][characterColumn] = '-';
        if (characterColumn < (world2D[characterRow].length - 1)){
            characterColumn += 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public void moveLeft(){
        world2D[characterRow][characterColumn] = '-';
        if (characterColumn > 0){
            characterColumn -= 1;
        }
        world2D[characterRow][characterColumn] = 'P';
    }

    public static void displayWorld(){
        for(int i = 0; i < world2D.length; i++){
            for(int j = 0; j < world2D[i].length; j++){
                System.out.print(world2D[i][j]);
            }
            System.out.println();
        }       
    }

}

Here is my second class called Driver

import java.util.Scanner;

public class Driver {
    public static void main(String[]args){
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        System.out.print("How tall should the world be?: ");
        int height = input.nextInt();
        System.out.print("How wide should the world be?: ");
        int width = input.nextInt();

        World myWorld = new World(width,height);
        World.displayWorld();
    }

}

Why don't I need to call displayWorld specifically on the myWorld instance of the World class?

What if I created multiple World instances? This can't be right.

**edit for more detail

I want to call one of the class methods (i.e. moveUp or moveDown) on the instance of the World class myWorld object. However, I can't pass my reference to that object (myWorld) into those methods. I want to be able to call one of those methods, which changes the postion of 'P' in the 2 dimensional array and print it out using the methods that I have defined including the displayWorld method




Kivy class in .py and .kv interaction 2

Follow up from Kivy class in .py and .kv interaction , but more complex.

Here is the full code of what I'm writing: http://ift.tt/1JVr7S2

The data/screens/learnkanji_want.kv has how I want the code to be, but I don't fully understand how the class KanjiOriginScreen() plays it's role in screen management.

data/screens/learnkanji.kv works how I want it, but for this to work I have to put 'keyb_height' in class KanjiOriginScreen() (main.py). However I want that code to be in the class LayoutFunction() (learnkanji.py).

Question

How can I put keyb_height in the function LayoutFunction() and access this in the .kv file in < LayoutFunction>?

Could you also explain why 'KanjiOriginScreen:' can be put in learnkanji.kv without < > and the program still recognizes it should use this?

If anything is unclear, please ask :)




Objective-C: Syntax to call method from another class

iOS newb trying to pull an array from another class and a getting error. Fundamentally, I don't really understand the difference between methods and properties, I realize, so this might help me get a better understanding of that.

I have created a method that returns an array. I want to use that array in the other class (like a function returning a value in other languages) so I thought I would do it as follows:

class1
- (id) getTags{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Tags"];
    fetchRequest.resultType = NSDictionaryResultType;

    NSError *error      = nil;
    NSArray *results    = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                                   error:&error];

    NSMutableArray * tags = [[results valueForKey:@"tag"] mutableCopy];
    return tags;
}

In other words, I want to use what that method returns as a sort of variable which in Objective C is called properties. The method is also in the .h file so that it is public.

In class 2 I import class 1 at top and then try to call method as follows:

NSArray *newarray = [class1 getTags];

However I get error "No known class method for selector getTags"

Can anyone tell me what I am doing wrong?

Thanks.




Error accessing static private variable in C++?

I wish to access a static variable declared in a class. Following this post's suggestions, I defined two files,

in test.h:

class foo
{
    private:
        static int i;
};

in test.cpp:

#include "test.h"
int main(int argc, char* argv[]){

    int foo::i = 0;
}

But, the compiler still generates this error when I do make test. I'm using a mac:

test.cpp:16:11: error: definition or redeclaration of 'i' not allowed inside a function
    int foo::i = 0;

How can I fix it?




Represent a graph using adjacency matix with DFS with stack class

Using C++, represent the following graph using adjacency matrix, and implement DFS by using stack (define it with class) to traverse the graph. Im not able to post pictures because my reputation isn't high enough but I will try and describe it the best I can. E(G) = {(0,1),(0,2),(0,3),(1,5),(2,4),(3,5),(3,4),(3,7),(4,5),(4,6),(6,7)}

I am working on some homework and have written code but have errors and really don't understand the concept. Would someone help me with my mistakes and logic.

#include <iostream>
using namespace std;
#define N 7

//Define stack
void DFS(int G[][], bool visited[], int a)
{
    stack s(N);
    cout<<a<<endl;
    visited[a] = true;
    s.push(a);
    while(!s.empty())
    {
        int b = s.pop();
        for(int i = 0; i<N; i++)
        {
            if(G[b][i] == 1 && visited[i] == false)
            {
                cout<<i<<endl;
                push(b);
                push(i);
                break;
            }
        }
    }
}

int main()
{
    int [N][N]
    //initialize graph
    bool visited [N];
    for(int i = o; i < N; i++)
    {
        if(visited[i] == false)
        {
             DFS(G,visited,i);
        }
    }
}




UML Class Diagram realization

http://ift.tt/1QPTA0O

Hi, the link above is my class diagram and i would like to ask is it possible to add Realization into it? if yes how? and hope pros would give some comment about my correctness of this class diagram




read content from text field in another class

I have two classes, one class is a GUI which asks the user to select 2 file directories and displays the directories in the two text fields "input Line" and "input Line 1" respectively text field. the second class is supposed to read these two directories and perform an indexing operation. My problem is I do not know how to get the second class to read the directory(path) in the text field from the first class into the "index path" and "doc path" I have tried importing the first class but it still didn't work it gives me a n error message saying "input Line cannot be resolved to a variable. these are the classes and their codes: first class snippet:

openButton.addActionListener(new ActionListener() {
        public  void actionPerformed(ActionEvent ae) {
          JFileChooser chooser = new JFileChooser();
          chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
          int option = chooser.showOpenDialog(uploaad.this);
          if (option == JFileChooser.APPROVE_OPTION) {
              File file = chooser.getSelectedFile();
              inputLine.setText(file.getAbsolutePath());

          }
          else {
            statusbar.setText("You canceled.");
          }
        }
      });


    indexButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ap) {
            JFileChooser chooser = new JFileChooser();
              chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              int option = chooser.showOpenDialog(uploaad.this);
              if (option == JFileChooser.APPROVE_OPTION) {
                  File file = chooser.getSelectedFile();
                  inputLine1.setText(file.getAbsolutePath());

              }
              else {
                statusbar.setText("You canceled.");
              }
            }
          });

second class snippet:

 String indexPath = inputLine.getText;
    String docsPath = inputLine1;
    boolean create = true;
    for(int i=0;i<args.length;i++) {
     if ("-index".equals(args[i])) {
    indexPath = args[i+1];
    i++;
    } else if ("-docs".equals(args[i])) {
    docsPath = args[i+1];
    i++;
    } else if ("-update".equals(args[i])) {
      create = false;
     }
   }

   if (docsPath == null) {
   System.err.println("Usage: " + usage);
   System.exit(1);
    }

  final Path docDir = Paths.get(docsPath);
  if (!Files.isReadable(docDir)) {
  System.out.println("Document directory '" +docDir.toAbsolutePath()+ "'  
  does not exist or is not readable, please check the path");           
  System.exit(1);
}




Does it make sense to use a component (from a component diagram) in a class diagram?

I have made a component diagram and now I'm in the process of doing a class diagram where I expand on some of the components to model which classes that constitute a component. However some of the components are not really relevant to expand into classes but I would still like to have them inside the class diagram.

E.g. a class has a dependency on a component. Expressed in a class diagram does this make sense?




Python how to assign a copy of a class to a variable? (Instead of by reference)

I have a list containing the same class but instantiated with different variables. Further along my code I am basically trying to get a template of one of classes in that list and then resetting some member variables. However, when I modify what I think is a copy of the class, its still affecting the original class within the list. This is making me think that I haven't successfully created a class but only a reference. How can I make a true copy of it so that they are not connected in any way?

Here is a basic (and hopefully understandable) schematic of the list of class datastructure:

ListofClass = [classA(1,2), classA(34,21), classA(55,32)]

And then here is the code further along:

def getClass(position):
    templateclass = ListofClass[position]
    templateclass.var1 = "BLAH"

After this part of the code, my ListofClass is also changed as the value "BLAH" is in it. This is not the intended outcome!

Many thanks.




Account class instantiated, and balance integer used, but returned unexpected return value

I am meant to create an Account class which withdraws and deposits to/from a balance integer, then another class, which creates an instance of Account and withdraws, deposits, and prints these balances respectively.

Error message presented:

Similar threads I researched: (Did not tailor to my situation exactly)

1: (My code spans two different classes, and I had trouble with this issue, this thread helped resolve that one.)

2: (My Account class also features a private variable)

3: (This is the current error I am getting)

(The Account Class) 

public class Account
{

Account() {} //Constructor

private int balance = 1000:
public int balance()
{
  //returns the actual account balance
  return balance;
}

 public void withdraw(int amount) throws NotSufficientFundException
 {
   //withdraws amount from balance if there are sufficient funds
   if (amount > balance)
   {
      throw new NotSufficientFundException(String.format("Current-
      balance %d is less than requested amount %d", balance, amount));
   }
   balance = balance - amount;
 }  //closes withdraw method

//insert deposit method not pertaining to the question
 } // closes the Account class


(TestDefinedException.java)

public class TestDefinedException extends Account
{
   //Constructor perceived to be needed possibly
   TestDefinedException() {}
   public static void main(String args)
   {
      Account acct = new Account();
      return acct.balance;

      //insert a withdraw method 
      //insert a println method
      //insert a deposit method
      //insert a println method
      //etc
   }
}




NetFileEnum Class

Im Trying to make a Program similar to ShareWatch but in C# The product of this will Be posted to github eventually (After lots of work)

For now i'm stuck, I was looking around for a class for NetFileEnum but i found nothing. So i decided to make my own class but i think i broke something.Because i can't seem to get it to work/ display the expected results.This is based of of pinterest's code.Before i took it into a class it was working...

So here is the class:

using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;

namespace MySerie_Commons
{
    public class ConnectionShare
    {
        public int id;
        public int numLocks;
        public string path;
        public int permission;
        public string username;

        public ConnectionShare(int id, int numLocks, string path,int permission, string username)
        {
            this.id = id;
            this.numLocks = numLocks;
            this.path = path;
            this.permission = permission;
            this.username = username;
        }

        public static List<ConnectionShare> BuildConnectionShareList(string server)
        {
            List<ConnectionShare> list = new List<ConnectionShare>();

            // Read Open Shares
            const int MAX_PREFERRED_LENGTH = -1;
            int dwReadEntries;
            int dwTotalEntries;
            IntPtr pBuffer = IntPtr.Zero;
            FILE_INFO_3 pCurrent = new FILE_INFO_3();

            int dwStatus = NetFileEnum(server, null, null, 3, ref pBuffer, MAX_PREFERRED_LENGTH, out dwReadEntries,
                out dwTotalEntries, IntPtr.Zero);

            if (dwStatus == 0)
            {
                for (int dwIndex = 0; dwIndex < dwReadEntries; dwIndex++)
                {

                    IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (dwIndex*Marshal.SizeOf(pCurrent)));
                    pCurrent = (FILE_INFO_3) Marshal.PtrToStructure(iPtr, typeof (FILE_INFO_3));

                    list.Add(new ConnectionShare(
                        pCurrent.fi3_id, 
                        pCurrent.fi3_num_locks,
                        pCurrent.fi3_pathname,
                        pCurrent.fi3_permission,
                        pCurrent.fi3_username
                        ));
                }
                NetApiBufferFree(pBuffer);
            }
            return list;
        }

        #region NetApi32

        [DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern int NetFileEnum(
            string servername,
            string basepath,
            string username,
            int level,
            ref IntPtr bufptr,
            int prefmaxlen,
            out int entriesread,
            out int totalentries,
            IntPtr resume_handle
            );

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct FILE_INFO_3
        {
            public int fi3_id;
            public int fi3_permission;
            public int fi3_num_locks;
            [MarshalAs(UnmanagedType.LPWStr)] public string fi3_pathname;
            [MarshalAs(UnmanagedType.LPWStr)] public string fi3_username;
        }

        [DllImport("Netapi32.dll", SetLastError = true)]
        private static extern int NetApiBufferFree(IntPtr Buffer);

        #endregion NetApi32
    }
}

And here is how i invoke it:

server = "localhost";
List<ConnectionShare> connections = ConnectionShare.BuildConnectionShareList(server);
IEnumerator myEnumerator = connections.GetEnumerator();
while (myEnumerator.MoveNext())
{
   Console.WriteLine(((ConnectionShare)myEnumerator.Current).path);
}

My current output is :

\srvsvc

This is suppose to show something like :

\c$
\print$
\IPC$

If you can link to a class Database for other windows API it would be helpful too




Bootstrap: what does class="collapsed" do in ?

It might sound like a shallow and pedantic question, but I can't find any explanation as to why this class is used or how it works. Obviously for collapsing links in the nav bar when viewport is reduced in size at mobile breakpoint, but I thought this was already achieved through data-toggle and data-target.

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">

The Bootstrap navbar explanation doesn't explain why they're using it, the class doesn't appear in bootstrap.css and tutorial sites don't include the class in their exercises.




Kivy class in .py and .kv interaction

I'm not fully grasping how classes in a python file and the kivy language interact. I'm currently modifying the Showcase example of Kivy to increase my understanding.

File structure

  • main.py
  • showcase.kv
  • data/screens/test.kv

main.py

class Testy(BoxLayout):
    variable = ''
    #other code

class ShowcaseScreen(Screen):
    fullscreen = BooleanProperty(False)

    def add_widget(self, *args):
        if 'content' in self.ids:
            return self.ids.content.add_widget(*args)
        return super(ShowcaseScreen, self).add_widget(*args)


class ShowcaseApp(App):
    #code

test.kv

<Testy>:
    orientation: 'vertical'

    Label:
        text: "Bla"

ShowcaseScreen:
    name: 'LearnKanji'
    fullscreen: True
    #Some ref to <Testy>

Question

I want to have my code in Testy(), because I'm planning to write a lot of code aimed at what happens in that single screen and I don't want to clutter ShowcaseScreen(), because ShowcaseScreen is also meant for other screens.

How do I refer to after calling ShowcaseScreen: in the test.kv file? So that I can put the code meant for Testy in Testy() and keep my files and classes more organized.




file.exe error when compiling dynamic matrix

I'm trying to make a dynamic matrix using classes. I'we made this code. Checked with other codes and it seems to be right. I get get no error messages when compiling, except for the file.exe error in the middle of the program when running this part of the code. It says file.exe has stopped working.

Can anyone see anything wrong with this code?

Matrix::Matrix(unsigned int nRows, unsigned int nColumns)
: nRows(nRows)
, nColumns(nColumns)
, board(nullptr)
{   

    board = new double*[nRows];
    for (int i = 0; i < nRows; ++i)
    {
    board[i] = new double[nColumns];
    }


    for (int i =0; i<nRows; ++i)
    {
        for(int j=0; j<nColumns; ++j)
        {
            board[i][j]=0.0;
        }
    }
}

I've already declared board as: double **board;in the beginning of the class

I'm running Visual Studios 2010




Replace/override JRE classes (in Eclipse IDE)

I have a project which has on its build path another project in which there is a java.lang package with a modified String implementation inside. Somehow it used to be that I started this project with a simple run configuration using stock OpenJDK 7 JRE and the modified String class was loaded (I think at least because in the code there is cast to an interface which is only implemented by the modified String). However recently I might have changed something (I don't know what) and I get a runtime ClassCastException obviously because the original String class is loaded. I tried in a demo project replacing the String class myself and although the auto-complete and go to declaration returned my String class when I started the application this was not the case and stock String was loaded and my app wouldn't work.

The question is: how to replace (/override) classes from JRE (without using a custom classloader)? Also how my experience can be justified?




Can I Define a Function in Code?

This is not a lambda function question, I know that I can assign a lambda to a variable.

There are a slew of questions on the Most Vexing Parse with an equally tremendous number of down votes: Why Can't I Use istream_iterators in a vector Ctor?, so here's my question:

What's the point of allowing us to declare, but not define a function inside code?

For example:

int main(){
    //int one(int bar){return 13 + bar;} This is illegal
    int two(int bar); // This is legal, but why would I want this?
    class three{
        int m_iBar;
    public:
        Foo(int bar):m_iBar(13 + bar){}
        operator int(){return m_iBar;}
    }; //This gets the job done but man it's complicated

    cout << three(42);
    return 0;
}

So what I want to know is why would C++ allow two which seems useless, and three which seems far more complicated, but disallow one?




for loop and arrays in classes for c++

Ok so I want to get a hold of several different arrays of x,y, and n(nr of photons) outside of a for-loop. I am using classes to help me with this but I still can't make it work. Here is the code.

//Class

class arrays_xyn
{
 public:

int value;
int get_value();
void set_value(int newvalue); 
void add_value(int n);
void foo(int n);
};

int n;

int arrays_xyn::get_value()
{
return value;
} 

void arrays_xyn::set_value(int newvalue)
{
  value = newvalue;
} 

void arrays_xyn::add_value(int n)
{
  value += n;   
}

//my arrays

arrays_xyn bin_zero[100];
arrays_xyn bin[100];
arrays_xyn binx[100];
arrays_xyn biny[100];

//pointers

arrays_xyn * pointer_zero, * pointer_n, * pointer_x, * pointer_y; 
pointer_zero = &bin_zero;
pointer_n = &bin;
pointer_x = &binx;
pointer_y = &biny;

//And the for loop

for (int n=0; n < 100; n=n+1)
  { 
  pointer_zero->add_value(n); bin_zero[n].set_value(hImage2D->GetBinContent(n)); 

  if (bin_zero[n].get_value()!=0)
   {  
     pointer_x->add_value(n); binx[n].set_value(xaxis->GetBinCenter(n));
     pointer_y->add_value(n); biny[n].set_value(yaxis->GetBinCenter(n)); 
     pointer_n->add_value(n); bin[n].set_value(hImage2D->GetBinContent(n)); 
  //if I put 
std::cout << "x = "<< binx[n].get_value() << " y= " << biny[n].get_value() << " n= " << bin[n].get_value() << std::endl;
//here then I get the right answer   

   }
  }

//But if I put 
std::cout << "x = "<< binx[n].get_value() << " y= " << biny[n].get_value() << " n= " << bin[n].get_value() << std::endl;
here then I get the wrong answer. And I want to get a hold binx, biny and bin outside of the for-loop since I want to use the binx, biny and bin arrays in another function that I have defined.

I am guessing that I need to define the for-loop in the class but I don't really understand how to do that so that it works.

Any help is greatly appreciated.

Thank you




What is, really, a "Special Class"?

After failing to get something like the following to compile:

public class Gen<T> where T : System.Array
{
}

with the error

A constraint cannot be special class `System.Array'

I started wondering, what, exactly, is a "special class"?

People often seem to get the same kind of error when they specify System.Enum in a generic constraint. I got the same results with System.Object, System.Delegate, System.MulticastDelegate and System.ValueType too.

Are there more of them? I cannot find any info on "special classes" in C#.

Also, what is so special about those classes that we can't use them as a generic type constraint?




Java: creating several instances of object in class itself or how to restructure

I'm a java beginner and have a question concerning how to best structure a cooking program. I have a class called Ingredient, this class currently looks like this:

public class Ingredient {

    private String identifier;
    private double ingredientFactor;
    private String titleInterface;

    public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
        this.identifier = identifier;
        this.ingredientFactor = ingredientFactor;
        this.titleInterface = titleInterface;
    }

I want to initialize several objects (about 40) with certain values as instance variables and save them in a Map, for example

Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");

Later on I want to retrieve all these objects in the form of a Map/HashMap in a different class. I'm not sure how to proceed best, initialize all these objects in the Ingredient class itself or provide a method that initializes it or would it be better to create an super class (AllIngredients or something like that?) that has a Map with Ingredients as instance variables?

Happy for any suggestions, thanks in advance :)




Assign the tree species most representitive of a specific size class in each location sampled

For this study, we recorded the species and diameter at breast height (dbh) for every tree > 1.5m in height and >1.8 cm in diameter within a 100m2 circular plot. There were 100+ circular plots sampled.

I would like to identify the most representative tree species in each of four diameter classes. The diameter classes are sapling (2.5-8 cm), pole (>8-18 cm), mature (>18-28 cm) and large (>28 cm).

If possible I would like an example of how to select the most representative species in each class by density (count of each species in each class) and also by volume (basal area).

I have posted a question on crossvalidated.com regarding which method (density or volume) is more appropriate...

http://ift.tt/1AcpTN2

Note, the name of each site sampled (location) does not follow any kind of pattern. The names were assigned based on the location in the dataset they were sub-sampled from. Also, if there are no species within a certain diameter class for a site, NA will work.

Here is an example dataset with 15 locations sampled and 1,200 trees measured. My data are very similar to the following example data.

tree.species<-c("PSME", "PIEN", "LAOC", "POTR", "SALIX")
tree.diameters<- data.frame(location= paste0(sample(LETTERS[c(2,4,6,8)], 4, replace=TRUE),sample(seq(006,250,57), 1200, replace = TRUE)), 
                            dbh= c(rep(3.81,200),rnorm(350, mean = 6.32, sd=1.5),rnorm(50, mean = 75, sd=6),
                                   runif(550, min=20, max=100),rnorm(50, mean = 150, sd=2.3)), #Units in cm
                            species = factor(sample(tree.species, 1200, replace=TRUE)))

#Add basal area (m sq. per ha)
tree.diameters$basal.area=100*(pi*((tree.diameters$dbh/2)^2)/(4*10000)) 

#Order the data
tree.diameters<-tree.diameters[order(tree.diameters$location, tree.diameters$dbh,tree.diameters$species),]

> head(tree.diameters, n=15)
    location      dbh species basal.area
426     B120 3.303363    PSME 0.02142607
358     B120 3.657538   SALIX 0.02626682
450     B120 3.667190    PSME 0.02640565
150     B120 3.810000    PIEN 0.02850230
94      B120 3.810000    POTR 0.02850230
10      B120 3.810000    PSME 0.02850230
90      B120 3.810000    PSME 0.02850230
18      B120 3.810000   SALIX 0.02850230
134     B120 3.810000   SALIX 0.02850230
194     B120 3.810000   SALIX 0.02850230
274     B120 3.979974   SALIX 0.03110214
290     B120 5.345510   SALIX 0.05610586
310     B120 5.480217    POTR 0.05896921
254     B120 5.625061   SALIX 0.06212757
478     B120 5.852126    LAOC 0.06724456

The general method I have been working on for selecting by density looks something like code below for location=="B120" & location=="B177" , but I am not sure how to iterate it and place all the results into a list or data.frame. I am also unsure how to calculate the same thing for volume (basal.area)

> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh < 8, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh < 8,
+                                select=species)))))
[1] "SALIX"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh >= 8 | dbh < 18, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh >= 8 | dbh < 18,
+                                select=species)))))
[1] "POTR"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh >= 18 | dbh < 28, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh >= 18 | dbh < 28,
+                                select=species)))))
[1] "POTR"
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh > 28, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh > 28, 
+                                select=species)))))
[1] "PIEN"
> #Location "B120"
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh < 8, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh < 8,
+                                select=species)))))
[1] "SALIX"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh >= 8 | dbh < 18, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh >= 8 | dbh < 18,
+                                select=species)))))
[1] "POTR"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh >= 18 | dbh < 28, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh >= 18 | dbh < 28,
+                                select=species)))))
[1] "POTR"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B120" & dbh > 28, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B120" & dbh > 28, 
+                                select=species)))))
[1] "PIEN"
> 
> #Location "B177"
> names(which(table(subset(tree.diameters, 
+                          location == "B177" & dbh < 8, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B177" & dbh < 8,
+                                select=species)))))
[1] "POTR"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B177" & dbh >= 8 | dbh < 18, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B177" & dbh >= 8 | dbh < 18,
+                                select=species)))))
[1] "POTR"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B177" & dbh >= 18 | dbh < 28, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B177" & dbh >= 18 | dbh < 28,
+                                select=species)))))
[1] "POTR"
> 
> names(which(table(subset(tree.diameters, 
+                          location == "B177" & dbh > 28, 
+                          select=species))
+             ==max(table(subset(tree.diameters, 
+                                location == "B177" & dbh > 28, 
+                                select=species)))))
[1] "PSME"

I would like the output to resemble something like this (except with vol.i filled in for each class).

location den.sap den.pole den.mat den.lrg vol.sap vol.pole vol.mat vol.lrg
B120     SALIX   POTR     POTR    PIEN    ?       ?        ?       ?
B177     POTR    POTR     POTR    PSME    ?       ?        ?       ?




Creating class object inside another class method giving fetal error

I am getting this error Catchable fatal error: Argument 1 passed to classes\session::session_check() must be an instance of classes\conf\collections, none given, called in /var/www/html/test1/index.php on line 48 and defined in /var/www/src/classes/session.php on line 18

My collections class is

namespace classes\conf{
        class collections{
            private $mongo;

            public function __construct(){
                $this -> mongo = new \MongoClient();
            }

            public function members(){
                return $this -> mongo -> publicData -> members;
            }
        }
    }

my session class is

namespace classes{
        use \classes\conf\collections;

        class session{
            private $session_id;
            private $session_token;
            private $cookie_token;

            public function __construct(){
                $this -> session_id = session_id();
                $this -> session_token = (isset($_SESSION['token'])) ? $_SESSION['token'] : NULL;
                $this -> cookie_token = (isset($_COOKIE['token'])) ? $_COOKIE['token'] : NULL;

                echo 'Hey';
            }

            public function session_check(collections $collection){
                $data = $collection -> members() -> findone(
                    array(
                        'account.username' => 'uday'
                    ),
                    array(
                        '_id' => 1
                    )
                );

                return true;
            }
        }
    }

I am using spl_autoload to include classes. Everything is working fine if I create new object outside session_check function and pass as variable. But this should work too. Can anybody explain why it is showing fetal error. Why collections $collection is not creating object as error shows none give




S4 method with "sockconn" in the signature

I want to set up a method, dealing with a socket connection as argument. But when I define it

setMethod("gmRequest", signature=c("sockconn", "character"),
  definition=function(db, args) {
    ...
  }
)

I always get the following error:

in Methode ‘gmRequest’ für Signatur ‘"sockconn","character","list"’: no definition for class “sockconn”

Does anyone know who to handle this issue? If I use S3, then it is possible with something like

gmRequest.sockconn <- function(db, args) { ... }

but I don't want to use S3.




mercredi 29 avril 2015

mysqli prepared statments class

I am building my first class for mysql statements to make queries easier for myself. Basically we would do.

Query::set_config($host,$username,$password);

if( Query::is_database("database_name") ) {
    Query::get_results("SELECT * FROM REGISTRY WHERE `name`=? AND `last`=?",[
        "s"=>"firstname",
        "s"=>"lastname"
    ]);
}

My problem is the slight difference between prepared and not, as well as procedural and OO.

Here is the underlying code behind get_results

/*Load Results from SQL Query*/ 
public static function results($sql,$prepared=null) {
    if($is_configurated) {
        self::connect();
        $rows = array();
        if($prepared === null) {
            $query = mysqli_query(self::$conn,$sql);
            if(!$query) 
                echo mysqli_error(self::$conn);

            while($r = mysqli_fetch_array($query)) {
                $rows[] = $r;
            }
        }
        else 
        {
            $stmt = mysqli_prepare(self::$conn,$sql);
            /*
                i   corresponding variable has type integer
                d   corresponding variable has type double
                s   corresponding variable has type string
                b   corresponding variable is a blob and will be sent in packets
            */
            foreach($prepared as $type=>$param) {
                if(strlen($type) > 1) {
                    self::$errors[]="Only one type is allowed";
                    continue;
                } else {
                    mysqli_stmt_bind_param($stmt,$type,$param);
                }
            }

            /*STUCK HERE NOW*/
            mysqli_stmt_execute($stmt);
            while (mysqli_stmt_fetch($stmt)) {
                $rows[] = $r;
            }

        }
        self::disconnect();
        return $rows;
    } else return "NO CONFIGURATED CONNECTION";
}

I wrote where I am stuck, is this just like a normal mysqli while where mysqli_fetch_row or what. The PHP.net docs aren't very fluid nor right out there. I just need help with doing this and seeing if there are any small flaws in my code. I need to return the rows from the results.

Would this be correct?

        /*Load Results from SQL Query*/ 
    public static function results($sql,$prepared=null) {
        if($is_configurated) {
            self::connect();
            $rows = array();
            if($prepared === null) {
                $query = mysqli_query(self::$conn,$sql);
                if(!$query) 
                    echo mysqli_error(self::$conn);

                while($r = mysqli_fetch_array($query)) {
                    $rows[] = $r;
                }
            }
            else 
            {
                $stmt = mysqli_prepare(self::$conn,$sql);
                /*
                    i   corresponding variable has type integer
                    d   corresponding variable has type double
                    s   corresponding variable has type string
                    b   corresponding variable is a blob and will be sent in packets
                */
                foreach($prepared as $type=>$param) {
                    if(strlen($type) > 1) {
                        self::$errors[]="Only one type is allowed";
                        continue;
                    } else {
                        mysqli_stmt_bind_param($stmt,$type,$param);
                    }
                }

                /*STUCK HERE NOW*/
                mysqli_stmt_execute($stmt);
                $stored = mysqli_store_result($stmt);
                if( count($stored) >= 1) {
                    while ($data = mysqli_stmt_fetch($stmt)) {
                        $rows[] = $data;
                    }
                }

            }
            self::disconnect();
            return $rows;
        } else return "NO CONFIGURATED CONNECTION";
    }




How does this Java code instantiate an abstract class?

I am making changes to a Java class of ours, and I noticed the following line of code:

OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};

What I find strange about that line is that OurClass is an abstract class - here's the definition of OurClass:

public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>

When I remove the {} at the end of the line, Eclipse tells me Cannot instantiate the type OurClass<OurInterface1>, but when I put the {} back, everything is OK.

How does {} allow you to instantiate an abstract class?




Insert a Date parameter in the constructor of a class object

I have to create a Cinema project in Java using BlueJ. I have a Class named Movie and a Class named Show. In the Show constructor I want to insert some parameters and I want one to be the date and time of the show using "Date". It should be something like this:

public Show(int ID, Movie movie, Date date, int seats)

But I am not able to insert the date. Is there a way to enter it or is it impossible to do it this way?

Thank you for any help.




Needs constructor/destructor/type conversion error

I get the error that after fracMult and before the ( I'm missing a constructor, destructor, or type conversion. I don't know what it means by that.

#include <cstdlib>  
#include <iostream>  
#include <cmath>  
#include <cstring>

using namespace std;

class fraction
{
private:
    int numerator;
    int denom;
    bool positive;
public:
fraction();
    fraction(int numerator, int denom, bool positive);
    void inputFrac();
    void printFrac();
    fraction fracMult(fraction b);
    fraction fracDiv(fraction b);
    fraction fracAdd(fraction b);
    fraction fracSub(fraction b);
};

fraction f1, f2, fresult;

int main(int argc, char** argv) {

f1.inputFrac();
f2.inputFrac();

cout << "The result of a * b is: ";
fresult = f1.fracMult(f2);
fresult.printFrac();

    return 0;
}

void fraction::printFrac()
{
    if(!positive){
        cout << "-";
    }
cout << numerator << "/" << denom << endl;
}

void fraction::inputFrac()
{
    string tempchar;

    cout << "What is the numerator? ";
    cin >> numerator;
    cout << "What is the denominator? ";
    cin >> denom;
    cout << "Is the fraction positive? (Y or N): ";
    cin >> tempchar;

    while(tempchar != "Y" && tempchar != "N"){
        cout << "Please enter Y or N: ";
        cin >> tempchar;
    }

    if(tempchar == "Y"){
        positive = true;
    }
    else{
        positive = false;
    }
}

fraction::fracMult(f2){ 
    fresult.numerator = f1.numerator * f2.numerator;
    fresult.denom = f1.denom * f2.denom;
    if(f1.positive != f2.positive){
        fresult.positive = false;
    }
    return fresult;
}

fraction::fracDiv(){
}

fraction::fracAdd(){
}

fraction::fracSub(){   
}

I know that fracDiv, fracAdd, and fracSub are all empty, I'm just working on making the fracMult work first.

I'm very new to c++, so sometimes small, obvious errors still evade me.




java substituting wrong object

I have this java 3d class

public class _3DPlane {

_3DPoint dps[]=new _3DPoint[6];

public _3DPlane() {

    System.out.println(dps[0].x+";"+dps[0].y+";"+dps[0].z);//0;0;0


    }

}

when i dont have any 3dpoint object in the class the 3dpoint arrays elements are all(0,0,0)by default, but when i add a 3dpoint object to the class without adding it to the array all of its elements become equal to it

public class _3DPlane {
_3DPoint dp0=new _3DPoint(50,50,50);

_3DPoint dps[]=new _3DPoint[6];


public _3DPlane() {

    System.out.println(dps[0].x+";"+dps[0].y+";"+dps[0].z);//50;50;50



   }

}

i have no idea any help?




How can I "load" content without include/require?

Ey guys.

How can "load" a php file into another without require or include? For example, can I in load my footer, header etc. in my index.php from another file? With for example a php class, even javascript would be fine ? (much like auto_apend/prepend .htacces). But I do not want to use .htacces..

Thanks!




Weird Error with Encapsulated Class

I have A Class Called "BaseMember"

I've made it abstact.

The reason for this is, I have two classes that extend BaseMember.

The one I'm focusing on right now is JuniorMember.

My Environment doesn't recognise JuniorMember as being a class, even though I've already made the class.

but for some reason it recognises "BaseMember.JuniorMember"

BaseMember.JuniorMember jmem2 = new BaseMember.JuniorMember("Andrew", "Adderson", "Bjorn", "Sir", "Hillclose", "Sweden", "zr13ny", "Adderson@hotmail.com",
            564312, 01698763122, 3, "Junior", "AA1299J", 0, 0, "none", "Swift Swe's", "Male", 2, 99, 1, 2, "dkane", "santa", "999292", "", "yes");

I have a few questions:

1) How do I fix my JuniorMember class so that I can use "JuniorMember" without having to write BaseMember, I know this isn't correct as I have another BaseRace class that kinda does the same thing, I can't see where I've made an error.

2)this is kinda a bonus question -- I have like, 25 parameters, do I really need to do stuff like this every time I make a new extending class constructor? it's unsightly.

  public Sprint(string rname, int rid, string rloc, string rtime, string rdist, string rclimb, string rdesc, string rimg, string rter,
                string rcon, string rdir, string rwin, int rrecord, string rrace, string rdate,string rdatec,string rcat,string rgen, string rdif, string rlim, string rcre)
                : base(rname,rid,rloc,rtime,rdist,rclimb,rdesc,rimg,rter,rcon,rdir,rwin,rrecord,rrace,rdate,rdatec,rcat,rgen,rdif,rlim,rcre)
            {
            nameRace = rname;


    RaceID = rid;

    }

Thanks guys.

By the way, this is for a project to do with Members (Junior and Senior) only being able to join Junior and Senior Races.




Python: How to add a static class array of objects?

i'm a python newbie! I'm playing with class, lists and dictionary and i have a problem!

i have this piece of code:

class Vacca( object ):
Munte = dict()

def __init__( self, nr ):
    self.nome = "VACCA_" + str( nr )
    self.numero = str(nr)
    self.mungiture = []

def mungi( self, latte ):
    nr = self.numero
    Vacca.Munte[ nr ] = self
    Vacca.Munte[ nr ].mungiture.append( latte )

vacca = Vacca( 1 )
vacca.mungi( "white milk" )

vacca = Vacca( 1 )
vacca.mungi( "black milk" )

vacca = Vacca( 1 )
vacca.mungi( "yellow milk" )

vacca = Vacca( 2 )
vacca.mungi( "dark chocolate" )

for v in Vacca.Munte:
    print Vacca.Munte[v].mungiture

If i run this is the result:

['yellow milk']
['dark chocolate']

but i need this:

['white milk','black milk','yellow milk']
['dark chocolate']

what i'm wrong?




Is it possible to call a different class when a Button is clicked

So I have a window with a JButton called "start". What I would like to happen is when that button is clicked it will run a separate class i have already created. Is this possible and if so how would i go about doing it? Thanks for all your help




F# initialize objects inside struct with constructor

I have the following struct in F#:

type public Data = 
    struct
        val class1: Class1
        new() {
            class1 = new Class1()
        }
    end

But I get an error that says structs cannot have an empty constructor. Class1 is a class that has a valid default constructor, and needs to be initialized before it is used. Thus, I want class1 to call its constructor when the Data struct is created. How can I do this, or should I not be doing this at all?




In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

I'm new to R and haven't done any programming before...

When I attempt to create a box chart with standard error bars I get the error message mentioned in the title.

I used a script I found on R Cookbook which I tweaked a bit:

ggplot(GVW, aes(x="variable",y="value",fill="Genotype")) + 
  geom_bar(position=position_dodge(),stat="identity",colour="black", size=.3)+
  geom_errorbar(data=GVW[1:64,3],aes(ymin=value-seSKO, ymax=value+seSKO), size=.3, width=.2, position=position_dodge(.9))+
  geom_errorbar(data=GVW[65:131,3],aes(ymin=value-seSWT, ymax=value+seSWT), size=.3, width=.2, position=position_dodge(.9))+
  geom_errorbar(data=GVW[132:195,3],aes(ymin=value-seEKO, ymax=value+seEKO), size=.3, width=.2, position=position_dodge(.9))+
  geom_errorbar(data=GVW[196:262,3],aes(ymin=value-seEWT, ymax=value+seEWT), size=.3, width=.2, position=position_dodge(.9))+
  xlab("Time")+
  ylab("Weight [g]")+
  scale_fill_hue(name="Genotype", breaks=c("KO", "WT"), labels=c("Knock-out", "Wild type"))+
  ggtitle("Effect of genotype on weight-gain")+
  scale_y_continuous(breaks=0:20*4) +
  theme_bw()




Class global variables for inheriting classes

I'm trying to create a class with some global parameters that need to be configured using some class method for all instances of the the class and a second class which inherit from the previous class and configure itself using the same configuration method...

Now, this is a bit confusing; here's a first example:

class cc_a(object):
    v1 = 0
    v2 = 0
    v3 = 0

    @classmethod
    def set_v1(cls, vv = 0):
        cls.v1 = vv

c1 = cc_a()
c2 = cc_a()

print c1.v1, c2.v1

c1.set_v1(100)

print c1.v1, c2.v1

In this first example the code correctly prints 0 0 before the configuration and 100 100 after the class configuration, great!

Now, classes inheriting from the prev class should behave in a similar manner, but should not interfere with the original class. Here's another bit of code:

class cc_a(object):
    v1 = 0
    v2 = 0
    v3 = 0

    @classmethod
    def set_v1(cls, vv = 0):
        cls.v1 = vv


class cc_10(cc_a):
    cc_a.set_v1(10)

class cc_20(cc_a):
    cc_a.set_v1(20)

c1 = cc_a()
c2 = cc_10()
c3 = cc_20()

print c1.v1, c2.v1, c3.v1

this unfortunately prints 20 20 20 instead of the intended 0 10 20

Thank you for the help in advance!




Passing value between classes

I'm tryng to pass value between two classes:

#ifndef classa_inc
#define classa_inc

#include "classb.hpp"

class classa {
    private:
        int a;
        classb tmp;
    public:
        classa(int);
        classa ();
        int get_a() const;
        int get_b() const;
};

#endif

// ..

#include "classa.hpp"

classa::classa (int _a) : a(_a), tmp(30) {}
classa::classa () : a(20), tmp(30) {}

int classa::get_a () const {
    return a;
}

int classa::get_b () const {
    return tmp->get_b ();
}

// ..

#ifndef classb_inc
#define classb_inc

#include "classa.hpp"

class classa;

class classb {
    private:
        classa *ca;
        int b;
    public:
        classb (int);
        classb (classa *);
        int get_b () const;
};

#endif

// ..

#include "classb.hpp"

classb::classb (int _b) : b(_b) {}

classb::classb (classa *ca) {
    b = ca->get_a ();
}

int classb::get_b () const {
    return b;
}

// ...
#include <iostream>
#include "classa.hpp"
#include "classb.hpp"

int main () {
    classa a(10);
    classa a1; // 20
    classb b(&a1); // pass 20
    std::cout << a.get_a() << std::endl; // 10
    std::cout << a.get_b() << std::endl; // 30
    std::cout << b.get_b() << std::endl; // 20
    return 0;
}

I've reading some blogs and tutorials about the topic and I'd like to ask you guys if this the propper way of doing it or there are another way or workaround about doing it, because I got error:

classa.hpp:9:3: error: ‘classb’ no nombra a un tipo

Something like classb don't name a type...any ideas?




Javascipt, do something when clicking on class [duplicate]

This question already has an answer here:

I am trying to run a function when user clicks on a class.

Here is a fiddle with a similar setup. Except that I am not using buttons in the my code.

FIDDLE

document.querySelectorAll('.menu').onclick = function () { alert("test"); };

I've also tried using the getElementsByClassName, with the same results. Is there something I am missing here?

*Note: I need to accomplish this without jQuery




having an issue converting fractions to double

For some reason I've been unable to print a fraction as a double. I can't get past it. It gives formatting errors every time. The parts giving me issues are commented. Class and driver code are below. and help is appreciated.

Class code

public class Fraction1
{
    private int numerator;     
    private int denominator;   

    public void Fraction1(int n, int d)
    {
        this.numerator = n;
        this.denominator = d;
    } 

    public void print()
    {
        System.out.println(numerator + "/" + denominator);
    }

    public Fraction1 add(Fraction1 other)
    {
        int n = this.numerator * other.denominator +
        this.denominator * other.numerator;
        int d = this.denominator * other.denominator;
        return this;
    }

    //public void printAsDouble()
    //{
    //  this.printAsDouble();
    //  System.out.println((double)(numerator)/(double)                (denominator));
    //}
}

Driver code

import java.util.*;

public class FractionDriver1
{
    public static void main (String[] args)
    {
        Scanner input = new Scanner(System.in);
        Fraction c, d, x;    
        x = new Fraction();

        System.out.println("Enter numerator; then denominator.");
        c = new Fraction(input.nextInt(), input.nextInt());
        c.print();

        System.out.println();

        System.out.println("Enter numerator; then denominator.");
        d = new Fraction(input.nextInt(), input.nextInt());
        d.print();

        System.out.println("Sum:");
        x.add(c).add(d);
        x.print();
        //x.printAsDouble();

    }
}




Concrete Methods in Interface Classes

I am building some classes (in PHP, although this question extends to other OOP languages as well) which hold information from a database. As such, I want to create an Interface: "syncable".

interface syncable{
  protected function _pushToDB();
  protected function _pullFromDB();
}

The problem I am encountering is that I want "syncable" to also have a method which (probably) never changes and variable to go with:

protected $sync = 0;

public function sync(){
  if($this->sync == 0){
    // DB in sync with class; Do nothing.
  }
  if(this->sync == 1){
    $this->_pushToDB();
    $this->sync = 0;
  }
  if(this->sync == -1){
    $this->_pullFromDB();
    $this->sync = 0;
  }
}

As variables are changed in an implemented class, or the database is updated elsewhere, the $sync variable is updated to properly reflect the type of sync needed, then sync() can be called at some point which in turn calls the proper implemented method. While _pushToDB() and _pullFromDB() are very specialized per class, sync() will remain constant between most, if not all, classes.

Since the classes implementing "syncable" such as "users", "foo", and "bar" have no real relation to "syncable" and may need to extend other classes, "syncable" should be an interface rather than an abstract class.

So my question is, what is the best way of accomplishing this? Must I copy-paste my sync() function into every class which implements "syncable"? Do I create an abstract class and hope no class which extends "syncable" ever needs to extend anything else? (Since PHP and many OOP don't support multiple-inheritance) Is there some other PHP solution which would better fit this situation? Are there any generic OOP solutions for this problem?




How to create a Swift object in Objective-C?

If you define a swift class like this

@objc class Cat {

}

In swift you can just do

var c = Cat()

But how do you make a Cat instance in Objective-C ?

Subclassing NSObject works because you can then "alloc-init" but can we achieve this without subclassing an Objective-C class?




Laravel - using a class in the same folder

I am looking to have a separate class to handle the validation of a new user.

Folder structure is:

| app
  | Website
    | UserCreator
       - UserCreator.php
       - UserValidation.php

In my UserCreator file I am trying to use a method in the UserValidation class like this:

public function createUser($input)
{
    UserValidation::validate($input);
}

However I am getting this:

Class 'Website\UserCreator\UserValidation' not found

Do I need to instantiate a class like this? As I do in my controller?

My controller is:

Use Website\UserCreator\UserCreator as UserCreator;

class UserCreatorController extends BaseController
{

  protected $userCreator;

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

  public function addNewUser() {
    return $this->userCreator->createUser($input);
  }


}

Because the classes are in the same folder, I didnt think I needed to namespace the validation one / define a use for it in the UserCreator?

Where am I going wrong?




Linked List Database Search c++

So here I've got a linked list that reads in person data from a file(ss_number, dob, fname, lname, state of residence), then creates a linked list of states and with a linked list of the people who reside in that state inside each state. I can perform a number of operations not shown here. However now I'm trying to find and print the youngest or oldest person from any state that the user inputs, however my print_oldest_or_youngest function prints just some random person from that state and gives me a seg fault, any help solving this problem would be greatly appreciated

-Heres one of 1000 lines from the file 10081957 101440980 Betty Lamprey NY //dob(DD/MM/YYYY) ss_number Fname Lname State of residence)

#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;



struct person
{
    int dob,ss_number,year,month,day;
    string fname, lname,state;
    bool isstate;

    person()
    { year = dob%10000;
         month = (dob/10000)%100;
         day = dob/1000000;}
    person(int a, int b, string c, string d, string e)
    {dob=a; ss_number=b; fname=c; lname=d; state=e; isstate=false;
        }
    void print()
    {
        cout<<dob<<" "<<ss_number<<" "<<fname<<" "<<lname<<" "<<state<<endl;
    }

};

template<typename T>struct Link
{
    T*data;
    Link*next;

    Link()
    {}
    Link(T*a,Link<T>*C=NULL)
    {
        data=a;
        next=C;

    }
    ~Link()
    {delete next;}

};
template<typename T>
struct List
{
    Link<T>*Head,*tail;
    int count;
    List(Link<T>*h=NULL, Link<T>*t=NULL)
    {
        Head=h;
        tail=t;

    }
    ~List()
    { delete Head;}

    void add(T*object)
    {
        {   if (Head == NULL && tail == NULL)
        {   Link<T> * newlink = new Link<T>(object);
            Head = newlink;
            tail = Head;  }
        else
        {   Link<T> * newlink = new Link<T>(object);
            tail->next = newlink;
            tail=newlink;} }
    }






    void print_oldest_or_youngest(string state)
    {
        Link<T>*printS=Head;
        //T*S=NULL;   //printS is a link with type state

        while(printS!=NULL)
        {
            if(printS->data->sname == state)
            {
                cout << "SEARCH RESULTS FOR STATE: \n" << "Name: " << state <<
                "\n\n";

                string a;

                cin>>a;
                Link<person>*temp=printS->data->P->Head;
                while(temp!=NULL)
                {
                    if(a=="youngest")
                        find_youngest();
                    else
                        find_oldest();

                    temp=temp->next;
                    temp->data->print();
                    break;}

            }
            printS = printS->next;
        }

    }

    person* find_youngest ()
    {
        Link<person> *temp=Head->data->P->Head;
        int youngY=0;
        int youngM=0;
        int youngD=0;
        person*hold=NULL;
        while(temp!=NULL)
        {
            if(temp->data->year<youngY)
            {
                youngY=temp->data->year;
                hold=temp->data;
                temp=temp->next;
            }
            else if(temp->data->year==youngY)
            {
                if(temp->data->month<youngM)
                {
                    youngM=temp->data->month;
                    hold=temp->data;
                    temp=temp->next;
                }
                else if(temp->data->month==youngM)
                {
                    if(temp->data->day<youngD)
                    {
                        youngD=temp->data->day;
                        hold=temp->data;
                        temp=temp->next;
                    }
                    else temp=temp->next;
                }
                else temp=temp->next;
            }
            else temp=temp->next;
        }
        return hold;
    }
   person* find_oldest()
    {
        Link<person> *temp=Head->data->P->Head;
        int youngY=0;
        int youngM=0;
        int youngD=0;
        person*hold=NULL;
        while(temp!=NULL)
        {
           if(temp->data->year>youngY)
           {
               youngY=temp->data->year;
               hold=temp->data;
               temp=temp->next;
           }
            else if(temp->data->year==youngY)
            {
                if(temp->data->month>youngM)
                {
                    youngM=temp->data->month;
                    hold=temp->data;
                    temp=temp->next;
                }
                else if(temp->data->month==youngM)
                {
                    if(temp->data->day>youngD)
                    {
                        youngD=temp->data->day;
                        hold=temp->data;
                        temp=temp->next;
                    }
                    else temp=temp->next;
                }
                else temp=temp->next;
            }
            else temp=temp->next;
        }
        //cout<<temp->data->fname;
        return hold;
    }

    };
struct state
{
    string sname;
    List<person>*P;
    bool isstate;
    state()
    {
        //        P=new person[3000];
    }
    state(string a,List<person> *x)
    {sname=a;
        P=x;
        isstate=true;}
    void print()
    {
        cout<<sname<<endl;
    }
};

List<state>*read_file(string file)//reads file, creates people and states and put people in their states
{
    List<state>* newlist=new List<state>();
        //        Link<T> * head=NULL;
    //        Link<T> * temp=NULL;
    ifstream fin;
    fin.open("data.txt");
    if (fin.fail())
        cout<<"file not found\n";
    if (!fin.fail())
    {
        while(true)
        {
            int a,b;
            string c,d,sn;
            fin>>a>>b>>c>>d>>sn;
            if (fin.fail())break;
            person * p=new person(a,b,c,d,sn);
            Link<state>*temp=newlist->Head;
            while(true)
            {
                if(temp==NULL)
                {
                    state*s=new state(sn,new List<person>());
                      newlist->add(s);
                    temp=newlist->tail;
                    temp->data->P->add(p);


                    break;
                }

                if(temp->data->sname == sn)
                {
                    temp->data->P->add(p);
                    break;
                }
                temp=temp->next;
            }
        }
    }
    else
        cout<<"Can't open file";
    fin.close();
    return newlist;
}

int main()
{
    person P;
    string a,b,c;
    cout<<"What file would you like to read in"<<endl;

    cin>>a;

List<state> *B= read_file(a);





    B->print_oldest_or_youngest(f);


    //B->find_oldest();



    return 0;
}




First Java project distinguishing between different instances of class

This is my first Java application that I have built, I have successfully created a class for the products, however now I need to declare 4 different instances of products so I can access each individual product in different parts of the code. The code I have at the moment is shown below but I can only seem to acces the last product i have created:

   Products = new Products(1,2.50,"Coke",15);

   Products = new Products(2,1.50,"Crisps",5);

   Products = new Products(3,2.00,"Juice",2);

   Products = new Products(4,2.50,"Chocolate",0);

   System.out.println(Products.getProductID()+ " " + Products.getProductName());

Is there some way to say 'where product ID is equal to' or assign a individual name to each instance of product? Appolagies if this question has been asked elsewhere I had a look through the related posts but couldn't find anything on this related to Java. The code below shows my products class:

public class Products {

 private int ProductID;
 private double ProductPrice;
 private String ProductName;
 private int ProductStock;

 public Products(int ID, double Price,String PName,int Stock){
  ProductID = ID;
  ProductPrice = Price;
  ProductName = PName;
  ProductStock = Stock;
}

 public void setProductID(int ID){
  ProductID = ID;
 }
 public void setProductPrice(double Price){
  ProductPrice = Price;
 }
 public void setProductName(String PName){
  ProductName = PName;
 }
 public void setProductStock(int Stock){
  ProductStock = Stock;
 }

 public int getProductID(){
  return ProductID;
 }
 public double getProductPrice(){
  return ProductPrice;
 }
 public String getProductName(){
  return ProductName;
 }
 public int getProductStock(){
  return ProductStock;
 }

Thanks in advance for any help.




Class to store data C#

I'm writing a program in C# and i have a little problem with passing variable between two forms. For example in form1 I have got textbox where I put some data and i need to show it in textbox in form2. I tried to make additional class with properties "get,set" but it doesnt work, don't know why.

Code from form1

private void button1_Click(object sender, EventArgs e)
        {

            DaneDelegacja Dane = new DaneDelegacja();
            Dane.MiejsceDocelowe = textBox1.Text;

            // Create a new instance of the Form2 class
            Form2 settingsForm = new Form2();

            // Show the settings form
            settingsForm.Show();
            this.Hide();
        }

and code from form2:

 public Form2()
        {
            InitializeComponent();
            DaneDelegacja Dane = new DaneDelegacja();
            textBox1.Text = Dane.MiejsceDocelowe;

        }

class to store data:

class DaneDelegacja
    {
        public  string MiejsceDocelowe { get; set; }
    }

Thank you for your help :)




Binary Tree Database

Here I've got a binary tree database. I have a insert method that should work but my read in file is completely screwed up because our teacher never showed us how to read data into a binary tree. I have to read in a data file and create a binary tree of states and within each state have a binary tree of the people living in each state. Any help would be greatly appreciated because this was technically due 2 days ago but no one in my class has finished it.(this is a beginner class so please be patient with my ignorance :))

-Heres what a line of data looks like in the file 10081957 101440980 Betty Lamprey NY

//ss number, dob, fname, lname, state

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

struct person
{
    string fname, lname, state;
    int ss_number, dob;
    bool isstate;

    person(string a, string b, string c, int d, int e)
    {
        fname=a;
        lname=b;
        state=c;
        ss_number=d;
        dob=e;
        isstate=false;
    }
    void print()
    {
        cout<<dob<<" "<<ss_number<< " "<<fname<<" "<<lname<<" "<<state<<endl;
    }
    bool compare(person *p)
    {
        if(fname<p->fname && lname<p->lname)
        {
            return true;
        }
        else
            return false;

    }
};
template<typename T>
struct node
{
    T *data;
    node<T>*left, *right;

    node(T*d,node<T>*l=NULL, node<T>*r=NULL)
    {
        data=d;
        left=l;
        right=r;
    }
};
template<typename T>
struct tree
{
    node<T>*root;
    tree()
    {
        root=NULL;
    }
    void insert(T*object,  node<T> * n)
    {

        if (n==NULL)
        {

            n=new node<T>(object);
            }


                if(object->compare(n->data))     //compare is to organize states by name and people by either first or last name.
                    insert(object,n->left);
                else
                    insert(object,n->right);
    }


        void insert(T*object)
        {
            if(root!=NULL)
                insert(object,root);
        }


    void print_states(node<T> * temp)
    {


        if (temp!=NULL)
        {
            print_states(temp->left);
            cout<<temp->data->sname;
            print_states(temp->right);


            }
    }






};
struct state
{
    string sname;
    tree<person>*P;
    bool isstate;
    state()
    {
        //        P=new person[3000];
    }
    state(string a,tree<person> *x)
    {sname=a;
        P=x;
        isstate=true;}
    void print()
    {
        cout<<sname<<endl;
    }
    bool compare(state*s)
    {
        if(sname<s->sname)
        {
            return true;
        }
        else
            return false;
    }
};

tree<state> * tree_from_file(string filename)
{
    tree<state>* StateTree=new tree<state>();
    //node<state> * root=NULL;
    ifstream fin (filename.c_str());
    if (fin.fail())
        cerr << "file not found\n";
    if(!fin.fail())
    {

    while(true)
    {
    string a,b,sn;
    int d,e;
    fin >> a >> b >> sn >> d>>e;
        if(fin.fail()) break;
        person * p = new person(a,b,sn,d,e);      //create person
        node<state>*temp=StateTree->root;         //go to first state node
        while(true)
        {
            if(temp==NULL)   //if state doesnt exist in tree yet
            {
                state*s=new state(sn,new tree<person>());       //create state
                StateTree->insert(s);                           //insert state into tree
                temp->data->P->insert(p);                       //insert person to state




                break;

            }
            if(temp->data->sname == sn)   //if state already exists
            {
                temp->data->P->insert(p);
                break;
            }
            temp=temp;   //not sure how to move through data
        }
    }
    }
    else
        cout<<"Can't Open!";
    fin.close();
    return StateTree;
}


int main()
{
    tree<state>*B=tree_from_file("data.txt");
    node<state>*A;
    B->print_states(A);

    return 0;
}




Organizing Code, Polymorphism, and more

I'm rather new to the Python language, but I have experience in several programming languages several being C++ and Java. I recently started learning Python because my school requires in our Computer Science class. Now I've used those programming languages extensively and some of the things in which Python does seems very odd.

I'll give you an example, firstly I can't import files from another directory. At the moment, I am trying to create a text-based RPG game. My idea was to have a entity superclass with the properties and then branch that off to other subclasses (player.. bosses.. enemies). I'd also thought I'll use for weapons and other items.

However, I recently discovered that by default you can't import files from other directories. I'm used to in Java and other languages that you being able to import files from anywhere you wanted. If that's the case then does every python file that's going to be used by another file have to be in the same directory? If that's the case then how do you organize the code? I assume there's a way, but I seem to be unable to find anything about it.




Passing a value into a class to be used when the class is instantiated in Swift

When creating an instance of a custom class, I want to pass a value back into the class declaration, to be used when it's instantiated.

I tried doing this through a property, but that doesn't work. What is the correct way to achieve this?

(Apologies if I'm not wording the question quite right, but hopefully the code below makes my question clear.)

class hello {
    let indexInArray: Int!
    override init(frame: CGRect) {
        super.init(frame: frame)
        println("This is hello number \(indexInArray).")
    }
}

for index in 0..<4 {
    let singleHello = hello()
    singleHello.indexInArray = index
}

The desired output:

// This is hello number 0.
// This is hello number 1.
// This is hello number 2.
// This is hello number 3.




dompdf->render(); not working in api class

I'm having a problem when trying to render html to pdf using dompdf.

I have the code placed inside a class and after the procedure code I would like it to create a pdf of the html.

This is the code I have at the moment:

$templatefile = file_get_contents("templates/costreport.htm");
//fill headers
$templatefile = str_replace("%DATES%",stripslashes($startdate)." - ".stripslashes($enddate),$templatefile);     

if ($siteid>0) {
    $pdfname = "costreport-".$clientid.".pdf";
} else {
    $pdfname = "costreport-".$clientid."-".$siteid.".pdf";
}
//insert into database
//Close and output PDF document
$pdfname = str_replace("/","-",$pdfname);
$pdfname = str_replace("\\","-",$pdfname);
//create pdf
// unregister Yii's autoloader
spl_autoload_unregister('my_autoloader');
// register dompdf's autoloader
require_once("../system/dompdf/dompdf_config.inc.php");
// register Yii's autoloader again
spl_autoload_register('my_autoloader');
$dompdf = new DOMPDF();
$dompdf->set_paper("A4","portrait");
$dompdf->load_html($templatefile);
//set_time_limit(240);
$dompdf->render();
$pdf = $dompdf->output();
// You can now write $pdf to disk, store it in a database or stream it
// to the folder.
file_put_contents('../tmp/'.$clientid.'/'.$pdfname, $pdf);  

The code fails when the dompdf->render(); is in but once I take that line out the code works and the file is created but I cant open it if it hasn't rendered.

I've tried debugging the code and made the template is HTML valid but I'm at a loss now.




Should action listeners be in the class they apply to?

I'm programming a web browser with multiple classes. One class is "navbar" which holds most of the buttons such as search, back, forward, etc. The navbar class has action listeners which, when the search button is pressed, become active, and lead to the production of a URL, which needs to be passed to the JEditorPane, but the editor pane is in a different class, "editor".

It does not make sense for an editor to be instantiated inside navbar, so how can i pass the variable from the navbar class to the editor class?

Is it okay to use statics in this situation?




Parse error: syntax error, unexpected T_PUBLIC in.. What does mean.?

class Test{     
// declare variables..
public $_name;

public function Sample(){
            return $this->_name;
        }
}

I getting the error from Above code.

The error-> Parse error: syntax error, unexpected T_PUBLIC in




Use extended class in place of base class

Java 1.6. I have extended a class to include some methods. Now I would like to use the extended class in place of the base class. However, the classes that could use the base class cannot "recognize" the extended class. What is the (recommended) fix?

I know this has been asked many times in different flavors, but I can't get it!

Example- Extend class SAMRecord and use SAMRecordExt afterwords:

public class SAMRecordExt extends SAMRecord{

    public SAMRecordExt(SAMFileHeader header) {
        super(header);
    }       

}

Now, while this works:

SAMRecord rec= sam.iterator().next();

This gives me

SAMRecordExt recext= sam.iterator().next();
>>> Type mismatch: cannot convert from SAMRecord to SAMRecordExt

Unsurprisingly, this doesn't work either:

SAMRecordExt recext= (SAMRecordExt) sam.iterator().next();
>>> SAMRecord cannot be cast to markDupsByStartEnd.SAMRecordExt

How can I make the extended class work where the base class worked?




Why do we create a private variable inside a class in c#?

Why do we create a private variable inside a class and then make a public property out of it on the following lines in c#? Also I do not get the concept of getting and setting a property.

I mean why do we do this

 public class MyClass
    {
        private string _myProperty;

        public string MyProperty
        {
           get
           { return _myProperty; }
           set
           { _myProperty = value; }
    }

or this

public class MyClass
{
    public string MyProperty {get;set;}
}

My question is much similar to this one: Why do we need to create class variables to get and set a property?

The above thread didn't seem to solve my problem. Somebody, please elaborate on :

  • Why do create private variables first and then make public properties out of it? Why not a single step?
  • What do we need 'get' and 'set' and why two approaches to use it?



Jquery if any element in a class meets the condition

I want to check if any element in a class meets certain conditions. Example.

$(document).on('click','.modalInner_form_nav', function(){
            var input = $(this).parents('.modalInner_form').find('.validate_g'); 

            //$(input).each(function(index, element) {
                    if ($(input).val() == ''){
                        $(input).css('border', '#BB0000 1px solid');
                        return false;
                    } else {
                            /////////go to next///////////
                            if ($(this).parents('.modalInner_form').is(':last-child')){

                            } else {
                                $(this).parents('.modalInner_form').slideUp();
                                $(this).parents('.modalInner_form').next('.modalInner_form').slideDown();
                            }           
                ////////////
            }
        //});

    });

This returns false if all input fields are empty, but if one in this class is not empty, it returns true.




mardi 28 avril 2015

Trouble with C++ Classes and Functions

I'm trying to make a Battleship game in C++ and I've been having a huge nightmare trying to get my classes set up the way I wanted them to be. Bellow I've included some code as well as more information about how I'm trying to program the game.

There are three classes and header files: Game.cpp, Ships.cpp and Player.cpp as well as their corresponding header files Game.h, Ships.h and Player.h. Ships and Player are only there to store the information regarding those items where as I want the bulk of functions to be associated with the Game class.

Currently the only way I can display my rudimentary game board is by initializing it in my main() and then using it as a local variable. I want to put that "print" function into my game.cpp. I've had several goes at it all which is why you'll see random bits of code all over the place. I feel like once I get it down once I'll have more confidence and be able to replicate other classes and function.

The functions I've identified that I need for my game so far are as follows: Clear //clears game board Show //shows the game board countNumberOfShips //counts how many ships there are ie when 0 ships remain you lose or win depending on who is at 0. setShips // allows you to place your ships and randomly places computer's ships. attack // controls the attack sequences, is responsible for shoot,hit miss, sink.

main.cpp

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

int board3[10][10] = {
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10},
    {1,2,3,4,5,6,7,8,9,10}
};

string name;
int option1;
bool playerWin = false;
string type;


int main()

{


cout << "Hello, welcome to battleship" << endl;
Game mygame;
//mygame.displayBoard();

for(int i=0; i < 10; i++)
{ 
    for(int j=0; j < 10; j++)
    { 
        cout <<  board3[i][j] << " ";
    }
    cout << endl;
}



/**Game go;
cout << "Welcome, please enter your name: "; cin >> name;
cout <<"Are you a player or a computer?"; cin >> type;
Player newPlayer(name, player);
go.addPlayer(newPlayer);

cout << "Okay " << name << "! Are you ready to lose?" << endl;


cout << "hello world" << endl; //game function goes here

**/

system("pause");
return 0;


};

game.h

#ifndef GAME_H
#define GAME_H

   #include "Player.h"
   #include "Ships.h"
   #include <vector>

   class Game {
public:
    Game();
    ~Game();
    //void addPlayer(Player newPlayer);
    void displayBoard();
    //void addShip(Ships newShip);
private:

};

#endif 

game.cpp

#include "Game.h"
#include <vector>

#include <iostream>
using namespace std;

Game::Game() {
    cout << "Hello Mr Rabbit!" << endl;
}

Game::~Game() {
}

void Game::displayBoard()

{
    int gameBoard[10][10];
    for(int i=0; i < 10; i++)
    { 
        for(int j=0; j < 10; j++)
        { 
            cout <<  gameBoard[i][j] << " ";
        }
        cout << endl;
    }


}




How can I allow one or more arguments for initializing a class?

If I want to create a class where each instance has to have at least one arguments but could have more. If it has none it should raise an exception. How can i achieve this?




(C++ Beginner) How do I call these class functions into the main?

I keep having errors, I'm not sure how to call this Car class into the main function. The instructions I was given are below.

#include <iostream>
#include <string>

class Car{
public:

Car(){
    int year = 1990;
    std::string make = "Bentley";
    int speed = 0;
};

Car(int new_year, std::string new_make, int new_speed) {
     year = new_year;
     make = new_make;
     speed = new_speed;
}

int get_year() { return year; }
std::string get_make() { return make; }
int get_speed() { return speed; }

void accelerate() {
    speed+=5;
}

void brake() {
    speed-=5;
}

private:
int year;
std::string make;
int speed;
};

int main()
{
int year = 1990;
std::string make = "Bentley";
int speed = 0;

Car YourCar(year, make, speed);

std::cout << "Year: " << YourCar.get_year << std::endl;
std::cout << "Make: " << YourCar.get_make << std::endl;
std::cout << "Speed: " << YourCar.get_speed << std::endl;
}

Instructions: Please implement a class named Car in C++ that has the following member variables:

  1. year. An int that holds the car’s model year.
  2. make. A string object that holds the make of car.
  3. speed. An int that holds the car’s current speed. In addition, the class should have the following member functions:
  4. Constructor. The constructor should accept the car’s year and make as arguments and assign these values to the object’s year and make member variables. The constructor should initialize the speed member variable to 0.
  5. Accessors or Getters. Appropriate accessors or getters should allow values to be retrieved from an object’s year, make and speed member variables.
  6. accelerate. The accelerate function should add 5 to the speed member variable each time it’s called.
  7. brake. The brake function should subtract 5 from the speed member variable each time it is called.

Demonstrate the class in a program that creates a Car object and then calls the accelerate function 5 times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function 5 times. After each call to the break function, get the current speed of car and display it.




Python Date Class Methods

brand new here!

This is my first time working with Python classes and I am a bit confused. I wanted to try and store dates with three attributes - year, month, and day (as integers).

What I want to do is:

for an ____init____() function to take a year, month and a date (with defaults 1900, 1 and 1) and return it with the month written out:

>>date_one = Date( 1973, 5, 2)
May 2, 1973
>>date_two = Date( 1984)
January 1, 1984

for a ____str____() function to format the data as a string with year, month, and day:

>>date_one = Date( 1973, 5, 2)
>>string = str(date_one)
>>string
'1973-05-02'
>>date_two = Date( 1984)
>>print date_two
1984-01-01

for same_date_in_year() to determine whether two dates fall on the same date, even if they aren't in the same year

>>date_one = Date( 1972, 3, 27)
>>date_two = Date( 1998, 4, 17)
>>date_three = Date(1957, 4, 17)
>>date_one.same_date_in_year(date_two)
False
>>date_two.same_date_in_year(date_three)
True

What I have so far:

days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

month_names = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

class Date(object):
    year = 1900
    month = 1
    day = 1

    def __init__(year, month, day):

    def __str__(year, month, day):

    def same_date_in_year(year, month, day):

    pass


if __name__ == "__main__":
    date_one = Date( 1972, 3, 27 )
    date_two = Date( 1998, 4, 13 )
    date_three = Date( 1996, 4, 13 )
    print "date_one is " + str(date_one)
    print "date_two is " + str(date_two)
    print "date_three is " + str(date_three)
    print "date_one.same_day_in_year(date_two)", date_one.same_day_in_year(date_two)
    print "date_two.same_day_in_year(date_three)", date_two.same_day_in_year(date_three)
    print  

I have no idea how the Class would work and the functions inside it, before the pass. If someone could help me, it would be much appreciated!