Hey. I would like to understand what "class << self" stands for in the next example.
module Utility
class Options #:nodoc:
class << self
def parse(args)
end
end
end
end
Thx!
I've had trouble finding a clear, concise laymans definition of a class. Usually, they give general ideas without specifically spelling it out, and I'm wondering if I'm understanding this correctly. As I understand it, a class is the set of code that controls an object. For example, in an app that has a button for 'Yes' and a button for 'No', and a text box for output, the code that tells the computer what to do when the user uses the Yes button is one class, the code for hitting No is another class, and an object is the two buttons and what they do together to influence the output box. Am I right, or am I confusing terms here?
Thanks
I'm reading about the State pattern. I have only just begun, so of course I begin by reading the entire Wikipedia article on it.
I noticed that both of the examples in the article have some base abstract class or Java interface for a generic State's methods/functions. Then there are some states which inherit from the base and implement those methods/functions in different ways. Then there's a Context class which has a private member of type State and which, at any time, can be equal to an instance of one of the implementations. That context class also implements the same methods, and passes them onto the current state instance, and then has an additional method to change the state (or depending on design I understand the change of state could be a reaction to one of the implemented methods).
Why doesn't this context class specifically "extend" or "implement" the generic State base class/interface?
I'm trying to use a class as a key in an NSDictionary. I looked at the answer to this question and what I have is pretty much the same; I'm using setObject: forKey:. However, XCode complains, saying Incompatible pointer types sending 'Class' to parameter of type 'id<NSCopying>'. The call I have is:
[_bugTypeToSerializerDictionary setObject: bugToStringSerializer
forKey: [bugToStringSerializer serializedObjectType]];
bugToStringSerializer is an instance of BugToStringSerializer whose concrete implementations implement serializedObjectType. An example of a concrete implementation looks like this:
- (Class) serializedObjectType {
return [InfectableBug class];
}
What am I doing wrong here?
Hi.
I created the following abstract class for job scheduler in red5:
package com.demogames.jobs;
import com.demogames.demofacebook.MysqlDb;
import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.scheduling.IScheduledJob;
import org.red5.server.api.so.ISharedObject;
import org.apache.log4j.Logger;
import org.red5.server.api.Red5;
/**
*
* @author ufk
*/
abstract public class DemoJob implements IScheduledJob {
protected IConnection conn;
protected IClient client;
protected ISharedObject so;
protected IScope scope;
protected MysqlDb mysqldb;
protected static org.apache.log4j.Logger log = Logger
.getLogger(DemoJob.class);
protected DemoJob (ISharedObject so, MysqlDb mysqldb){
this.conn=Red5.getConnectionLocal();
this.client = conn.getClient();
this.so=so;
this.mysqldb=mysqldb;
this.scope=conn.getScope();
}
protected DemoJob(ISharedObject so) {
this.conn=Red5.getConnectionLocal();
this.client=this.conn.getClient();
this.so=so;
this.scope=conn.getScope();
}
protected DemoJob() {
this.conn=Red5.getConnectionLocal();
this.client=this.conn.getClient();
this.scope=conn.getScope();
}
}
Then i created a simple class that extends the previous one:
public class StartChallengeJob extends DemoJob {
public void execute(ISchedulingService service) {
log.error("test");
}
}
The problem is that my main application can only see the constructor without any parameters.
with means i can do new StartChallengeJob()
why doesn't the main application sees all the constructors ?
thanks!
Hello,
i've the following code and tried the whole day to refactor the class methods to a sperate module to share the functionality with all of my model classes.
Code (http://pastie.org/974847):
class Merchant
include DataMapper::Resource
property :id, Serial
[...]
class << self
@allowed_properties = [:id,:vendor_id, :identifier]
alias_method :old_get, :get
def get *args
[...]
end
def first_or_create_or_update attr_hash
[...]
end
end
end
I'd like to archive something like:
class Merchant
include DataMapper::Resource
include MyClassFunctions
[...]
end
module MyClassFunctions
def get [...]
def first_or_create_or_update[...]
end
=> Merchant.allowed_properties = [:id]
=> Merchant.get( :id=> 1 )
But unfortunately, my ruby skills are to bad. I read a lot of stuff (e.g. here) and now i'm even more confused. I stumbled over the following two points:
alias_method will fail, because it will dynamically defined in the DataMapper::Resource module.
How to get a class method allowed_properties due including a module?
What's the ruby way to go?
Many thanks in advance.
module MyModule
def my_method; 'hello'; end
end
class MyClass
class << self
include MyModule
end
end
MyClass.my_method # => "hello
I'm unsure why "include MyModule" needs to be in the singleton class in order to be called using just MyClass.
Why can't I go:
X = MyClass.new
X.my_method
This is a topic that, as a beginner to PHP and programming, sort of perplexes me. I'm building a stockmarket website and want users to add their own stocks. I can clearly see the benefit of having each stock be a class instance with all the methods of a class. What I am stumped on is the best way to give that instance a name when I instantiate it. If I have:
class Stock() {
....doing stuff.....
}
what is the best way to give my instances of it a name. Obviously I can write:
$newStock = new Stock();
$newStock.getPrice();
or whatever, but if a user adds a stock via the app, where can the name of that instance come from? I guess that there is little harm in always creating a new child with $newStock = new Stock() and then storing that to the DB which leads me to my next question!
What would be the best way to retrieve 20 user stocks(for example) into instances of class Stock()? Do I need to instantiate 20 new instances of class Stock() every time the user logs in or is there something I'm missing?
I hope someone answers this and more important hope a bunch of people answer this and it somehow helps someone else who is having a hard time wrapping their head around what probably leads to a really elegant solution. Thanks guys!
I am using a SQL Server database in my current project. I was watching the MVC Storefront videos (specifically the repository pattern) and I noticed that Rob (the creator of MVC Storefront) used a class called Category and Product, instead of a database and I have notice that using LINQ-SQL or ADO.NET, that a class is generated. Is there an advantage to using a class over a database to store information? Or is it the other way around? Or are they even comparable?
I'm trying to run through an example given for the C++ Xerces XML library implementation. I've copied the code exactly, but I'm having trouble compiling it.
error: expected class-name before '{' token
I've looked around for a solution, and I know that this error can be caused by circular includes or not defining a class before it is used, but as you can see from the code, I only have 2 files: MySAXHandler.hpp and MySAXHandler.cpp. However, the MySAXHandler class is derived from HandlerBase, which is included.
MyHandler.hpp
#include <xercesc/sax/HandlerBase.hpp>
class MySAXHandler : public HandlerBase {
public:
void startElement(const XMLCh* const, AttributeList&);
void fatalError(const SAXParseException&);
};
MySAXHandler.cpp
#include "MySAXHandler.hpp"
#include <iostream>
using namespace std;
MySAXHandler::MySAXHandler()
{
}
void MySAXHandler::startElement(const XMLCh* const name,
AttributeList& attributes)
{
char* message = XMLString::transcode(name);
cout << "I saw element: "<< message << endl;
XMLString::release(&message);
}
void MySAXHandler::fatalError(const SAXParseException& exception)
{
char* message = XMLString::transcode(exception.getMessage());
cout << "Fatal Error: " << message
<< " at line: " << exception.getLineNumber()
<< endl;
XMLString::release(&message);
}
I'm compiling like so:
g++ -L/usr/local/lib -lxerces-c -I/usr/local/include -c MySAXHandler.cpp
I've looked through the HandlerBase and it is defined, so I don't know why I can't derive a class from it? Do I have to override all the virtual functions in HandlerBase? I'm kinda new to C++.
Thanks in advance.
decorator 1:
def dec(f):
def wrap(obj, *args, **kwargs):
f(obj, *args,**kwargs)
return wrap
decorator 2:
class dec:
def __init__(self, f):
self.f = f
def __call__(self, obj, *args, **kwargs):
self.f(obj, *args, **kwargs)
A sample class,
class Test:
@dec
def disp(self, *args, **kwargs):
print(*args,**kwargs)
The follwing code works with decorator 1 but not with decorator 2.
a = Test()
a.disp("Message")
I dont understand why decorator 2 is not working here. Can someone help me with this?
I have so many modules and I am showing border to each module.
Below is what I have
div.ja-moduletable-inner,
div.moduletable-inner {
background: none;
padding: 1.5em;
box-shadow: 0px 0px 3px 3px rgba(0,0,0,.25);
}
<div id="Mod143">
<div class="moduletable-inner clearfix">
</div>
</div>
<div id="Mod148">
<div class="moduletable-inner clearfix">
</div>
</div>
<div id="Mod149">
<div class="moduletable-inner clearfix">
</div>
</div>
Note : These modules are added by-default by Joomla, so I can't handle this. What I want is using Javascript, I want to add class in Mod149 so that I will have it as
<div id="Mod149">
<div class="moduletable-inner clearfix newMyOwnClass">`
^^^^^^^^^^^^^^
</div>
and I will have in css as
div.newMyOwnClass {
box-shadow: 0px 0px 0px 0px rgba(0,0,0,.25);
^^^^^^^
}
Any idea how to get this done in Javascript?
No jQuery... Only Javascript AND only with div id Mod149
Hi,
I'd like to validate a form using the jquery validate plugin, but I'm unable to use the 'name' value within the html - as this is a field also used by the server app.
Specifically, I need to limit the number of checkboxes checked from a group. (Maximum of 3.) All of the examples I have seen, use the name attribute of each element. What I'd like to do is use the class instead, and then declare a rule for that.
html
This works:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation" value="1" />
This doesn't work, but is what I'm aiming for:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" />
javascript:
var validator = $(".formToValidate").validate({
rules:{
"salutation":{
required:true,
},
"checkBox":{
required:true,
minlength:3 }
}
});
Is it possible to do this - is there a way of targeting the class instead of the name within the rules options? Or do I have to add a custom method?
Cheers,
Matt
how do you access the class attribute of a in a jQuery selector statement?
for example
<asp:CheckBox runat="server" ID="cbTest" Text="Cb Test" FieldName="1st Test Check Box" class="toggleBox"/>
this:
$(':checkbox').toggleAttr("checked", true, false)
accesses the checkbox and applies a custom function to the checked attribute but if i want to filter based on a certain class how do i access/filter based on that?
I've got a series of web actions I'm implementing in Seam to perform create, read, update, etc. operations. For my read/update/delete actions, I'd like to have individual action classes that all extend an abstract base class. I'd like to put the @Factory method in the abstract base class to retrieve the item that is to be acted upon. For example, I have this as the base class:
public abstract class BaseAction {
@In(required=false)@Out(required=false)
private MyItem item=null;
public MyItem getItem(){...}
public void setItem(...){...}
@Factory("item")
public void initItem(){...}
}
My subclasses would extend BaseAction, so that I don't have to repeat the logic to load the item that is to be viewed, deleted, updated, etc. However, when I start my application, Seam throws errors saying I have declared multiple @Factory's for the same object.
Is there any way around this? Is there any way to provide the @Factory in the base class without encoutnering these errors?
Hello,
is it possible to decorate a field of a LINQ generated class with [Column(IsDbGenerated=true)] using a buddy class (which is linked to the LINQ class via [MetadataType(typeof(BuddyMetadata))]) ?
My goal is to be able to clear and repopulate the LINQ ORM designer without having to set the "Auto Generate Value" property manually every time to re-establish the fact that certain columns are autogenerated.
Thanks!
In a Visual Studio website, I have created a user control. This control is derived from a class (in App_Code) that is itself derived from System.Web.UI.UserControl. This is an abstract class with an abstract method. I then try to implement that method in the user control, but I get the following errors from Visual Studio:
Error 1 'WebUserControl.AbstractMethod()': no suitable method found to override C:\Users\User\Documents\Visual Studio 2010\WebSites\Delme\WebUserControl.ascx.cs 10 28 C:\...\Delme\
Error 2 'WebUserControl' does not implement inherited abstract member 'AbstractBaseClass.AbstractMethod()' c:\Users\User\AppData\Local\Temp\Temporary ASP.NET Files\delme\0eebaa86\f1a48678\App_Web_nrsbzxex.0.cs 14
Error 1 says that my override of the abstract method is invalid, it doesn't recognise the abstract method in the base class. Error 2 says that the partial class automatically built by asp.net doesn't implement the abstract method!
Note that this works fine when the code is used in a Web Application project.
Why is this happening?
I have a problem calling class method from the with_option block with validations:
Model:
class Model < ActiveRecord::Base
attr_accessible :field
with_options :if => "<not important>" do |step|
... bunch of validations
step.validates :field, :inclusion => {:within => Model.field}
end
private
self.field
(1..10)
end
end
And it returns: undefined method `field' for #Class:0x5f394a8
self.class.field also doesn't work.
What is wrong with it ? How to fix it ?
Big big thanks!
Hello,
I have a abstract class called WizardViewModelBase.
All my WizardXXXViewModel classes inherit from the base abstract class.
The base has a property with a getter. Every sub class needs and overrides that string
property as its the DisplayName of the ViewModel.
Only ONE ViewModel called WizardTimeTableWeekViewModel needs a setter because I have to set
wether the ViewModel is a timetable for week A or week B. Using 2 ViewModels like
WizardTimeTableWeekAViewModel and WizardTimeTableWeekBViewModel would be redundant.
I do not want to override the setter in all other classes as they do not need a setter.
Can I somehow tell the sub class it needs not to override the setter?
Or any other suggestion?
With interfaces I would be free to use getter or setter but having many empty setter
properties is not an option for me.
I want to apply the same decorator to every method in a given class, other than those that start and end with __.
It seems to me it should be doable using a class decorator. Are there any pitfalls to be aware of?
Ideally, I'd also like to be able to:
disable this mechanism for some methods by marking them with a special decorator
enable this mechanism for subclasses as well
enable this mechanism even for methods that are added to this class in runtime
[Note: I'm using Python 3.2, so I'm fine if this relies on features added recently.]
Here's my attempt:
_methods_to_skip = {}
def apply(decorator):
def apply_decorator(cls):
for method_name, method in get_all_instance_methods(cls):
if (cls, method) in _methods_to_skip:
continue
if method_name[:2] == `__` and method_name[-2:] == `__`:
continue
cls.method_name = decorator(method)
return apply_decorator
def dont_decorate(method):
_methods_to_skip.add((get_class_from_method(method), method))
return method
Here are things I have problems with:
how to implement get_all_instance_methods function
not sure if my cls.method_name = decorator(method) line is correct
how to do the same to any methods added to a class in runtime
how to apply this to subclasses
how to implement get_class_from_method
I have a problem with my code.
public abstract class SimplePolygon implements Polygon
{
...
public String toString(){
String str = "Polygon: vertices =";
for(int i = 0;i<varray.length;i++){
str += " ";
str += varray[i];
}
return str;
}
}
public class ArrayPolygon extends SimplePolygon
{
private Vertex2D[] varray;
public ArrayPolygon(Vertex2D[] array){
varray = new Vertex2D[array.length];
if (array == null){}
for(int i = 0;i<array.length;i++){
if (array[i] == null){}
varray[i] = array[i];
}
...
}
Problem is, that i'm not allowed to add any atribute or method to abstract class SimplePolygon, so i'cant properly initialize varray. It could simply be solved with protected atrib in that class, but for some (stupid) reason i'cant do that. Has anybody an idea how to solve it without that? Thanks for all help.
Hi,
It's been two years since I last coded something in Java so my coding skills are bit rusty.
I need to save data (an user profile) in different data structures, ArrayList and LinkedList, and they both come from List. I want to avoid code duplication where I can and I also want to follow good Java practices.
For that, I'm trying to create an abstract class where the private variables will be of type List<E> and then create 2 sub-classes depending on the type of variable.
Thing is, I don't know if I'm doing this correctly, you can take a look at my code:
Class: DBList
import java.util.List;
public abstract class DBList {
private List<UserProfile> listName;
private List<UserProfile> listSSN;
public List<UserProfile> getListName() {
return this.listName;
}
public List<UserProfile> getListSSN() {
return this.listSSN;
}
public void setListName(List<UserProfile> listName) {
this.listName = listName;
}
public void setListSSN(List<UserProfile> listSSN) {
this.listSSN = listSSN;
}
}
Class: DBListArray
import java.util.ArrayList;
public class DBListArray extends DBList {
public DBListArray() {
super.setListName(new ArrayList<UserProfile>());
super.setListSSN(new ArrayList<UserProfile>());
}
public DBListArray(ArrayList<UserProfile> listName, ArrayList<UserProfile> listSSN) {
super.setListName(listName);
super.setListSSN(listSSN);
}
public DBListArray(DBListArray dbListArray) {
super.setListName(dbListArray.getListName());
super.setListSSN(dbListArray.getListSSN());
}
}
Class: DBListLinked
import java.util.LinkedList;
public class DBListLinked extends DBList {
public DBListLinked() {
super.setListName(new LinkedList<UserProfile>());
super.setListSSN(new LinkedList<UserProfile>());
}
public DBListLinked(LinkedList<UserProfile> listName, LinkedList<UserProfile> listSSN) {
super.setListName(listName);
super.setListSSN(listSSN);
}
public DBListLinked(DBListLinked dbListLinked) {
super.setListName(dbListLinked.getListName());
super.setListSSN(dbListLinked.getListSSN());
}
}
1) Does any of this make any sense? What am I doing wrong? Do you have any recommendations?
2) It would make more sense for me to have the constructors in DBList and calling them (with super()) in the subclasses but I can't do that because I can't initialize a variable with new List<E>().
3) I was thought to do deep copies whenever possible and for that I always override the clone() method of my classes and code it accordingly. But those classes never had any lists, sets or maps on them, they only had strings, ints, floats. How do I do deep copies in this situation?
Hi! I am interested in saving and load objects using the pickle module as you can read in a question I asked before:
Python: Errors saving and loading objects with pickle module
Someone commment:
1, In an other way: the error is raise because pickle wanted to load an instance of the class Fruits and search for the class definition where it was defined, but it didn't find it so it raise the error
Now I want to save and load a class definition in order to solve the problem I describe in the question mentioned before.
Thank you so much!
Hi Folk,
Here is a sample java program.
I wonder why the two approaches reslut different stories. Is it a bug or kind of bitter java feature?
And I run the sample upon java 1.5
package test;
public class TestOut{
public static void main(String[] args){
new TestIn();//it works
Class.forName("test.TestOut$TestIn").newInstance();// throw IllegalAccessException
}
private static class TestIn{}
}