w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Is it a common/acceptable pattern in Java development for a test class to extend the class being tested?
1) Well, I do not know if it is a general pattern but i already used it and found some drawbacks. 2) the reasons to not do it are fairy simple. It is recommended to use private accessor and final class or method. If you really apply the later, you will end up with producing many duplicate classes to test a class or a method. Also, How can you make sure somebody in your team will not end up using the dummy extended class in production? My solution to this problem was to use reflection to access private constructors and methods. It is somehow a bit tricky but afterwards it is a repetition. I am using now my utility reflection class for all my tests. Below is my reflection utility class: import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.F

Categories : Java

Is there a pattern where you have a class whose job it is to instantiate common implementations of another class?
I tend to stay away from the term "Helper" as all classes are supposed to be helpful, right? :) I think that calling this either Factory or Builder would be acceptable. The point of abstract factory is to encapsulate the construction/instantiation of an object. It could return different types, but it doesn't need to. The type consuming the factory shouldn't care. I tend to use the "Builder" name when it is doing any complex construction like this.

Categories : C#

Use field of class that implements Singleton pattern in another class
Just make it like this: class B { public object obj { get { return A.Instance.obj; } } } If it's the first time anyone touches A.Instance, this will initialize it. On subsequent calls it will reuse the same instance of A.

Categories : C#

Geocoder Class Explanation
First you need to get a LocationManager instance and the name of the provider you want to use to do a location look-up. For example: String provider = LocationManager.NETWORK_PROVIDER; LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Next, you call requestLocationUpdates(...) like so: locationManager.requestLocationUpdates(provider, 1000, 0, this); This can be invoked on the main thread since (I think) the system will do the location lookup using the specified provider on a background thread. When a location is found, the Android system will invoke the onLocationChanged(...) callback, which you need to override. Since you're trying to do an address lookup, you would put in: Geocoder geocoder = new Geocoder(this); geocoder.getFromLocati

Categories : Android

Angular-UI & Bootstrap: change class based on class
You can use a directive to conditionally set the class by observing the model value app.directive('myClass', function () { return { link: function (scope, element, attrs) { attrs.$observe('ngModel', function (item) { if (scope.myBtn !== 'B') { attrs.$set('class', "btn-primary"); } else { attrs.$set('class', "btn-success"); } }); } } }); Working Demo

Categories : Angularjs

Real life use and explanation of the AtomicLongFieldUpdate class
Atomics are usually used in parallel programming. Under the work-stealing mode, it only supports async, finish, forasync, isolated, and atomic variables. You can view atomic as a safe protection from data race and other problems that you need to concern in parallel programming.

Categories : Java

If a class inherits a method does calling that method on that class point to the super class or does it make a local copy within the child class?
It will follow the way you have it currently written: -> New object of class B -> Call method One on this object -> First line calls supermethod, proceed to execute it -> Second line prints out after that Your code doesn't compile at all though, you might want to clear that up. What's keeping you from testing this yourself? Here's the new situation as you described it. Everything still works as expected, you just add a layer. public class C { public void test() { System.out.println("Inside C"); } } public class B extends C { public void test() { super.test(); System.out.println("Inside B"); } } public class A extends B { public static void main(String[] args) { A obj = new A(); obj.test(); } } Out

Categories : Java

Is [class*="span"] also contains .row-fluid [class*="span"] in twitter bootstrap?
Thanks David Taiaroa (see his comment below the question and his informative link), the reason that this occurs is selectors specification priority. I thought that later defined properties will override prior properties but it turns out that more specific selectors will override more general selectors regardless where are placed. In this case .row-fluid span1, .row-fluid span2 etc has been specifically selected in order to set their width in bootstrap in various places. Therefor [class*="span"] is unable to override them because it is more general selector. And this is way we need .row-fluid [class*="span"] for selecting these elements.

Categories : CSS

Singleton pattern explanation
It's pointer to the only one instance of your class . You can access to this instance by 'Log::getInstance()' static function. We use singleton pattern when we in practice don't need more than one instance of a class in our code.

Categories : C++

MVC pattern with only one controller class?
There's a certain point where making decisions regarding MVC becomes a little less cut and dry. For a very small (and simple) site, you may only need one controller that does all your work for you, pulling data from models and constructing the views. You can certainly construct your MVC architecture so that all the models and views are instantiated by a single controller, but of course, this quickly falls apart once you get to a site of even remote complexity. My recommendation is to make your controllers conceptually separated in the same way you might design an application in a modular way. I would have a BlogController with all my blog methods and page serving, a ContactController, a PortfolioController, all inheriting from a master PageController in order to make sure that when the co

Categories : PHP

Cannot find method (class)(class)getRange((class),number) Error on Google Forms
The problem is that you're calling getRange(rowNumber... when rowNumber may not being defined. If you did as Srik suggests, and ran this in the debugger, you'd probably find execution stopping at: var preApproved = sheet.getRange(rowNumber, 14, 1, 1); ...and you'd see that rowNumber is undefined, because no match for responseID was found. A couple of lines later, you're checking whether preApproved is "trueish". I don't know why you're doing that - maybe this is recognition that responseID might not be found, and an expectation that the result would be a null range for the resulting getRange() call. Or maybe you meant to get the value at that cell? (Let's assume that's the case - then you need to use Range.getValue().) Better would be to properly validate the result of the search. Wh

Categories : Google Apps Script

Cleaner view with class="name1", class="name2" and jQuery regexp or not use numbers in class
To explain a little more my comment: jQuery's data function can be used to retreive and store ANY kind of javascript data to a DOM element. Since jQuery caches the DOM elements, it is not stored in the DOM at all, it simply is linked to it internally. This method of storing data is one of the easiest to use and one of the fastest when you need to link data to DOM elements. A little catch is to be avoided though, as it is described above, jQuery does not store directly in the data attribute of the DOM element. So if you have this piece of HTML: <a href="#" data-linkto="homepage">Link</a> you could, find this element with the attribute selector like $('[data-linkto]') to add your onclick event listener. But if, after some user interaction, you do $mylinkelement.data('linkto',

Categories : Javascript

Rational Class Built Off of Polynomial Class: An Analysis of Class Dependency and Operator Overloading
Source: Polynomial Multiply(const Polynomial & poly1, const Polynomial & poly2) { if( poly2.get_size()==1 && poly2.Coefficient(0)==1) The problemic method: int Polynomial::Coefficient(int k) const { return coefficient[k + 1]; } If the size is 1 then you can only reach the coefficient[0] and k + 1 here is 1. You may meant: int Polynomial::Coefficient(int k) const { return coefficient[k]; }

Categories : C++

i'm trying to insert after
After clarifying yourself in the comments, I think that's what you're looking for: jsFiddle Demo $('.cts').find('div.tbox, div.tarea').each(function(i) { var val; switch ($(this).attr("class")) { case ("tbox"): val = "first"; break; case ("tarea"): val = "second"; break; } var properties = $('<div class="fieldProperties">' + '<input type="text" value="' + val + '" name="fields['+i+'].id" ' + 'id="fields['+i+'].id"> </div>'); properties.insertAfter(this); });

Categories : Jquery

How to test that a type declared as "public class" is a class using java.lang.Class?
Class objects are singletons. Therefore, if you have an instance of any type, you can test that it is an exact class instance using: theInstance.getClass() == TheTargetClass.class As to testing whether a class is a "full" class, just negate all the test you mentioned. This first test is already an efficient filter... And do not forget .isSynthetic().

Categories : Java

initialize member variable of base class inside child class and use in other class
There are two instances of BaseClass in the example you posted. One is the one instantiated with new ChildClass() and the other one is instantiated by the main() method (TestClass). Each one of them, being a subclass of BaseClass, has its own test member (they are different variables with different values). Remember that the this keyword always references the instance in which it is used. In this case, System.out.println(this.test); is accessing the test property of the TestClass instance created in the main method. You need to access the test property of the other instance. You could do so by keeping a reference to the ChildClass instance and accessing the test property afterwards: ChildClass instance = new ChildClass().initialize(); System.out.println(instance.test); You

Categories : Java

Objective-C and Class Cluster pattern
Basically, the instance you have allocated could be thrown away and replaced with a different instance. Technically, this isn't specific to class clusters and that is why when you call super in any init method you need to set the result as self: self = [super init];

Categories : IOS

scala Class.forName pattern matching
First, you need to use the full and properly cased class name. Second, Class.forName returns a Class[_], not an instance of the class you give it. Take a look at modifications to your code that I made to get a clearer pciture: abstract class Person { val name: String //removed comma val age: Int } case class Man(name: String, age: Int, workPlace: String) extends Person val manClassName = classOf[Man].getName //get the proper name of the class println("Man class name: %s".format(manClassName)) val aclass = Class.forName(manClassName) //returns Class[Man] aclass match { case m: Class[Man] => println("this is a man class") //Pattern match on Class[Man] case p: Class[Person] => println("Person") case _ => println("Nothing") }

Categories : Scala

What is best Ruby Class design / pattern for this scenario?
Like @James Woodward said, you're going to want to create a class for each retailer. The pattern I'm going to post has three parts: A couple of ActiveRecord classes that implement a common interface for storing the data you want to record from each site 700 different classes, one for each site you want to scrape. These classes implement the algorithms for scraping the sites, but don't know how to store the information in the database. To do that, they rely on the common interface from step 1. One final class that ties it all together running each of the scraping algorithms you wrote in step 2. Step 1: ActiveRecord Interface This step is pretty easy. You already have a Site and SiteDetail class. You can keep them for storing the data you scrape from website in your database. You told

Categories : Mysql

Rebinding immutable class attribute in the base class from a derived class
Use the __bases__ attribute: In [68]: class Base(object): ...: # class attribute: ...: class_attr = 0 ...: In [69]: class Derived(Base): ...: @classmethod ...: def inc(cls): ...: p, = cls.__bases__ ...: p.class_attr += 1 ...: In [70]: Base.class_attr Out[70]: 0 In [71]: Derived.inc() In [72]: Derived.inc() In [73]: Base.class_attr Out[73]: 2 If you have multiple inheritance: In [88]: class DifferentInherited(object): ...: class2_attr = 0 ...: In [90]: class Der2(Base, DifferentInherited): ...: @classmethod ...: def inc(cls): ...: print cls.__bases__ ...: a, b, = cls.__bases__ ...: print a.class_attr ...: print b.class2_attr

Categories : Python

How to protected/private class #1 but allow wrapper class #2 to be public and containing in-house class #1?
In your example, if you have a separate assembly containing Class1 and Class2, you could give Class1 an internal constructor, so you could only instantiate it in your assembly. public class Class1 { internal Class1() { } public string Foo1() { return "Hello World!"; } } public class Class2 { Class1 class1 = new Class1(); public Class1 Class1_Test { get { return class1; } } } Anything outside of the assembly that tries to instantiate Class1 will receive the error The type 'MyAssembly.Class1' has no constructors defined

Categories : C#

why is bash pattern match for ?(*[[:class:]])foobar slow?
Simply because you do many forks of bash (one for the subshell, and one for the cat command), and also, you read the cat binary as well while you execute it. [[ `cat foobar.txt` == *[[:print:]]foobar ]] This form would be faster: [[ $(<foobar.txt) == *[[:print:]]foobar ]] Or IFS= read -r LINE < foobar.txt && [[ $LINE == *[[:print:]]foobar ]] If it doesn't make a difference the speed of pattern matching could be related to the version of Bash you're using.

Categories : Regex

Java improving Builder pattern on a specific class
What I find extremely elegant in this situations is to write a utility class with static factory methods like. public static Constraint userName(...) { ... } and to import static blabla.Utility.username; Then you can write almost declarative human-readable queries in java. This is very much as for the hamcrest library for unit testing where you write something like. Assert.assertThat(blabla, is(equalTo(nullValue())); In this case Not should implement Constraint and just negates the nested (referenced) constraint like this: public static Constraint not(Constraint negated) { return new Not(negated); } this results in code like PreparedStatement ps = new QueryBuilder() .select() .from(table("accounts") .where(not(username(equalTo("blabla"))) .compile(); You can add static fac

Categories : Java

config dict construction pattern, using a helper class?
I'm not sure if I understand the purpose of this construct. If you wish to ensure that the user only uses valid keys for the config dict, I would protect the attributes with the property decorator (see http://docs.python.org/2/library/functions.html#property): class Options: def __init__(self): self._A = 'A' self._B = 'B' # etc. @property def A(self): return self._A @property def B(self): return self._B # etc. Not that completely prevents the user to mess up your class, but at least it's less easy to do so.

Categories : Python

Strategy pattern with Factory class Unit testing
You have to redesign your code to use Dependency Injection. In your case define ILeaveFactoryCategory with GetCategory method. Make your ProRate class dependent on it (for example set factory by constructor parameter). Then mock the factory interface not calculator itself and set expectations for them. Use mocked object as parameter for class under test (LeaveCalculator). Verify expectations for you mocked object. ILeaveCalculation expectedCalculator = new MyCalculator(); LeaveCalculationType expectedCalculationType = LeaveCalculationType.MyType; ILeaveFactoryCategory factoryMock = MockRepository.GenerateMock<ILeaveFactoryCategory >(); factoryMock.Expect(f => f.GetCategory(Arg<LeaveCalculationType>.Is.Equal(expectedCalculationType)).Returns(expectedCalculator); var proRa

Categories : C#

How to unit test a timer class (adapter pattern)?
As no one answered this question yet, I'll tell you how I approached the problem: I used the spy pattern to actually implement the code that observes the behavior of the timer. The class looks like this: public class ThreadPoolTimerSpy : IDisposable { private readonly ThreadPoolTimer _threadPoolTimer; private int _intervalElapsedCallCount; private readonly ManualResetEvent _resetEvent = new ManualResetEvent(false); public int NumberOfIntervals { get; set; } public DateTime StartTime { get; private set; } public DateTime EndTime { get; private set; } public ThreadPoolTimerSpy(ThreadPoolTimer threadPoolTimer) { if (threadPoolTimer == null) throw new ArgumentNullException("threadPoolTimer"); _threadPoolTimer = threadPoolTimer; _thr

Categories : C#

Creating a custom image class in WPF following MVVM pattern
As far as my understanding of MVVM and your question goes, I have one main comment about your code. I think your CustomImage is actually both Model and ViewModel layer, and you should split it in two : the Model, which would contain the path itself ; the ViewModel, which contain the BitmapImage and initialize it from the Model and constructing time. The path is the mere data used for saving, and it fits the Model, whereas the BitmapImage is how the data is shown and should be constructed in the ViewModel. One advantage is that now, your BitmapImage gets its own NotifyPropertyChanged call at setting time, and you won't have anymore problem or a View part directly bound to the Model. As for your CustomImageViewModel, this looks like more of a MainViewModel-ish thing. You can still use

Categories : C#

Assign a subclass of a Generic class to a super class of this class
public class SimpleFinder<S extends Stack<T>,T extends Item> implements Finder<S,T>{ public S find(S s, int a){ Stack<T> stack = ....; ... stack = s.getCopy(); ..... return (S) stack; } } should work. Keep in mind that stack must be a Stack<T> and not S to match getCopy() return type. I would expect S type to be Ok, since it extends Stack<T>, but implementing it this is the behavior that I'm observing.

Categories : Java

PHP Class calling base class extended class function
This is weird way of OOP. The Base class should not know anything about its children so we shall go more correct way. Let's implement Decorator pattern: interface IExt { public function test(); } abstract class ExtDecorator implements IExt { protected $instance; public function __construct(IExt $ext) { $this->instance = $ext; } } class ExtA extends ExtDecorator { public function test() { return 'ExtA::test here and calling... ' . $this->instance->test(); } } class ExtB extends ExtDecorator { public function test() { return 'ExtB::test is here and calling... ' . $this->instance->test(); } } class Base implements IExt { public function test() { return 'Base::test here!'; } } class P

Categories : PHP

Class template where variable class derives from certain abstract class
Use std::is_base_of: template <class A> class B { static_assert(std::is_base_of<C, A>::value , "A must derive from C"); //... }; Note that is_base_of<C, C>::value is true, so you may want to also use std::is_same to ensure A is not actually C itself: static_assert(std::is_base_of<C, A>::value && !std::is_same<C, A>::value , "A must derive from C");

Categories : C++

How do we create instances of a class in JavaScript using new operator and factory pattern?
var Foo = function (a) { this.a = a; }; Foo.prototype.state = function () { return this.a; }; var a = new Foo(10); a.state(); // 10 Bun you can also declare the state method from constructor itself like: var Foo = function (a) { this.a = a; this.state = function () { return this.a; }; }; UPDATE: Factory pattern. I usually use this for my factories: var Foo = function (a) { this.a = a; }; Foo.prototype.state = function () { return this.a; }; var FooFactory = function () {}; FooFactory.prototype.create = function (a) { return new Foo(a); }; var factory = new FooFactory(); var a = factory.create(20); a instanceOf Foo; // true a.state(); // 20

Categories : Javascript

Is there a C# pattern for strongly typed class members with external set/get methods?
This pattern allows loosely coupled resource keys. A hashmap that excepts any key type, for the purpose of extensibility. You often see this with system messages in IoC containers. In my experience, this pattern grants great flexibility with the cost of required documentation. Consider solving the problem with convention rather than implementation. I try to stick to enumerated values where possible. They are immutable primitives with strong names. They can be groupedinto their parent type. They can be iterated quite simply if required. They respond to refactoring.

Categories : C#

Alternative design pattern to a base class function call
Unfortunately, this is one of those cases where you "have to do the right thing" when writing the code. This applies to many things in programming. If you don't do the right calculations when calculating something, that's also wrong. Or if you call a function twice that should only be called once. Or not calling it at all when it has to be called. All of these things are "doing it wrong". You can't prevent programmers from making mistakes... Of course, if you hadn't added a bunch of extra parameters, you could do it "in reverse" by having a non-virtual function in the base-class that doesn't get overridden, and then let the base-class call a virtual function in the derived class. As I said, it doesn't work if you have parameters that aren't present in the base class that needs to go into

Categories : C++

Is it possible to take advantage of case class inheritance in pattern matching in Scala 2.10.0?
As far as I could understand the problem, I have no reason to use "case classes" for the children. Hopefully the correct code is as follows: object AST { sealed abstract class Expr case class MathOp(e1: Expr, e2: Expr) extends Expr case class Number extends Expr class Add(e1: Expr, e2: Expr) extends MathOp(e1, e2) class Sub(e1: Expr, e2: Expr) extends MathOp(e1, e2) } expr match { case MathOp(e1: Expr, e2: Expr) => //do something that would be done to Add, Sub, Mul, Div case Number => //do another thing }

Categories : Scala

Curiously Recurring Template Pattern and statics in the base class
Func in the derived class hides all base members with the same name. Use using declarative to bring the names from the base class into the derived class. class Derived : public Base< Derived > { public: using Base<Derived>::Func; //rest.. };

Categories : C++

AspectJ: target vs signature pattern to select methods on a class
Target expects an instance of the class specified, while call itself has no such restriction. That means the pointcut with just call(..) can catch static method executions as well, while one with a target(Class) can not. It only catches methods executed on an object of the specified class (hence the name 'target').

Categories : Java

Looking for a pattern for class creation & configuration based on input params
I think you need the Strategy Pattern. You define an interface with a method: interface Configure{ public YourObject excecute(YourObject o); } You implement the interface in the variety of ways you want and you declare it as a member field. Then you instantiate the appropriate class according to the values of the variables. If you want to save the Objects then you can use the Command Pattern as well. Update: Ok in Software Enginneering there is usually no absolute truth. With the Command Pattern you have already a class that does some tasks and you want to save them as Objects from a class deriving from an interface, in order to use them later etc. I do not reckon that your case requires such an approach, since you need merely diverse functionalities defined as an interface metho

Categories : Java

Bootstrap 3.0 Grid Explanation
The basic gist of it is that the different iterations of the .col class allow you to specify grid behavior for different devices (phones, tablets, desktops). So, in the example you are asking about the .col-lg-8 specifies that the div should take up 8 columns on desktop while .col-12 specifies that the div should take up 12 columns (the entire row) on a mobile device. This level of specificity gives you precise control over how your content will be laid out on different screen sizes in a way that was not as straightforward with Bootstrap 2. In general I've found the best way to understand what these mean in practice is to bring up the example pages on the different device types or re-size your browser window and simply compare the results. Also, as stated in the comments to your quest

Categories : HTML

Class design / pattern for a chain of objects separated by a variable delimiter
Here comes a proposal of how to face your problem: Public Class ExpressionFromChainOfExpressions Inherits Expression Private ExprChain As List(Of Expression) Private ExprConn As List(Of Connector) Public Enum Connector AndConn OrConn End Enum Public Sub AddExpression(Expr As Expression) 'Might have to be changed to account for connectors If ExprChain Is Nothing Then ExprChain = New List(Of Expression) ExprChain.Add(Expr) End Sub Public Overrides Function ToString() As String Dim outStr As String = "(" For i = 0 To ExprChain.Count - 1 outStr &= ExprChain(i).ToString() If i < ExprChain.Count - 1 Then outStr &= 'will account for the given connector (as stored in

Categories : Vb.Net

extend unknown super class with decorator pattern and override functions
You can't override the function this way because I is more precise that LayoutInflater I suggest you use something tike that : public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { I infl = (I) inflater; // May be unchecked if (view == null) { view = doOnCreateView(infl, container, savedInstanceState); loadingIndicator = doGetLoadingIndicatorView(view); } return view; } In fact, I wonder why you need to use a TypeVariable for I. You got a subclass of LayoutInflater ? Maybe just using LayoutInflater everywhere should be enough ?

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.