Search Results

Search found 63799 results on 2552 pages for 'case class'.

Page 5/2552 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Using "public" vars or attributes in class calls, functional approach

    - by marw
    I was always wondering about two things I tend to do in my little projects. Sometimes I will have this design: class FooClass ... self.foo = "it's a bar" self._do_some_stuff(self) def _do_some_stuff(self): print(self.foo) And sometimes this one: class FooClass2 ... self.do_some_stuff(foo="it's a bar") def do_some_stuff(self, foo): print(foo) Although I roughly understand the differences between functional and class approaches, I struggle with the design. For example, in FooClass the self.foo is always accessible as an attribute. If there are numerous calls to it, is that faster than making foo a local variable that is passed from method to method (like in FooClass2)? What happens in memory in both cases? If FooClass2 is preferred (ie. I don't need to access foo) and other attributes inside do not change their states (the class is executed once only and returns the result), should the code then be written as a series of functions in a module?

    Read the article

  • Nested class or not nested class?

    - by eriks
    I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new class, ATime, that will hold ptr to A instance and the time A::f should be executed. The scheduler will hold a min priority queue of Atime. Do you think it is the correct implementation? Should ATime be a nested class of the scheduler?

    Read the article

  • C++ threaded class design from non-threaded class

    - by macs
    I'm working on a library doing audio encoding/decoding. The encoder shall be able to use multiple cores (i.e. multiple threads, using boost library), if available. What i have right now is a class that performs all encoding-relevant operations. The next step i want to take is to make that class threaded. So i'm wondering how to do this. I thought about writing a thread-class, creating n threads for n cores and then calling the encoder with the appropriate arguments. But maybe this is an overkill and there is no need for another class, so i'm going to make use of the "user interface" for thread-creation. I hope there are any suggestions.

    Read the article

  • Include a Class in another model / class / lib

    - by jaycode
    I need to use function "image_path" in my lib class. I tried this (and couple of other variations): class CustomHelpers::Base include ActionView::Helpers::AssetTagHelper def self.image_url(source) abs_path = image_path(source) unless abs_path =~ /^http/ abs_path = "#{request.protocol}#{request.host_with_port}#{abs_path}" end abs_path end end But it didn't work. Am I doing it right? Another question is, how do I find the right class to include? For example if I look at this module: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html is there a rule of thumb how to include that module in a model / library / class / anything else ?

    Read the article

  • How to call a method from another class that's been instantiated within the current class

    - by Pavan
    my screen has a few views like such __________________ | _____ | | | | | //viewX is a video screen | | | | | viewX | vY | | //viewY is a custom uiview i created. | |____| | //it contains a method which i would like to call that toggles |_________________| //the hidden property of this view. and when it hides, a little | | //button is replaced no the top right corner on top of viewX | viewZ | //the video layer | | |_________________| //viewZ is a view containing many square views - thumbnails. my question is, i dont know how to register for touch events so that it recognises any touch event on no matter which view the user touches the screen.. atm im handling the touch events for each view inside it. so all works well... however what im trying to do is that when the user taps anywhere else on the screen but on viewY, viewY should dissapear by calling that method in the viewY class. this viewY class is instantiated and has no xib file attached to it. the uiview is created progammatically in the viewY class. this whole class for viewY behviour is instantiated in viewX - the video view. my boss says add delegates.. although i have now clue how to do that... any help? is there anyway i can just make it really simple and be able to say REMOVE VIEW no matter which class im calling from? Also ive seen other people achieve this by using these funky arrows - ... <- etc.. although im not sure if thats what i need or how to implement such a thing. ah i think ive made my question quite complicated but i really mean it to be a simple one, and know it can be done in an easy way!

    Read the article

  • Use nested static class as ActionListener for the Outer class

    - by Digvijay Yadav
    I want to use an nested static class as an actionListener for the enclosing class's GUI elements. I did something like this: public class OuterClass { public static void myImplementation() { OuterClass.StartupHandler startupHandler = new OuterClass.StartupHandler(); exitMenuItem.addActionListener(startupHandler); // error Line } public static class StartupHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { //throw new UnsupportedOperationException("Not supported yet."); if (e.getSource() == exitMenuItem) { System.exit(1); } else if (e.getSource() == helpMenuItem) { // show help menu } } } } But when I invoke this code I get the NullPointerException at the //error Line. Is this the right method to do do this or there is something I did am missing?

    Read the article

  • Thread class closing from other Class (Activity) with protected void onStop() Android

    - by user1761337
    I have a Problem with Closing the Thread. I will Closing the Thread with onStop,onPause and onDestroy. This is my Source in the Activity Class: @Override protected void onStop(){ super.onStop(); finish(); } @Override protected void onPause() { super.onPause(); finish(); } @Override public void onDestroy() { this.mWakeLock.release(); super.onDestroy(); } And the Thread Class: public class GameThread extends Thread { private SurfaceHolder mSurfaceHolder; private Handler mHandler; private Context mContext; private Paint mLinePaint; private Paint blackPaint; //for consistent rendering private long sleepTime; //amount of time to sleep for (in milliseconds) private long delay=1000/30; //state of game (Running or Paused). int state = 1; public final static int RUNNING = 1; public final static int PAUSED = 2; public final static int STOPED = 3; GameSurface gEngine; public GameThread(SurfaceHolder surfaceHolder, Context context, Handler handler,GameSurface gEngineS){ //data about the screen mSurfaceHolder = surfaceHolder; mHandler = handler; mContext = context; gEngine=gEngineS; } //This is the most important part of the code. It is invoked when the call to start() is //made from the SurfaceView class. It loops continuously until the game is finished or //the application is suspended. private long beforeTime; @Override public void run() { //UPDATE while (state==RUNNING) { Log.d("State","Thread is runnig"); //time before update beforeTime = System.nanoTime(); //This is where we update the game engine gEngine.Update(); //DRAW Canvas c = null; try { //lock canvas so nothing else can use it c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { //clear the screen with the black painter. //reset the canvas c.drawColor(Color.BLACK); //This is where we draw the game engine. gEngine.doDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L); try { //actual sleep code if(sleepTime>0){ this.sleep(sleepTime); } } catch (InterruptedException ex) { Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE, null, ex); } while (state==PAUSED){ Log.d("State","Thread is pausing"); try { this.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }} How i can close the Thread from Activity Class??

    Read the article

  • Add class to elements which already have a class

    - by bwstud
    I have a group of divs which I'm dynamically generating when a button is clicked with the class, "brick". This gives them dimension and starting position of top: 0. I'm trying to get them to animate to the bottom of the view using a css transition with a second class assignment which gives them a bottom position: 0;. Can't figure out the syntax for adding a second class to elements with a pre-existing class. On inspection they only show the original class of, "brick". HTML <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="container"> <div id="button" >Click Me</div> </div> </body> </html> CSS #container { width: 100%; height: 100vh; padding: 10vmax; } #button { position: fixed; } .brick { position: relative; top: 0; height: 10vmax; width: 20vmax; background: white; margin: 0; padding: 0; transition: all 1s; } .drop { transition: all 1s; bottom 0; } The offending JS: var brickCount = function() { var count = prompt("How many boxes you lookin' for?"); for(var i=0; i < count; i++) { var newBrick = document.createElement("div"); newBrick.className="brick"; document.querySelector("#container") .appendChild(newBrick); } }; var getBricks = function(){ document.getElementByClass("brick"); }; var changeColor = function(){ getBricks.style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16); }; var addDrop = function() { getBricks.brick = "getBricks.brick" + " drop"; }; var multiple = function() { brickCount(); getBricks(); changeColor(); addDrop(); }; document.getElementById("button").onclick = function() {multiple();}; Thanks!

    Read the article

  • PHP Changing Class Variables Outside of Class

    - by Jamie Bicknell
    Apologies for the wording on this question, I'm having difficulties explaining what I'm after, but hopefully it makes sense. Let's say I have a class, and I wish to pass a variable through one of it's methods, then I have another method which outputs this variable. That's all fine, but what I'm after is that if I update the variable which was originally passed, and do this outside the class methods, it should be reflected in the class. I've created a very basic example: class Test { private $var = ''; function setVar($input) { $this->var = $input; } function getVar() { echo 'Var = ' . $this->var . '<br />'; } } If I run $test = new Test(); $string = 'Howdy'; $test->setVar($string); $test->getVar(); I get Var = Howdy However, this is the flow I would like: $test = new Test(); $test->setVar($string); $string = 'Hello'; $test->getVar(); $string = 'Goodbye'; $test->getVar(); Expected output to be Var = Hello Var = Goodbye I don't know what the correct naming of this would be, and I've tried using references to the original variable but no luck. I've come across this in the past, with the PDO prepared statements, see Example #2 $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $value); // insert one row $name = 'one'; $value = 1; $stmt->execute(); // insert another row with different values $name = 'two'; $value = 2; $stmt->execute(); I know I can change the variable to public and do the following, but it isn't quite the same as how the PDO class handles it, and I'm really looking to mimic that behaviour. $test = new Test(); $test->setVar($string); $test->var = 'Hello'; $test->getVar(); $test->var = 'Goodbye'; $test->getVar(); Any help, ideas, pointers, or advice would be greatly appreciated, thanks.

    Read the article

  • PC case and PSU screw question....

    - by user32569
    Hi, I have maybe a funny one to ask.... To this Christmass I bought new PC. When I started to asseble it, I found that my case (Artic Cooling Silentium T11) has 12 screws for HDD, DVD etc, and 6 screws for the expansion cards. Well, first thing that surprised me was, why only 6 screws for expansion card, when case has actually 7 slots. And second, what are PSU screws supposed to some with? The PSU, Case or nothing? Becouse neighter PSU or Case had them. PSU is Evolve Storm 600W. Well, I know case and PSU are not some high end devices, but still, would it hurt them to add 1 screw for expansion cards and 4 for PSU? So, my question is, is this situation normall, or which one (Case or PSU) does normally screws come with? Thanks.

    Read the article

  • How bad is it to have two methods with the same name but different signatures in two classes?

    - by Super User
    I have a design problem related to a public interface, the names of methods, and the understanding of my API and code. I have two classes like this: class A: ... function collision(self): .... ... class B: .... function _collision(self, another_object, l, r, t, b): .... The first class has one public method named collision, and the second has one private method called _collision. The two methods differs in argument type and number. As an example let's say that _collision checks if the object is colliding with another object with certain conditions l, r, t, b (collide on the left side, right side, etc) and returns true or false. The public collision method, on the other hand, resolves all the collisions of the object with other objects. The two methods have the same name because I think it's better to avoid overloading the design with different names for methods that do almost the same thing, but in distinct contexts and classes. Is this clear enough to the reader or I should change the method's name?

    Read the article

  • How bad it's have two methods with the same name but differents signatures in two classes?

    - by Super User
    I have a design problem relationated with the public interface, the names of methods and the understanding of my API and my code. I have two classes like this: class A: ... function collision(self): .... ... class B: .... function _collision(self, another_object, l, r, t, b): .... The first class have one public method named collision and the second have one private method called _collision. The two methods differs in arguments type and number. In the API _m method is private. For the example let's say that the _collision method checks if the object is colliding with another_ object with certain conditions l, r, t, b (for example, collide the left side, the right side, etc) and returns true or false according to the case. The collision method, on the other hand, resolves all the collisions of the object with other objects. The two methods have the same name because I think is better avoid overload the design with different names for methods who do almost the same think, but in distinct contexts and classes. This is clear enough to the reader or I should change the method's name?

    Read the article

  • private class calling a method from its outer class

    - by oxinabox.ucc.asn.au
    Ok, so I have a class for a "Advanced Data Structure" (in this case a kinda tree) SO I implimented a Iterator as a private class with in it. So the iterator needs to implement a remove function to remove the last retuirned element. now my ADT already impliments a remove function, and in this case there is very little (thinking about it, i think nothing) to be gain by implimenting a different remove function for the iterator. so how do I go about calling the remove from my ADT sketch of my struture: public class ADT { ... private class ADT_Iterator impliments java.util.Itorator{ ... public void remove(){ //where I want to call the ADT's remove function from } ... public void remove( Object paramFoo ) { ... } ... } So just calling remove(FooInstance) won't work (will it?) and this.remove(FooInstance) is the same thing. what do i call? (and changign the name of the ADT's remove function is not an option, as that AD T has to meet an Interace wich I am note at liberty to change) I could make both of them call a removeHelper functon, I guess...

    Read the article

  • passing reference of class to another class android error

    - by prolink007
    I recently asked the precursor to this question and had a great reply. However, when i was working this into my android application i am getting an unexpected error and was wondering if everyone could take a look at my code and help me see what i am doing wrong. Link to the initial question: passing reference of class to another class My ERROR: "The constructor ConnectDevice(new View.OnClickListener(){}) is undefined" The above is an error detected by eclipse. Thanks in advance! Below are My code snippets: public class SmartApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intro); final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton); connectDeviceButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Thread cThread = new Thread(new ConnectDevice(this)); cThread.start(); } }); } } public class ConnectDevice implements Runnable { private boolean connected; private SmartApp smartAppRef; private ObjectInputStream ois; public ConnectDevice(SmartApp smartAppRef) { this.smartAppRef = smartAppRef; } }

    Read the article

  • C++ Problem: Class Promotion using derived class

    - by Michael Fitzpatrick
    I have a class for Float32 that is derived from Float32_base class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; return *this;}; Float32_base operator +(float x) const { return value + x;}; protected: float value; } class Float32 : public Float32_base { public: float Tad() { return value + .01; } } int main() { Float32 x, y, z; x = 1; y = 2; // WILL NOT COMPILE! z = (x + y).Tad(); // COMPILES OK z = ((Float32)(x + y)).Tad(); } The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's. Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?

    Read the article

  • Class or Dictionary

    - by user2038134
    I want to create a immutable Scale class in C#. public sealed class Scale { string _Name; string _Description; SomeOrderedCollection _ScaleValueDefinitions; Unit _Unit // properties .... // methods ContainsValue(double value) .... // constructors // all parameters except scalevaluedefinitions are optional // for a Scale to be useful atleast 1 ScaleValueDefinition should exist public Scale(string name, string description, SomeOrderedCollection scaleValueDefinitions, unit) { /* initialize */} } so first a ScaleValueDefinition should be represented by to values: Value (double) Definition (string) these values are known before the Scale class is created and should be unique. so what is the best approach. create a immutable class ScaleValueDefinition with value and definition as properties and use it in a list. use a dictionary. use another way i didn't think of... and how to implement it. for option 1. i can use params ScaleValueDefinition[] ValueDefinitions in the constructor, but how to do it for the other options? and as last at what amount of value's (properties) should i choose one option over the other?

    Read the article

  • PHP class data implementation

    - by Bakanyaka
    I'm studying OOP PHP and have watched two tutorials that implement user login\registration system as an example. But implementation varies. Which way will be more correct one to work with data such as this? Load all data retrieved from database as array into a property called something like _data on class creation and further methods operate with this property Create separate properties for each field retrieved from database, on class creation load all data fields into respective properties and operate with that properties separately? Then let's say I want to create a method that returns a list of all users with their data. Which way is better? Method that returns just an array of userdata like this: Array([0]=>array([id] => 1, [username] => 'John', ...), [1]=>array([id] => 2, [username] => 'Jack', ...), ...) Method that creates a new instance of it's class for each user and returns an array of objects

    Read the article

  • Access static class variable of parent class in Python

    - by fuenfundachtzig
    I have someting like this class A: __a = 0 def __init__(self): A.__a = A.__a + 1 def a(self): return A.__a class B(A): def __init__(self): # how can I access / modify A.__a here? A.__a = A.__a + 1 # does not work def a(self): return A.__a Can I access the __astatic variable in B? It's possible writing a instead of __a, is this the only way? (I guess the answer might be rather short: yes :)

    Read the article

  • Rails 3 Abstract Class vs Inherited Class

    - by R. Yanchuleff
    In my rails 3 model, I have two classes: Product, Service. I want both to be of type InventoryItem because I have another model called Store and Store has_many :InventoryItems This is what I'm trying to get to, but I'm not sure how to model this in my InventoryItem model and my Product and Service models. Should InventoryItem just be a parent class that Product and Service inherit from, or should InventoryItem be modeled as a class abstract of which Product and Service extend from. Thanks in advance for the advice!

    Read the article

  • Setting attributes of a class during construction from **kwargs

    - by Carson Myers
    Python noob here, Currently I'm working with SQLAlchemy, and I have this: from __init__ import Base from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String from sqlalchemy.orm import relationship class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) username = Column(String, unique=True) email = Column(String) password = Column(String) salt = Column(String) openids = relationship("OpenID", backref="users") User.__table__.create(checkfirst=True) #snip definition of OpenID class def create(**kwargs): user = User() if "username" in kwargs.keys(): user.username = kwargs['username'] if "email" in kwargs.keys(): user.username = kwargs['email'] if "password" in kwargs.keys(): user.password = kwargs['password'] return user This is in /db/users.py, so it would be used like: from db import users new_user = users.create(username="Carson", password="1234") new_user.email = "[email protected]" users.add(new_user) #this function obviously not defined yet but the code in create() is a little stupid, and I'm wondering if there's a better way to do it that doesn't require an if ladder, and that will fail if any keys are added that aren't in the User object already. Like: for attribute in kwargs.keys(): if attribute in User: user.__attribute__[attribute] = kwargs[attribute] else: raise Exception("blah") that way I could put this in its own function (unless one hopefully already exists?) So I wouldn't have to do the if ladder again and again, and so I could change the table structure without modifying this code. Any suggestions?

    Read the article

  • rename file names from lower case to upper case

    - by Adnan
    Hello, I have about 2k of file that are currently in lower case like: file_one.cfr file_two.cfr .... I am searching for a fast way to rename them to upper case so they would be like; FILE_ONE.cfr FILE_TWO.cfr .... If I use from my shell; for i in *; do mv $i `echo $i | tr [:lower:] [:upper:]`; done I can get all file and the file extensions to upper case. But the extension should remain in lowercase, so my approach does not work. Any programming language is welcome.

    Read the article

  • base class , inheritate class sizeof()

    - by user1279988
    why sizeof(X) is 4 and sizeof(Y) is 8? and another question, in class X, only the int(i) count as sizeof() 4? member function does take any memory space? Plz tell me, thanks! class X { int i; public: X() { i = 0; } void set(int ii) { i = ii; } int read() const { return i; } int permute() { return i = i * 47; } }; class Y : public X { int i; // Different from X's i public: Y() { i = 0; } int change() { i = permute(); // Different name call return i; } void set(int ii) { i = ii; X::set(ii); // Same-name function call } }; cout << "sizeof(X) = " << sizeof(X) << endl; cout << "sizeof(Y) = "

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >